clang 20.0.0git
SemaInit.cpp
Go to the documentation of this file.
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/Lookup.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/FoldingSet.h"
35#include "llvm/ADT/PointerIntPair.h"
36#include "llvm/ADT/STLForwardCompat.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// Sema Initialization Checking
47//===----------------------------------------------------------------------===//
48
49/// Check whether T is compatible with a wide character type (wchar_t,
50/// char16_t or char32_t).
51static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
52 if (Context.typesAreCompatible(Context.getWideCharType(), T))
53 return true;
54 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
55 return Context.typesAreCompatible(Context.Char16Ty, T) ||
56 Context.typesAreCompatible(Context.Char32Ty, T);
57 }
58 return false;
59}
60
69};
70
71/// Check whether the array of type AT can be initialized by the Init
72/// expression by means of string initialization. Returns SIF_None if so,
73/// otherwise returns a StringInitFailureKind that describes why the
74/// initialization would not work.
76 ASTContext &Context) {
77 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
78 return SIF_Other;
79
80 // See if this is a string literal or @encode.
81 Init = Init->IgnoreParens();
82
83 // Handle @encode, which is a narrow string.
84 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
85 return SIF_None;
86
87 // Otherwise we can only handle string literals.
88 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
89 if (!SL)
90 return SIF_Other;
91
92 const QualType ElemTy =
94
95 auto IsCharOrUnsignedChar = [](const QualType &T) {
96 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
97 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
98 };
99
100 switch (SL->getKind()) {
101 case StringLiteralKind::UTF8:
102 // char8_t array can be initialized with a UTF-8 string.
103 // - C++20 [dcl.init.string] (DR)
104 // Additionally, an array of char or unsigned char may be initialized
105 // by a UTF-8 string literal.
106 if (ElemTy->isChar8Type() ||
107 (Context.getLangOpts().Char8 &&
108 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
109 return SIF_None;
110 [[fallthrough]];
111 case StringLiteralKind::Ordinary:
112 // char array can be initialized with a narrow string.
113 // Only allow char x[] = "foo"; not char x[] = L"foo";
114 if (ElemTy->isCharType())
115 return (SL->getKind() == StringLiteralKind::UTF8 &&
116 Context.getLangOpts().Char8)
118 : SIF_None;
119 if (ElemTy->isChar8Type())
121 if (IsWideCharCompatible(ElemTy, Context))
123 return SIF_Other;
124 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
125 // "An array with element type compatible with a qualified or unqualified
126 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
127 // string literal with the corresponding encoding prefix (L, u, or U,
128 // respectively), optionally enclosed in braces.
129 case StringLiteralKind::UTF16:
130 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
131 return SIF_None;
132 if (ElemTy->isCharType() || ElemTy->isChar8Type())
134 if (IsWideCharCompatible(ElemTy, Context))
136 return SIF_Other;
137 case StringLiteralKind::UTF32:
138 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
139 return SIF_None;
140 if (ElemTy->isCharType() || ElemTy->isChar8Type())
142 if (IsWideCharCompatible(ElemTy, Context))
144 return SIF_Other;
145 case StringLiteralKind::Wide:
146 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
147 return SIF_None;
148 if (ElemTy->isCharType() || ElemTy->isChar8Type())
150 if (IsWideCharCompatible(ElemTy, Context))
152 return SIF_Other;
153 case StringLiteralKind::Unevaluated:
154 assert(false && "Unevaluated string literal in initialization");
155 break;
156 }
157
158 llvm_unreachable("missed a StringLiteral kind?");
159}
160
162 ASTContext &Context) {
163 const ArrayType *arrayType = Context.getAsArrayType(declType);
164 if (!arrayType)
165 return SIF_Other;
166 return IsStringInit(init, arrayType, Context);
167}
168
170 return ::IsStringInit(Init, AT, Context) == SIF_None;
171}
172
173/// Update the type of a string literal, including any surrounding parentheses,
174/// to match the type of the object which it is initializing.
176 while (true) {
177 E->setType(Ty);
179 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
180 break;
182 }
183}
184
185/// Fix a compound literal initializing an array so it's correctly marked
186/// as an rvalue.
188 while (true) {
190 if (isa<CompoundLiteralExpr>(E))
191 break;
193 }
194}
195
197 Decl *D = Entity.getDecl();
198 const InitializedEntity *Parent = &Entity;
199
200 while (Parent) {
201 D = Parent->getDecl();
202 Parent = Parent->getParent();
203 }
204
205 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
206 return true;
207
208 return false;
209}
210
212 Sema &SemaRef, QualType &TT);
213
214static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
215 Sema &S, bool CheckC23ConstexprInit = false) {
216 // Get the length of the string as parsed.
217 auto *ConstantArrayTy =
218 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
219 uint64_t StrLength = ConstantArrayTy->getZExtSize();
220
221 if (CheckC23ConstexprInit)
222 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
224
225 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
226 // C99 6.7.8p14. We have an array of character type with unknown size
227 // being initialized to a string literal.
228 llvm::APInt ConstVal(32, StrLength);
229 // Return a new array type (C99 6.7.8p22).
231 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
232 updateStringLiteralType(Str, DeclT);
233 return;
234 }
235
236 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
237
238 // We have an array of character type with known size. However,
239 // the size may be smaller or larger than the string we are initializing.
240 // FIXME: Avoid truncation for 64-bit length strings.
241 if (S.getLangOpts().CPlusPlus) {
242 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
243 // For Pascal strings it's OK to strip off the terminating null character,
244 // so the example below is valid:
245 //
246 // unsigned char a[2] = "\pa";
247 if (SL->isPascal())
248 StrLength--;
249 }
250
251 // [dcl.init.string]p2
252 if (StrLength > CAT->getZExtSize())
253 S.Diag(Str->getBeginLoc(),
254 diag::err_initializer_string_for_char_array_too_long)
255 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
256 } else {
257 // C99 6.7.8p14.
258 if (StrLength - 1 > CAT->getZExtSize())
259 S.Diag(Str->getBeginLoc(),
260 diag::ext_initializer_string_for_char_array_too_long)
261 << Str->getSourceRange();
262 }
263
264 // Set the type to the actual size that we are initializing. If we have
265 // something like:
266 // char x[1] = "foo";
267 // then this will set the string literal's type to char[1].
268 updateStringLiteralType(Str, DeclT);
269}
270
271//===----------------------------------------------------------------------===//
272// Semantic checking for initializer lists.
273//===----------------------------------------------------------------------===//
274
275namespace {
276
277/// Semantic checking for initializer lists.
278///
279/// The InitListChecker class contains a set of routines that each
280/// handle the initialization of a certain kind of entity, e.g.,
281/// arrays, vectors, struct/union types, scalars, etc. The
282/// InitListChecker itself performs a recursive walk of the subobject
283/// structure of the type to be initialized, while stepping through
284/// the initializer list one element at a time. The IList and Index
285/// parameters to each of the Check* routines contain the active
286/// (syntactic) initializer list and the index into that initializer
287/// list that represents the current initializer. Each routine is
288/// responsible for moving that Index forward as it consumes elements.
289///
290/// Each Check* routine also has a StructuredList/StructuredIndex
291/// arguments, which contains the current "structured" (semantic)
292/// initializer list and the index into that initializer list where we
293/// are copying initializers as we map them over to the semantic
294/// list. Once we have completed our recursive walk of the subobject
295/// structure, we will have constructed a full semantic initializer
296/// list.
297///
298/// C99 designators cause changes in the initializer list traversal,
299/// because they make the initialization "jump" into a specific
300/// subobject and then continue the initialization from that
301/// point. CheckDesignatedInitializer() recursively steps into the
302/// designated subobject and manages backing out the recursion to
303/// initialize the subobjects after the one designated.
304///
305/// If an initializer list contains any designators, we build a placeholder
306/// structured list even in 'verify only' mode, so that we can track which
307/// elements need 'empty' initializtion.
308class InitListChecker {
309 Sema &SemaRef;
310 bool hadError = false;
311 bool VerifyOnly; // No diagnostics.
312 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
313 bool InOverloadResolution;
314 InitListExpr *FullyStructuredList = nullptr;
315 NoInitExpr *DummyExpr = nullptr;
316 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
317 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
318 unsigned CurEmbedIndex = 0;
319
320 NoInitExpr *getDummyInit() {
321 if (!DummyExpr)
322 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
323 return DummyExpr;
324 }
325
326 void CheckImplicitInitList(const InitializedEntity &Entity,
327 InitListExpr *ParentIList, QualType T,
328 unsigned &Index, InitListExpr *StructuredList,
329 unsigned &StructuredIndex);
330 void CheckExplicitInitList(const InitializedEntity &Entity,
331 InitListExpr *IList, QualType &T,
332 InitListExpr *StructuredList,
333 bool TopLevelObject = false);
334 void CheckListElementTypes(const InitializedEntity &Entity,
335 InitListExpr *IList, QualType &DeclType,
336 bool SubobjectIsDesignatorContext,
337 unsigned &Index,
338 InitListExpr *StructuredList,
339 unsigned &StructuredIndex,
340 bool TopLevelObject = false);
341 void CheckSubElementType(const InitializedEntity &Entity,
342 InitListExpr *IList, QualType ElemType,
343 unsigned &Index,
344 InitListExpr *StructuredList,
345 unsigned &StructuredIndex,
346 bool DirectlyDesignated = false);
347 void CheckComplexType(const InitializedEntity &Entity,
348 InitListExpr *IList, QualType DeclType,
349 unsigned &Index,
350 InitListExpr *StructuredList,
351 unsigned &StructuredIndex);
352 void CheckScalarType(const InitializedEntity &Entity,
353 InitListExpr *IList, QualType DeclType,
354 unsigned &Index,
355 InitListExpr *StructuredList,
356 unsigned &StructuredIndex);
357 void CheckReferenceType(const InitializedEntity &Entity,
358 InitListExpr *IList, QualType DeclType,
359 unsigned &Index,
360 InitListExpr *StructuredList,
361 unsigned &StructuredIndex);
362 void CheckVectorType(const InitializedEntity &Entity,
363 InitListExpr *IList, QualType DeclType, unsigned &Index,
364 InitListExpr *StructuredList,
365 unsigned &StructuredIndex);
366 void CheckStructUnionTypes(const InitializedEntity &Entity,
367 InitListExpr *IList, QualType DeclType,
370 bool SubobjectIsDesignatorContext, unsigned &Index,
371 InitListExpr *StructuredList,
372 unsigned &StructuredIndex,
373 bool TopLevelObject = false);
374 void CheckArrayType(const InitializedEntity &Entity,
375 InitListExpr *IList, QualType &DeclType,
376 llvm::APSInt elementIndex,
377 bool SubobjectIsDesignatorContext, unsigned &Index,
378 InitListExpr *StructuredList,
379 unsigned &StructuredIndex);
380 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
381 InitListExpr *IList, DesignatedInitExpr *DIE,
382 unsigned DesigIdx,
383 QualType &CurrentObjectType,
385 llvm::APSInt *NextElementIndex,
386 unsigned &Index,
387 InitListExpr *StructuredList,
388 unsigned &StructuredIndex,
389 bool FinishSubobjectInit,
390 bool TopLevelObject);
391 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
392 QualType CurrentObjectType,
393 InitListExpr *StructuredList,
394 unsigned StructuredIndex,
395 SourceRange InitRange,
396 bool IsFullyOverwritten = false);
397 void UpdateStructuredListElement(InitListExpr *StructuredList,
398 unsigned &StructuredIndex,
399 Expr *expr);
400 InitListExpr *createInitListExpr(QualType CurrentObjectType,
401 SourceRange InitRange,
402 unsigned ExpectedNumInits);
403 int numArrayElements(QualType DeclType);
404 int numStructUnionElements(QualType DeclType);
405 static RecordDecl *getRecordDecl(QualType DeclType);
406
407 ExprResult PerformEmptyInit(SourceLocation Loc,
408 const InitializedEntity &Entity);
409
410 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
411 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
412 bool UnionOverride = false,
413 bool FullyOverwritten = true) {
414 // Overriding an initializer via a designator is valid with C99 designated
415 // initializers, but ill-formed with C++20 designated initializers.
416 unsigned DiagID =
417 SemaRef.getLangOpts().CPlusPlus
418 ? (UnionOverride ? diag::ext_initializer_union_overrides
419 : diag::ext_initializer_overrides)
420 : diag::warn_initializer_overrides;
421
422 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
423 // In overload resolution, we have to strictly enforce the rules, and so
424 // don't allow any overriding of prior initializers. This matters for a
425 // case such as:
426 //
427 // union U { int a, b; };
428 // struct S { int a, b; };
429 // void f(U), f(S);
430 //
431 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
432 // consistency, we disallow all overriding of prior initializers in
433 // overload resolution, not only overriding of union members.
434 hadError = true;
435 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
436 // If we'll be keeping around the old initializer but overwriting part of
437 // the object it initialized, and that object is not trivially
438 // destructible, this can leak. Don't allow that, not even as an
439 // extension.
440 //
441 // FIXME: It might be reasonable to allow this in cases where the part of
442 // the initializer that we're overriding has trivial destruction.
443 DiagID = diag::err_initializer_overrides_destructed;
444 } else if (!OldInit->getSourceRange().isValid()) {
445 // We need to check on source range validity because the previous
446 // initializer does not have to be an explicit initializer. e.g.,
447 //
448 // struct P { int a, b; };
449 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
450 //
451 // There is an overwrite taking place because the first braced initializer
452 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
453 //
454 // Such overwrites are harmless, so we don't diagnose them. (Note that in
455 // C++, this cannot be reached unless we've already seen and diagnosed a
456 // different conformance issue, such as a mixture of designated and
457 // non-designated initializers or a multi-level designator.)
458 return;
459 }
460
461 if (!VerifyOnly) {
462 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
463 << NewInitRange << FullyOverwritten << OldInit->getType();
464 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
465 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
466 << OldInit->getSourceRange();
467 }
468 }
469
470 // Explanation on the "FillWithNoInit" mode:
471 //
472 // Assume we have the following definitions (Case#1):
473 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
474 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
475 //
476 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
477 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
478 //
479 // But if we have (Case#2):
480 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
481 //
482 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
483 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
484 //
485 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
486 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
487 // initializers but with special "NoInitExpr" place holders, which tells the
488 // CodeGen not to generate any initializers for these parts.
489 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
490 const InitializedEntity &ParentEntity,
491 InitListExpr *ILE, bool &RequiresSecondPass,
492 bool FillWithNoInit);
493 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
494 const InitializedEntity &ParentEntity,
495 InitListExpr *ILE, bool &RequiresSecondPass,
496 bool FillWithNoInit = false);
497 void FillInEmptyInitializations(const InitializedEntity &Entity,
498 InitListExpr *ILE, bool &RequiresSecondPass,
499 InitListExpr *OuterILE, unsigned OuterIndex,
500 bool FillWithNoInit = false);
501 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
502 Expr *InitExpr, FieldDecl *Field,
503 bool TopLevelObject);
504 void CheckEmptyInitializable(const InitializedEntity &Entity,
506
507 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
508 Expr *Result = nullptr;
509 // Undrestand which part of embed we'd like to reference.
510 if (!CurEmbed) {
511 CurEmbed = Embed;
512 CurEmbedIndex = 0;
513 }
514 // Reference just one if we're initializing a single scalar.
515 uint64_t ElsCount = 1;
516 // Otherwise try to fill whole array with embed data.
518 auto *AType =
519 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
520 assert(AType && "expected array type when initializing array");
521 ElsCount = Embed->getDataElementCount();
522 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
523 ElsCount = std::min(CAType->getSize().getZExtValue(),
524 ElsCount - CurEmbedIndex);
525 if (ElsCount == Embed->getDataElementCount()) {
526 CurEmbed = nullptr;
527 CurEmbedIndex = 0;
528 return Embed;
529 }
530 }
531
532 Result = new (SemaRef.Context)
533 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
534 CurEmbedIndex, ElsCount);
535 CurEmbedIndex += ElsCount;
536 if (CurEmbedIndex >= Embed->getDataElementCount()) {
537 CurEmbed = nullptr;
538 CurEmbedIndex = 0;
539 }
540 return Result;
541 }
542
543public:
544 InitListChecker(
545 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
546 bool VerifyOnly, bool TreatUnavailableAsInvalid,
547 bool InOverloadResolution = false,
548 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
549 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
550 QualType &T,
551 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
552 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
553 /*TreatUnavailableAsInvalid=*/false,
554 /*InOverloadResolution=*/false,
555 &AggrDeductionCandidateParamTypes) {}
556
557 bool HadError() { return hadError; }
558
559 // Retrieves the fully-structured initializer list used for
560 // semantic analysis and code generation.
561 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
562};
563
564} // end anonymous namespace
565
566ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
567 const InitializedEntity &Entity) {
569 true);
570 MultiExprArg SubInit;
571 Expr *InitExpr;
572 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
573
574 // C++ [dcl.init.aggr]p7:
575 // If there are fewer initializer-clauses in the list than there are
576 // members in the aggregate, then each member not explicitly initialized
577 // ...
578 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
580 if (EmptyInitList) {
581 // C++1y / DR1070:
582 // shall be initialized [...] from an empty initializer list.
583 //
584 // We apply the resolution of this DR to C++11 but not C++98, since C++98
585 // does not have useful semantics for initialization from an init list.
586 // We treat this as copy-initialization, because aggregate initialization
587 // always performs copy-initialization on its elements.
588 //
589 // Only do this if we're initializing a class type, to avoid filling in
590 // the initializer list where possible.
591 InitExpr = VerifyOnly
592 ? &DummyInitList
593 : new (SemaRef.Context)
594 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
595 InitExpr->setType(SemaRef.Context.VoidTy);
596 SubInit = InitExpr;
598 } else {
599 // C++03:
600 // shall be value-initialized.
601 }
602
603 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
604 // libstdc++4.6 marks the vector default constructor as explicit in
605 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
606 // stlport does so too. Look for std::__debug for libstdc++, and for
607 // std:: for stlport. This is effectively a compiler-side implementation of
608 // LWG2193.
609 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
613 InitSeq.getFailedCandidateSet()
614 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
615 (void)O;
616 assert(O == OR_Success && "Inconsistent overload resolution");
617 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
618 CXXRecordDecl *R = CtorDecl->getParent();
619
620 if (CtorDecl->getMinRequiredArguments() == 0 &&
621 CtorDecl->isExplicit() && R->getDeclName() &&
622 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
623 bool IsInStd = false;
624 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
625 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
627 IsInStd = true;
628 }
629
630 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
631 .Cases("basic_string", "deque", "forward_list", true)
632 .Cases("list", "map", "multimap", "multiset", true)
633 .Cases("priority_queue", "queue", "set", "stack", true)
634 .Cases("unordered_map", "unordered_set", "vector", true)
635 .Default(false)) {
636 InitSeq.InitializeFrom(
637 SemaRef, Entity,
639 MultiExprArg(), /*TopLevelOfInitList=*/false,
640 TreatUnavailableAsInvalid);
641 // Emit a warning for this. System header warnings aren't shown
642 // by default, but people working on system headers should see it.
643 if (!VerifyOnly) {
644 SemaRef.Diag(CtorDecl->getLocation(),
645 diag::warn_invalid_initializer_from_system_header);
647 SemaRef.Diag(Entity.getDecl()->getLocation(),
648 diag::note_used_in_initialization_here);
649 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
650 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
651 }
652 }
653 }
654 }
655 if (!InitSeq) {
656 if (!VerifyOnly) {
657 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
659 SemaRef.Diag(Entity.getDecl()->getLocation(),
660 diag::note_in_omitted_aggregate_initializer)
661 << /*field*/1 << Entity.getDecl();
662 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
663 bool IsTrailingArrayNewMember =
664 Entity.getParent() &&
666 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
667 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
668 << Entity.getElementIndex();
669 }
670 }
671 hadError = true;
672 return ExprError();
673 }
674
675 return VerifyOnly ? ExprResult()
676 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
677}
678
679void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
681 // If we're building a fully-structured list, we'll check this at the end
682 // once we know which elements are actually initialized. Otherwise, we know
683 // that there are no designators so we can just check now.
684 if (FullyStructuredList)
685 return;
686 PerformEmptyInit(Loc, Entity);
687}
688
689void InitListChecker::FillInEmptyInitForBase(
690 unsigned Init, const CXXBaseSpecifier &Base,
691 const InitializedEntity &ParentEntity, InitListExpr *ILE,
692 bool &RequiresSecondPass, bool FillWithNoInit) {
694 SemaRef.Context, &Base, false, &ParentEntity);
695
696 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
697 ExprResult BaseInit = FillWithNoInit
698 ? new (SemaRef.Context) NoInitExpr(Base.getType())
699 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
700 if (BaseInit.isInvalid()) {
701 hadError = true;
702 return;
703 }
704
705 if (!VerifyOnly) {
706 assert(Init < ILE->getNumInits() && "should have been expanded");
707 ILE->setInit(Init, BaseInit.getAs<Expr>());
708 }
709 } else if (InitListExpr *InnerILE =
710 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
711 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
712 ILE, Init, FillWithNoInit);
713 } else if (DesignatedInitUpdateExpr *InnerDIUE =
714 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
715 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
716 RequiresSecondPass, ILE, Init,
717 /*FillWithNoInit =*/true);
718 }
719}
720
721void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
722 const InitializedEntity &ParentEntity,
723 InitListExpr *ILE,
724 bool &RequiresSecondPass,
725 bool FillWithNoInit) {
727 unsigned NumInits = ILE->getNumInits();
728 InitializedEntity MemberEntity
729 = InitializedEntity::InitializeMember(Field, &ParentEntity);
730
731 if (Init >= NumInits || !ILE->getInit(Init)) {
732 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
733 if (!RType->getDecl()->isUnion())
734 assert((Init < NumInits || VerifyOnly) &&
735 "This ILE should have been expanded");
736
737 if (FillWithNoInit) {
738 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
739 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
740 if (Init < NumInits)
741 ILE->setInit(Init, Filler);
742 else
743 ILE->updateInit(SemaRef.Context, Init, Filler);
744 return;
745 }
746 // C++1y [dcl.init.aggr]p7:
747 // If there are fewer initializer-clauses in the list than there are
748 // members in the aggregate, then each member not explicitly initialized
749 // shall be initialized from its brace-or-equal-initializer [...]
750 if (Field->hasInClassInitializer()) {
751 if (VerifyOnly)
752 return;
753
754 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
755 if (DIE.isInvalid()) {
756 hadError = true;
757 return;
758 }
759 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
760 if (Init < NumInits)
761 ILE->setInit(Init, DIE.get());
762 else {
763 ILE->updateInit(SemaRef.Context, Init, DIE.get());
764 RequiresSecondPass = true;
765 }
766 return;
767 }
768
769 if (Field->getType()->isReferenceType()) {
770 if (!VerifyOnly) {
771 // C++ [dcl.init.aggr]p9:
772 // If an incomplete or empty initializer-list leaves a
773 // member of reference type uninitialized, the program is
774 // ill-formed.
775 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
776 << Field->getType()
777 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
778 ->getSourceRange();
779 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
780 }
781 hadError = true;
782 return;
783 }
784
785 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
786 if (MemberInit.isInvalid()) {
787 hadError = true;
788 return;
789 }
790
791 if (hadError || VerifyOnly) {
792 // Do nothing
793 } else if (Init < NumInits) {
794 ILE->setInit(Init, MemberInit.getAs<Expr>());
795 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
796 // Empty initialization requires a constructor call, so
797 // extend the initializer list to include the constructor
798 // call and make a note that we'll need to take another pass
799 // through the initializer list.
800 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
801 RequiresSecondPass = true;
802 }
803 } else if (InitListExpr *InnerILE
804 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
805 FillInEmptyInitializations(MemberEntity, InnerILE,
806 RequiresSecondPass, ILE, Init, FillWithNoInit);
807 } else if (DesignatedInitUpdateExpr *InnerDIUE =
808 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
809 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
810 RequiresSecondPass, ILE, Init,
811 /*FillWithNoInit =*/true);
812 }
813}
814
815/// Recursively replaces NULL values within the given initializer list
816/// with expressions that perform value-initialization of the
817/// appropriate type, and finish off the InitListExpr formation.
818void
819InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
820 InitListExpr *ILE,
821 bool &RequiresSecondPass,
822 InitListExpr *OuterILE,
823 unsigned OuterIndex,
824 bool FillWithNoInit) {
825 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
826 "Should not have void type");
827
828 // We don't need to do any checks when just filling NoInitExprs; that can't
829 // fail.
830 if (FillWithNoInit && VerifyOnly)
831 return;
832
833 // If this is a nested initializer list, we might have changed its contents
834 // (and therefore some of its properties, such as instantiation-dependence)
835 // while filling it in. Inform the outer initializer list so that its state
836 // can be updated to match.
837 // FIXME: We should fully build the inner initializers before constructing
838 // the outer InitListExpr instead of mutating AST nodes after they have
839 // been used as subexpressions of other nodes.
840 struct UpdateOuterILEWithUpdatedInit {
841 InitListExpr *Outer;
842 unsigned OuterIndex;
843 ~UpdateOuterILEWithUpdatedInit() {
844 if (Outer)
845 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
846 }
847 } UpdateOuterRAII = {OuterILE, OuterIndex};
848
849 // A transparent ILE is not performing aggregate initialization and should
850 // not be filled in.
851 if (ILE->isTransparent())
852 return;
853
854 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
855 const RecordDecl *RDecl = RType->getDecl();
856 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
857 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
858 RequiresSecondPass, FillWithNoInit);
859 } else {
860 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
861 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
862 "We should have computed initialized fields already");
863 // The fields beyond ILE->getNumInits() are default initialized, so in
864 // order to leave them uninitialized, the ILE is expanded and the extra
865 // fields are then filled with NoInitExpr.
866 unsigned NumElems = numStructUnionElements(ILE->getType());
867 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
868 ++NumElems;
869 if (!VerifyOnly && ILE->getNumInits() < NumElems)
870 ILE->resizeInits(SemaRef.Context, NumElems);
871
872 unsigned Init = 0;
873
874 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
875 for (auto &Base : CXXRD->bases()) {
876 if (hadError)
877 return;
878
879 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
880 FillWithNoInit);
881 ++Init;
882 }
883 }
884
885 for (auto *Field : RDecl->fields()) {
886 if (Field->isUnnamedBitField())
887 continue;
888
889 if (hadError)
890 return;
891
892 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
893 FillWithNoInit);
894 if (hadError)
895 return;
896
897 ++Init;
898
899 // Only look at the first initialization of a union.
900 if (RDecl->isUnion())
901 break;
902 }
903 }
904
905 return;
906 }
907
908 QualType ElementType;
909
910 InitializedEntity ElementEntity = Entity;
911 unsigned NumInits = ILE->getNumInits();
912 uint64_t NumElements = NumInits;
913 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
914 ElementType = AType->getElementType();
915 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
916 NumElements = CAType->getZExtSize();
917 // For an array new with an unknown bound, ask for one additional element
918 // in order to populate the array filler.
919 if (Entity.isVariableLengthArrayNew())
920 ++NumElements;
921 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
922 0, Entity);
923 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
924 ElementType = VType->getElementType();
925 NumElements = VType->getNumElements();
926 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
927 0, Entity);
928 } else
929 ElementType = ILE->getType();
930
931 bool SkipEmptyInitChecks = false;
932 for (uint64_t Init = 0; Init != NumElements; ++Init) {
933 if (hadError)
934 return;
935
936 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
938 ElementEntity.setElementIndex(Init);
939
940 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
941 return;
942
943 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
944 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
945 ILE->setInit(Init, ILE->getArrayFiller());
946 else if (!InitExpr && !ILE->hasArrayFiller()) {
947 // In VerifyOnly mode, there's no point performing empty initialization
948 // more than once.
949 if (SkipEmptyInitChecks)
950 continue;
951
952 Expr *Filler = nullptr;
953
954 if (FillWithNoInit)
955 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
956 else {
957 ExprResult ElementInit =
958 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
959 if (ElementInit.isInvalid()) {
960 hadError = true;
961 return;
962 }
963
964 Filler = ElementInit.getAs<Expr>();
965 }
966
967 if (hadError) {
968 // Do nothing
969 } else if (VerifyOnly) {
970 SkipEmptyInitChecks = true;
971 } else if (Init < NumInits) {
972 // For arrays, just set the expression used for value-initialization
973 // of the "holes" in the array.
974 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
975 ILE->setArrayFiller(Filler);
976 else
977 ILE->setInit(Init, Filler);
978 } else {
979 // For arrays, just set the expression used for value-initialization
980 // of the rest of elements and exit.
981 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
982 ILE->setArrayFiller(Filler);
983 return;
984 }
985
986 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
987 // Empty initialization requires a constructor call, so
988 // extend the initializer list to include the constructor
989 // call and make a note that we'll need to take another pass
990 // through the initializer list.
991 ILE->updateInit(SemaRef.Context, Init, Filler);
992 RequiresSecondPass = true;
993 }
994 }
995 } else if (InitListExpr *InnerILE
996 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
997 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
998 ILE, Init, FillWithNoInit);
999 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1000 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1001 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1002 RequiresSecondPass, ILE, Init,
1003 /*FillWithNoInit =*/true);
1004 }
1005 }
1006}
1007
1008static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1009 for (const Stmt *Init : *IL)
1010 if (isa_and_nonnull<DesignatedInitExpr>(Init))
1011 return true;
1012 return false;
1013}
1014
1015InitListChecker::InitListChecker(
1016 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1017 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1018 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1019 : SemaRef(S), VerifyOnly(VerifyOnly),
1020 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1021 InOverloadResolution(InOverloadResolution),
1022 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1023 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1024 FullyStructuredList =
1025 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
1026
1027 // FIXME: Check that IL isn't already the semantic form of some other
1028 // InitListExpr. If it is, we'd create a broken AST.
1029 if (!VerifyOnly)
1030 FullyStructuredList->setSyntacticForm(IL);
1031 }
1032
1033 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1034 /*TopLevelObject=*/true);
1035
1036 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1037 bool RequiresSecondPass = false;
1038 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1039 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1040 if (RequiresSecondPass && !hadError)
1041 FillInEmptyInitializations(Entity, FullyStructuredList,
1042 RequiresSecondPass, nullptr, 0);
1043 }
1044 if (hadError && FullyStructuredList)
1045 FullyStructuredList->markError();
1046}
1047
1048int InitListChecker::numArrayElements(QualType DeclType) {
1049 // FIXME: use a proper constant
1050 int maxElements = 0x7FFFFFFF;
1051 if (const ConstantArrayType *CAT =
1052 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1053 maxElements = static_cast<int>(CAT->getZExtSize());
1054 }
1055 return maxElements;
1056}
1057
1058int InitListChecker::numStructUnionElements(QualType DeclType) {
1059 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1060 int InitializableMembers = 0;
1061 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1062 InitializableMembers += CXXRD->getNumBases();
1063 for (const auto *Field : structDecl->fields())
1064 if (!Field->isUnnamedBitField())
1065 ++InitializableMembers;
1066
1067 if (structDecl->isUnion())
1068 return std::min(InitializableMembers, 1);
1069 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1070}
1071
1072RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1073 if (const auto *RT = DeclType->getAs<RecordType>())
1074 return RT->getDecl();
1075 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1076 return Inject->getDecl();
1077 return nullptr;
1078}
1079
1080/// Determine whether Entity is an entity for which it is idiomatic to elide
1081/// the braces in aggregate initialization.
1083 // Recursive initialization of the one and only field within an aggregate
1084 // class is considered idiomatic. This case arises in particular for
1085 // initialization of std::array, where the C++ standard suggests the idiom of
1086 //
1087 // std::array<T, N> arr = {1, 2, 3};
1088 //
1089 // (where std::array is an aggregate struct containing a single array field.
1090
1091 if (!Entity.getParent())
1092 return false;
1093
1094 // Allows elide brace initialization for aggregates with empty base.
1095 if (Entity.getKind() == InitializedEntity::EK_Base) {
1096 auto *ParentRD =
1097 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1098 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1099 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1100 }
1101
1102 // Allow brace elision if the only subobject is a field.
1103 if (Entity.getKind() == InitializedEntity::EK_Member) {
1104 auto *ParentRD =
1105 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1106 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1107 if (CXXRD->getNumBases()) {
1108 return false;
1109 }
1110 }
1111 auto FieldIt = ParentRD->field_begin();
1112 assert(FieldIt != ParentRD->field_end() &&
1113 "no fields but have initializer for member?");
1114 return ++FieldIt == ParentRD->field_end();
1115 }
1116
1117 return false;
1118}
1119
1120/// Check whether the range of the initializer \p ParentIList from element
1121/// \p Index onwards can be used to initialize an object of type \p T. Update
1122/// \p Index to indicate how many elements of the list were consumed.
1123///
1124/// This also fills in \p StructuredList, from element \p StructuredIndex
1125/// onwards, with the fully-braced, desugared form of the initialization.
1126void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1127 InitListExpr *ParentIList,
1128 QualType T, unsigned &Index,
1129 InitListExpr *StructuredList,
1130 unsigned &StructuredIndex) {
1131 int maxElements = 0;
1132
1133 if (T->isArrayType())
1134 maxElements = numArrayElements(T);
1135 else if (T->isRecordType())
1136 maxElements = numStructUnionElements(T);
1137 else if (T->isVectorType())
1138 maxElements = T->castAs<VectorType>()->getNumElements();
1139 else
1140 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1141
1142 if (maxElements == 0) {
1143 if (!VerifyOnly)
1144 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1145 diag::err_implicit_empty_initializer);
1146 ++Index;
1147 hadError = true;
1148 return;
1149 }
1150
1151 // Build a structured initializer list corresponding to this subobject.
1152 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1153 ParentIList, Index, T, StructuredList, StructuredIndex,
1154 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1155 ParentIList->getSourceRange().getEnd()));
1156 unsigned StructuredSubobjectInitIndex = 0;
1157
1158 // Check the element types and build the structural subobject.
1159 unsigned StartIndex = Index;
1160 CheckListElementTypes(Entity, ParentIList, T,
1161 /*SubobjectIsDesignatorContext=*/false, Index,
1162 StructuredSubobjectInitList,
1163 StructuredSubobjectInitIndex);
1164
1165 if (StructuredSubobjectInitList) {
1166 StructuredSubobjectInitList->setType(T);
1167
1168 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1169 // Update the structured sub-object initializer so that it's ending
1170 // range corresponds with the end of the last initializer it used.
1171 if (EndIndex < ParentIList->getNumInits() &&
1172 ParentIList->getInit(EndIndex)) {
1173 SourceLocation EndLoc
1174 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1175 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1176 }
1177
1178 // Complain about missing braces.
1179 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1180 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1182 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1183 diag::warn_missing_braces)
1184 << StructuredSubobjectInitList->getSourceRange()
1186 StructuredSubobjectInitList->getBeginLoc(), "{")
1188 SemaRef.getLocForEndOfToken(
1189 StructuredSubobjectInitList->getEndLoc()),
1190 "}");
1191 }
1192
1193 // Warn if this type won't be an aggregate in future versions of C++.
1194 auto *CXXRD = T->getAsCXXRecordDecl();
1195 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1196 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1197 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1198 << StructuredSubobjectInitList->getSourceRange() << T;
1199 }
1200 }
1201}
1202
1203/// Warn that \p Entity was of scalar type and was initialized by a
1204/// single-element braced initializer list.
1205static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1207 // Don't warn during template instantiation. If the initialization was
1208 // non-dependent, we warned during the initial parse; otherwise, the
1209 // type might not be scalar in some uses of the template.
1211 return;
1212
1213 unsigned DiagID = 0;
1214
1215 switch (Entity.getKind()) {
1224 // Extra braces here are suspicious.
1225 DiagID = diag::warn_braces_around_init;
1226 break;
1227
1229 // Warn on aggregate initialization but not on ctor init list or
1230 // default member initializer.
1231 if (Entity.getParent())
1232 DiagID = diag::warn_braces_around_init;
1233 break;
1234
1237 // No warning, might be direct-list-initialization.
1238 // FIXME: Should we warn for copy-list-initialization in these cases?
1239 break;
1240
1244 // No warning, braces are part of the syntax of the underlying construct.
1245 break;
1246
1248 // No warning, we already warned when initializing the result.
1249 break;
1250
1258 llvm_unreachable("unexpected braced scalar init");
1259 }
1260
1261 if (DiagID) {
1262 S.Diag(Braces.getBegin(), DiagID)
1263 << Entity.getType()->isSizelessBuiltinType() << Braces
1264 << FixItHint::CreateRemoval(Braces.getBegin())
1265 << FixItHint::CreateRemoval(Braces.getEnd());
1266 }
1267}
1268
1269/// Check whether the initializer \p IList (that was written with explicit
1270/// braces) can be used to initialize an object of type \p T.
1271///
1272/// This also fills in \p StructuredList with the fully-braced, desugared
1273/// form of the initialization.
1274void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1275 InitListExpr *IList, QualType &T,
1276 InitListExpr *StructuredList,
1277 bool TopLevelObject) {
1278 unsigned Index = 0, StructuredIndex = 0;
1279 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1280 Index, StructuredList, StructuredIndex, TopLevelObject);
1281 if (StructuredList) {
1282 QualType ExprTy = T;
1283 if (!ExprTy->isArrayType())
1284 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1285 if (!VerifyOnly)
1286 IList->setType(ExprTy);
1287 StructuredList->setType(ExprTy);
1288 }
1289 if (hadError)
1290 return;
1291
1292 // Don't complain for incomplete types, since we'll get an error elsewhere.
1293 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1294 // We have leftover initializers
1295 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1296 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1297 hadError = ExtraInitsIsError;
1298 if (VerifyOnly) {
1299 return;
1300 } else if (StructuredIndex == 1 &&
1301 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1302 SIF_None) {
1303 unsigned DK =
1304 ExtraInitsIsError
1305 ? diag::err_excess_initializers_in_char_array_initializer
1306 : diag::ext_excess_initializers_in_char_array_initializer;
1307 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1308 << IList->getInit(Index)->getSourceRange();
1309 } else if (T->isSizelessBuiltinType()) {
1310 unsigned DK = ExtraInitsIsError
1311 ? diag::err_excess_initializers_for_sizeless_type
1312 : diag::ext_excess_initializers_for_sizeless_type;
1313 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1314 << T << IList->getInit(Index)->getSourceRange();
1315 } else {
1316 int initKind = T->isArrayType() ? 0 :
1317 T->isVectorType() ? 1 :
1318 T->isScalarType() ? 2 :
1319 T->isUnionType() ? 3 :
1320 4;
1321
1322 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1323 : diag::ext_excess_initializers;
1324 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1325 << initKind << IList->getInit(Index)->getSourceRange();
1326 }
1327 }
1328
1329 if (!VerifyOnly) {
1330 if (T->isScalarType() && IList->getNumInits() == 1 &&
1331 !isa<InitListExpr>(IList->getInit(0)))
1332 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1333
1334 // Warn if this is a class type that won't be an aggregate in future
1335 // versions of C++.
1336 auto *CXXRD = T->getAsCXXRecordDecl();
1337 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1338 // Don't warn if there's an equivalent default constructor that would be
1339 // used instead.
1340 bool HasEquivCtor = false;
1341 if (IList->getNumInits() == 0) {
1342 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1343 HasEquivCtor = CD && !CD->isDeleted();
1344 }
1345
1346 if (!HasEquivCtor) {
1347 SemaRef.Diag(IList->getBeginLoc(),
1348 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1349 << IList->getSourceRange() << T;
1350 }
1351 }
1352 }
1353}
1354
1355void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1356 InitListExpr *IList,
1357 QualType &DeclType,
1358 bool SubobjectIsDesignatorContext,
1359 unsigned &Index,
1360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex,
1362 bool TopLevelObject) {
1363 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1364 // Explicitly braced initializer for complex type can be real+imaginary
1365 // parts.
1366 CheckComplexType(Entity, IList, DeclType, Index,
1367 StructuredList, StructuredIndex);
1368 } else if (DeclType->isScalarType()) {
1369 CheckScalarType(Entity, IList, DeclType, Index,
1370 StructuredList, StructuredIndex);
1371 } else if (DeclType->isVectorType()) {
1372 CheckVectorType(Entity, IList, DeclType, Index,
1373 StructuredList, StructuredIndex);
1374 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1375 auto Bases =
1378 if (DeclType->isRecordType()) {
1379 assert(DeclType->isAggregateType() &&
1380 "non-aggregate records should be handed in CheckSubElementType");
1381 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1382 Bases = CXXRD->bases();
1383 } else {
1384 Bases = cast<CXXRecordDecl>(RD)->bases();
1385 }
1386 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1387 SubobjectIsDesignatorContext, Index, StructuredList,
1388 StructuredIndex, TopLevelObject);
1389 } else if (DeclType->isArrayType()) {
1390 llvm::APSInt Zero(
1391 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1392 false);
1393 CheckArrayType(Entity, IList, DeclType, Zero,
1394 SubobjectIsDesignatorContext, Index,
1395 StructuredList, StructuredIndex);
1396 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1397 // This type is invalid, issue a diagnostic.
1398 ++Index;
1399 if (!VerifyOnly)
1400 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1401 << DeclType;
1402 hadError = true;
1403 } else if (DeclType->isReferenceType()) {
1404 CheckReferenceType(Entity, IList, DeclType, Index,
1405 StructuredList, StructuredIndex);
1406 } else if (DeclType->isObjCObjectType()) {
1407 if (!VerifyOnly)
1408 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1409 hadError = true;
1410 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1411 DeclType->isSizelessBuiltinType()) {
1412 // Checks for scalar type are sufficient for these types too.
1413 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1414 StructuredIndex);
1415 } else if (DeclType->isDependentType()) {
1416 // C++ [over.match.class.deduct]p1.5:
1417 // brace elision is not considered for any aggregate element that has a
1418 // dependent non-array type or an array type with a value-dependent bound
1419 ++Index;
1420 assert(AggrDeductionCandidateParamTypes);
1421 AggrDeductionCandidateParamTypes->push_back(DeclType);
1422 } else {
1423 if (!VerifyOnly)
1424 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1425 << DeclType;
1426 hadError = true;
1427 }
1428}
1429
1430void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1431 InitListExpr *IList,
1432 QualType ElemType,
1433 unsigned &Index,
1434 InitListExpr *StructuredList,
1435 unsigned &StructuredIndex,
1436 bool DirectlyDesignated) {
1437 Expr *expr = IList->getInit(Index);
1438
1439 if (ElemType->isReferenceType())
1440 return CheckReferenceType(Entity, IList, ElemType, Index,
1441 StructuredList, StructuredIndex);
1442
1443 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1444 if (SubInitList->getNumInits() == 1 &&
1445 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1446 SIF_None) {
1447 // FIXME: It would be more faithful and no less correct to include an
1448 // InitListExpr in the semantic form of the initializer list in this case.
1449 expr = SubInitList->getInit(0);
1450 }
1451 // Nested aggregate initialization and C++ initialization are handled later.
1452 } else if (isa<ImplicitValueInitExpr>(expr)) {
1453 // This happens during template instantiation when we see an InitListExpr
1454 // that we've already checked once.
1455 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1456 "found implicit initialization for the wrong type");
1457 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1458 ++Index;
1459 return;
1460 }
1461
1462 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1463 // C++ [dcl.init.aggr]p2:
1464 // Each member is copy-initialized from the corresponding
1465 // initializer-clause.
1466
1467 // FIXME: Better EqualLoc?
1470
1471 // Vector elements can be initialized from other vectors in which case
1472 // we need initialization entity with a type of a vector (and not a vector
1473 // element!) initializing multiple vector elements.
1474 auto TmpEntity =
1475 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1477 : Entity;
1478
1479 if (TmpEntity.getType()->isDependentType()) {
1480 // C++ [over.match.class.deduct]p1.5:
1481 // brace elision is not considered for any aggregate element that has a
1482 // dependent non-array type or an array type with a value-dependent
1483 // bound
1484 assert(AggrDeductionCandidateParamTypes);
1485
1486 // In the presence of a braced-init-list within the initializer, we should
1487 // not perform brace-elision, even if brace elision would otherwise be
1488 // applicable. For example, given:
1489 //
1490 // template <class T> struct Foo {
1491 // T t[2];
1492 // };
1493 //
1494 // Foo t = {{1, 2}};
1495 //
1496 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1497 // {{1, 2}}.
1498 if (isa<InitListExpr, DesignatedInitExpr>(expr) ||
1499 !isa_and_present<ConstantArrayType>(
1500 SemaRef.Context.getAsArrayType(ElemType))) {
1501 ++Index;
1502 AggrDeductionCandidateParamTypes->push_back(ElemType);
1503 return;
1504 }
1505 } else {
1506 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1507 /*TopLevelOfInitList*/ true);
1508 // C++14 [dcl.init.aggr]p13:
1509 // If the assignment-expression can initialize a member, the member is
1510 // initialized. Otherwise [...] brace elision is assumed
1511 //
1512 // Brace elision is never performed if the element is not an
1513 // assignment-expression.
1514 if (Seq || isa<InitListExpr>(expr)) {
1515 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1516 expr = HandleEmbed(Embed, Entity);
1517 }
1518 if (!VerifyOnly) {
1519 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1520 if (Result.isInvalid())
1521 hadError = true;
1522
1523 UpdateStructuredListElement(StructuredList, StructuredIndex,
1524 Result.getAs<Expr>());
1525 } else if (!Seq) {
1526 hadError = true;
1527 } else if (StructuredList) {
1528 UpdateStructuredListElement(StructuredList, StructuredIndex,
1529 getDummyInit());
1530 }
1531 if (!CurEmbed)
1532 ++Index;
1533 if (AggrDeductionCandidateParamTypes)
1534 AggrDeductionCandidateParamTypes->push_back(ElemType);
1535 return;
1536 }
1537 }
1538
1539 // Fall through for subaggregate initialization
1540 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1541 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1542 return CheckScalarType(Entity, IList, ElemType, Index,
1543 StructuredList, StructuredIndex);
1544 } else if (const ArrayType *arrayType =
1545 SemaRef.Context.getAsArrayType(ElemType)) {
1546 // arrayType can be incomplete if we're initializing a flexible
1547 // array member. There's nothing we can do with the completed
1548 // type here, though.
1549
1550 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1551 // FIXME: Should we do this checking in verify-only mode?
1552 if (!VerifyOnly)
1553 CheckStringInit(expr, ElemType, arrayType, SemaRef,
1554 SemaRef.getLangOpts().C23 &&
1556 if (StructuredList)
1557 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1558 ++Index;
1559 return;
1560 }
1561
1562 // Fall through for subaggregate initialization.
1563
1564 } else {
1565 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1566 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1567
1568 // C99 6.7.8p13:
1569 //
1570 // The initializer for a structure or union object that has
1571 // automatic storage duration shall be either an initializer
1572 // list as described below, or a single expression that has
1573 // compatible structure or union type. In the latter case, the
1574 // initial value of the object, including unnamed members, is
1575 // that of the expression.
1576 ExprResult ExprRes = expr;
1578 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1579 if (ExprRes.isInvalid())
1580 hadError = true;
1581 else {
1582 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1583 if (ExprRes.isInvalid())
1584 hadError = true;
1585 }
1586 UpdateStructuredListElement(StructuredList, StructuredIndex,
1587 ExprRes.getAs<Expr>());
1588 ++Index;
1589 return;
1590 }
1591 ExprRes.get();
1592 // Fall through for subaggregate initialization
1593 }
1594
1595 // C++ [dcl.init.aggr]p12:
1596 //
1597 // [...] Otherwise, if the member is itself a non-empty
1598 // subaggregate, brace elision is assumed and the initializer is
1599 // considered for the initialization of the first member of
1600 // the subaggregate.
1601 // OpenCL vector initializer is handled elsewhere.
1602 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1603 ElemType->isAggregateType()) {
1604 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1605 StructuredIndex);
1606 ++StructuredIndex;
1607
1608 // In C++20, brace elision is not permitted for a designated initializer.
1609 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1610 if (InOverloadResolution)
1611 hadError = true;
1612 if (!VerifyOnly) {
1613 SemaRef.Diag(expr->getBeginLoc(),
1614 diag::ext_designated_init_brace_elision)
1615 << expr->getSourceRange()
1616 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1618 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1619 }
1620 }
1621 } else {
1622 if (!VerifyOnly) {
1623 // We cannot initialize this element, so let PerformCopyInitialization
1624 // produce the appropriate diagnostic. We already checked that this
1625 // initialization will fail.
1628 /*TopLevelOfInitList=*/true);
1629 (void)Copy;
1630 assert(Copy.isInvalid() &&
1631 "expected non-aggregate initialization to fail");
1632 }
1633 hadError = true;
1634 ++Index;
1635 ++StructuredIndex;
1636 }
1637}
1638
1639void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1640 InitListExpr *IList, QualType DeclType,
1641 unsigned &Index,
1642 InitListExpr *StructuredList,
1643 unsigned &StructuredIndex) {
1644 assert(Index == 0 && "Index in explicit init list must be zero");
1645
1646 // As an extension, clang supports complex initializers, which initialize
1647 // a complex number component-wise. When an explicit initializer list for
1648 // a complex number contains two initializers, this extension kicks in:
1649 // it expects the initializer list to contain two elements convertible to
1650 // the element type of the complex type. The first element initializes
1651 // the real part, and the second element intitializes the imaginary part.
1652
1653 if (IList->getNumInits() < 2)
1654 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1655 StructuredIndex);
1656
1657 // This is an extension in C. (The builtin _Complex type does not exist
1658 // in the C++ standard.)
1659 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1660 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1661 << IList->getSourceRange();
1662
1663 // Initialize the complex number.
1664 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1665 InitializedEntity ElementEntity =
1667
1668 for (unsigned i = 0; i < 2; ++i) {
1669 ElementEntity.setElementIndex(Index);
1670 CheckSubElementType(ElementEntity, IList, elementType, Index,
1671 StructuredList, StructuredIndex);
1672 }
1673}
1674
1675void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1676 InitListExpr *IList, QualType DeclType,
1677 unsigned &Index,
1678 InitListExpr *StructuredList,
1679 unsigned &StructuredIndex) {
1680 if (Index >= IList->getNumInits()) {
1681 if (!VerifyOnly) {
1682 if (SemaRef.getLangOpts().CPlusPlus) {
1683 if (DeclType->isSizelessBuiltinType())
1684 SemaRef.Diag(IList->getBeginLoc(),
1685 SemaRef.getLangOpts().CPlusPlus11
1686 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1687 : diag::err_empty_sizeless_initializer)
1688 << DeclType << IList->getSourceRange();
1689 else
1690 SemaRef.Diag(IList->getBeginLoc(),
1691 SemaRef.getLangOpts().CPlusPlus11
1692 ? diag::warn_cxx98_compat_empty_scalar_initializer
1693 : diag::err_empty_scalar_initializer)
1694 << IList->getSourceRange();
1695 }
1696 }
1697 hadError =
1698 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1699 ++Index;
1700 ++StructuredIndex;
1701 return;
1702 }
1703
1704 Expr *expr = IList->getInit(Index);
1705 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1706 // FIXME: This is invalid, and accepting it causes overload resolution
1707 // to pick the wrong overload in some corner cases.
1708 if (!VerifyOnly)
1709 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1710 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1711
1712 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1713 StructuredIndex);
1714 return;
1715 } else if (isa<DesignatedInitExpr>(expr)) {
1716 if (!VerifyOnly)
1717 SemaRef.Diag(expr->getBeginLoc(),
1718 diag::err_designator_for_scalar_or_sizeless_init)
1719 << DeclType->isSizelessBuiltinType() << DeclType
1720 << expr->getSourceRange();
1721 hadError = true;
1722 ++Index;
1723 ++StructuredIndex;
1724 return;
1725 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1726 expr = HandleEmbed(Embed, Entity);
1727 }
1728
1729 ExprResult Result;
1730 if (VerifyOnly) {
1731 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1732 Result = getDummyInit();
1733 else
1734 Result = ExprError();
1735 } else {
1736 Result =
1737 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1738 /*TopLevelOfInitList=*/true);
1739 }
1740
1741 Expr *ResultExpr = nullptr;
1742
1743 if (Result.isInvalid())
1744 hadError = true; // types weren't compatible.
1745 else {
1746 ResultExpr = Result.getAs<Expr>();
1747
1748 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1749 // The type was promoted, update initializer list.
1750 // FIXME: Why are we updating the syntactic init list?
1751 IList->setInit(Index, ResultExpr);
1752 }
1753 }
1754
1755 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1756 if (!CurEmbed)
1757 ++Index;
1758 if (AggrDeductionCandidateParamTypes)
1759 AggrDeductionCandidateParamTypes->push_back(DeclType);
1760}
1761
1762void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1763 InitListExpr *IList, QualType DeclType,
1764 unsigned &Index,
1765 InitListExpr *StructuredList,
1766 unsigned &StructuredIndex) {
1767 if (Index >= IList->getNumInits()) {
1768 // FIXME: It would be wonderful if we could point at the actual member. In
1769 // general, it would be useful to pass location information down the stack,
1770 // so that we know the location (or decl) of the "current object" being
1771 // initialized.
1772 if (!VerifyOnly)
1773 SemaRef.Diag(IList->getBeginLoc(),
1774 diag::err_init_reference_member_uninitialized)
1775 << DeclType << IList->getSourceRange();
1776 hadError = true;
1777 ++Index;
1778 ++StructuredIndex;
1779 return;
1780 }
1781
1782 Expr *expr = IList->getInit(Index);
1783 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1784 if (!VerifyOnly)
1785 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1786 << DeclType << IList->getSourceRange();
1787 hadError = true;
1788 ++Index;
1789 ++StructuredIndex;
1790 return;
1791 }
1792
1793 ExprResult Result;
1794 if (VerifyOnly) {
1795 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1796 Result = getDummyInit();
1797 else
1798 Result = ExprError();
1799 } else {
1800 Result =
1801 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1802 /*TopLevelOfInitList=*/true);
1803 }
1804
1805 if (Result.isInvalid())
1806 hadError = true;
1807
1808 expr = Result.getAs<Expr>();
1809 // FIXME: Why are we updating the syntactic init list?
1810 if (!VerifyOnly && expr)
1811 IList->setInit(Index, expr);
1812
1813 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1814 ++Index;
1815 if (AggrDeductionCandidateParamTypes)
1816 AggrDeductionCandidateParamTypes->push_back(DeclType);
1817}
1818
1819void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1820 InitListExpr *IList, QualType DeclType,
1821 unsigned &Index,
1822 InitListExpr *StructuredList,
1823 unsigned &StructuredIndex) {
1824 const VectorType *VT = DeclType->castAs<VectorType>();
1825 unsigned maxElements = VT->getNumElements();
1826 unsigned numEltsInit = 0;
1827 QualType elementType = VT->getElementType();
1828
1829 if (Index >= IList->getNumInits()) {
1830 // Make sure the element type can be value-initialized.
1831 CheckEmptyInitializable(
1833 IList->getEndLoc());
1834 return;
1835 }
1836
1837 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1838 // If the initializing element is a vector, try to copy-initialize
1839 // instead of breaking it apart (which is doomed to failure anyway).
1840 Expr *Init = IList->getInit(Index);
1841 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1842 ExprResult Result;
1843 if (VerifyOnly) {
1844 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1845 Result = getDummyInit();
1846 else
1847 Result = ExprError();
1848 } else {
1849 Result =
1850 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1851 /*TopLevelOfInitList=*/true);
1852 }
1853
1854 Expr *ResultExpr = nullptr;
1855 if (Result.isInvalid())
1856 hadError = true; // types weren't compatible.
1857 else {
1858 ResultExpr = Result.getAs<Expr>();
1859
1860 if (ResultExpr != Init && !VerifyOnly) {
1861 // The type was promoted, update initializer list.
1862 // FIXME: Why are we updating the syntactic init list?
1863 IList->setInit(Index, ResultExpr);
1864 }
1865 }
1866 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1867 ++Index;
1868 if (AggrDeductionCandidateParamTypes)
1869 AggrDeductionCandidateParamTypes->push_back(elementType);
1870 return;
1871 }
1872
1873 InitializedEntity ElementEntity =
1875
1876 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1877 // Don't attempt to go past the end of the init list
1878 if (Index >= IList->getNumInits()) {
1879 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1880 break;
1881 }
1882
1883 ElementEntity.setElementIndex(Index);
1884 CheckSubElementType(ElementEntity, IList, elementType, Index,
1885 StructuredList, StructuredIndex);
1886 }
1887
1888 if (VerifyOnly)
1889 return;
1890
1891 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1892 const VectorType *T = Entity.getType()->castAs<VectorType>();
1893 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1894 T->getVectorKind() == VectorKind::NeonPoly)) {
1895 // The ability to use vector initializer lists is a GNU vector extension
1896 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1897 // endian machines it works fine, however on big endian machines it
1898 // exhibits surprising behaviour:
1899 //
1900 // uint32x2_t x = {42, 64};
1901 // return vget_lane_u32(x, 0); // Will return 64.
1902 //
1903 // Because of this, explicitly call out that it is non-portable.
1904 //
1905 SemaRef.Diag(IList->getBeginLoc(),
1906 diag::warn_neon_vector_initializer_non_portable);
1907
1908 const char *typeCode;
1909 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1910
1911 if (elementType->isFloatingType())
1912 typeCode = "f";
1913 else if (elementType->isSignedIntegerType())
1914 typeCode = "s";
1915 else if (elementType->isUnsignedIntegerType())
1916 typeCode = "u";
1917 else
1918 llvm_unreachable("Invalid element type!");
1919
1920 SemaRef.Diag(IList->getBeginLoc(),
1921 SemaRef.Context.getTypeSize(VT) > 64
1922 ? diag::note_neon_vector_initializer_non_portable_q
1923 : diag::note_neon_vector_initializer_non_portable)
1924 << typeCode << typeSize;
1925 }
1926
1927 return;
1928 }
1929
1930 InitializedEntity ElementEntity =
1932
1933 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1934 for (unsigned i = 0; i < maxElements; ++i) {
1935 // Don't attempt to go past the end of the init list
1936 if (Index >= IList->getNumInits())
1937 break;
1938
1939 ElementEntity.setElementIndex(Index);
1940
1941 QualType IType = IList->getInit(Index)->getType();
1942 if (!IType->isVectorType()) {
1943 CheckSubElementType(ElementEntity, IList, elementType, Index,
1944 StructuredList, StructuredIndex);
1945 ++numEltsInit;
1946 } else {
1947 QualType VecType;
1948 const VectorType *IVT = IType->castAs<VectorType>();
1949 unsigned numIElts = IVT->getNumElements();
1950
1951 if (IType->isExtVectorType())
1952 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1953 else
1954 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1955 IVT->getVectorKind());
1956 CheckSubElementType(ElementEntity, IList, VecType, Index,
1957 StructuredList, StructuredIndex);
1958 numEltsInit += numIElts;
1959 }
1960 }
1961
1962 // OpenCL and HLSL require all elements to be initialized.
1963 if (numEltsInit != maxElements) {
1964 if (!VerifyOnly)
1965 SemaRef.Diag(IList->getBeginLoc(),
1966 diag::err_vector_incorrect_num_initializers)
1967 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1968 hadError = true;
1969 }
1970}
1971
1972/// Check if the type of a class element has an accessible destructor, and marks
1973/// it referenced. Returns true if we shouldn't form a reference to the
1974/// destructor.
1975///
1976/// Aggregate initialization requires a class element's destructor be
1977/// accessible per 11.6.1 [dcl.init.aggr]:
1978///
1979/// The destructor for each element of class type is potentially invoked
1980/// (15.4 [class.dtor]) from the context where the aggregate initialization
1981/// occurs.
1983 Sema &SemaRef) {
1984 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1985 if (!CXXRD)
1986 return false;
1987
1989 if (!Destructor)
1990 return false;
1991
1993 SemaRef.PDiag(diag::err_access_dtor_temp)
1994 << ElementType);
1996 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1997}
1998
1999static bool
2001 const InitializedEntity &Entity,
2002 ASTContext &Context) {
2003 QualType InitType = Entity.getType();
2004 const InitializedEntity *Parent = &Entity;
2005
2006 while (Parent) {
2007 InitType = Parent->getType();
2008 Parent = Parent->getParent();
2009 }
2010
2011 // Only one initializer, it's an embed and the types match;
2012 EmbedExpr *EE =
2013 ExprList.size() == 1
2014 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2015 : nullptr;
2016 if (!EE)
2017 return false;
2018
2019 if (InitType->isArrayType()) {
2020 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2021 QualType InitElementTy = InitArrayType->getElementType();
2022 QualType EmbedExprElementTy = EE->getDataStringLiteral()->getType();
2023 const bool TypesMatch =
2024 Context.typesAreCompatible(InitElementTy, EmbedExprElementTy) ||
2025 (InitElementTy->isCharType() && EmbedExprElementTy->isCharType());
2026 if (TypesMatch)
2027 return true;
2028 }
2029 return false;
2030}
2031
2032void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2033 InitListExpr *IList, QualType &DeclType,
2034 llvm::APSInt elementIndex,
2035 bool SubobjectIsDesignatorContext,
2036 unsigned &Index,
2037 InitListExpr *StructuredList,
2038 unsigned &StructuredIndex) {
2039 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2040
2041 if (!VerifyOnly) {
2042 if (checkDestructorReference(arrayType->getElementType(),
2043 IList->getEndLoc(), SemaRef)) {
2044 hadError = true;
2045 return;
2046 }
2047 }
2048
2049 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2050 SemaRef.Context)) {
2051 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2052 IList->setInit(0, Embed->getDataStringLiteral());
2053 }
2054
2055 // Check for the special-case of initializing an array with a string.
2056 if (Index < IList->getNumInits()) {
2057 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2058 SIF_None) {
2059 // We place the string literal directly into the resulting
2060 // initializer list. This is the only place where the structure
2061 // of the structured initializer list doesn't match exactly,
2062 // because doing so would involve allocating one character
2063 // constant for each string.
2064 // FIXME: Should we do these checks in verify-only mode too?
2065 if (!VerifyOnly)
2066 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
2067 SemaRef.getLangOpts().C23 &&
2069 if (StructuredList) {
2070 UpdateStructuredListElement(StructuredList, StructuredIndex,
2071 IList->getInit(Index));
2072 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2073 }
2074 ++Index;
2075 if (AggrDeductionCandidateParamTypes)
2076 AggrDeductionCandidateParamTypes->push_back(DeclType);
2077 return;
2078 }
2079 }
2080 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2081 // Check for VLAs; in standard C it would be possible to check this
2082 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2083 // them in all sorts of strange places).
2084 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2085 if (!VerifyOnly) {
2086 // C23 6.7.10p4: An entity of variable length array type shall not be
2087 // initialized except by an empty initializer.
2088 //
2089 // The C extension warnings are issued from ParseBraceInitializer() and
2090 // do not need to be issued here. However, we continue to issue an error
2091 // in the case there are initializers or we are compiling C++. We allow
2092 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2093 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2094 // FIXME: should we allow this construct in C++ when it makes sense to do
2095 // so?
2096 if (HasErr)
2097 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2098 diag::err_variable_object_no_init)
2099 << VAT->getSizeExpr()->getSourceRange();
2100 }
2101 hadError = HasErr;
2102 ++Index;
2103 ++StructuredIndex;
2104 return;
2105 }
2106
2107 // We might know the maximum number of elements in advance.
2108 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2109 elementIndex.isUnsigned());
2110 bool maxElementsKnown = false;
2111 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2112 maxElements = CAT->getSize();
2113 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2114 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2115 maxElementsKnown = true;
2116 }
2117
2118 QualType elementType = arrayType->getElementType();
2119 while (Index < IList->getNumInits()) {
2120 Expr *Init = IList->getInit(Index);
2121 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2122 // If we're not the subobject that matches up with the '{' for
2123 // the designator, we shouldn't be handling the
2124 // designator. Return immediately.
2125 if (!SubobjectIsDesignatorContext)
2126 return;
2127
2128 // Handle this designated initializer. elementIndex will be
2129 // updated to be the next array element we'll initialize.
2130 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2131 DeclType, nullptr, &elementIndex, Index,
2132 StructuredList, StructuredIndex, true,
2133 false)) {
2134 hadError = true;
2135 continue;
2136 }
2137
2138 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2139 maxElements = maxElements.extend(elementIndex.getBitWidth());
2140 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2141 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2142 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2143
2144 // If the array is of incomplete type, keep track of the number of
2145 // elements in the initializer.
2146 if (!maxElementsKnown && elementIndex > maxElements)
2147 maxElements = elementIndex;
2148
2149 continue;
2150 }
2151
2152 // If we know the maximum number of elements, and we've already
2153 // hit it, stop consuming elements in the initializer list.
2154 if (maxElementsKnown && elementIndex == maxElements)
2155 break;
2156
2158 SemaRef.Context, StructuredIndex, Entity);
2159
2160 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2161 // Check this element.
2162 CheckSubElementType(ElementEntity, IList, elementType, Index,
2163 StructuredList, StructuredIndex);
2164 ++elementIndex;
2165 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2166 if (CurEmbed) {
2167 elementIndex =
2168 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2169 } else {
2170 auto Embed = cast<EmbedExpr>(Init);
2171 elementIndex = elementIndex + Embed->getDataElementCount() -
2172 EmbedElementIndexBeforeInit - 1;
2173 }
2174 }
2175
2176 // If the array is of incomplete type, keep track of the number of
2177 // elements in the initializer.
2178 if (!maxElementsKnown && elementIndex > maxElements)
2179 maxElements = elementIndex;
2180 }
2181 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2182 // If this is an incomplete array type, the actual type needs to
2183 // be calculated here.
2184 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2185 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2186 // Sizing an array implicitly to zero is not allowed by ISO C,
2187 // but is supported by GNU.
2188 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2189 }
2190
2191 DeclType = SemaRef.Context.getConstantArrayType(
2192 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2193 }
2194 if (!hadError) {
2195 // If there are any members of the array that get value-initialized, check
2196 // that is possible. That happens if we know the bound and don't have
2197 // enough elements, or if we're performing an array new with an unknown
2198 // bound.
2199 if ((maxElementsKnown && elementIndex < maxElements) ||
2200 Entity.isVariableLengthArrayNew())
2201 CheckEmptyInitializable(
2203 IList->getEndLoc());
2204 }
2205}
2206
2207bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2208 Expr *InitExpr,
2209 FieldDecl *Field,
2210 bool TopLevelObject) {
2211 // Handle GNU flexible array initializers.
2212 unsigned FlexArrayDiag;
2213 if (isa<InitListExpr>(InitExpr) &&
2214 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2215 // Empty flexible array init always allowed as an extension
2216 FlexArrayDiag = diag::ext_flexible_array_init;
2217 } else if (!TopLevelObject) {
2218 // Disallow flexible array init on non-top-level object
2219 FlexArrayDiag = diag::err_flexible_array_init;
2220 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2221 // Disallow flexible array init on anything which is not a variable.
2222 FlexArrayDiag = diag::err_flexible_array_init;
2223 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2224 // Disallow flexible array init on local variables.
2225 FlexArrayDiag = diag::err_flexible_array_init;
2226 } else {
2227 // Allow other cases.
2228 FlexArrayDiag = diag::ext_flexible_array_init;
2229 }
2230
2231 if (!VerifyOnly) {
2232 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2233 << InitExpr->getBeginLoc();
2234 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2235 << Field;
2236 }
2237
2238 return FlexArrayDiag != diag::ext_flexible_array_init;
2239}
2240
2241void InitListChecker::CheckStructUnionTypes(
2242 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2244 bool SubobjectIsDesignatorContext, unsigned &Index,
2245 InitListExpr *StructuredList, unsigned &StructuredIndex,
2246 bool TopLevelObject) {
2247 const RecordDecl *RD = getRecordDecl(DeclType);
2248
2249 // If the record is invalid, some of it's members are invalid. To avoid
2250 // confusion, we forgo checking the initializer for the entire record.
2251 if (RD->isInvalidDecl()) {
2252 // Assume it was supposed to consume a single initializer.
2253 ++Index;
2254 hadError = true;
2255 return;
2256 }
2257
2258 if (RD->isUnion() && IList->getNumInits() == 0) {
2259 if (!VerifyOnly)
2260 for (FieldDecl *FD : RD->fields()) {
2261 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2262 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2263 hadError = true;
2264 return;
2265 }
2266 }
2267
2268 // If there's a default initializer, use it.
2269 if (isa<CXXRecordDecl>(RD) &&
2270 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2271 if (!StructuredList)
2272 return;
2273 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2274 Field != FieldEnd; ++Field) {
2275 if (Field->hasInClassInitializer() ||
2276 (Field->isAnonymousStructOrUnion() &&
2277 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
2278 StructuredList->setInitializedFieldInUnion(*Field);
2279 // FIXME: Actually build a CXXDefaultInitExpr?
2280 return;
2281 }
2282 }
2283 llvm_unreachable("Couldn't find in-class initializer");
2284 }
2285
2286 // Value-initialize the first member of the union that isn't an unnamed
2287 // bitfield.
2288 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2289 Field != FieldEnd; ++Field) {
2290 if (!Field->isUnnamedBitField()) {
2291 CheckEmptyInitializable(
2292 InitializedEntity::InitializeMember(*Field, &Entity),
2293 IList->getEndLoc());
2294 if (StructuredList)
2295 StructuredList->setInitializedFieldInUnion(*Field);
2296 break;
2297 }
2298 }
2299 return;
2300 }
2301
2302 bool InitializedSomething = false;
2303
2304 // If we have any base classes, they are initialized prior to the fields.
2305 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2306 auto &Base = *I;
2307 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2308
2309 // Designated inits always initialize fields, so if we see one, all
2310 // remaining base classes have no explicit initializer.
2311 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2312 Init = nullptr;
2313
2314 // C++ [over.match.class.deduct]p1.6:
2315 // each non-trailing aggregate element that is a pack expansion is assumed
2316 // to correspond to no elements of the initializer list, and (1.7) a
2317 // trailing aggregate element that is a pack expansion is assumed to
2318 // correspond to all remaining elements of the initializer list (if any).
2319
2320 // C++ [over.match.class.deduct]p1.9:
2321 // ... except that additional parameter packs of the form P_j... are
2322 // inserted into the parameter list in their original aggregate element
2323 // position corresponding to each non-trailing aggregate element of
2324 // type P_j that was skipped because it was a parameter pack, and the
2325 // trailing sequence of parameters corresponding to a trailing
2326 // aggregate element that is a pack expansion (if any) is replaced
2327 // by a single parameter of the form T_n....
2328 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2329 AggrDeductionCandidateParamTypes->push_back(
2330 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2331
2332 // Trailing pack expansion
2333 if (I + 1 == E && RD->field_empty()) {
2334 if (Index < IList->getNumInits())
2335 Index = IList->getNumInits();
2336 return;
2337 }
2338
2339 continue;
2340 }
2341
2342 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2344 SemaRef.Context, &Base, false, &Entity);
2345 if (Init) {
2346 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2347 StructuredList, StructuredIndex);
2348 InitializedSomething = true;
2349 } else {
2350 CheckEmptyInitializable(BaseEntity, InitLoc);
2351 }
2352
2353 if (!VerifyOnly)
2354 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2355 hadError = true;
2356 return;
2357 }
2358 }
2359
2360 // If structDecl is a forward declaration, this loop won't do
2361 // anything except look at designated initializers; That's okay,
2362 // because an error should get printed out elsewhere. It might be
2363 // worthwhile to skip over the rest of the initializer, though.
2364 RecordDecl::field_iterator FieldEnd = RD->field_end();
2365 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2366 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2367 });
2368 bool HasDesignatedInit = false;
2369
2370 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2371
2372 while (Index < IList->getNumInits()) {
2373 Expr *Init = IList->getInit(Index);
2374 SourceLocation InitLoc = Init->getBeginLoc();
2375
2376 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2377 // If we're not the subobject that matches up with the '{' for
2378 // the designator, we shouldn't be handling the
2379 // designator. Return immediately.
2380 if (!SubobjectIsDesignatorContext)
2381 return;
2382
2383 HasDesignatedInit = true;
2384
2385 // Handle this designated initializer. Field will be updated to
2386 // the next field that we'll be initializing.
2387 bool DesignatedInitFailed = CheckDesignatedInitializer(
2388 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2389 StructuredList, StructuredIndex, true, TopLevelObject);
2390 if (DesignatedInitFailed)
2391 hadError = true;
2392
2393 // Find the field named by the designated initializer.
2394 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2395 if (!VerifyOnly && D->isFieldDesignator()) {
2396 FieldDecl *F = D->getFieldDecl();
2397 InitializedFields.insert(F);
2398 if (!DesignatedInitFailed) {
2399 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2400 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2401 hadError = true;
2402 return;
2403 }
2404 }
2405 }
2406
2407 InitializedSomething = true;
2408 continue;
2409 }
2410
2411 // Check if this is an initializer of forms:
2412 //
2413 // struct foo f = {};
2414 // struct foo g = {0};
2415 //
2416 // These are okay for randomized structures. [C99 6.7.8p19]
2417 //
2418 // Also, if there is only one element in the structure, we allow something
2419 // like this, because it's really not randomized in the traditional sense.
2420 //
2421 // struct foo h = {bar};
2422 auto IsZeroInitializer = [&](const Expr *I) {
2423 if (IList->getNumInits() == 1) {
2424 if (NumRecordDecls == 1)
2425 return true;
2426 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2427 return IL->getValue().isZero();
2428 }
2429 return false;
2430 };
2431
2432 // Don't allow non-designated initializers on randomized structures.
2433 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2434 if (!VerifyOnly)
2435 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2436 hadError = true;
2437 break;
2438 }
2439
2440 if (Field == FieldEnd) {
2441 // We've run out of fields. We're done.
2442 break;
2443 }
2444
2445 // We've already initialized a member of a union. We can stop entirely.
2446 if (InitializedSomething && RD->isUnion())
2447 return;
2448
2449 // Stop if we've hit a flexible array member.
2450 if (Field->getType()->isIncompleteArrayType())
2451 break;
2452
2453 if (Field->isUnnamedBitField()) {
2454 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2455 ++Field;
2456 continue;
2457 }
2458
2459 // Make sure we can use this declaration.
2460 bool InvalidUse;
2461 if (VerifyOnly)
2462 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2463 else
2464 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2465 *Field, IList->getInit(Index)->getBeginLoc());
2466 if (InvalidUse) {
2467 ++Index;
2468 ++Field;
2469 hadError = true;
2470 continue;
2471 }
2472
2473 if (!VerifyOnly) {
2474 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2475 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2476 hadError = true;
2477 return;
2478 }
2479 }
2480
2481 InitializedEntity MemberEntity =
2482 InitializedEntity::InitializeMember(*Field, &Entity);
2483 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2484 StructuredList, StructuredIndex);
2485 InitializedSomething = true;
2486 InitializedFields.insert(*Field);
2487
2488 if (RD->isUnion() && StructuredList) {
2489 // Initialize the first field within the union.
2490 StructuredList->setInitializedFieldInUnion(*Field);
2491 }
2492
2493 ++Field;
2494 }
2495
2496 // Emit warnings for missing struct field initializers.
2497 // This check is disabled for designated initializers in C.
2498 // This matches gcc behaviour.
2499 bool IsCDesignatedInitializer =
2500 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2501 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2502 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2503 !IsCDesignatedInitializer) {
2504 // It is possible we have one or more unnamed bitfields remaining.
2505 // Find first (if any) named field and emit warning.
2506 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2507 : Field,
2508 end = RD->field_end();
2509 it != end; ++it) {
2510 if (HasDesignatedInit && InitializedFields.count(*it))
2511 continue;
2512
2513 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2514 !it->getType()->isIncompleteArrayType()) {
2515 auto Diag = HasDesignatedInit
2516 ? diag::warn_missing_designated_field_initializers
2517 : diag::warn_missing_field_initializers;
2518 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2519 break;
2520 }
2521 }
2522 }
2523
2524 // Check that any remaining fields can be value-initialized if we're not
2525 // building a structured list. (If we are, we'll check this later.)
2526 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2527 !Field->getType()->isIncompleteArrayType()) {
2528 for (; Field != FieldEnd && !hadError; ++Field) {
2529 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2530 CheckEmptyInitializable(
2531 InitializedEntity::InitializeMember(*Field, &Entity),
2532 IList->getEndLoc());
2533 }
2534 }
2535
2536 // Check that the types of the remaining fields have accessible destructors.
2537 if (!VerifyOnly) {
2538 // If the initializer expression has a designated initializer, check the
2539 // elements for which a designated initializer is not provided too.
2540 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2541 : Field;
2542 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2543 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2544 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2545 hadError = true;
2546 return;
2547 }
2548 }
2549 }
2550
2551 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2552 Index >= IList->getNumInits())
2553 return;
2554
2555 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2556 TopLevelObject)) {
2557 hadError = true;
2558 ++Index;
2559 return;
2560 }
2561
2562 InitializedEntity MemberEntity =
2563 InitializedEntity::InitializeMember(*Field, &Entity);
2564
2565 if (isa<InitListExpr>(IList->getInit(Index)) ||
2566 AggrDeductionCandidateParamTypes)
2567 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2568 StructuredList, StructuredIndex);
2569 else
2570 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2571 StructuredList, StructuredIndex);
2572
2573 if (RD->isUnion() && StructuredList) {
2574 // Initialize the first field within the union.
2575 StructuredList->setInitializedFieldInUnion(*Field);
2576 }
2577}
2578
2579/// Expand a field designator that refers to a member of an
2580/// anonymous struct or union into a series of field designators that
2581/// refers to the field within the appropriate subobject.
2582///
2584 DesignatedInitExpr *DIE,
2585 unsigned DesigIdx,
2586 IndirectFieldDecl *IndirectField) {
2588
2589 // Build the replacement designators.
2590 SmallVector<Designator, 4> Replacements;
2591 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2592 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2593 if (PI + 1 == PE)
2594 Replacements.push_back(Designator::CreateFieldDesignator(
2595 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2596 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2597 else
2598 Replacements.push_back(Designator::CreateFieldDesignator(
2599 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2600 assert(isa<FieldDecl>(*PI));
2601 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2602 }
2603
2604 // Expand the current designator into the set of replacement
2605 // designators, so we have a full subobject path down to where the
2606 // member of the anonymous struct/union is actually stored.
2607 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2608 &Replacements[0] + Replacements.size());
2609}
2610
2612 DesignatedInitExpr *DIE) {
2613 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2614 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2615 for (unsigned I = 0; I < NumIndexExprs; ++I)
2616 IndexExprs[I] = DIE->getSubExpr(I + 1);
2617 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2618 IndexExprs,
2619 DIE->getEqualOrColonLoc(),
2620 DIE->usesGNUSyntax(), DIE->getInit());
2621}
2622
2623namespace {
2624
2625// Callback to only accept typo corrections that are for field members of
2626// the given struct or union.
2627class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2628 public:
2629 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2630 : Record(RD) {}
2631
2632 bool ValidateCandidate(const TypoCorrection &candidate) override {
2633 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2634 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2635 }
2636
2637 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2638 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2639 }
2640
2641 private:
2642 const RecordDecl *Record;
2643};
2644
2645} // end anonymous namespace
2646
2647/// Check the well-formedness of a C99 designated initializer.
2648///
2649/// Determines whether the designated initializer @p DIE, which
2650/// resides at the given @p Index within the initializer list @p
2651/// IList, is well-formed for a current object of type @p DeclType
2652/// (C99 6.7.8). The actual subobject that this designator refers to
2653/// within the current subobject is returned in either
2654/// @p NextField or @p NextElementIndex (whichever is appropriate).
2655///
2656/// @param IList The initializer list in which this designated
2657/// initializer occurs.
2658///
2659/// @param DIE The designated initializer expression.
2660///
2661/// @param DesigIdx The index of the current designator.
2662///
2663/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2664/// into which the designation in @p DIE should refer.
2665///
2666/// @param NextField If non-NULL and the first designator in @p DIE is
2667/// a field, this will be set to the field declaration corresponding
2668/// to the field named by the designator. On input, this is expected to be
2669/// the next field that would be initialized in the absence of designation,
2670/// if the complete object being initialized is a struct.
2671///
2672/// @param NextElementIndex If non-NULL and the first designator in @p
2673/// DIE is an array designator or GNU array-range designator, this
2674/// will be set to the last index initialized by this designator.
2675///
2676/// @param Index Index into @p IList where the designated initializer
2677/// @p DIE occurs.
2678///
2679/// @param StructuredList The initializer list expression that
2680/// describes all of the subobject initializers in the order they'll
2681/// actually be initialized.
2682///
2683/// @returns true if there was an error, false otherwise.
2684bool
2685InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2686 InitListExpr *IList,
2687 DesignatedInitExpr *DIE,
2688 unsigned DesigIdx,
2689 QualType &CurrentObjectType,
2690 RecordDecl::field_iterator *NextField,
2691 llvm::APSInt *NextElementIndex,
2692 unsigned &Index,
2693 InitListExpr *StructuredList,
2694 unsigned &StructuredIndex,
2695 bool FinishSubobjectInit,
2696 bool TopLevelObject) {
2697 if (DesigIdx == DIE->size()) {
2698 // C++20 designated initialization can result in direct-list-initialization
2699 // of the designated subobject. This is the only way that we can end up
2700 // performing direct initialization as part of aggregate initialization, so
2701 // it needs special handling.
2702 if (DIE->isDirectInit()) {
2703 Expr *Init = DIE->getInit();
2704 assert(isa<InitListExpr>(Init) &&
2705 "designator result in direct non-list initialization?");
2707 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2708 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2709 /*TopLevelOfInitList*/ true);
2710 if (StructuredList) {
2711 ExprResult Result = VerifyOnly
2712 ? getDummyInit()
2713 : Seq.Perform(SemaRef, Entity, Kind, Init);
2714 UpdateStructuredListElement(StructuredList, StructuredIndex,
2715 Result.get());
2716 }
2717 ++Index;
2718 if (AggrDeductionCandidateParamTypes)
2719 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2720 return !Seq;
2721 }
2722
2723 // Check the actual initialization for the designated object type.
2724 bool prevHadError = hadError;
2725
2726 // Temporarily remove the designator expression from the
2727 // initializer list that the child calls see, so that we don't try
2728 // to re-process the designator.
2729 unsigned OldIndex = Index;
2730 IList->setInit(OldIndex, DIE->getInit());
2731
2732 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2733 StructuredIndex, /*DirectlyDesignated=*/true);
2734
2735 // Restore the designated initializer expression in the syntactic
2736 // form of the initializer list.
2737 if (IList->getInit(OldIndex) != DIE->getInit())
2738 DIE->setInit(IList->getInit(OldIndex));
2739 IList->setInit(OldIndex, DIE);
2740
2741 return hadError && !prevHadError;
2742 }
2743
2745 bool IsFirstDesignator = (DesigIdx == 0);
2746 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2747 // Determine the structural initializer list that corresponds to the
2748 // current subobject.
2749 if (IsFirstDesignator)
2750 StructuredList = FullyStructuredList;
2751 else {
2752 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2753 StructuredList->getInit(StructuredIndex) : nullptr;
2754 if (!ExistingInit && StructuredList->hasArrayFiller())
2755 ExistingInit = StructuredList->getArrayFiller();
2756
2757 if (!ExistingInit)
2758 StructuredList = getStructuredSubobjectInit(
2759 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2760 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2761 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2762 StructuredList = Result;
2763 else {
2764 // We are creating an initializer list that initializes the
2765 // subobjects of the current object, but there was already an
2766 // initialization that completely initialized the current
2767 // subobject, e.g., by a compound literal:
2768 //
2769 // struct X { int a, b; };
2770 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2771 //
2772 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2773 // designated initializer re-initializes only its current object
2774 // subobject [0].b.
2775 diagnoseInitOverride(ExistingInit,
2776 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2777 /*UnionOverride=*/false,
2778 /*FullyOverwritten=*/false);
2779
2780 if (!VerifyOnly) {
2782 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2783 StructuredList = E->getUpdater();
2784 else {
2785 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2787 ExistingInit, DIE->getEndLoc());
2788 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2789 StructuredList = DIUE->getUpdater();
2790 }
2791 } else {
2792 // We don't need to track the structured representation of a
2793 // designated init update of an already-fully-initialized object in
2794 // verify-only mode. The only reason we would need the structure is
2795 // to determine where the uninitialized "holes" are, and in this
2796 // case, we know there aren't any and we can't introduce any.
2797 StructuredList = nullptr;
2798 }
2799 }
2800 }
2801 }
2802
2803 if (D->isFieldDesignator()) {
2804 // C99 6.7.8p7:
2805 //
2806 // If a designator has the form
2807 //
2808 // . identifier
2809 //
2810 // then the current object (defined below) shall have
2811 // structure or union type and the identifier shall be the
2812 // name of a member of that type.
2813 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2814 if (!RD) {
2815 SourceLocation Loc = D->getDotLoc();
2816 if (Loc.isInvalid())
2817 Loc = D->getFieldLoc();
2818 if (!VerifyOnly)
2819 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2820 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2821 ++Index;
2822 return true;
2823 }
2824
2825 FieldDecl *KnownField = D->getFieldDecl();
2826 if (!KnownField) {
2827 const IdentifierInfo *FieldName = D->getFieldName();
2828 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2829 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2830 KnownField = FD;
2831 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2832 // In verify mode, don't modify the original.
2833 if (VerifyOnly)
2834 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2835 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2836 D = DIE->getDesignator(DesigIdx);
2837 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2838 }
2839 if (!KnownField) {
2840 if (VerifyOnly) {
2841 ++Index;
2842 return true; // No typo correction when just trying this out.
2843 }
2844
2845 // We found a placeholder variable
2846 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2847 FieldName)) {
2848 ++Index;
2849 return true;
2850 }
2851 // Name lookup found something, but it wasn't a field.
2852 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2853 !Lookup.empty()) {
2854 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2855 << FieldName;
2856 SemaRef.Diag(Lookup.front()->getLocation(),
2857 diag::note_field_designator_found);
2858 ++Index;
2859 return true;
2860 }
2861
2862 // Name lookup didn't find anything.
2863 // Determine whether this was a typo for another field name.
2864 FieldInitializerValidatorCCC CCC(RD);
2865 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2866 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2867 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2869 SemaRef.diagnoseTypo(
2870 Corrected,
2871 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2872 << FieldName << CurrentObjectType);
2873 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2874 hadError = true;
2875 } else {
2876 // Typo correction didn't find anything.
2877 SourceLocation Loc = D->getFieldLoc();
2878
2879 // The loc can be invalid with a "null" designator (i.e. an anonymous
2880 // union/struct). Do our best to approximate the location.
2881 if (Loc.isInvalid())
2882 Loc = IList->getBeginLoc();
2883
2884 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2885 << FieldName << CurrentObjectType << DIE->getSourceRange();
2886 ++Index;
2887 return true;
2888 }
2889 }
2890 }
2891
2892 unsigned NumBases = 0;
2893 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2894 NumBases = CXXRD->getNumBases();
2895
2896 unsigned FieldIndex = NumBases;
2897
2898 for (auto *FI : RD->fields()) {
2899 if (FI->isUnnamedBitField())
2900 continue;
2901 if (declaresSameEntity(KnownField, FI)) {
2902 KnownField = FI;
2903 break;
2904 }
2905 ++FieldIndex;
2906 }
2907
2910
2911 // All of the fields of a union are located at the same place in
2912 // the initializer list.
2913 if (RD->isUnion()) {
2914 FieldIndex = 0;
2915 if (StructuredList) {
2916 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2917 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2918 assert(StructuredList->getNumInits() == 1
2919 && "A union should never have more than one initializer!");
2920
2921 Expr *ExistingInit = StructuredList->getInit(0);
2922 if (ExistingInit) {
2923 // We're about to throw away an initializer, emit warning.
2924 diagnoseInitOverride(
2925 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2926 /*UnionOverride=*/true,
2927 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2928 : true);
2929 }
2930
2931 // remove existing initializer
2932 StructuredList->resizeInits(SemaRef.Context, 0);
2933 StructuredList->setInitializedFieldInUnion(nullptr);
2934 }
2935
2936 StructuredList->setInitializedFieldInUnion(*Field);
2937 }
2938 }
2939
2940 // Make sure we can use this declaration.
2941 bool InvalidUse;
2942 if (VerifyOnly)
2943 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2944 else
2945 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2946 if (InvalidUse) {
2947 ++Index;
2948 return true;
2949 }
2950
2951 // C++20 [dcl.init.list]p3:
2952 // The ordered identifiers in the designators of the designated-
2953 // initializer-list shall form a subsequence of the ordered identifiers
2954 // in the direct non-static data members of T.
2955 //
2956 // Note that this is not a condition on forming the aggregate
2957 // initialization, only on actually performing initialization,
2958 // so it is not checked in VerifyOnly mode.
2959 //
2960 // FIXME: This is the only reordering diagnostic we produce, and it only
2961 // catches cases where we have a top-level field designator that jumps
2962 // backwards. This is the only such case that is reachable in an
2963 // otherwise-valid C++20 program, so is the only case that's required for
2964 // conformance, but for consistency, we should diagnose all the other
2965 // cases where a designator takes us backwards too.
2966 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2967 NextField &&
2968 (*NextField == RD->field_end() ||
2969 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2970 // Find the field that we just initialized.
2971 FieldDecl *PrevField = nullptr;
2972 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2973 if (FI->isUnnamedBitField())
2974 continue;
2975 if (*NextField != RD->field_end() &&
2976 declaresSameEntity(*FI, **NextField))
2977 break;
2978 PrevField = *FI;
2979 }
2980
2981 if (PrevField &&
2982 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2983 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2984 diag::ext_designated_init_reordered)
2985 << KnownField << PrevField << DIE->getSourceRange();
2986
2987 unsigned OldIndex = StructuredIndex - 1;
2988 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2989 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2990 SemaRef.Diag(PrevInit->getBeginLoc(),
2991 diag::note_previous_field_init)
2992 << PrevField << PrevInit->getSourceRange();
2993 }
2994 }
2995 }
2996 }
2997
2998
2999 // Update the designator with the field declaration.
3000 if (!VerifyOnly)
3001 D->setFieldDecl(*Field);
3002
3003 // Make sure that our non-designated initializer list has space
3004 // for a subobject corresponding to this field.
3005 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3006 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3007
3008 // This designator names a flexible array member.
3009 if (Field->getType()->isIncompleteArrayType()) {
3010 bool Invalid = false;
3011 if ((DesigIdx + 1) != DIE->size()) {
3012 // We can't designate an object within the flexible array
3013 // member (because GCC doesn't allow it).
3014 if (!VerifyOnly) {
3016 = DIE->getDesignator(DesigIdx + 1);
3017 SemaRef.Diag(NextD->getBeginLoc(),
3018 diag::err_designator_into_flexible_array_member)
3019 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3020 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3021 << *Field;
3022 }
3023 Invalid = true;
3024 }
3025
3026 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3027 !isa<StringLiteral>(DIE->getInit())) {
3028 // The initializer is not an initializer list.
3029 if (!VerifyOnly) {
3030 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3031 diag::err_flexible_array_init_needs_braces)
3032 << DIE->getInit()->getSourceRange();
3033 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3034 << *Field;
3035 }
3036 Invalid = true;
3037 }
3038
3039 // Check GNU flexible array initializer.
3040 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3041 TopLevelObject))
3042 Invalid = true;
3043
3044 if (Invalid) {
3045 ++Index;
3046 return true;
3047 }
3048
3049 // Initialize the array.
3050 bool prevHadError = hadError;
3051 unsigned newStructuredIndex = FieldIndex;
3052 unsigned OldIndex = Index;
3053 IList->setInit(Index, DIE->getInit());
3054
3055 InitializedEntity MemberEntity =
3056 InitializedEntity::InitializeMember(*Field, &Entity);
3057 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3058 StructuredList, newStructuredIndex);
3059
3060 IList->setInit(OldIndex, DIE);
3061 if (hadError && !prevHadError) {
3062 ++Field;
3063 ++FieldIndex;
3064 if (NextField)
3065 *NextField = Field;
3066 StructuredIndex = FieldIndex;
3067 return true;
3068 }
3069 } else {
3070 // Recurse to check later designated subobjects.
3071 QualType FieldType = Field->getType();
3072 unsigned newStructuredIndex = FieldIndex;
3073
3074 InitializedEntity MemberEntity =
3075 InitializedEntity::InitializeMember(*Field, &Entity);
3076 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3077 FieldType, nullptr, nullptr, Index,
3078 StructuredList, newStructuredIndex,
3079 FinishSubobjectInit, false))
3080 return true;
3081 }
3082
3083 // Find the position of the next field to be initialized in this
3084 // subobject.
3085 ++Field;
3086 ++FieldIndex;
3087
3088 // If this the first designator, our caller will continue checking
3089 // the rest of this struct/class/union subobject.
3090 if (IsFirstDesignator) {
3091 if (Field != RD->field_end() && Field->isUnnamedBitField())
3092 ++Field;
3093
3094 if (NextField)
3095 *NextField = Field;
3096
3097 StructuredIndex = FieldIndex;
3098 return false;
3099 }
3100
3101 if (!FinishSubobjectInit)
3102 return false;
3103
3104 // We've already initialized something in the union; we're done.
3105 if (RD->isUnion())
3106 return hadError;
3107
3108 // Check the remaining fields within this class/struct/union subobject.
3109 bool prevHadError = hadError;
3110
3111 auto NoBases =
3114 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3115 false, Index, StructuredList, FieldIndex);
3116 return hadError && !prevHadError;
3117 }
3118
3119 // C99 6.7.8p6:
3120 //
3121 // If a designator has the form
3122 //
3123 // [ constant-expression ]
3124 //
3125 // then the current object (defined below) shall have array
3126 // type and the expression shall be an integer constant
3127 // expression. If the array is of unknown size, any
3128 // nonnegative value is valid.
3129 //
3130 // Additionally, cope with the GNU extension that permits
3131 // designators of the form
3132 //
3133 // [ constant-expression ... constant-expression ]
3134 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3135 if (!AT) {
3136 if (!VerifyOnly)
3137 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3138 << CurrentObjectType;
3139 ++Index;
3140 return true;
3141 }
3142
3143 Expr *IndexExpr = nullptr;
3144 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3145 if (D->isArrayDesignator()) {
3146 IndexExpr = DIE->getArrayIndex(*D);
3147 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3148 DesignatedEndIndex = DesignatedStartIndex;
3149 } else {
3150 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3151
3152 DesignatedStartIndex =
3154 DesignatedEndIndex =
3156 IndexExpr = DIE->getArrayRangeEnd(*D);
3157
3158 // Codegen can't handle evaluating array range designators that have side
3159 // effects, because we replicate the AST value for each initialized element.
3160 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3161 // elements with something that has a side effect, so codegen can emit an
3162 // "error unsupported" error instead of miscompiling the app.
3163 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3164 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3165 FullyStructuredList->sawArrayRangeDesignator();
3166 }
3167
3168 if (isa<ConstantArrayType>(AT)) {
3169 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3170 DesignatedStartIndex
3171 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3172 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3173 DesignatedEndIndex
3174 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3175 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3176 if (DesignatedEndIndex >= MaxElements) {
3177 if (!VerifyOnly)
3178 SemaRef.Diag(IndexExpr->getBeginLoc(),
3179 diag::err_array_designator_too_large)
3180 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3181 << IndexExpr->getSourceRange();
3182 ++Index;
3183 return true;
3184 }
3185 } else {
3186 unsigned DesignatedIndexBitWidth =
3188 DesignatedStartIndex =
3189 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3190 DesignatedEndIndex =
3191 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3192 DesignatedStartIndex.setIsUnsigned(true);
3193 DesignatedEndIndex.setIsUnsigned(true);
3194 }
3195
3196 bool IsStringLiteralInitUpdate =
3197 StructuredList && StructuredList->isStringLiteralInit();
3198 if (IsStringLiteralInitUpdate && VerifyOnly) {
3199 // We're just verifying an update to a string literal init. We don't need
3200 // to split the string up into individual characters to do that.
3201 StructuredList = nullptr;
3202 } else if (IsStringLiteralInitUpdate) {
3203 // We're modifying a string literal init; we have to decompose the string
3204 // so we can modify the individual characters.
3205 ASTContext &Context = SemaRef.Context;
3206 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3207
3208 // Compute the character type
3209 QualType CharTy = AT->getElementType();
3210
3211 // Compute the type of the integer literals.
3212 QualType PromotedCharTy = CharTy;
3213 if (Context.isPromotableIntegerType(CharTy))
3214 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3215 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3216
3217 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3218 // Get the length of the string.
3219 uint64_t StrLen = SL->getLength();
3220 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3221 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3222 StructuredList->resizeInits(Context, StrLen);
3223
3224 // Build a literal for each character in the string, and put them into
3225 // the init list.
3226 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3227 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3228 Expr *Init = new (Context) IntegerLiteral(
3229 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3230 if (CharTy != PromotedCharTy)
3231 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3232 Init, nullptr, VK_PRValue,
3234 StructuredList->updateInit(Context, i, Init);
3235 }
3236 } else {
3237 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3238 std::string Str;
3239 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3240
3241 // Get the length of the string.
3242 uint64_t StrLen = Str.size();
3243 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3244 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3245 StructuredList->resizeInits(Context, StrLen);
3246
3247 // Build a literal for each character in the string, and put them into
3248 // the init list.
3249 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3250 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3251 Expr *Init = new (Context) IntegerLiteral(
3252 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3253 if (CharTy != PromotedCharTy)
3254 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3255 Init, nullptr, VK_PRValue,
3257 StructuredList->updateInit(Context, i, Init);
3258 }
3259 }
3260 }
3261
3262 // Make sure that our non-designated initializer list has space
3263 // for a subobject corresponding to this array element.
3264 if (StructuredList &&
3265 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3266 StructuredList->resizeInits(SemaRef.Context,
3267 DesignatedEndIndex.getZExtValue() + 1);
3268
3269 // Repeatedly perform subobject initializations in the range
3270 // [DesignatedStartIndex, DesignatedEndIndex].
3271
3272 // Move to the next designator
3273 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3274 unsigned OldIndex = Index;
3275
3276 InitializedEntity ElementEntity =
3278
3279 while (DesignatedStartIndex <= DesignatedEndIndex) {
3280 // Recurse to check later designated subobjects.
3281 QualType ElementType = AT->getElementType();
3282 Index = OldIndex;
3283
3284 ElementEntity.setElementIndex(ElementIndex);
3285 if (CheckDesignatedInitializer(
3286 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3287 nullptr, Index, StructuredList, ElementIndex,
3288 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3289 false))
3290 return true;
3291
3292 // Move to the next index in the array that we'll be initializing.
3293 ++DesignatedStartIndex;
3294 ElementIndex = DesignatedStartIndex.getZExtValue();
3295 }
3296
3297 // If this the first designator, our caller will continue checking
3298 // the rest of this array subobject.
3299 if (IsFirstDesignator) {
3300 if (NextElementIndex)
3301 *NextElementIndex = DesignatedStartIndex;
3302 StructuredIndex = ElementIndex;
3303 return false;
3304 }
3305
3306 if (!FinishSubobjectInit)
3307 return false;
3308
3309 // Check the remaining elements within this array subobject.
3310 bool prevHadError = hadError;
3311 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3312 /*SubobjectIsDesignatorContext=*/false, Index,
3313 StructuredList, ElementIndex);
3314 return hadError && !prevHadError;
3315}
3316
3317// Get the structured initializer list for a subobject of type
3318// @p CurrentObjectType.
3320InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3321 QualType CurrentObjectType,
3322 InitListExpr *StructuredList,
3323 unsigned StructuredIndex,
3324 SourceRange InitRange,
3325 bool IsFullyOverwritten) {
3326 if (!StructuredList)
3327 return nullptr;
3328
3329 Expr *ExistingInit = nullptr;
3330 if (StructuredIndex < StructuredList->getNumInits())
3331 ExistingInit = StructuredList->getInit(StructuredIndex);
3332
3333 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3334 // There might have already been initializers for subobjects of the current
3335 // object, but a subsequent initializer list will overwrite the entirety
3336 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3337 //
3338 // struct P { char x[6]; };
3339 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3340 //
3341 // The first designated initializer is ignored, and l.x is just "f".
3342 if (!IsFullyOverwritten)
3343 return Result;
3344
3345 if (ExistingInit) {
3346 // We are creating an initializer list that initializes the
3347 // subobjects of the current object, but there was already an
3348 // initialization that completely initialized the current
3349 // subobject:
3350 //
3351 // struct X { int a, b; };
3352 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3353 //
3354 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3355 // designated initializer overwrites the [0].b initializer
3356 // from the prior initialization.
3357 //
3358 // When the existing initializer is an expression rather than an
3359 // initializer list, we cannot decompose and update it in this way.
3360 // For example:
3361 //
3362 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3363 //
3364 // This case is handled by CheckDesignatedInitializer.
3365 diagnoseInitOverride(ExistingInit, InitRange);
3366 }
3367
3368 unsigned ExpectedNumInits = 0;
3369 if (Index < IList->getNumInits()) {
3370 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3371 ExpectedNumInits = Init->getNumInits();
3372 else
3373 ExpectedNumInits = IList->getNumInits() - Index;
3374 }
3375
3376 InitListExpr *Result =
3377 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3378
3379 // Link this new initializer list into the structured initializer
3380 // lists.
3381 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3382 return Result;
3383}
3384
3386InitListChecker::createInitListExpr(QualType CurrentObjectType,
3387 SourceRange InitRange,
3388 unsigned ExpectedNumInits) {
3389 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3390 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3391
3392 QualType ResultType = CurrentObjectType;
3393 if (!ResultType->isArrayType())
3394 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3395 Result->setType(ResultType);
3396
3397 // Pre-allocate storage for the structured initializer list.
3398 unsigned NumElements = 0;
3399
3400 if (const ArrayType *AType
3401 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3402 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3403 NumElements = CAType->getZExtSize();
3404 // Simple heuristic so that we don't allocate a very large
3405 // initializer with many empty entries at the end.
3406 if (NumElements > ExpectedNumInits)
3407 NumElements = 0;
3408 }
3409 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3410 NumElements = VType->getNumElements();
3411 } else if (CurrentObjectType->isRecordType()) {
3412 NumElements = numStructUnionElements(CurrentObjectType);
3413 } else if (CurrentObjectType->isDependentType()) {
3414 NumElements = 1;
3415 }
3416
3417 Result->reserveInits(SemaRef.Context, NumElements);
3418
3419 return Result;
3420}
3421
3422/// Update the initializer at index @p StructuredIndex within the
3423/// structured initializer list to the value @p expr.
3424void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3425 unsigned &StructuredIndex,
3426 Expr *expr) {
3427 // No structured initializer list to update
3428 if (!StructuredList)
3429 return;
3430
3431 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3432 StructuredIndex, expr)) {
3433 // This initializer overwrites a previous initializer.
3434 // No need to diagnose when `expr` is nullptr because a more relevant
3435 // diagnostic has already been issued and this diagnostic is potentially
3436 // noise.
3437 if (expr)
3438 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3439 }
3440
3441 ++StructuredIndex;
3442}
3443
3445 const InitializedEntity &Entity, InitListExpr *From) {
3446 QualType Type = Entity.getType();
3447 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3448 /*TreatUnavailableAsInvalid=*/false,
3449 /*InOverloadResolution=*/true);
3450 return !Check.HadError();
3451}
3452
3453/// Check that the given Index expression is a valid array designator
3454/// value. This is essentially just a wrapper around
3455/// VerifyIntegerConstantExpression that also checks for negative values
3456/// and produces a reasonable diagnostic if there is a
3457/// failure. Returns the index expression, possibly with an implicit cast
3458/// added, on success. If everything went okay, Value will receive the
3459/// value of the constant expression.
3460static ExprResult
3461CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3462 SourceLocation Loc = Index->getBeginLoc();
3463
3464 // Make sure this is an integer constant expression.
3467 if (Result.isInvalid())
3468 return Result;
3469
3470 if (Value.isSigned() && Value.isNegative())
3471 return S.Diag(Loc, diag::err_array_designator_negative)
3472 << toString(Value, 10) << Index->getSourceRange();
3473
3474 Value.setIsUnsigned(true);
3475 return Result;
3476}
3477
3479 SourceLocation EqualOrColonLoc,
3480 bool GNUSyntax,
3481 ExprResult Init) {
3482 typedef DesignatedInitExpr::Designator ASTDesignator;
3483
3484 bool Invalid = false;
3486 SmallVector<Expr *, 32> InitExpressions;
3487
3488 // Build designators and check array designator expressions.
3489 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3490 const Designator &D = Desig.getDesignator(Idx);
3491
3492 if (D.isFieldDesignator()) {
3493 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3494 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3495 } else if (D.isArrayDesignator()) {
3496 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3497 llvm::APSInt IndexValue;
3498 if (!Index->isTypeDependent() && !Index->isValueDependent())
3499 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3500 if (!Index)
3501 Invalid = true;
3502 else {
3503 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3504 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3505 InitExpressions.push_back(Index);
3506 }
3507 } else if (D.isArrayRangeDesignator()) {
3508 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3509 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3510 llvm::APSInt StartValue;
3511 llvm::APSInt EndValue;
3512 bool StartDependent = StartIndex->isTypeDependent() ||
3513 StartIndex->isValueDependent();
3514 bool EndDependent = EndIndex->isTypeDependent() ||
3515 EndIndex->isValueDependent();
3516 if (!StartDependent)
3517 StartIndex =
3518 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3519 if (!EndDependent)
3520 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3521
3522 if (!StartIndex || !EndIndex)
3523 Invalid = true;
3524 else {
3525 // Make sure we're comparing values with the same bit width.
3526 if (StartDependent || EndDependent) {
3527 // Nothing to compute.
3528 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3529 EndValue = EndValue.extend(StartValue.getBitWidth());
3530 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3531 StartValue = StartValue.extend(EndValue.getBitWidth());
3532
3533 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3534 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3535 << toString(StartValue, 10) << toString(EndValue, 10)
3536 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3537 Invalid = true;
3538 } else {
3539 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3540 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3541 D.getRBracketLoc()));
3542 InitExpressions.push_back(StartIndex);
3543 InitExpressions.push_back(EndIndex);
3544 }
3545 }
3546 }
3547 }
3548
3549 if (Invalid || Init.isInvalid())
3550 return ExprError();
3551
3552 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3553 EqualOrColonLoc, GNUSyntax,
3554 Init.getAs<Expr>());
3555}
3556
3557//===----------------------------------------------------------------------===//
3558// Initialization entity
3559//===----------------------------------------------------------------------===//
3560
3561InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3563 : Parent(&Parent), Index(Index)
3564{
3565 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3566 Kind = EK_ArrayElement;
3567 Type = AT->getElementType();
3568 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3569 Kind = EK_VectorElement;
3570 Type = VT->getElementType();
3571 } else {
3572 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3573 assert(CT && "Unexpected type");
3574 Kind = EK_ComplexElement;
3575 Type = CT->getElementType();
3576 }
3577}
3578
3581 const CXXBaseSpecifier *Base,
3582 bool IsInheritedVirtualBase,
3583 const InitializedEntity *Parent) {
3585 Result.Kind = EK_Base;
3586 Result.Parent = Parent;
3587 Result.Base = {Base, IsInheritedVirtualBase};
3588 Result.Type = Base->getType();
3589 return Result;
3590}
3591
3593 switch (getKind()) {
3594 case EK_Parameter:
3596 ParmVarDecl *D = Parameter.getPointer();
3597 return (D ? D->getDeclName() : DeclarationName());
3598 }
3599
3600 case EK_Variable:
3601 case EK_Member:
3603 case EK_Binding:
3605 return Variable.VariableOrMember->getDeclName();
3606
3607 case EK_LambdaCapture:
3608 return DeclarationName(Capture.VarID);
3609
3610 case EK_Result:
3611 case EK_StmtExprResult:
3612 case EK_Exception:
3613 case EK_New:
3614 case EK_Temporary:
3615 case EK_Base:
3616 case EK_Delegating:
3617 case EK_ArrayElement:
3618 case EK_VectorElement:
3619 case EK_ComplexElement:
3620 case EK_BlockElement:
3623 case EK_RelatedResult:
3624 return DeclarationName();
3625 }
3626
3627 llvm_unreachable("Invalid EntityKind!");
3628}
3629
3631 switch (getKind()) {
3632 case EK_Variable:
3633 case EK_Member:
3635 case EK_Binding:
3637 return Variable.VariableOrMember;
3638
3639 case EK_Parameter:
3641 return Parameter.getPointer();
3642
3643 case EK_Result:
3644 case EK_StmtExprResult:
3645 case EK_Exception:
3646 case EK_New:
3647 case EK_Temporary:
3648 case EK_Base:
3649 case EK_Delegating:
3650 case EK_ArrayElement:
3651 case EK_VectorElement:
3652 case EK_ComplexElement:
3653 case EK_BlockElement:
3655 case EK_LambdaCapture:
3657 case EK_RelatedResult:
3658 return nullptr;
3659 }
3660
3661 llvm_unreachable("Invalid EntityKind!");
3662}
3663
3665 switch (getKind()) {
3666 case EK_Result:
3667 case EK_Exception:
3668 return LocAndNRVO.NRVO;
3669
3670 case EK_StmtExprResult:
3671 case EK_Variable:
3672 case EK_Parameter:
3675 case EK_Member:
3677 case EK_Binding:
3678 case EK_New:
3679 case EK_Temporary:
3681 case EK_Base:
3682 case EK_Delegating:
3683 case EK_ArrayElement:
3684 case EK_VectorElement:
3685 case EK_ComplexElement:
3686 case EK_BlockElement:
3688 case EK_LambdaCapture:
3689 case EK_RelatedResult:
3690 break;
3691 }
3692
3693 return false;
3694}
3695
3696unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3697 assert(getParent() != this);
3698 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3699 for (unsigned I = 0; I != Depth; ++I)
3700 OS << "`-";
3701
3702 switch (getKind()) {
3703 case EK_Variable: OS << "Variable"; break;
3704 case EK_Parameter: OS << "Parameter"; break;
3705 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3706 break;
3707 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3708 case EK_Result: OS << "Result"; break;
3709 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3710 case EK_Exception: OS << "Exception"; break;
3711 case EK_Member:
3713 OS << "Member";
3714 break;
3715 case EK_Binding: OS << "Binding"; break;
3716 case EK_New: OS << "New"; break;
3717 case EK_Temporary: OS << "Temporary"; break;
3718 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3719 case EK_RelatedResult: OS << "RelatedResult"; break;
3720 case EK_Base: OS << "Base"; break;
3721 case EK_Delegating: OS << "Delegating"; break;
3722 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3723 case EK_VectorElement: OS << "VectorElement " << Index; break;
3724 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3725 case EK_BlockElement: OS << "Block"; break;
3727 OS << "Block (lambda)";
3728 break;
3729 case EK_LambdaCapture:
3730 OS << "LambdaCapture ";
3731 OS << DeclarationName(Capture.VarID);
3732 break;
3733 }
3734
3735 if (auto *D = getDecl()) {
3736 OS << " ";
3737 D->printQualifiedName(OS);
3738 }
3739
3740 OS << " '" << getType() << "'\n";
3741
3742 return Depth + 1;
3743}
3744
3745LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3746 dumpImpl(llvm::errs());
3747}
3748
3749//===----------------------------------------------------------------------===//
3750// Initialization sequence
3751//===----------------------------------------------------------------------===//
3752
3754 switch (Kind) {
3759 case SK_BindReference:
3761 case SK_FinalCopy:
3763 case SK_UserConversion:
3770 case SK_UnwrapInitList:
3771 case SK_RewrapInitList:
3775 case SK_CAssignment:
3776 case SK_StringInit:
3778 case SK_ArrayLoopIndex:
3779 case SK_ArrayLoopInit:
3780 case SK_ArrayInit:
3781 case SK_GNUArrayInit:
3788 case SK_OCLSamplerInit:
3791 break;
3792
3795 delete ICS;
3796 }
3797}
3798
3800 // There can be some lvalue adjustments after the SK_BindReference step.
3801 for (const Step &S : llvm::reverse(Steps)) {
3802 if (S.Kind == SK_BindReference)
3803 return true;
3804 if (S.Kind == SK_BindReferenceToTemporary)
3805 return false;
3806 }
3807 return false;
3808}
3809
3811 if (!Failed())
3812 return false;
3813
3814 switch (getFailureKind()) {
3825 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3842 case FK_Incomplete:
3847 case FK_PlaceholderType:
3852 return false;
3853
3858 return FailedOverloadResult == OR_Ambiguous;
3859 }
3860
3861 llvm_unreachable("Invalid EntityKind!");
3862}
3863
3865 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3866}
3867
3868void
3869InitializationSequence
3870::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3872 bool HadMultipleCandidates) {
3873 Step S;
3875 S.Type = Function->getType();
3876 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3877 S.Function.Function = Function;
3878 S.Function.FoundDecl = Found;
3879 Steps.push_back(S);
3880}
3881
3883 ExprValueKind VK) {
3884 Step S;
3885 switch (VK) {
3886 case VK_PRValue:
3888 break;
3889 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3890 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3891 }
3892 S.Type = BaseType;
3893 Steps.push_back(S);
3894}
3895
3897 bool BindingTemporary) {
3898 Step S;
3899 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3900 S.Type = T;
3901 Steps.push_back(S);
3902}
3903
3905 Step S;
3906 S.Kind = SK_FinalCopy;
3907 S.Type = T;
3908 Steps.push_back(S);
3909}
3910
3912 Step S;
3914 S.Type = T;
3915 Steps.push_back(S);
3916}
3917
3918void
3920 DeclAccessPair FoundDecl,
3921 QualType T,
3922 bool HadMultipleCandidates) {
3923 Step S;
3924 S.Kind = SK_UserConversion;
3925 S.Type = T;
3926 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3927 S.Function.Function = Function;
3928 S.Function.FoundDecl = FoundDecl;
3929 Steps.push_back(S);
3930}
3931
3933 ExprValueKind VK) {
3934 Step S;
3935 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3936 switch (VK) {
3937 case VK_PRValue:
3939 break;
3940 case VK_XValue:
3942 break;
3943 case VK_LValue:
3945 break;
3946 }
3947 S.Type = Ty;
3948 Steps.push_back(S);
3949}
3950
3952 Step S;
3954 S.Type = Ty;
3955 Steps.push_back(S);
3956}
3957
3959 Step S;
3960 S.Kind = SK_AtomicConversion;
3961 S.Type = Ty;
3962 Steps.push_back(S);
3963}
3964
3967 bool TopLevelOfInitList) {
3968 Step S;
3969 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3971 S.Type = T;
3972 S.ICS = new ImplicitConversionSequence(ICS);
3973 Steps.push_back(S);
3974}
3975
3977 Step S;
3978 S.Kind = SK_ListInitialization;
3979 S.Type = T;
3980 Steps.push_back(S);
3981}
3982
3984 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3985 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3986 Step S;
3987 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3990 S.Type = T;
3991 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3992 S.Function.Function = Constructor;
3993 S.Function.FoundDecl = FoundDecl;
3994 Steps.push_back(S);
3995}
3996
3998 Step S;
3999 S.Kind = SK_ZeroInitialization;
4000 S.Type = T;
4001 Steps.push_back(S);
4002}
4003
4005 Step S;
4006 S.Kind = SK_CAssignment;
4007 S.Type = T;
4008 Steps.push_back(S);
4009}
4010
4012 Step S;
4013 S.Kind = SK_StringInit;
4014 S.Type = T;
4015 Steps.push_back(S);
4016}
4017
4019 Step S;
4020 S.Kind = SK_ObjCObjectConversion;
4021 S.Type = T;
4022 Steps.push_back(S);
4023}
4024
4026 Step S;
4027 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4028 S.Type = T;
4029 Steps.push_back(S);
4030}
4031
4033 Step S;
4034 S.Kind = SK_ArrayLoopIndex;
4035 S.Type = EltT;
4036 Steps.insert(Steps.begin(), S);
4037
4038 S.Kind = SK_ArrayLoopInit;
4039 S.Type = T;
4040 Steps.push_back(S);
4041}
4042
4044 Step S;
4046 S.Type = T;
4047 Steps.push_back(S);
4048}
4049
4051 bool shouldCopy) {
4052 Step s;
4053 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4055 s.Type = type;
4056 Steps.push_back(s);
4057}
4058
4060 Step S;
4061 S.Kind = SK_ProduceObjCObject;
4062 S.Type = T;
4063 Steps.push_back(S);
4064}
4065
4067 Step S;
4068 S.Kind = SK_StdInitializerList;
4069 S.Type = T;
4070 Steps.push_back(S);
4071}
4072
4074 Step S;
4075 S.Kind = SK_OCLSamplerInit;
4076 S.Type = T;
4077 Steps.push_back(S);
4078}
4079
4081 Step S;
4082 S.Kind = SK_OCLZeroOpaqueType;
4083 S.Type = T;
4084 Steps.push_back(S);
4085}
4086
4088 Step S;
4089 S.Kind = SK_ParenthesizedListInit;
4090 S.Type = T;
4091 Steps.push_back(S);
4092}
4093
4095 InitListExpr *Syntactic) {
4096 assert(Syntactic->getNumInits() == 1 &&
4097 "Can only rewrap trivial init lists.");
4098 Step S;
4099 S.Kind = SK_UnwrapInitList;
4100 S.Type = Syntactic->getInit(0)->getType();
4101 Steps.insert(Steps.begin(), S);
4102
4103 S.Kind = SK_RewrapInitList;
4104 S.Type = T;
4105 S.WrappingSyntacticList = Syntactic;
4106 Steps.push_back(S);
4107}
4108
4112 this->Failure = Failure;
4113 this->FailedOverloadResult = Result;
4114}
4115
4116//===----------------------------------------------------------------------===//
4117// Attempt initialization
4118//===----------------------------------------------------------------------===//
4119
4120/// Tries to add a zero initializer. Returns true if that worked.
4121static bool
4123 const InitializedEntity &Entity) {
4125 return false;
4126
4127 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4128 if (VD->getInit() || VD->getEndLoc().isMacroID())
4129 return false;
4130
4131 QualType VariableTy = VD->getType().getCanonicalType();
4133 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4134 if (!Init.empty()) {
4135 Sequence.AddZeroInitializationStep(Entity.getType());
4137 return true;
4138 }
4139 return false;
4140}
4141
4143 InitializationSequence &Sequence,
4144 const InitializedEntity &Entity) {
4145 if (!S.getLangOpts().ObjCAutoRefCount) return;
4146
4147 /// When initializing a parameter, produce the value if it's marked
4148 /// __attribute__((ns_consumed)).
4149 if (Entity.isParameterKind()) {
4150 if (!Entity.isParameterConsumed())
4151 return;
4152
4153 assert(Entity.getType()->isObjCRetainableType() &&
4154 "consuming an object of unretainable type?");
4155 Sequence.AddProduceObjCObjectStep(Entity.getType());
4156
4157 /// When initializing a return value, if the return type is a
4158 /// retainable type, then returns need to immediately retain the
4159 /// object. If an autorelease is required, it will be done at the
4160 /// last instant.
4161 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4163 if (!Entity.getType()->isObjCRetainableType())
4164 return;
4165
4166 Sequence.AddProduceObjCObjectStep(Entity.getType());
4167 }
4168}
4169
4170static void TryListInitialization(Sema &S,
4171 const InitializedEntity &Entity,
4172 const InitializationKind &Kind,
4173 InitListExpr *InitList,
4174 InitializationSequence &Sequence,
4175 bool TreatUnavailableAsInvalid);
4176
4177/// When initializing from init list via constructor, handle
4178/// initialization of an object of type std::initializer_list<T>.
4179///
4180/// \return true if we have handled initialization of an object of type
4181/// std::initializer_list<T>, false otherwise.
4183 InitListExpr *List,
4184 QualType DestType,
4185 InitializationSequence &Sequence,
4186 bool TreatUnavailableAsInvalid) {
4187 QualType E;
4188 if (!S.isStdInitializerList(DestType, &E))
4189 return false;
4190
4191 if (!S.isCompleteType(List->getExprLoc(), E)) {
4192 Sequence.setIncompleteTypeFailure(E);
4193 return true;
4194 }
4195
4196 // Try initializing a temporary array from the init list.
4198 E.withConst(),
4199 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4200 List->getNumInits()),
4202 InitializedEntity HiddenArray =
4205 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4206 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4207 TreatUnavailableAsInvalid);
4208 if (Sequence)
4209 Sequence.AddStdInitializerListConstructionStep(DestType);
4210 return true;
4211}
4212
4213/// Determine if the constructor has the signature of a copy or move
4214/// constructor for the type T of the class in which it was found. That is,
4215/// determine if its first parameter is of type T or reference to (possibly
4216/// cv-qualified) T.
4218 const ConstructorInfo &Info) {
4219 if (Info.Constructor->getNumParams() == 0)
4220 return false;
4221
4222 QualType ParmT =
4224 QualType ClassT =
4225 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4226
4227 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4228}
4229
4231 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4232 OverloadCandidateSet &CandidateSet, QualType DestType,
4234 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4235 bool IsListInit, bool RequireActualConstructor,
4236 bool SecondStepOfCopyInit = false) {
4238 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4239
4240 for (NamedDecl *D : Ctors) {
4241 auto Info = getConstructorInfo(D);
4242 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4243 continue;
4244
4245 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4246 continue;
4247
4248 // C++11 [over.best.ics]p4:
4249 // ... and the constructor or user-defined conversion function is a
4250 // candidate by
4251 // - 13.3.1.3, when the argument is the temporary in the second step
4252 // of a class copy-initialization, or
4253 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4254 // - the second phase of 13.3.1.7 when the initializer list has exactly
4255 // one element that is itself an initializer list, and the target is
4256 // the first parameter of a constructor of class X, and the conversion
4257 // is to X or reference to (possibly cv-qualified X),
4258 // user-defined conversion sequences are not considered.
4259 bool SuppressUserConversions =
4260 SecondStepOfCopyInit ||
4261 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4263
4264 if (Info.ConstructorTmpl)
4266 Info.ConstructorTmpl, Info.FoundDecl,
4267 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4268 /*PartialOverloading=*/false, AllowExplicit);
4269 else {
4270 // C++ [over.match.copy]p1:
4271 // - When initializing a temporary to be bound to the first parameter
4272 // of a constructor [for type T] that takes a reference to possibly
4273 // cv-qualified T as its first argument, called with a single
4274 // argument in the context of direct-initialization, explicit
4275 // conversion functions are also considered.
4276 // FIXME: What if a constructor template instantiates to such a signature?
4277 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4278 Args.size() == 1 &&
4280 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4281 CandidateSet, SuppressUserConversions,
4282 /*PartialOverloading=*/false, AllowExplicit,
4283 AllowExplicitConv);
4284 }
4285 }
4286
4287 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4288 //
4289 // When initializing an object of class type T by constructor
4290 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4291 // from a single expression of class type U, conversion functions of
4292 // U that convert to the non-reference type cv T are candidates.
4293 // Explicit conversion functions are only candidates during
4294 // direct-initialization.
4295 //
4296 // Note: SecondStepOfCopyInit is only ever true in this case when
4297 // evaluating whether to produce a C++98 compatibility warning.
4298 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4299 !RequireActualConstructor && !SecondStepOfCopyInit) {
4300 Expr *Initializer = Args[0];
4301 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4302 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4303 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4304 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4305 NamedDecl *D = *I;
4306 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4307 D = D->getUnderlyingDecl();
4308
4309 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4310 CXXConversionDecl *Conv;
4311 if (ConvTemplate)
4312 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4313 else
4314 Conv = cast<CXXConversionDecl>(D);
4315
4316 if (ConvTemplate)
4318 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4319 CandidateSet, AllowExplicit, AllowExplicit,
4320 /*AllowResultConversion*/ false);
4321 else
4322 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4323 DestType, CandidateSet, AllowExplicit,
4324 AllowExplicit,
4325 /*AllowResultConversion*/ false);
4326 }
4327 }
4328 }
4329
4330 // Perform overload resolution and return the result.
4331 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4332}
4333
4334/// Attempt initialization by constructor (C++ [dcl.init]), which
4335/// enumerates the constructors of the initialized entity and performs overload
4336/// resolution to select the best.
4337/// \param DestType The destination class type.
4338/// \param DestArrayType The destination type, which is either DestType or
4339/// a (possibly multidimensional) array of DestType.
4340/// \param IsListInit Is this list-initialization?
4341/// \param IsInitListCopy Is this non-list-initialization resulting from a
4342/// list-initialization from {x} where x is the same
4343/// aggregate type as the entity?
4345 const InitializedEntity &Entity,
4346 const InitializationKind &Kind,
4347 MultiExprArg Args, QualType DestType,
4348 QualType DestArrayType,
4349 InitializationSequence &Sequence,
4350 bool IsListInit = false,
4351 bool IsInitListCopy = false) {
4352 assert(((!IsListInit && !IsInitListCopy) ||
4353 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4354 "IsListInit/IsInitListCopy must come with a single initializer list "
4355 "argument.");
4356 InitListExpr *ILE =
4357 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4358 MultiExprArg UnwrappedArgs =
4359 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4360
4361 // The type we're constructing needs to be complete.
4362 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4363 Sequence.setIncompleteTypeFailure(DestType);
4364 return;
4365 }
4366
4367 bool RequireActualConstructor =
4368 !(Entity.getKind() != InitializedEntity::EK_Base &&
4370 Entity.getKind() !=
4372
4373 bool CopyElisionPossible = false;
4374 auto ElideConstructor = [&] {
4375 // Convert qualifications if necessary.
4376 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4377 if (ILE)
4378 Sequence.RewrapReferenceInitList(DestType, ILE);
4379 };
4380
4381 // C++17 [dcl.init]p17:
4382 // - If the initializer expression is a prvalue and the cv-unqualified
4383 // version of the source type is the same class as the class of the
4384 // destination, the initializer expression is used to initialize the
4385 // destination object.
4386 // Per DR (no number yet), this does not apply when initializing a base
4387 // class or delegating to another constructor from a mem-initializer.
4388 // ObjC++: Lambda captured by the block in the lambda to block conversion
4389 // should avoid copy elision.
4390 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4391 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4392 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4393 if (ILE && !DestType->isAggregateType()) {
4394 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4395 // Make this an elision if this won't call an initializer-list
4396 // constructor. (Always on an aggregate type or check constructors first.)
4397
4398 // This effectively makes our resolution as follows. The parts in angle
4399 // brackets are additions.
4400 // C++17 [over.match.list]p(1.2):
4401 // - If no viable initializer-list constructor is found <and the
4402 // initializer list does not consist of exactly a single element with
4403 // the same cv-unqualified class type as T>, [...]
4404 // C++17 [dcl.init.list]p(3.6):
4405 // - Otherwise, if T is a class type, constructors are considered. The
4406 // applicable constructors are enumerated and the best one is chosen
4407 // through overload resolution. <If no constructor is found and the
4408 // initializer list consists of exactly a single element with the same
4409 // cv-unqualified class type as T, the object is initialized from that
4410 // element (by copy-initialization for copy-list-initialization, or by
4411 // direct-initialization for direct-list-initialization). Otherwise, >
4412 // if a narrowing conversion [...]
4413 assert(!IsInitListCopy &&
4414 "IsInitListCopy only possible with aggregate types");
4415 CopyElisionPossible = true;
4416 } else {
4417 ElideConstructor();
4418 return;
4419 }
4420 }
4421
4422 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4423 assert(DestRecordType && "Constructor initialization requires record type");
4424 CXXRecordDecl *DestRecordDecl
4425 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4426
4427 // Build the candidate set directly in the initialization sequence
4428 // structure, so that it will persist if we fail.
4429 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4430
4431 // Determine whether we are allowed to call explicit constructors or
4432 // explicit conversion operators.
4433 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4434 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4435
4436 // - Otherwise, if T is a class type, constructors are considered. The
4437 // applicable constructors are enumerated, and the best one is chosen
4438 // through overload resolution.
4439 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4440
4443 bool AsInitializerList = false;
4444
4445 // C++11 [over.match.list]p1, per DR1467:
4446 // When objects of non-aggregate type T are list-initialized, such that
4447 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4448 // according to the rules in this section, overload resolution selects
4449 // the constructor in two phases:
4450 //
4451 // - Initially, the candidate functions are the initializer-list
4452 // constructors of the class T and the argument list consists of the
4453 // initializer list as a single argument.
4454 if (IsListInit) {
4455 AsInitializerList = true;
4456
4457 // If the initializer list has no elements and T has a default constructor,
4458 // the first phase is omitted.
4459 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4461 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4462 CopyInitialization, AllowExplicit,
4463 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4464
4465 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4466 // No initializer list candidate
4467 ElideConstructor();
4468 return;
4469 }
4470 }
4471
4472 // C++11 [over.match.list]p1:
4473 // - If no viable initializer-list constructor is found, overload resolution
4474 // is performed again, where the candidate functions are all the
4475 // constructors of the class T and the argument list consists of the
4476 // elements of the initializer list.
4478 AsInitializerList = false;
4480 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4481 Best, CopyInitialization, AllowExplicit,
4482 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4483 }
4484 if (Result) {
4485 Sequence.SetOverloadFailure(
4488 Result);
4489
4490 if (Result != OR_Deleted)
4491 return;
4492 }
4493
4494 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4495
4496 // In C++17, ResolveConstructorOverload can select a conversion function
4497 // instead of a constructor.
4498 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4499 // Add the user-defined conversion step that calls the conversion function.
4500 QualType ConvType = CD->getConversionType();
4501 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4502 "should not have selected this conversion function");
4503 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4504 HadMultipleCandidates);
4505 if (!S.Context.hasSameType(ConvType, DestType))
4506 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4507 if (IsListInit)
4508 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4509 return;
4510 }
4511
4512 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4513 if (Result != OR_Deleted) {
4514 // C++11 [dcl.init]p6:
4515 // If a program calls for the default initialization of an object
4516 // of a const-qualified type T, T shall be a class type with a
4517 // user-provided default constructor.
4518 // C++ core issue 253 proposal:
4519 // If the implicit default constructor initializes all subobjects, no
4520 // initializer should be required.
4521 // The 253 proposal is for example needed to process libstdc++ headers
4522 // in 5.x.
4523 if (Kind.getKind() == InitializationKind::IK_Default &&
4524 Entity.getType().isConstQualified()) {
4525 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4526 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4528 return;
4529 }
4530 }
4531
4532 // C++11 [over.match.list]p1:
4533 // In copy-list-initialization, if an explicit constructor is chosen, the
4534 // initializer is ill-formed.
4535 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4537 return;
4538 }
4539 }
4540
4541 // [class.copy.elision]p3:
4542 // In some copy-initialization contexts, a two-stage overload resolution
4543 // is performed.
4544 // If the first overload resolution selects a deleted function, we also
4545 // need the initialization sequence to decide whether to perform the second
4546 // overload resolution.
4547 // For deleted functions in other contexts, there is no need to get the
4548 // initialization sequence.
4549 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4550 return;
4551
4552 // Add the constructor initialization step. Any cv-qualification conversion is
4553 // subsumed by the initialization.
4555 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4556 IsListInit | IsInitListCopy, AsInitializerList);
4557}
4558
4559static bool
4562 QualType &SourceType,
4563 QualType &UnqualifiedSourceType,
4564 QualType UnqualifiedTargetType,
4565 InitializationSequence &Sequence) {
4566 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4567 S.Context.OverloadTy) {
4569 bool HadMultipleCandidates = false;
4570 if (FunctionDecl *Fn
4572 UnqualifiedTargetType,
4573 false, Found,
4574 &HadMultipleCandidates)) {
4576 HadMultipleCandidates);
4577 SourceType = Fn->getType();
4578 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4579 } else if (!UnqualifiedTargetType->isRecordType()) {
4581 return true;
4582 }
4583 }
4584 return false;
4585}
4586
4588 const InitializedEntity &Entity,
4589 const InitializationKind &Kind,
4591 QualType cv1T1, QualType T1,
4592 Qualifiers T1Quals,
4593 QualType cv2T2, QualType T2,
4594 Qualifiers T2Quals,
4595 InitializationSequence &Sequence,
4596 bool TopLevelOfInitList);
4597
4598static void TryValueInitialization(Sema &S,
4599 const InitializedEntity &Entity,
4600 const InitializationKind &Kind,
4601 InitializationSequence &Sequence,
4602 InitListExpr *InitList = nullptr);
4603
4604/// Attempt list initialization of a reference.
4606 const InitializedEntity &Entity,
4607 const InitializationKind &Kind,
4608 InitListExpr *InitList,
4609 InitializationSequence &Sequence,
4610 bool TreatUnavailableAsInvalid) {
4611 // First, catch C++03 where this isn't possible.
4612 if (!S.getLangOpts().CPlusPlus11) {
4614 return;
4615 }
4616 // Can't reference initialize a compound literal.
4619 return;
4620 }
4621
4622 QualType DestType = Entity.getType();
4623 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4624 Qualifiers T1Quals;
4625 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4626
4627 // Reference initialization via an initializer list works thus:
4628 // If the initializer list consists of a single element that is
4629 // reference-related to the referenced type, bind directly to that element
4630 // (possibly creating temporaries).
4631 // Otherwise, initialize a temporary with the initializer list and
4632 // bind to that.
4633 if (InitList->getNumInits() == 1) {
4634 Expr *Initializer = InitList->getInit(0);
4636 Qualifiers T2Quals;
4637 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4638
4639 // If this fails, creating a temporary wouldn't work either.
4641 T1, Sequence))
4642 return;
4643
4644 SourceLocation DeclLoc = Initializer->getBeginLoc();
4645 Sema::ReferenceCompareResult RefRelationship
4646 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4647 if (RefRelationship >= Sema::Ref_Related) {
4648 // Try to bind the reference here.
4649 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4650 T1Quals, cv2T2, T2, T2Quals, Sequence,
4651 /*TopLevelOfInitList=*/true);
4652 if (Sequence)
4653 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4654 return;
4655 }
4656
4657 // Update the initializer if we've resolved an overloaded function.
4658 if (Sequence.step_begin() != Sequence.step_end())
4659 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4660 }
4661 // Perform address space compatibility check.
4662 QualType cv1T1IgnoreAS = cv1T1;
4663 if (T1Quals.hasAddressSpace()) {
4664 Qualifiers T2Quals;
4665 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4666 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4667 Sequence.SetFailed(
4669 return;
4670 }
4671 // Ignore address space of reference type at this point and perform address
4672 // space conversion after the reference binding step.
4673 cv1T1IgnoreAS =
4675 }
4676 // Not reference-related. Create a temporary and bind to that.
4677 InitializedEntity TempEntity =
4679
4680 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4681 TreatUnavailableAsInvalid);
4682 if (Sequence) {
4683 if (DestType->isRValueReferenceType() ||
4684 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4685 if (S.getLangOpts().CPlusPlus20 &&
4686 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4687 DestType->isRValueReferenceType()) {
4688 // C++20 [dcl.init.list]p3.10:
4689 // List-initialization of an object or reference of type T is defined as
4690 // follows:
4691 // ..., unless T is “reference to array of unknown bound of U”, in which
4692 // case the type of the prvalue is the type of x in the declaration U
4693 // x[] H, where H is the initializer list.
4695 }
4696 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4697 /*BindingTemporary=*/true);
4698 if (T1Quals.hasAddressSpace())
4700 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4701 } else
4702 Sequence.SetFailed(
4704 }
4705}
4706
4707/// Attempt list initialization (C++0x [dcl.init.list])
4709 const InitializedEntity &Entity,
4710 const InitializationKind &Kind,
4711 InitListExpr *InitList,
4712 InitializationSequence &Sequence,
4713 bool TreatUnavailableAsInvalid) {
4714 QualType DestType = Entity.getType();
4715
4716 // C++ doesn't allow scalar initialization with more than one argument.
4717 // But C99 complex numbers are scalars and it makes sense there.
4718 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4719 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4721 return;
4722 }
4723 if (DestType->isReferenceType()) {
4724 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4725 TreatUnavailableAsInvalid);
4726 return;
4727 }
4728
4729 if (DestType->isRecordType() &&
4730 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4731 Sequence.setIncompleteTypeFailure(DestType);
4732 return;
4733 }
4734
4735 // C++20 [dcl.init.list]p3:
4736 // - If the braced-init-list contains a designated-initializer-list, T shall
4737 // be an aggregate class. [...] Aggregate initialization is performed.
4738 //
4739 // We allow arrays here too in order to support array designators.
4740 //
4741 // FIXME: This check should precede the handling of reference initialization.
4742 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4743 // as a tentative DR resolution.
4744 bool IsDesignatedInit = InitList->hasDesignatedInit();
4745 if (!DestType->isAggregateType() && IsDesignatedInit) {
4746 Sequence.SetFailed(
4748 return;
4749 }
4750
4751 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4752 // - If T is an aggregate class and the initializer list has a single element
4753 // of type cv U, where U is T or a class derived from T, the object is
4754 // initialized from that element (by copy-initialization for
4755 // copy-list-initialization, or by direct-initialization for
4756 // direct-list-initialization).
4757 // - Otherwise, if T is a character array and the initializer list has a
4758 // single element that is an appropriately-typed string literal
4759 // (8.5.2 [dcl.init.string]), initialization is performed as described
4760 // in that section.
4761 // - Otherwise, if T is an aggregate, [...] (continue below).
4762 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4763 !IsDesignatedInit) {
4764 if (DestType->isRecordType() && DestType->isAggregateType()) {
4765 QualType InitType = InitList->getInit(0)->getType();
4766 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4767 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4768 Expr *InitListAsExpr = InitList;
4769 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4770 DestType, Sequence,
4771 /*InitListSyntax*/false,
4772 /*IsInitListCopy*/true);
4773 return;
4774 }
4775 }
4776 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4777 Expr *SubInit[1] = {InitList->getInit(0)};
4778 if (!isa<VariableArrayType>(DestAT) &&
4779 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4780 InitializationKind SubKind =
4781 Kind.getKind() == InitializationKind::IK_DirectList
4782 ? InitializationKind::CreateDirect(Kind.getLocation(),
4783 InitList->getLBraceLoc(),
4784 InitList->getRBraceLoc())
4785 : Kind;
4786 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4787 /*TopLevelOfInitList*/ true,
4788 TreatUnavailableAsInvalid);
4789
4790 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4791 // the element is not an appropriately-typed string literal, in which
4792 // case we should proceed as in C++11 (below).
4793 if (Sequence) {
4794 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4795 return;
4796 }
4797 }
4798 }
4799 }
4800
4801 // C++11 [dcl.init.list]p3:
4802 // - If T is an aggregate, aggregate initialization is performed.
4803 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4804 (S.getLangOpts().CPlusPlus11 &&
4805 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4806 if (S.getLangOpts().CPlusPlus11) {
4807 // - Otherwise, if the initializer list has no elements and T is a
4808 // class type with a default constructor, the object is
4809 // value-initialized.
4810 if (InitList->getNumInits() == 0) {
4811 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4812 if (S.LookupDefaultConstructor(RD)) {
4813 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4814 return;
4815 }
4816 }
4817
4818 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4819 // an initializer_list object constructed [...]
4820 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4821 TreatUnavailableAsInvalid))
4822 return;
4823
4824 // - Otherwise, if T is a class type, constructors are considered.
4825 Expr *InitListAsExpr = InitList;
4826 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4827 DestType, Sequence, /*InitListSyntax*/true);
4828 } else
4830 return;
4831 }
4832
4833 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4834 InitList->getNumInits() == 1) {
4835 Expr *E = InitList->getInit(0);
4836
4837 // - Otherwise, if T is an enumeration with a fixed underlying type,
4838 // the initializer-list has a single element v, and the initialization
4839 // is direct-list-initialization, the object is initialized with the
4840 // value T(v); if a narrowing conversion is required to convert v to
4841 // the underlying type of T, the program is ill-formed.
4842 auto *ET = DestType->getAs<EnumType>();
4843 if (S.getLangOpts().CPlusPlus17 &&
4844 Kind.getKind() == InitializationKind::IK_DirectList &&
4845 ET && ET->getDecl()->isFixed() &&
4846 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4848 E->getType()->isFloatingType())) {
4849 // There are two ways that T(v) can work when T is an enumeration type.
4850 // If there is either an implicit conversion sequence from v to T or
4851 // a conversion function that can convert from v to T, then we use that.
4852 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4853 // type, it is converted to the enumeration type via its underlying type.
4854 // There is no overlap possible between these two cases (except when the
4855 // source value is already of the destination type), and the first
4856 // case is handled by the general case for single-element lists below.
4858 ICS.setStandard();
4860 if (!E->isPRValue())
4862 // If E is of a floating-point type, then the conversion is ill-formed
4863 // due to narrowing, but go through the motions in order to produce the
4864 // right diagnostic.
4868 ICS.Standard.setFromType(E->getType());
4869 ICS.Standard.setToType(0, E->getType());
4870 ICS.Standard.setToType(1, DestType);
4871 ICS.Standard.setToType(2, DestType);
4872 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4873 /*TopLevelOfInitList*/true);
4874 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4875 return;
4876 }
4877
4878 // - Otherwise, if the initializer list has a single element of type E
4879 // [...references are handled above...], the object or reference is
4880 // initialized from that element (by copy-initialization for
4881 // copy-list-initialization, or by direct-initialization for
4882 // direct-list-initialization); if a narrowing conversion is required
4883 // to convert the element to T, the program is ill-formed.
4884 //
4885 // Per core-24034, this is direct-initialization if we were performing
4886 // direct-list-initialization and copy-initialization otherwise.
4887 // We can't use InitListChecker for this, because it always performs
4888 // copy-initialization. This only matters if we might use an 'explicit'
4889 // conversion operator, or for the special case conversion of nullptr_t to
4890 // bool, so we only need to handle those cases.
4891 //
4892 // FIXME: Why not do this in all cases?
4893 Expr *Init = InitList->getInit(0);
4894 if (Init->getType()->isRecordType() ||
4895 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4896 InitializationKind SubKind =
4897 Kind.getKind() == InitializationKind::IK_DirectList
4898 ? InitializationKind::CreateDirect(Kind.getLocation(),
4899 InitList->getLBraceLoc(),
4900 InitList->getRBraceLoc())
4901 : Kind;
4902 Expr *SubInit[1] = { Init };
4903 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4904 /*TopLevelOfInitList*/true,
4905 TreatUnavailableAsInvalid);
4906 if (Sequence)
4907 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4908 return;
4909 }
4910 }
4911
4912 InitListChecker CheckInitList(S, Entity, InitList,
4913 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4914 if (CheckInitList.HadError()) {
4916 return;
4917 }
4918
4919 // Add the list initialization step with the built init list.
4920 Sequence.AddListInitializationStep(DestType);
4921}
4922
4923/// Try a reference initialization that involves calling a conversion
4924/// function.
4926 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4927 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4928 InitializationSequence &Sequence) {
4929 QualType DestType = Entity.getType();
4930 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4931 QualType T1 = cv1T1.getUnqualifiedType();
4932 QualType cv2T2 = Initializer->getType();
4933 QualType T2 = cv2T2.getUnqualifiedType();
4934
4935 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4936 "Must have incompatible references when binding via conversion");
4937
4938 // Build the candidate set directly in the initialization sequence
4939 // structure, so that it will persist if we fail.
4940 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4942
4943 // Determine whether we are allowed to call explicit conversion operators.
4944 // Note that none of [over.match.copy], [over.match.conv], nor
4945 // [over.match.ref] permit an explicit constructor to be chosen when
4946 // initializing a reference, not even for direct-initialization.
4947 bool AllowExplicitCtors = false;
4948 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4949
4950 const RecordType *T1RecordType = nullptr;
4951 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4952 S.isCompleteType(Kind.getLocation(), T1)) {
4953 // The type we're converting to is a class type. Enumerate its constructors
4954 // to see if there is a suitable conversion.
4955 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4956
4957 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4958 auto Info = getConstructorInfo(D);
4959 if (!Info.Constructor)
4960 continue;
4961
4962 if (!Info.Constructor->isInvalidDecl() &&
4963 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4964 if (Info.ConstructorTmpl)
4966 Info.ConstructorTmpl, Info.FoundDecl,
4967 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4968 /*SuppressUserConversions=*/true,
4969 /*PartialOverloading*/ false, AllowExplicitCtors);
4970 else
4972 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4973 /*SuppressUserConversions=*/true,
4974 /*PartialOverloading*/ false, AllowExplicitCtors);
4975 }
4976 }
4977 }
4978 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4979 return OR_No_Viable_Function;
4980
4981 const RecordType *T2RecordType = nullptr;
4982 if ((T2RecordType = T2->getAs<RecordType>()) &&
4983 S.isCompleteType(Kind.getLocation(), T2)) {
4984 // The type we're converting from is a class type, enumerate its conversion
4985 // functions.
4986 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4987
4988 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4989 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4990 NamedDecl *D = *I;
4991 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4992 if (isa<UsingShadowDecl>(D))
4993 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4994
4995 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4996 CXXConversionDecl *Conv;
4997 if (ConvTemplate)
4998 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4999 else
5000 Conv = cast<CXXConversionDecl>(D);
5001
5002 // If the conversion function doesn't return a reference type,
5003 // it can't be considered for this conversion unless we're allowed to
5004 // consider rvalues.
5005 // FIXME: Do we need to make sure that we only consider conversion
5006 // candidates with reference-compatible results? That might be needed to
5007 // break recursion.
5008 if ((AllowRValues ||
5010 if (ConvTemplate)
5012 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5013 CandidateSet,
5014 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5015 else
5017 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5018 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5019 }
5020 }
5021 }
5022 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
5023 return OR_No_Viable_Function;
5024
5025 SourceLocation DeclLoc = Initializer->getBeginLoc();
5026
5027 // Perform overload resolution. If it fails, return the failed result.
5030 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5031 return Result;
5032
5033 FunctionDecl *Function = Best->Function;
5034 // This is the overload that will be used for this initialization step if we
5035 // use this initialization. Mark it as referenced.
5036 Function->setReferenced();
5037
5038 // Compute the returned type and value kind of the conversion.
5039 QualType cv3T3;
5040 if (isa<CXXConversionDecl>(Function))
5041 cv3T3 = Function->getReturnType();
5042 else
5043 cv3T3 = T1;
5044
5046 if (cv3T3->isLValueReferenceType())
5047 VK = VK_LValue;
5048 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5049 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5050 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5051
5052 // Add the user-defined conversion step.
5053 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5054 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5055 HadMultipleCandidates);
5056
5057 // Determine whether we'll need to perform derived-to-base adjustments or
5058 // other conversions.
5060 Sema::ReferenceCompareResult NewRefRelationship =
5061 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5062
5063 // Add the final conversion sequence, if necessary.
5064 if (NewRefRelationship == Sema::Ref_Incompatible) {
5065 assert(!isa<CXXConstructorDecl>(Function) &&
5066 "should not have conversion after constructor");
5067
5069 ICS.setStandard();
5070 ICS.Standard = Best->FinalConversion;
5071 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5072
5073 // Every implicit conversion results in a prvalue, except for a glvalue
5074 // derived-to-base conversion, which we handle below.
5075 cv3T3 = ICS.Standard.getToType(2);
5076 VK = VK_PRValue;
5077 }
5078
5079 // If the converted initializer is a prvalue, its type T4 is adjusted to
5080 // type "cv1 T4" and the temporary materialization conversion is applied.
5081 //
5082 // We adjust the cv-qualifications to match the reference regardless of
5083 // whether we have a prvalue so that the AST records the change. In this
5084 // case, T4 is "cv3 T3".
5085 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5086 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5087 Sequence.AddQualificationConversionStep(cv1T4, VK);
5088 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5089 VK = IsLValueRef ? VK_LValue : VK_XValue;
5090
5091 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5092 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5093 else if (RefConv & Sema::ReferenceConversions::ObjC)
5094 Sequence.AddObjCObjectConversionStep(cv1T1);
5095 else if (RefConv & Sema::ReferenceConversions::Function)
5096 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5097 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5098 if (!S.Context.hasSameType(cv1T4, cv1T1))
5099 Sequence.AddQualificationConversionStep(cv1T1, VK);
5100 }
5101
5102 return OR_Success;
5103}
5104
5106 const InitializedEntity &Entity,
5107 Expr *CurInitExpr);
5108
5109/// Attempt reference initialization (C++0x [dcl.init.ref])
5111 const InitializationKind &Kind,
5113 InitializationSequence &Sequence,
5114 bool TopLevelOfInitList) {
5115 QualType DestType = Entity.getType();
5116 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5117 Qualifiers T1Quals;
5118 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5120 Qualifiers T2Quals;
5121 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5122
5123 // If the initializer is the address of an overloaded function, try
5124 // to resolve the overloaded function. If all goes well, T2 is the
5125 // type of the resulting function.
5127 T1, Sequence))
5128 return;
5129
5130 // Delegate everything else to a subfunction.
5131 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5132 T1Quals, cv2T2, T2, T2Quals, Sequence,
5133 TopLevelOfInitList);
5134}
5135
5136/// Determine whether an expression is a non-referenceable glvalue (one to
5137/// which a reference can never bind). Attempting to bind a reference to
5138/// such a glvalue will always create a temporary.
5140 return E->refersToBitField() || E->refersToVectorElement() ||
5142}
5143
5144/// Reference initialization without resolving overloaded functions.
5145///
5146/// We also can get here in C if we call a builtin which is declared as
5147/// a function with a parameter of reference type (such as __builtin_va_end()).
5149 const InitializedEntity &Entity,
5150 const InitializationKind &Kind,
5152 QualType cv1T1, QualType T1,
5153 Qualifiers T1Quals,
5154 QualType cv2T2, QualType T2,
5155 Qualifiers T2Quals,
5156 InitializationSequence &Sequence,
5157 bool TopLevelOfInitList) {
5158 QualType DestType = Entity.getType();
5159 SourceLocation DeclLoc = Initializer->getBeginLoc();
5160
5161 // Compute some basic properties of the types and the initializer.
5162 bool isLValueRef = DestType->isLValueReferenceType();
5163 bool isRValueRef = !isLValueRef;
5164 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5165
5167 Sema::ReferenceCompareResult RefRelationship =
5168 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5169
5170 // C++0x [dcl.init.ref]p5:
5171 // A reference to type "cv1 T1" is initialized by an expression of type
5172 // "cv2 T2" as follows:
5173 //
5174 // - If the reference is an lvalue reference and the initializer
5175 // expression
5176 // Note the analogous bullet points for rvalue refs to functions. Because
5177 // there are no function rvalues in C++, rvalue refs to functions are treated
5178 // like lvalue refs.
5179 OverloadingResult ConvOvlResult = OR_Success;
5180 bool T1Function = T1->isFunctionType();
5181 if (isLValueRef || T1Function) {
5182 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5183 (RefRelationship == Sema::Ref_Compatible ||
5184 (Kind.isCStyleOrFunctionalCast() &&
5185 RefRelationship == Sema::Ref_Related))) {
5186 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5187 // reference-compatible with "cv2 T2," or
5188 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5189 Sema::ReferenceConversions::ObjC)) {
5190 // If we're converting the pointee, add any qualifiers first;
5191 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5192 if (RefConv & (Sema::ReferenceConversions::Qualification))
5194 S.Context.getQualifiedType(T2, T1Quals),
5195 Initializer->getValueKind());
5196 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5197 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5198 else
5199 Sequence.AddObjCObjectConversionStep(cv1T1);
5200 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5201 // Perform a (possibly multi-level) qualification conversion.
5202 Sequence.AddQualificationConversionStep(cv1T1,
5203 Initializer->getValueKind());
5204 } else if (RefConv & Sema::ReferenceConversions::Function) {
5205 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5206 }
5207
5208 // We only create a temporary here when binding a reference to a
5209 // bit-field or vector element. Those cases are't supposed to be
5210 // handled by this bullet, but the outcome is the same either way.
5211 Sequence.AddReferenceBindingStep(cv1T1, false);
5212 return;
5213 }
5214
5215 // - has a class type (i.e., T2 is a class type), where T1 is not
5216 // reference-related to T2, and can be implicitly converted to an
5217 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5218 // with "cv3 T3" (this conversion is selected by enumerating the
5219 // applicable conversion functions (13.3.1.6) and choosing the best
5220 // one through overload resolution (13.3)),
5221 // If we have an rvalue ref to function type here, the rhs must be
5222 // an rvalue. DR1287 removed the "implicitly" here.
5223 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5224 (isLValueRef || InitCategory.isRValue())) {
5225 if (S.getLangOpts().CPlusPlus) {
5226 // Try conversion functions only for C++.
5227 ConvOvlResult = TryRefInitWithConversionFunction(
5228 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5229 /*IsLValueRef*/ isLValueRef, Sequence);
5230 if (ConvOvlResult == OR_Success)
5231 return;
5232 if (ConvOvlResult != OR_No_Viable_Function)
5233 Sequence.SetOverloadFailure(
5235 ConvOvlResult);
5236 } else {
5237 ConvOvlResult = OR_No_Viable_Function;
5238 }
5239 }
5240 }
5241
5242 // - Otherwise, the reference shall be an lvalue reference to a
5243 // non-volatile const type (i.e., cv1 shall be const), or the reference
5244 // shall be an rvalue reference.
5245 // For address spaces, we interpret this to mean that an addr space
5246 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5247 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5248 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5251 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5252 Sequence.SetOverloadFailure(
5254 ConvOvlResult);
5255 else if (!InitCategory.isLValue())
5256 Sequence.SetFailed(
5257 T1Quals.isAddressSpaceSupersetOf(T2Quals)
5261 else {
5263 switch (RefRelationship) {
5265 if (Initializer->refersToBitField())
5268 else if (Initializer->refersToVectorElement())
5271 else if (Initializer->refersToMatrixElement())
5274 else
5275 llvm_unreachable("unexpected kind of compatible initializer");
5276 break;
5277 case Sema::Ref_Related:
5279 break;
5283 break;
5284 }
5285 Sequence.SetFailed(FK);
5286 }
5287 return;
5288 }
5289
5290 // - If the initializer expression
5291 // - is an
5292 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5293 // [1z] rvalue (but not a bit-field) or
5294 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5295 //
5296 // Note: functions are handled above and below rather than here...
5297 if (!T1Function &&
5298 (RefRelationship == Sema::Ref_Compatible ||
5299 (Kind.isCStyleOrFunctionalCast() &&
5300 RefRelationship == Sema::Ref_Related)) &&
5301 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5302 (InitCategory.isPRValue() &&
5303 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5304 T2->isArrayType())))) {
5305 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5306 if (InitCategory.isPRValue() && T2->isRecordType()) {
5307 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5308 // compiler the freedom to perform a copy here or bind to the
5309 // object, while C++0x requires that we bind directly to the
5310 // object. Hence, we always bind to the object without making an
5311 // extra copy. However, in C++03 requires that we check for the
5312 // presence of a suitable copy constructor:
5313 //
5314 // The constructor that would be used to make the copy shall
5315 // be callable whether or not the copy is actually done.
5316 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5317 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5318 else if (S.getLangOpts().CPlusPlus11)
5320 }
5321
5322 // C++1z [dcl.init.ref]/5.2.1.2:
5323 // If the converted initializer is a prvalue, its type T4 is adjusted
5324 // to type "cv1 T4" and the temporary materialization conversion is
5325 // applied.
5326 // Postpone address space conversions to after the temporary materialization
5327 // conversion to allow creating temporaries in the alloca address space.
5328 auto T1QualsIgnoreAS = T1Quals;
5329 auto T2QualsIgnoreAS = T2Quals;
5330 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5331 T1QualsIgnoreAS.removeAddressSpace();
5332 T2QualsIgnoreAS.removeAddressSpace();
5333 }
5334 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5335 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5336 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5337 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5338 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5339 // Add addr space conversion if required.
5340 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5341 auto T4Quals = cv1T4.getQualifiers();
5342 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5343 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5344 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5345 cv1T4 = cv1T4WithAS;
5346 }
5347
5348 // In any case, the reference is bound to the resulting glvalue (or to
5349 // an appropriate base class subobject).
5350 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5351 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5352 else if (RefConv & Sema::ReferenceConversions::ObjC)
5353 Sequence.AddObjCObjectConversionStep(cv1T1);
5354 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5355 if (!S.Context.hasSameType(cv1T4, cv1T1))
5356 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5357 }
5358 return;
5359 }
5360
5361 // - has a class type (i.e., T2 is a class type), where T1 is not
5362 // reference-related to T2, and can be implicitly converted to an
5363 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5364 // where "cv1 T1" is reference-compatible with "cv3 T3",
5365 //
5366 // DR1287 removes the "implicitly" here.
5367 if (T2->isRecordType()) {
5368 if (RefRelationship == Sema::Ref_Incompatible) {
5369 ConvOvlResult = TryRefInitWithConversionFunction(
5370 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5371 /*IsLValueRef*/ isLValueRef, Sequence);
5372 if (ConvOvlResult)
5373 Sequence.SetOverloadFailure(
5375 ConvOvlResult);
5376
5377 return;
5378 }
5379
5380 if (RefRelationship == Sema::Ref_Compatible &&
5381 isRValueRef && InitCategory.isLValue()) {
5382 Sequence.SetFailed(
5384 return;
5385 }
5386
5388 return;
5389 }
5390
5391 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5392 // from the initializer expression using the rules for a non-reference
5393 // copy-initialization (8.5). The reference is then bound to the
5394 // temporary. [...]
5395
5396 // Ignore address space of reference type at this point and perform address
5397 // space conversion after the reference binding step.
5398 QualType cv1T1IgnoreAS =
5399 T1Quals.hasAddressSpace()
5401 : cv1T1;
5402
5403 InitializedEntity TempEntity =
5405
5406 // FIXME: Why do we use an implicit conversion here rather than trying
5407 // copy-initialization?
5409 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5410 /*SuppressUserConversions=*/false,
5411 Sema::AllowedExplicit::None,
5412 /*FIXME:InOverloadResolution=*/false,
5413 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5414 /*AllowObjCWritebackConversion=*/false);
5415
5416 if (ICS.isBad()) {
5417 // FIXME: Use the conversion function set stored in ICS to turn
5418 // this into an overloading ambiguity diagnostic. However, we need
5419 // to keep that set as an OverloadCandidateSet rather than as some
5420 // other kind of set.
5421 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5422 Sequence.SetOverloadFailure(
5424 ConvOvlResult);
5425 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5427 else
5429 return;
5430 } else {
5431 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5432 TopLevelOfInitList);
5433 }
5434
5435 // [...] If T1 is reference-related to T2, cv1 must be the
5436 // same cv-qualification as, or greater cv-qualification
5437 // than, cv2; otherwise, the program is ill-formed.
5438 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5439 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5440 if (RefRelationship == Sema::Ref_Related &&
5441 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5442 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5444 return;
5445 }
5446
5447 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5448 // reference, the initializer expression shall not be an lvalue.
5449 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5450 InitCategory.isLValue()) {
5451 Sequence.SetFailed(
5453 return;
5454 }
5455
5456 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5457
5458 if (T1Quals.hasAddressSpace()) {
5460 LangAS::Default)) {
5461 Sequence.SetFailed(
5463 return;
5464 }
5465 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5466 : VK_XValue);
5467 }
5468}
5469
5470/// Attempt character array initialization from a string literal
5471/// (C++ [dcl.init.string], C99 6.7.8).
5473 const InitializedEntity &Entity,
5474 const InitializationKind &Kind,
5476 InitializationSequence &Sequence) {
5477 Sequence.AddStringInitStep(Entity.getType());
5478}
5479
5480/// Attempt value initialization (C++ [dcl.init]p7).
5482 const InitializedEntity &Entity,
5483 const InitializationKind &Kind,
5484 InitializationSequence &Sequence,
5485 InitListExpr *InitList) {
5486 assert((!InitList || InitList->getNumInits() == 0) &&
5487 "Shouldn't use value-init for non-empty init lists");
5488
5489 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5490 //
5491 // To value-initialize an object of type T means:
5492 QualType T = Entity.getType();
5493
5494 // -- if T is an array type, then each element is value-initialized;
5496
5497 if (const RecordType *RT = T->getAs<RecordType>()) {
5498 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5499 bool NeedZeroInitialization = true;
5500 // C++98:
5501 // -- if T is a class type (clause 9) with a user-declared constructor
5502 // (12.1), then the default constructor for T is called (and the
5503 // initialization is ill-formed if T has no accessible default
5504 // constructor);
5505 // C++11:
5506 // -- if T is a class type (clause 9) with either no default constructor
5507 // (12.1 [class.ctor]) or a default constructor that is user-provided
5508 // or deleted, then the object is default-initialized;
5509 //
5510 // Note that the C++11 rule is the same as the C++98 rule if there are no
5511 // defaulted or deleted constructors, so we just use it unconditionally.
5513 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5514 NeedZeroInitialization = false;
5515
5516 // -- if T is a (possibly cv-qualified) non-union class type without a
5517 // user-provided or deleted default constructor, then the object is
5518 // zero-initialized and, if T has a non-trivial default constructor,
5519 // default-initialized;
5520 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5521 // constructor' part was removed by DR1507.
5522 if (NeedZeroInitialization)
5523 Sequence.AddZeroInitializationStep(Entity.getType());
5524
5525 // C++03:
5526 // -- if T is a non-union class type without a user-declared constructor,
5527 // then every non-static data member and base class component of T is
5528 // value-initialized;
5529 // [...] A program that calls for [...] value-initialization of an
5530 // entity of reference type is ill-formed.
5531 //
5532 // C++11 doesn't need this handling, because value-initialization does not
5533 // occur recursively there, and the implicit default constructor is
5534 // defined as deleted in the problematic cases.
5535 if (!S.getLangOpts().CPlusPlus11 &&
5536 ClassDecl->hasUninitializedReferenceMember()) {
5538 return;
5539 }
5540
5541 // If this is list-value-initialization, pass the empty init list on when
5542 // building the constructor call. This affects the semantics of a few
5543 // things (such as whether an explicit default constructor can be called).
5544 Expr *InitListAsExpr = InitList;
5545 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5546 bool InitListSyntax = InitList;
5547
5548 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5549 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5551 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5552 }
5553 }
5554
5555 Sequence.AddZeroInitializationStep(Entity.getType());
5556}
5557
5558/// Attempt default initialization (C++ [dcl.init]p6).
5560 const InitializedEntity &Entity,
5561 const InitializationKind &Kind,
5562 InitializationSequence &Sequence) {
5563 assert(Kind.getKind() == InitializationKind::IK_Default);
5564
5565 // C++ [dcl.init]p6:
5566 // To default-initialize an object of type T means:
5567 // - if T is an array type, each element is default-initialized;
5568 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5569
5570 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5571 // constructor for T is called (and the initialization is ill-formed if
5572 // T has no accessible default constructor);
5573 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5574 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5575 Entity.getType(), Sequence);
5576 return;
5577 }
5578
5579 // - otherwise, no initialization is performed.
5580
5581 // If a program calls for the default initialization of an object of
5582 // a const-qualified type T, T shall be a class type with a user-provided
5583 // default constructor.
5584 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5585 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5587 return;
5588 }
5589
5590 // If the destination type has a lifetime property, zero-initialize it.
5591 if (DestType.getQualifiers().hasObjCLifetime()) {
5592 Sequence.AddZeroInitializationStep(Entity.getType());
5593 return;
5594 }
5595}
5596
5598 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5599 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5600 ExprResult *Result = nullptr) {
5601 unsigned EntityIndexToProcess = 0;
5602 SmallVector<Expr *, 4> InitExprs;
5603 QualType ResultType;
5604 Expr *ArrayFiller = nullptr;
5605 FieldDecl *InitializedFieldInUnion = nullptr;
5606
5607 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5608 const InitializationKind &SubKind,
5609 Expr *Arg, Expr **InitExpr = nullptr) {
5611 S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5612
5613 if (IS.Failed()) {
5614 if (!VerifyOnly) {
5615 IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);
5616 } else {
5617 Sequence.SetFailed(
5619 }
5620
5621 return false;
5622 }
5623 if (!VerifyOnly) {
5624 ExprResult ER;
5625 ER = IS.Perform(S, SubEntity, SubKind,
5626 Arg ? MultiExprArg(Arg) : std::nullopt);
5627
5628 if (ER.isInvalid())
5629 return false;
5630
5631 if (InitExpr)
5632 *InitExpr = ER.get();
5633 else
5634 InitExprs.push_back(ER.get());
5635 }
5636 return true;
5637 };
5638
5639 if (const ArrayType *AT =
5640 S.getASTContext().getAsArrayType(Entity.getType())) {
5641 SmallVector<InitializedEntity, 4> ElementEntities;
5642 uint64_t ArrayLength;
5643 // C++ [dcl.init]p16.5
5644 // if the destination type is an array, the object is initialized as
5645 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5646 // the destination type is an array of unknown bound, it is defined as
5647 // having k elements.
5648 if (const ConstantArrayType *CAT =
5650 ArrayLength = CAT->getZExtSize();
5651 ResultType = Entity.getType();
5652 } else if (const VariableArrayType *VAT =
5654 // Braced-initialization of variable array types is not allowed, even if
5655 // the size is greater than or equal to the number of args, so we don't
5656 // allow them to be initialized via parenthesized aggregate initialization
5657 // either.
5658 const Expr *SE = VAT->getSizeExpr();
5659 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5660 << SE->getSourceRange();
5661 return;
5662 } else {
5663 assert(Entity.getType()->isIncompleteArrayType());
5664 ArrayLength = Args.size();
5665 }
5666 EntityIndexToProcess = ArrayLength;
5667
5668 // ...the ith array element is copy-initialized with xi for each
5669 // 1 <= i <= k
5670 for (Expr *E : Args) {
5672 S.getASTContext(), EntityIndexToProcess, Entity);
5674 E->getExprLoc(), /*isDirectInit=*/false, E);
5675 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5676 return;
5677 }
5678 // ...and value-initialized for each k < i <= n;
5679 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5681 S.getASTContext(), Args.size(), Entity);
5683 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5684 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5685 return;
5686 }
5687
5688 if (ResultType.isNull()) {
5689 ResultType = S.Context.getConstantArrayType(
5690 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5691 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5692 }
5693 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5694 bool IsUnion = RT->isUnionType();
5695 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5696 if (RD->isInvalidDecl()) {
5697 // Exit early to avoid confusion when processing members.
5698 // We do the same for braced list initialization in
5699 // `CheckStructUnionTypes`.
5700 Sequence.SetFailed(
5702 return;
5703 }
5704
5705 if (!IsUnion) {
5706 for (const CXXBaseSpecifier &Base : RD->bases()) {
5708 S.getASTContext(), &Base, false, &Entity);
5709 if (EntityIndexToProcess < Args.size()) {
5710 // C++ [dcl.init]p16.6.2.2.
5711 // ...the object is initialized is follows. Let e1, ..., en be the
5712 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5713 // the elements of the expression-list...The element ei is
5714 // copy-initialized with xi for 1 <= i <= k.
5715 Expr *E = Args[EntityIndexToProcess];
5717 E->getExprLoc(), /*isDirectInit=*/false, E);
5718 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5719 return;
5720 } else {
5721 // We've processed all of the args, but there are still base classes
5722 // that have to be initialized.
5723 // C++ [dcl.init]p17.6.2.2
5724 // The remaining elements...otherwise are value initialzed
5726 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5727 /*IsImplicit=*/true);
5728 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5729 return;
5730 }
5731 EntityIndexToProcess++;
5732 }
5733 }
5734
5735 for (FieldDecl *FD : RD->fields()) {
5736 // Unnamed bitfields should not be initialized at all, either with an arg
5737 // or by default.
5738 if (FD->isUnnamedBitField())
5739 continue;
5740
5741 InitializedEntity SubEntity =
5743
5744 if (EntityIndexToProcess < Args.size()) {
5745 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5746 Expr *E = Args[EntityIndexToProcess];
5747
5748 // Incomplete array types indicate flexible array members. Do not allow
5749 // paren list initializations of structs with these members, as GCC
5750 // doesn't either.
5751 if (FD->getType()->isIncompleteArrayType()) {
5752 if (!VerifyOnly) {
5753 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5754 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5755 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5756 }
5757 Sequence.SetFailed(
5759 return;
5760 }
5761
5763 E->getExprLoc(), /*isDirectInit=*/false, E);
5764 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5765 return;
5766
5767 // Unions should have only one initializer expression, so we bail out
5768 // after processing the first field. If there are more initializers then
5769 // it will be caught when we later check whether EntityIndexToProcess is
5770 // less than Args.size();
5771 if (IsUnion) {
5772 InitializedFieldInUnion = FD;
5773 EntityIndexToProcess = 1;
5774 break;
5775 }
5776 } else {
5777 // We've processed all of the args, but there are still members that
5778 // have to be initialized.
5779 if (FD->hasInClassInitializer()) {
5780 if (!VerifyOnly) {
5781 // C++ [dcl.init]p16.6.2.2
5782 // The remaining elements are initialized with their default
5783 // member initializers, if any
5785 Kind.getParenOrBraceRange().getEnd(), FD);
5786 if (DIE.isInvalid())
5787 return;
5788 S.checkInitializerLifetime(SubEntity, DIE.get());
5789 InitExprs.push_back(DIE.get());
5790 }
5791 } else {
5792 // C++ [dcl.init]p17.6.2.2
5793 // The remaining elements...otherwise are value initialzed
5794 if (FD->getType()->isReferenceType()) {
5795 Sequence.SetFailed(
5797 if (!VerifyOnly) {
5798 SourceRange SR = Kind.getParenOrBraceRange();
5799 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5800 << FD->getType() << SR;
5801 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5802 }
5803 return;
5804 }
5806 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5807 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5808 return;
5809 }
5810 }
5811 EntityIndexToProcess++;
5812 }
5813 ResultType = Entity.getType();
5814 }
5815
5816 // Not all of the args have been processed, so there must've been more args
5817 // than were required to initialize the element.
5818 if (EntityIndexToProcess < Args.size()) {
5820 if (!VerifyOnly) {
5821 QualType T = Entity.getType();
5822 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5823 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5824 Args.back()->getEndLoc());
5825 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5826 << InitKind << ExcessInitSR;
5827 }
5828 return;
5829 }
5830
5831 if (VerifyOnly) {
5833 Sequence.AddParenthesizedListInitStep(Entity.getType());
5834 } else if (Result) {
5835 SourceRange SR = Kind.getParenOrBraceRange();
5836 auto *CPLIE = CXXParenListInitExpr::Create(
5837 S.getASTContext(), InitExprs, ResultType, Args.size(),
5838 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5839 if (ArrayFiller)
5840 CPLIE->setArrayFiller(ArrayFiller);
5841 if (InitializedFieldInUnion)
5842 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5843 *Result = CPLIE;
5844 S.Diag(Kind.getLocation(),
5845 diag::warn_cxx17_compat_aggregate_init_paren_list)
5846 << Kind.getLocation() << SR << ResultType;
5847 }
5848}
5849
5850/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5851/// which enumerates all conversion functions and performs overload resolution
5852/// to select the best.
5854 QualType DestType,
5855 const InitializationKind &Kind,
5857 InitializationSequence &Sequence,
5858 bool TopLevelOfInitList) {
5859 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5860 QualType SourceType = Initializer->getType();
5861 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5862 "Must have a class type to perform a user-defined conversion");
5863
5864 // Build the candidate set directly in the initialization sequence
5865 // structure, so that it will persist if we fail.
5866 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5868 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5869
5870 // Determine whether we are allowed to call explicit constructors or
5871 // explicit conversion operators.
5872 bool AllowExplicit = Kind.AllowExplicit();
5873
5874 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5875 // The type we're converting to is a class type. Enumerate its constructors
5876 // to see if there is a suitable conversion.
5877 CXXRecordDecl *DestRecordDecl
5878 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5879
5880 // Try to complete the type we're converting to.
5881 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5882 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5883 auto Info = getConstructorInfo(D);
5884 if (!Info.Constructor)
5885 continue;
5886
5887 if (!Info.Constructor->isInvalidDecl() &&
5888 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5889 if (Info.ConstructorTmpl)
5891 Info.ConstructorTmpl, Info.FoundDecl,
5892 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5893 /*SuppressUserConversions=*/true,
5894 /*PartialOverloading*/ false, AllowExplicit);
5895 else
5896 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5897 Initializer, CandidateSet,
5898 /*SuppressUserConversions=*/true,
5899 /*PartialOverloading*/ false, AllowExplicit);
5900 }
5901 }
5902 }
5903 }
5904
5905 SourceLocation DeclLoc = Initializer->getBeginLoc();
5906
5907 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5908 // The type we're converting from is a class type, enumerate its conversion
5909 // functions.
5910
5911 // We can only enumerate the conversion functions for a complete type; if
5912 // the type isn't complete, simply skip this step.
5913 if (S.isCompleteType(DeclLoc, SourceType)) {
5914 CXXRecordDecl *SourceRecordDecl
5915 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5916
5917 const auto &Conversions =
5918 SourceRecordDecl->getVisibleConversionFunctions();
5919 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5920 NamedDecl *D = *I;
5921 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5922 if (isa<UsingShadowDecl>(D))
5923 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5924
5925 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5926 CXXConversionDecl *Conv;
5927 if (ConvTemplate)
5928 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5929 else
5930 Conv = cast<CXXConversionDecl>(D);
5931
5932 if (ConvTemplate)
5934 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5935 CandidateSet, AllowExplicit, AllowExplicit);
5936 else
5937 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5938 DestType, CandidateSet, AllowExplicit,
5939 AllowExplicit);
5940 }
5941 }
5942 }
5943
5944 // Perform overload resolution. If it fails, return the failed result.
5947 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5948 Sequence.SetOverloadFailure(
5950
5951 // [class.copy.elision]p3:
5952 // In some copy-initialization contexts, a two-stage overload resolution
5953 // is performed.
5954 // If the first overload resolution selects a deleted function, we also
5955 // need the initialization sequence to decide whether to perform the second
5956 // overload resolution.
5957 if (!(Result == OR_Deleted &&
5958 Kind.getKind() == InitializationKind::IK_Copy))
5959 return;
5960 }
5961
5962 FunctionDecl *Function = Best->Function;
5963 Function->setReferenced();
5964 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5965
5966 if (isa<CXXConstructorDecl>(Function)) {
5967 // Add the user-defined conversion step. Any cv-qualification conversion is
5968 // subsumed by the initialization. Per DR5, the created temporary is of the
5969 // cv-unqualified type of the destination.
5970 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5971 DestType.getUnqualifiedType(),
5972 HadMultipleCandidates);
5973
5974 // C++14 and before:
5975 // - if the function is a constructor, the call initializes a temporary
5976 // of the cv-unqualified version of the destination type. The [...]
5977 // temporary [...] is then used to direct-initialize, according to the
5978 // rules above, the object that is the destination of the
5979 // copy-initialization.
5980 // Note that this just performs a simple object copy from the temporary.
5981 //
5982 // C++17:
5983 // - if the function is a constructor, the call is a prvalue of the
5984 // cv-unqualified version of the destination type whose return object
5985 // is initialized by the constructor. The call is used to
5986 // direct-initialize, according to the rules above, the object that
5987 // is the destination of the copy-initialization.
5988 // Therefore we need to do nothing further.
5989 //
5990 // FIXME: Mark this copy as extraneous.
5991 if (!S.getLangOpts().CPlusPlus17)
5992 Sequence.AddFinalCopy(DestType);
5993 else if (DestType.hasQualifiers())
5994 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5995 return;
5996 }
5997
5998 // Add the user-defined conversion step that calls the conversion function.
5999 QualType ConvType = Function->getCallResultType();
6000 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6001 HadMultipleCandidates);
6002
6003 if (ConvType->getAs<RecordType>()) {
6004 // The call is used to direct-initialize [...] the object that is the
6005 // destination of the copy-initialization.
6006 //
6007 // In C++17, this does not call a constructor if we enter /17.6.1:
6008 // - If the initializer expression is a prvalue and the cv-unqualified
6009 // version of the source type is the same as the class of the
6010 // destination [... do not make an extra copy]
6011 //
6012 // FIXME: Mark this copy as extraneous.
6013 if (!S.getLangOpts().CPlusPlus17 ||
6014 Function->getReturnType()->isReferenceType() ||
6015 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6016 Sequence.AddFinalCopy(DestType);
6017 else if (!S.Context.hasSameType(ConvType, DestType))
6018 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6019 return;
6020 }
6021
6022 // If the conversion following the call to the conversion function
6023 // is interesting, add it as a separate step.
6024 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6025 Best->FinalConversion.Third) {
6027 ICS.setStandard();
6028 ICS.Standard = Best->FinalConversion;
6029 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6030 }
6031}
6032
6033/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
6034/// a function with a pointer return type contains a 'return false;' statement.
6035/// In C++11, 'false' is not a null pointer, so this breaks the build of any
6036/// code using that header.
6037///
6038/// Work around this by treating 'return false;' as zero-initializing the result
6039/// if it's used in a pointer-returning function in a system header.
6041 const InitializedEntity &Entity,
6042 const Expr *Init) {
6043 return S.getLangOpts().CPlusPlus11 &&
6045 Entity.getType()->isPointerType() &&
6046 isa<CXXBoolLiteralExpr>(Init) &&
6047 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
6048 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
6049}
6050
6051/// The non-zero enum values here are indexes into diagnostic alternatives.
6053
6054/// Determines whether this expression is an acceptable ICR source.
6056 bool isAddressOf, bool &isWeakAccess) {
6057 // Skip parens.
6058 e = e->IgnoreParens();
6059
6060 // Skip address-of nodes.
6061 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6062 if (op->getOpcode() == UO_AddrOf)
6063 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6064 isWeakAccess);
6065
6066 // Skip certain casts.
6067 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6068 switch (ce->getCastKind()) {
6069 case CK_Dependent:
6070 case CK_BitCast:
6071 case CK_LValueBitCast:
6072 case CK_NoOp:
6073 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6074
6075 case CK_ArrayToPointerDecay:
6076 return IIK_nonscalar;
6077
6078 case CK_NullToPointer:
6079 return IIK_okay;
6080
6081 default:
6082 break;
6083 }
6084
6085 // If we have a declaration reference, it had better be a local variable.
6086 } else if (isa<DeclRefExpr>(e)) {
6087 // set isWeakAccess to true, to mean that there will be an implicit
6088 // load which requires a cleanup.
6090 isWeakAccess = true;
6091
6092 if (!isAddressOf) return IIK_nonlocal;
6093
6094 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6095 if (!var) return IIK_nonlocal;
6096
6097 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6098
6099 // If we have a conditional operator, check both sides.
6100 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6101 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6102 isWeakAccess))
6103 return iik;
6104
6105 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6106
6107 // These are never scalar.
6108 } else if (isa<ArraySubscriptExpr>(e)) {
6109 return IIK_nonscalar;
6110
6111 // Otherwise, it needs to be a null pointer constant.
6112 } else {
6115 }
6116
6117 return IIK_nonlocal;
6118}
6119
6120/// Check whether the given expression is a valid operand for an
6121/// indirect copy/restore.
6123 assert(src->isPRValue());
6124 bool isWeakAccess = false;
6125 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6126 // If isWeakAccess to true, there will be an implicit
6127 // load which requires a cleanup.
6128 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6130
6131 if (iik == IIK_okay) return;
6132
6133 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6134 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6135 << src->getSourceRange();
6136}
6137
6138/// Determine whether we have compatible array types for the
6139/// purposes of GNU by-copy array initialization.
6140static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6141 const ArrayType *Source) {
6142 // If the source and destination array types are equivalent, we're
6143 // done.
6144 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6145 return true;
6146
6147 // Make sure that the element types are the same.
6148 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6149 return false;
6150
6151 // The only mismatch we allow is when the destination is an
6152 // incomplete array type and the source is a constant array type.
6153 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6154}
6155
6157 InitializationSequence &Sequence,
6158 const InitializedEntity &Entity,
6159 Expr *Initializer) {
6160 bool ArrayDecay = false;
6161 QualType ArgType = Initializer->getType();
6162 QualType ArgPointee;
6163 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6164 ArrayDecay = true;
6165 ArgPointee = ArgArrayType->getElementType();
6166 ArgType = S.Context.getPointerType(ArgPointee);
6167 }
6168
6169 // Handle write-back conversion.
6170 QualType ConvertedArgType;
6171 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6172 ConvertedArgType))
6173 return false;
6174
6175 // We should copy unless we're passing to an argument explicitly
6176 // marked 'out'.
6177 bool ShouldCopy = true;
6178 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6179 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6180
6181 // Do we need an lvalue conversion?
6182 if (ArrayDecay || Initializer->isGLValue()) {
6184 ICS.setStandard();
6186
6187 QualType ResultType;
6188 if (ArrayDecay) {
6190 ResultType = S.Context.getPointerType(ArgPointee);
6191 } else {
6193 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6194 }
6195
6196 Sequence.AddConversionSequenceStep(ICS, ResultType);
6197 }
6198
6199 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6200 return true;
6201}
6202
6204 InitializationSequence &Sequence,
6205 QualType DestType,
6206 Expr *Initializer) {
6207 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6208 (!Initializer->isIntegerConstantExpr(S.Context) &&
6209 !Initializer->getType()->isSamplerT()))
6210 return false;
6211
6212 Sequence.AddOCLSamplerInitStep(DestType);
6213 return true;
6214}
6215
6217 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6218 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6219}
6220
6222 InitializationSequence &Sequence,
6223 QualType DestType,
6224 Expr *Initializer) {
6225 if (!S.getLangOpts().OpenCL)
6226 return false;
6227
6228 //
6229 // OpenCL 1.2 spec, s6.12.10
6230 //
6231 // The event argument can also be used to associate the
6232 // async_work_group_copy with a previous async copy allowing
6233 // an event to be shared by multiple async copies; otherwise
6234 // event should be zero.
6235 //
6236 if (DestType->isEventT() || DestType->isQueueT()) {
6238 return false;
6239
6240 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6241 return true;
6242 }
6243
6244 // We should allow zero initialization for all types defined in the
6245 // cl_intel_device_side_avc_motion_estimation extension, except
6246 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6248 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6249 DestType->isOCLIntelSubgroupAVCType()) {
6250 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6251 DestType->isOCLIntelSubgroupAVCMceResultType())
6252 return false;
6254 return false;
6255
6256 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6257 return true;
6258 }
6259
6260 return false;
6261}
6262
6264 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6265 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6266 : FailedOverloadResult(OR_Success),
6267 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6268 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6269 TreatUnavailableAsInvalid);
6270}
6271
6272/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6273/// address of that function, this returns true. Otherwise, it returns false.
6274static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6275 auto *DRE = dyn_cast<DeclRefExpr>(E);
6276 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6277 return false;
6278
6280 cast<FunctionDecl>(DRE->getDecl()));
6281}
6282
6283/// Determine whether we can perform an elementwise array copy for this kind
6284/// of entity.
6285static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6286 switch (Entity.getKind()) {
6288 // C++ [expr.prim.lambda]p24:
6289 // For array members, the array elements are direct-initialized in
6290 // increasing subscript order.
6291 return true;
6292
6294 // C++ [dcl.decomp]p1:
6295 // [...] each element is copy-initialized or direct-initialized from the
6296 // corresponding element of the assignment-expression [...]
6297 return isa<DecompositionDecl>(Entity.getDecl());
6298
6300 // C++ [class.copy.ctor]p14:
6301 // - if the member is an array, each element is direct-initialized with
6302 // the corresponding subobject of x
6303 return Entity.isImplicitMemberInitializer();
6304
6306 // All the above cases are intended to apply recursively, even though none
6307 // of them actually say that.
6308 if (auto *E = Entity.getParent())
6309 return canPerformArrayCopy(*E);
6310 break;
6311
6312 default:
6313 break;
6314 }
6315
6316 return false;
6317}
6318
6320 const InitializedEntity &Entity,
6321 const InitializationKind &Kind,
6322 MultiExprArg Args,
6323 bool TopLevelOfInitList,
6324 bool TreatUnavailableAsInvalid) {
6325 ASTContext &Context = S.Context;
6326
6327 // Eliminate non-overload placeholder types in the arguments. We
6328 // need to do this before checking whether types are dependent
6329 // because lowering a pseudo-object expression might well give us
6330 // something of dependent type.
6331 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6332 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6333 // FIXME: should we be doing this here?
6334 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6335 if (result.isInvalid()) {
6337 return;
6338 }
6339 Args[I] = result.get();
6340 }
6341
6342 // C++0x [dcl.init]p16:
6343 // The semantics of initializers are as follows. The destination type is
6344 // the type of the object or reference being initialized and the source
6345 // type is the type of the initializer expression. The source type is not
6346 // defined when the initializer is a braced-init-list or when it is a
6347 // parenthesized list of expressions.
6348 QualType DestType = Entity.getType();
6349
6350 if (DestType->isDependentType() ||
6353 return;
6354 }
6355
6356 // Almost everything is a normal sequence.
6358
6359 QualType SourceType;
6360 Expr *Initializer = nullptr;
6361 if (Args.size() == 1) {
6362 Initializer = Args[0];
6363 if (S.getLangOpts().ObjC) {
6365 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6366 Initializer) ||
6368 Args[0] = Initializer;
6369 }
6370 if (!isa<InitListExpr>(Initializer))
6371 SourceType = Initializer->getType();
6372 }
6373
6374 // - If the initializer is a (non-parenthesized) braced-init-list, the
6375 // object is list-initialized (8.5.4).
6376 if (Kind.getKind() != InitializationKind::IK_Direct) {
6377 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6378 TryListInitialization(S, Entity, Kind, InitList, *this,
6379 TreatUnavailableAsInvalid);
6380 return;
6381 }
6382 }
6383
6384 // - If the destination type is a reference type, see 8.5.3.
6385 if (DestType->isReferenceType()) {
6386 // C++0x [dcl.init.ref]p1:
6387 // A variable declared to be a T& or T&&, that is, "reference to type T"
6388 // (8.3.2), shall be initialized by an object, or function, of type T or
6389 // by an object that can be converted into a T.
6390 // (Therefore, multiple arguments are not permitted.)
6391 if (Args.size() != 1)
6393 // C++17 [dcl.init.ref]p5:
6394 // A reference [...] is initialized by an expression [...] as follows:
6395 // If the initializer is not an expression, presumably we should reject,
6396 // but the standard fails to actually say so.
6397 else if (isa<InitListExpr>(Args[0]))
6399 else
6400 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6401 TopLevelOfInitList);
6402 return;
6403 }
6404
6405 // - If the initializer is (), the object is value-initialized.
6406 if (Kind.getKind() == InitializationKind::IK_Value ||
6407 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6408 TryValueInitialization(S, Entity, Kind, *this);
6409 return;
6410 }
6411
6412 // Handle default initialization.
6413 if (Kind.getKind() == InitializationKind::IK_Default) {
6414 TryDefaultInitialization(S, Entity, Kind, *this);
6415 return;
6416 }
6417
6418 // - If the destination type is an array of characters, an array of
6419 // char16_t, an array of char32_t, or an array of wchar_t, and the
6420 // initializer is a string literal, see 8.5.2.
6421 // - Otherwise, if the destination type is an array, the program is
6422 // ill-formed.
6423 // - Except in HLSL, where non-decaying array parameters behave like
6424 // non-array types for initialization.
6425 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6426 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6427 if (Initializer && isa<VariableArrayType>(DestAT)) {
6429 return;
6430 }
6431
6432 if (Initializer) {
6433 switch (IsStringInit(Initializer, DestAT, Context)) {
6434 case SIF_None:
6435 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6436 return;
6439 return;
6442 return;
6445 return;
6448 return;
6451 return;
6452 case SIF_Other:
6453 break;
6454 }
6455 }
6456
6457 // Some kinds of initialization permit an array to be initialized from
6458 // another array of the same type, and perform elementwise initialization.
6459 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6461 Entity.getType()) &&
6462 canPerformArrayCopy(Entity)) {
6463 // If source is a prvalue, use it directly.
6464 if (Initializer->isPRValue()) {
6465 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6466 return;
6467 }
6468
6469 // Emit element-at-a-time copy loop.
6470 InitializedEntity Element =
6472 QualType InitEltT =
6473 Context.getAsArrayType(Initializer->getType())->getElementType();
6474 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6475 Initializer->getValueKind(),
6476 Initializer->getObjectKind());
6477 Expr *OVEAsExpr = &OVE;
6478 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6479 TreatUnavailableAsInvalid);
6480 if (!Failed())
6481 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6482 return;
6483 }
6484
6485 // Note: as an GNU C extension, we allow initialization of an
6486 // array from a compound literal that creates an array of the same
6487 // type, so long as the initializer has no side effects.
6488 if (!S.getLangOpts().CPlusPlus && Initializer &&
6489 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6490 Initializer->getType()->isArrayType()) {
6491 const ArrayType *SourceAT
6492 = Context.getAsArrayType(Initializer->getType());
6493 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6495 else if (Initializer->HasSideEffects(S.Context))
6497 else {
6498 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6499 }
6500 }
6501 // Note: as a GNU C++ extension, we allow list-initialization of a
6502 // class member of array type from a parenthesized initializer list.
6503 else if (S.getLangOpts().CPlusPlus &&
6505 isa_and_nonnull<InitListExpr>(Initializer)) {
6506 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6507 *this, TreatUnavailableAsInvalid);
6509 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6510 Kind.getKind() == InitializationKind::IK_Direct)
6511 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6512 /*VerifyOnly=*/true);
6513 else if (DestAT->getElementType()->isCharType())
6515 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6517 else
6519
6520 return;
6521 }
6522
6523 // Determine whether we should consider writeback conversions for
6524 // Objective-C ARC.
6525 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6526 Entity.isParameterKind();
6527
6528 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6529 return;
6530
6531 // We're at the end of the line for C: it's either a write-back conversion
6532 // or it's a C assignment. There's no need to check anything else.
6533 if (!S.getLangOpts().CPlusPlus) {
6534 assert(Initializer && "Initializer must be non-null");
6535 // If allowed, check whether this is an Objective-C writeback conversion.
6536 if (allowObjCWritebackConversion &&
6537 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6538 return;
6539 }
6540
6541 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6542 return;
6543
6544 // Handle initialization in C
6545 AddCAssignmentStep(DestType);
6546 MaybeProduceObjCObject(S, *this, Entity);
6547 return;
6548 }
6549
6550 assert(S.getLangOpts().CPlusPlus);
6551
6552 // - If the destination type is a (possibly cv-qualified) class type:
6553 if (DestType->isRecordType()) {
6554 // - If the initialization is direct-initialization, or if it is
6555 // copy-initialization where the cv-unqualified version of the
6556 // source type is the same class as, or a derived class of, the
6557 // class of the destination, constructors are considered. [...]
6558 if (Kind.getKind() == InitializationKind::IK_Direct ||
6559 (Kind.getKind() == InitializationKind::IK_Copy &&
6560 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6561 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6562 SourceType, DestType))))) {
6563 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6564 *this);
6565
6566 // We fall back to the "no matching constructor" path if the
6567 // failed candidate set has functions other than the three default
6568 // constructors. For example, conversion function.
6569 if (const auto *RD =
6570 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6571 // In general, we should call isCompleteType for RD to check its
6572 // completeness, we don't call it here as it was already called in the
6573 // above TryConstructorInitialization.
6574 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6575 RD->isAggregate() && Failed() &&
6577 // Do not attempt paren list initialization if overload resolution
6578 // resolves to a deleted function .
6579 //
6580 // We may reach this condition if we have a union wrapping a class with
6581 // a non-trivial copy or move constructor and we call one of those two
6582 // constructors. The union is an aggregate, but the matched constructor
6583 // is implicitly deleted, so we need to prevent aggregate initialization
6584 // (otherwise, it'll attempt aggregate initialization by initializing
6585 // the first element with a reference to the union).
6588 S, Kind.getLocation(), Best);
6590 // C++20 [dcl.init] 17.6.2.2:
6591 // - Otherwise, if no constructor is viable, the destination type is
6592 // an
6593 // aggregate class, and the initializer is a parenthesized
6594 // expression-list.
6595 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6596 /*VerifyOnly=*/true);
6597 }
6598 }
6599 } else {
6600 // - Otherwise (i.e., for the remaining copy-initialization cases),
6601 // user-defined conversion sequences that can convert from the
6602 // source type to the destination type or (when a conversion
6603 // function is used) to a derived class thereof are enumerated as
6604 // described in 13.3.1.4, and the best one is chosen through
6605 // overload resolution (13.3).
6606 assert(Initializer && "Initializer must be non-null");
6607 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6608 TopLevelOfInitList);
6609 }
6610 return;
6611 }
6612
6613 assert(Args.size() >= 1 && "Zero-argument case handled above");
6614
6615 // For HLSL ext vector types we allow list initialization behavior for C++
6616 // constructor syntax. This is accomplished by converting initialization
6617 // arguments an InitListExpr late.
6618 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6619 (SourceType.isNull() ||
6620 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6621
6623 for (auto *Arg : Args) {
6624 if (Arg->getType()->isExtVectorType()) {
6625 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6626 unsigned Elm = VTy->getNumElements();
6627 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6628 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6629 Arg,
6631 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6632 Context.IntTy, SourceLocation()),
6633 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6634 SourceLocation()));
6635 }
6636 } else
6637 InitArgs.emplace_back(Arg);
6638 }
6639 InitListExpr *ILE = new (Context) InitListExpr(
6640 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6641 Args[0] = ILE;
6642 AddListInitializationStep(DestType);
6643 return;
6644 }
6645
6646 // The remaining cases all need a source type.
6647 if (Args.size() > 1) {
6649 return;
6650 } else if (isa<InitListExpr>(Args[0])) {
6652 return;
6653 }
6654
6655 // - Otherwise, if the source type is a (possibly cv-qualified) class
6656 // type, conversion functions are considered.
6657 if (!SourceType.isNull() && SourceType->isRecordType()) {
6658 assert(Initializer && "Initializer must be non-null");
6659 // For a conversion to _Atomic(T) from either T or a class type derived
6660 // from T, initialize the T object then convert to _Atomic type.
6661 bool NeedAtomicConversion = false;
6662 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6663 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6664 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6665 Atomic->getValueType())) {
6666 DestType = Atomic->getValueType();
6667 NeedAtomicConversion = true;
6668 }
6669 }
6670
6671 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6672 TopLevelOfInitList);
6673 MaybeProduceObjCObject(S, *this, Entity);
6674 if (!Failed() && NeedAtomicConversion)
6676 return;
6677 }
6678
6679 // - Otherwise, if the initialization is direct-initialization, the source
6680 // type is std::nullptr_t, and the destination type is bool, the initial
6681 // value of the object being initialized is false.
6682 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6683 DestType->isBooleanType() &&
6684 Kind.getKind() == InitializationKind::IK_Direct) {
6687 Initializer->isGLValue()),
6688 DestType);
6689 return;
6690 }
6691
6692 // - Otherwise, the initial value of the object being initialized is the
6693 // (possibly converted) value of the initializer expression. Standard
6694 // conversions (Clause 4) will be used, if necessary, to convert the
6695 // initializer expression to the cv-unqualified version of the
6696 // destination type; no user-defined conversions are considered.
6697
6699 = S.TryImplicitConversion(Initializer, DestType,
6700 /*SuppressUserConversions*/true,
6701 Sema::AllowedExplicit::None,
6702 /*InOverloadResolution*/ false,
6703 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6704 allowObjCWritebackConversion);
6705
6706 if (ICS.isStandard() &&
6708 // Objective-C ARC writeback conversion.
6709
6710 // We should copy unless we're passing to an argument explicitly
6711 // marked 'out'.
6712 bool ShouldCopy = true;
6713 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6714 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6715
6716 // If there was an lvalue adjustment, add it as a separate conversion.
6717 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6720 LvalueICS.setStandard();
6722 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6723 LvalueICS.Standard.First = ICS.Standard.First;
6724 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6725 }
6726
6727 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6728 } else if (ICS.isBad()) {
6731 else if (DeclAccessPair Found;
6732 Initializer->getType() == Context.OverloadTy &&
6734 /*Complain=*/false, Found))
6736 else if (Initializer->getType()->isFunctionType() &&
6739 else
6741 } else {
6742 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6743
6744 MaybeProduceObjCObject(S, *this, Entity);
6745 }
6746}
6747
6749 for (auto &S : Steps)
6750 S.Destroy();
6751}
6752
6753//===----------------------------------------------------------------------===//
6754// Perform initialization
6755//===----------------------------------------------------------------------===//
6757getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6758 switch(Entity.getKind()) {
6764 return Sema::AA_Initializing;
6765
6767 if (Entity.getDecl() &&
6768 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6769 return Sema::AA_Sending;
6770
6771 return Sema::AA_Passing;
6772
6774 if (Entity.getDecl() &&
6775 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6776 return Sema::AA_Sending;
6777
6778 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6779
6781 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6782 return Sema::AA_Returning;
6783
6786 // FIXME: Can we tell apart casting vs. converting?
6787 return Sema::AA_Casting;
6788
6790 // This is really initialization, but refer to it as conversion for
6791 // consistency with CheckConvertedConstantExpression.
6792 return Sema::AA_Converting;
6793
6804 return Sema::AA_Initializing;
6805 }
6806
6807 llvm_unreachable("Invalid EntityKind!");
6808}
6809
6810/// Whether we should bind a created object as a temporary when
6811/// initializing the given entity.
6812static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6813 switch (Entity.getKind()) {
6831 return false;
6832
6838 return true;
6839 }
6840
6841 llvm_unreachable("missed an InitializedEntity kind?");
6842}
6843
6844/// Whether the given entity, when initialized with an object
6845/// created for that initialization, requires destruction.
6846static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6847 switch (Entity.getKind()) {
6858 return false;
6859
6872 return true;
6873 }
6874
6875 llvm_unreachable("missed an InitializedEntity kind?");
6876}
6877
6878/// Get the location at which initialization diagnostics should appear.
6880 Expr *Initializer) {
6881 switch (Entity.getKind()) {
6884 return Entity.getReturnLoc();
6885
6887 return Entity.getThrowLoc();
6888
6891 return Entity.getDecl()->getLocation();
6892
6894 return Entity.getCaptureLoc();
6895
6912 return Initializer->getBeginLoc();
6913 }
6914 llvm_unreachable("missed an InitializedEntity kind?");
6915}
6916
6917/// Make a (potentially elidable) temporary copy of the object
6918/// provided by the given initializer by calling the appropriate copy
6919/// constructor.
6920///
6921/// \param S The Sema object used for type-checking.
6922///
6923/// \param T The type of the temporary object, which must either be
6924/// the type of the initializer expression or a superclass thereof.
6925///
6926/// \param Entity The entity being initialized.
6927///
6928/// \param CurInit The initializer expression.
6929///
6930/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6931/// is permitted in C++03 (but not C++0x) when binding a reference to
6932/// an rvalue.
6933///
6934/// \returns An expression that copies the initializer expression into
6935/// a temporary object, or an error expression if a copy could not be
6936/// created.
6938 QualType T,
6939 const InitializedEntity &Entity,
6940 ExprResult CurInit,
6941 bool IsExtraneousCopy) {
6942 if (CurInit.isInvalid())
6943 return CurInit;
6944 // Determine which class type we're copying to.
6945 Expr *CurInitExpr = (Expr *)CurInit.get();
6946 CXXRecordDecl *Class = nullptr;
6947 if (const RecordType *Record = T->getAs<RecordType>())
6948 Class = cast<CXXRecordDecl>(Record->getDecl());
6949 if (!Class)
6950 return CurInit;
6951
6952 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6953
6954 // Make sure that the type we are copying is complete.
6955 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6956 return CurInit;
6957
6958 // Perform overload resolution using the class's constructors. Per
6959 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6960 // is direct-initialization.
6963
6966 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6967 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6968 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6969 /*RequireActualConstructor=*/false,
6970 /*SecondStepOfCopyInit=*/true)) {
6971 case OR_Success:
6972 break;
6973
6975 CandidateSet.NoteCandidates(
6977 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6978 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6979 : diag::err_temp_copy_no_viable)
6980 << (int)Entity.getKind() << CurInitExpr->getType()
6981 << CurInitExpr->getSourceRange()),
6982 S, OCD_AllCandidates, CurInitExpr);
6983 if (!IsExtraneousCopy || S.isSFINAEContext())
6984 return ExprError();
6985 return CurInit;
6986
6987 case OR_Ambiguous:
6988 CandidateSet.NoteCandidates(
6989 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6990 << (int)Entity.getKind()
6991 << CurInitExpr->getType()
6992 << CurInitExpr->getSourceRange()),
6993 S, OCD_AmbiguousCandidates, CurInitExpr);
6994 return ExprError();
6995
6996 case OR_Deleted:
6997 S.Diag(Loc, diag::err_temp_copy_deleted)
6998 << (int)Entity.getKind() << CurInitExpr->getType()
6999 << CurInitExpr->getSourceRange();
7000 S.NoteDeletedFunction(Best->Function);
7001 return ExprError();
7002 }
7003
7004 bool HadMultipleCandidates = CandidateSet.size() > 1;
7005
7006 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
7007 SmallVector<Expr*, 8> ConstructorArgs;
7008 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7009
7010 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7011 IsExtraneousCopy);
7012
7013 if (IsExtraneousCopy) {
7014 // If this is a totally extraneous copy for C++03 reference
7015 // binding purposes, just return the original initialization
7016 // expression. We don't generate an (elided) copy operation here
7017 // because doing so would require us to pass down a flag to avoid
7018 // infinite recursion, where each step adds another extraneous,
7019 // elidable copy.
7020
7021 // Instantiate the default arguments of any extra parameters in
7022 // the selected copy constructor, as if we were going to create a
7023 // proper call to the copy constructor.
7024 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7025 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7026 if (S.RequireCompleteType(Loc, Parm->getType(),
7027 diag::err_call_incomplete_argument))
7028 break;
7029
7030 // Build the default argument expression; we don't actually care
7031 // if this succeeds or not, because this routine will complain
7032 // if there was a problem.
7033 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7034 }
7035
7036 return CurInitExpr;
7037 }
7038
7039 // Determine the arguments required to actually perform the
7040 // constructor call (we might have derived-to-base conversions, or
7041 // the copy constructor may have default arguments).
7042 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7043 ConstructorArgs))
7044 return ExprError();
7045
7046 // C++0x [class.copy]p32:
7047 // When certain criteria are met, an implementation is allowed to
7048 // omit the copy/move construction of a class object, even if the
7049 // copy/move constructor and/or destructor for the object have
7050 // side effects. [...]
7051 // - when a temporary class object that has not been bound to a
7052 // reference (12.2) would be copied/moved to a class object
7053 // with the same cv-unqualified type, the copy/move operation
7054 // can be omitted by constructing the temporary object
7055 // directly into the target of the omitted copy/move
7056 //
7057 // Note that the other three bullets are handled elsewhere. Copy
7058 // elision for return statements and throw expressions are handled as part
7059 // of constructor initialization, while copy elision for exception handlers
7060 // is handled by the run-time.
7061 //
7062 // FIXME: If the function parameter is not the same type as the temporary, we
7063 // should still be able to elide the copy, but we don't have a way to
7064 // represent in the AST how much should be elided in this case.
7065 bool Elidable =
7066 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7068 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7069 CurInitExpr->getType());
7070
7071 // Actually perform the constructor call.
7072 CurInit = S.BuildCXXConstructExpr(
7073 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7074 HadMultipleCandidates,
7075 /*ListInit*/ false,
7076 /*StdInitListInit*/ false,
7077 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7078
7079 // If we're supposed to bind temporaries, do so.
7080 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7081 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7082 return CurInit;
7083}
7084
7085/// Check whether elidable copy construction for binding a reference to
7086/// a temporary would have succeeded if we were building in C++98 mode, for
7087/// -Wc++98-compat.
7089 const InitializedEntity &Entity,
7090 Expr *CurInitExpr) {
7091 assert(S.getLangOpts().CPlusPlus11);
7092
7093 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
7094 if (!Record)
7095 return;
7096
7097 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7098 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7099 return;
7100
7101 // Find constructors which would have been considered.
7104 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
7105
7106 // Perform overload resolution.
7109 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7110 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7111 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7112 /*RequireActualConstructor=*/false,
7113 /*SecondStepOfCopyInit=*/true);
7114
7115 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7116 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7117 << CurInitExpr->getSourceRange();
7118
7119 switch (OR) {
7120 case OR_Success:
7121 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7122 Best->FoundDecl, Entity, Diag);
7123 // FIXME: Check default arguments as far as that's possible.
7124 break;
7125
7127 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7128 OCD_AllCandidates, CurInitExpr);
7129 break;
7130
7131 case OR_Ambiguous:
7132 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7133 OCD_AmbiguousCandidates, CurInitExpr);
7134 break;
7135
7136 case OR_Deleted:
7137 S.Diag(Loc, Diag);
7138 S.NoteDeletedFunction(Best->Function);
7139 break;
7140 }
7141}
7142
7143void InitializationSequence::PrintInitLocationNote(Sema &S,
7144 const InitializedEntity &Entity) {
7145 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7146 if (Entity.getDecl()->getLocation().isInvalid())
7147 return;
7148
7149 if (Entity.getDecl()->getDeclName())
7150 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7151 << Entity.getDecl()->getDeclName();
7152 else
7153 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7154 }
7155 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7156 Entity.getMethodDecl())
7157 S.Diag(Entity.getMethodDecl()->getLocation(),
7158 diag::note_method_return_type_change)
7159 << Entity.getMethodDecl()->getDeclName();
7160}
7161
7162/// Returns true if the parameters describe a constructor initialization of
7163/// an explicit temporary object, e.g. "Point(x, y)".
7164static bool isExplicitTemporary(const InitializedEntity &Entity,
7165 const InitializationKind &Kind,
7166 unsigned NumArgs) {
7167 switch (Entity.getKind()) {
7171 break;
7172 default:
7173 return false;
7174 }
7175
7176 switch (Kind.getKind()) {
7178 return true;
7179 // FIXME: Hack to work around cast weirdness.
7182 return NumArgs != 1;
7183 default:
7184 return false;
7185 }
7186}
7187
7188static ExprResult
7190 const InitializedEntity &Entity,
7191 const InitializationKind &Kind,
7192 MultiExprArg Args,
7193 const InitializationSequence::Step& Step,
7194 bool &ConstructorInitRequiresZeroInit,
7195 bool IsListInitialization,
7196 bool IsStdInitListInitialization,
7197 SourceLocation LBraceLoc,
7198 SourceLocation RBraceLoc) {
7199 unsigned NumArgs = Args.size();
7200 CXXConstructorDecl *Constructor
7201 = cast<CXXConstructorDecl>(Step.Function.Function);
7202 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7203
7204 // Build a call to the selected constructor.
7205 SmallVector<Expr*, 8> ConstructorArgs;
7206 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7207 ? Kind.getEqualLoc()
7208 : Kind.getLocation();
7209
7210 if (Kind.getKind() == InitializationKind::IK_Default) {
7211 // Force even a trivial, implicit default constructor to be
7212 // semantically checked. We do this explicitly because we don't build
7213 // the definition for completely trivial constructors.
7214 assert(Constructor->getParent() && "No parent class for constructor.");
7215 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7216 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7218 S.DefineImplicitDefaultConstructor(Loc, Constructor);
7219 });
7220 }
7221 }
7222
7223 ExprResult CurInit((Expr *)nullptr);
7224
7225 // C++ [over.match.copy]p1:
7226 // - When initializing a temporary to be bound to the first parameter
7227 // of a constructor that takes a reference to possibly cv-qualified
7228 // T as its first argument, called with a single argument in the
7229 // context of direct-initialization, explicit conversion functions
7230 // are also considered.
7231 bool AllowExplicitConv =
7232 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7235
7236 // A smart pointer constructed from a nullable pointer is nullable.
7237 if (NumArgs == 1 && !Kind.isExplicitCast())
7239 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7240
7241 // Determine the arguments required to actually perform the constructor
7242 // call.
7243 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7244 ConstructorArgs, AllowExplicitConv,
7245 IsListInitialization))
7246 return ExprError();
7247
7248 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7249 // An explicitly-constructed temporary, e.g., X(1, 2).
7251 return ExprError();
7252
7253 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7254 if (!TSInfo)
7255 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7256 SourceRange ParenOrBraceRange =
7257 (Kind.getKind() == InitializationKind::IK_DirectList)
7258 ? SourceRange(LBraceLoc, RBraceLoc)
7259 : Kind.getParenOrBraceRange();
7260
7261 CXXConstructorDecl *CalleeDecl = Constructor;
7262 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7263 Step.Function.FoundDecl.getDecl())) {
7264 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7265 }
7266 S.MarkFunctionReferenced(Loc, CalleeDecl);
7267
7268 CurInit = S.CheckForImmediateInvocation(
7270 S.Context, CalleeDecl,
7271 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7272 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7273 IsListInitialization, IsStdInitListInitialization,
7274 ConstructorInitRequiresZeroInit),
7275 CalleeDecl);
7276 } else {
7278
7279 if (Entity.getKind() == InitializedEntity::EK_Base) {
7280 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7283 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7284 ConstructKind = CXXConstructionKind::Delegating;
7285 }
7286
7287 // Only get the parenthesis or brace range if it is a list initialization or
7288 // direct construction.
7289 SourceRange ParenOrBraceRange;
7290 if (IsListInitialization)
7291 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7292 else if (Kind.getKind() == InitializationKind::IK_Direct)
7293 ParenOrBraceRange = Kind.getParenOrBraceRange();
7294
7295 // If the entity allows NRVO, mark the construction as elidable
7296 // unconditionally.
7297 if (Entity.allowsNRVO())
7298 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7299 Step.Function.FoundDecl,
7300 Constructor, /*Elidable=*/true,
7301 ConstructorArgs,
7302 HadMultipleCandidates,
7303 IsListInitialization,
7304 IsStdInitListInitialization,
7305 ConstructorInitRequiresZeroInit,
7306 ConstructKind,
7307 ParenOrBraceRange);
7308 else
7309 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7310 Step.Function.FoundDecl,
7311 Constructor,
7312 ConstructorArgs,
7313 HadMultipleCandidates,
7314 IsListInitialization,
7315 IsStdInitListInitialization,
7316 ConstructorInitRequiresZeroInit,
7317 ConstructKind,
7318 ParenOrBraceRange);
7319 }
7320 if (CurInit.isInvalid())
7321 return ExprError();
7322
7323 // Only check access if all of that succeeded.
7324 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7326 return ExprError();
7327
7328 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7330 return ExprError();
7331
7332 if (shouldBindAsTemporary(Entity))
7333 CurInit = S.MaybeBindToTemporary(CurInit.get());
7334
7335 return CurInit;
7336}
7337
7339 Expr *Init) {
7340 return sema::checkExprLifetime(*this, Entity, Init);
7341}
7342
7343static void DiagnoseNarrowingInInitList(Sema &S,
7344 const ImplicitConversionSequence &ICS,
7345 QualType PreNarrowingType,
7346 QualType EntityType,
7347 const Expr *PostInit);
7348
7349static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7350 QualType ToType, Expr *Init);
7351
7352/// Provide warnings when std::move is used on construction.
7353static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7354 bool IsReturnStmt) {
7355 if (!InitExpr)
7356 return;
7357
7359 return;
7360
7361 QualType DestType = InitExpr->getType();
7362 if (!DestType->isRecordType())
7363 return;
7364
7365 unsigned DiagID = 0;
7366 if (IsReturnStmt) {
7367 const CXXConstructExpr *CCE =
7368 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7369 if (!CCE || CCE->getNumArgs() != 1)
7370 return;
7371
7373 return;
7374
7375 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7376 }
7377
7378 // Find the std::move call and get the argument.
7379 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7380 if (!CE || !CE->isCallToStdMove())
7381 return;
7382
7383 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7384
7385 if (IsReturnStmt) {
7386 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7387 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7388 return;
7389
7390 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7391 if (!VD || !VD->hasLocalStorage())
7392 return;
7393
7394 // __block variables are not moved implicitly.
7395 if (VD->hasAttr<BlocksAttr>())
7396 return;
7397
7398 QualType SourceType = VD->getType();
7399 if (!SourceType->isRecordType())
7400 return;
7401
7402 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7403 return;
7404 }
7405
7406 // If we're returning a function parameter, copy elision
7407 // is not possible.
7408 if (isa<ParmVarDecl>(VD))
7409 DiagID = diag::warn_redundant_move_on_return;
7410 else
7411 DiagID = diag::warn_pessimizing_move_on_return;
7412 } else {
7413 DiagID = diag::warn_pessimizing_move_on_initialization;
7414 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7415 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7416 return;
7417 }
7418
7419 S.Diag(CE->getBeginLoc(), DiagID);
7420
7421 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7422 // is within a macro.
7423 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7424 if (CallBegin.isMacroID())
7425 return;
7426 SourceLocation RParen = CE->getRParenLoc();
7427 if (RParen.isMacroID())
7428 return;
7429 SourceLocation LParen;
7430 SourceLocation ArgLoc = Arg->getBeginLoc();
7431
7432 // Special testing for the argument location. Since the fix-it needs the
7433 // location right before the argument, the argument location can be in a
7434 // macro only if it is at the beginning of the macro.
7435 while (ArgLoc.isMacroID() &&
7438 }
7439
7440 if (LParen.isMacroID())
7441 return;
7442
7443 LParen = ArgLoc.getLocWithOffset(-1);
7444
7445 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7446 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7447 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7448}
7449
7451 // Check to see if we are dereferencing a null pointer. If so, this is
7452 // undefined behavior, so warn about it. This only handles the pattern
7453 // "*null", which is a very syntactic check.
7454 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7455 if (UO->getOpcode() == UO_Deref &&
7456 UO->getSubExpr()->IgnoreParenCasts()->
7457 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7458 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7459 S.PDiag(diag::warn_binding_null_to_reference)
7460 << UO->getSubExpr()->getSourceRange());
7461 }
7462}
7463
7466 bool BoundToLvalueReference) {
7467 auto MTE = new (Context)
7468 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7469
7470 // Order an ExprWithCleanups for lifetime marks.
7471 //
7472 // TODO: It'll be good to have a single place to check the access of the
7473 // destructor and generate ExprWithCleanups for various uses. Currently these
7474 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7475 // but there may be a chance to merge them.
7478 auto &Record = ExprEvalContexts.back();
7479 Record.ForRangeLifetimeExtendTemps.push_back(MTE);
7480 }
7481 return MTE;
7482}
7483
7485 // In C++98, we don't want to implicitly create an xvalue.
7486 // FIXME: This means that AST consumers need to deal with "prvalues" that
7487 // denote materialized temporaries. Maybe we should add another ValueKind
7488 // for "xvalue pretending to be a prvalue" for C++98 support.
7489 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
7490 return E;
7491
7492 // C++1z [conv.rval]/1: T shall be a complete type.
7493 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7494 // If so, we should check for a non-abstract class type here too.
7495 QualType T = E->getType();
7496 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7497 return ExprError();
7498
7499 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7500}
7501
7503 ExprValueKind VK,
7505
7506 CastKind CK = CK_NoOp;
7507
7508 if (VK == VK_PRValue) {
7509 auto PointeeTy = Ty->getPointeeType();
7510 auto ExprPointeeTy = E->getType()->getPointeeType();
7511 if (!PointeeTy.isNull() &&
7512 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7513 CK = CK_AddressSpaceConversion;
7514 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7515 CK = CK_AddressSpaceConversion;
7516 }
7517
7518 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7519}
7520
7522 const InitializedEntity &Entity,
7523 const InitializationKind &Kind,
7524 MultiExprArg Args,
7525 QualType *ResultType) {
7526 if (Failed()) {
7527 Diagnose(S, Entity, Kind, Args);
7528 return ExprError();
7529 }
7530 if (!ZeroInitializationFixit.empty()) {
7531 const Decl *D = Entity.getDecl();
7532 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7533 QualType DestType = Entity.getType();
7534
7535 // The initialization would have succeeded with this fixit. Since the fixit
7536 // is on the error, we need to build a valid AST in this case, so this isn't
7537 // handled in the Failed() branch above.
7538 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7539 // Use a more useful diagnostic for constexpr variables.
7540 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7541 << VD
7542 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7543 ZeroInitializationFixit);
7544 } else {
7545 unsigned DiagID = diag::err_default_init_const;
7546 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7547 DiagID = diag::ext_default_init_const;
7548
7549 S.Diag(Kind.getLocation(), DiagID)
7550 << DestType << (bool)DestType->getAs<RecordType>()
7551 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7552 ZeroInitializationFixit);
7553 }
7554 }
7555
7556 if (getKind() == DependentSequence) {
7557 // If the declaration is a non-dependent, incomplete array type
7558 // that has an initializer, then its type will be completed once
7559 // the initializer is instantiated.
7560 if (ResultType && !Entity.getType()->isDependentType() &&
7561 Args.size() == 1) {
7562 QualType DeclType = Entity.getType();
7563 if (const IncompleteArrayType *ArrayT
7564 = S.Context.getAsIncompleteArrayType(DeclType)) {
7565 // FIXME: We don't currently have the ability to accurately
7566 // compute the length of an initializer list without
7567 // performing full type-checking of the initializer list
7568 // (since we have to determine where braces are implicitly
7569 // introduced and such). So, we fall back to making the array
7570 // type a dependently-sized array type with no specified
7571 // bound.
7572 if (isa<InitListExpr>((Expr *)Args[0])) {
7573 SourceRange Brackets;
7574
7575 // Scavange the location of the brackets from the entity, if we can.
7576 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
7577 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7578 TypeLoc TL = TInfo->getTypeLoc();
7579 if (IncompleteArrayTypeLoc ArrayLoc =
7581 Brackets = ArrayLoc.getBracketsRange();
7582 }
7583 }
7584
7585 *ResultType
7586 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
7587 /*NumElts=*/nullptr,
7588 ArrayT->getSizeModifier(),
7589 ArrayT->getIndexTypeCVRQualifiers(),
7590 Brackets);
7591 }
7592
7593 }
7594 }
7595 if (Kind.getKind() == InitializationKind::IK_Direct &&
7596 !Kind.isExplicitCast()) {
7597 // Rebuild the ParenListExpr.
7598 SourceRange ParenRange = Kind.getParenOrBraceRange();
7599 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7600 Args);
7601 }
7602 assert(Kind.getKind() == InitializationKind::IK_Copy ||
7603 Kind.isExplicitCast() ||
7604 Kind.getKind() == InitializationKind::IK_DirectList);
7605 return ExprResult(Args[0]);
7606 }
7607
7608 // No steps means no initialization.
7609 if (Steps.empty())
7610 return ExprResult((Expr *)nullptr);
7611
7612 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7613 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7614 !Entity.isParamOrTemplateParamKind()) {
7615 // Produce a C++98 compatibility warning if we are initializing a reference
7616 // from an initializer list. For parameters, we produce a better warning
7617 // elsewhere.
7618 Expr *Init = Args[0];
7619 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7620 << Init->getSourceRange();
7621 }
7622
7623 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
7624 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
7625 // Produce a Microsoft compatibility warning when initializing from a
7626 // predefined expression since MSVC treats predefined expressions as string
7627 // literals.
7628 Expr *Init = Args[0];
7629 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
7630 }
7631
7632 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7633 QualType ETy = Entity.getType();
7634 bool HasGlobalAS = ETy.hasAddressSpace() &&
7636
7637 if (S.getLangOpts().OpenCLVersion >= 200 &&
7638 ETy->isAtomicType() && !HasGlobalAS &&
7639 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7640 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7641 << 1
7642 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7643 return ExprError();
7644 }
7645
7646 QualType DestType = Entity.getType().getNonReferenceType();
7647 // FIXME: Ugly hack around the fact that Entity.getType() is not
7648 // the same as Entity.getDecl()->getType() in cases involving type merging,
7649 // and we want latter when it makes sense.
7650 if (ResultType)
7651 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
7652 Entity.getType();
7653
7654 ExprResult CurInit((Expr *)nullptr);
7655 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
7656
7657 // HLSL allows vector initialization to function like list initialization, but
7658 // use the syntax of a C++-like constructor.
7659 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
7660 isa<InitListExpr>(Args[0]);
7661 (void)IsHLSLVectorInit;
7662
7663 // For initialization steps that start with a single initializer,
7664 // grab the only argument out the Args and place it into the "current"
7665 // initializer.
7666 switch (Steps.front().Kind) {
7671 case SK_BindReference:
7673 case SK_FinalCopy:
7675 case SK_UserConversion:
7684 case SK_UnwrapInitList:
7685 case SK_RewrapInitList:
7686 case SK_CAssignment:
7687 case SK_StringInit:
7689 case SK_ArrayLoopIndex:
7690 case SK_ArrayLoopInit:
7691 case SK_ArrayInit:
7692 case SK_GNUArrayInit:
7698 case SK_OCLSamplerInit:
7699 case SK_OCLZeroOpaqueType: {
7700 assert(Args.size() == 1 || IsHLSLVectorInit);
7701 CurInit = Args[0];
7702 if (!CurInit.get()) return ExprError();
7703 break;
7704 }
7705
7711 break;
7712 }
7713
7714 // Promote from an unevaluated context to an unevaluated list context in
7715 // C++11 list-initialization; we need to instantiate entities usable in
7716 // constant expressions here in order to perform narrowing checks =(
7719 isa_and_nonnull<InitListExpr>(CurInit.get()));
7720
7721 // C++ [class.abstract]p2:
7722 // no objects of an abstract class can be created except as subobjects
7723 // of a class derived from it
7724 auto checkAbstractType = [&](QualType T) -> bool {
7725 if (Entity.getKind() == InitializedEntity::EK_Base ||
7727 return false;
7728 return S.RequireNonAbstractType(Kind.getLocation(), T,
7729 diag::err_allocation_of_abstract_type);
7730 };
7731
7732 // Walk through the computed steps for the initialization sequence,
7733 // performing the specified conversions along the way.
7734 bool ConstructorInitRequiresZeroInit = false;
7735 for (step_iterator Step = step_begin(), StepEnd = step_end();
7736 Step != StepEnd; ++Step) {
7737 if (CurInit.isInvalid())
7738 return ExprError();
7739
7740 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
7741
7742 switch (Step->Kind) {
7744 // Overload resolution determined which function invoke; update the
7745 // initializer to reflect that choice.
7747 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7748 return ExprError();
7749 CurInit = S.FixOverloadedFunctionReference(CurInit,
7752 // We might get back another placeholder expression if we resolved to a
7753 // builtin.
7754 if (!CurInit.isInvalid())
7755 CurInit = S.CheckPlaceholderExpr(CurInit.get());
7756 break;
7757
7761 // We have a derived-to-base cast that produces either an rvalue or an
7762 // lvalue. Perform that cast.
7763
7764 CXXCastPath BasePath;
7765
7766 // Casts to inaccessible base classes are allowed with C-style casts.
7767 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
7769 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7770 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
7771 return ExprError();
7772
7773 ExprValueKind VK =
7775 ? VK_LValue
7777 : VK_PRValue);
7779 CK_DerivedToBase, CurInit.get(),
7780 &BasePath, VK, FPOptionsOverride());
7781 break;
7782 }
7783
7784 case SK_BindReference:
7785 // Reference binding does not have any corresponding ASTs.
7786
7787 // Check exception specifications
7788 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
7789 return ExprError();
7790
7791 // We don't check for e.g. function pointers here, since address
7792 // availability checks should only occur when the function first decays
7793 // into a pointer or reference.
7794 if (CurInit.get()->getType()->isFunctionProtoType()) {
7795 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7796 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7797 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7798 DRE->getBeginLoc()))
7799 return ExprError();
7800 }
7801 }
7802 }
7803
7804 CheckForNullPointerDereference(S, CurInit.get());
7805 break;
7806
7808 // Make sure the "temporary" is actually an rvalue.
7809 assert(CurInit.get()->isPRValue() && "not a temporary");
7810
7811 // Check exception specifications
7812 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
7813 return ExprError();
7814
7815 QualType MTETy = Step->Type;
7816
7817 // When this is an incomplete array type (such as when this is
7818 // initializing an array of unknown bounds from an init list), use THAT
7819 // type instead so that we propagate the array bounds.
7820 if (MTETy->isIncompleteArrayType() &&
7821 !CurInit.get()->getType()->isIncompleteArrayType() &&
7824 CurInit.get()->getType()->getPointeeOrArrayElementType()))
7825 MTETy = CurInit.get()->getType();
7826
7827 // Materialize the temporary into memory.
7829 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
7830 CurInit = MTE;
7831
7832 // If we're extending this temporary to automatic storage duration -- we
7833 // need to register its cleanup during the full-expression's cleanups.
7834 if (MTE->getStorageDuration() == SD_Automatic &&
7835 MTE->getType().isDestructedType())
7837 break;
7838 }
7839
7840 case SK_FinalCopy:
7841 if (checkAbstractType(Step->Type))
7842 return ExprError();
7843
7844 // If the overall initialization is initializing a temporary, we already
7845 // bound our argument if it was necessary to do so. If not (if we're
7846 // ultimately initializing a non-temporary), our argument needs to be
7847 // bound since it's initializing a function parameter.
7848 // FIXME: This is a mess. Rationalize temporary destruction.
7849 if (!shouldBindAsTemporary(Entity))
7850 CurInit = S.MaybeBindToTemporary(CurInit.get());
7851 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7852 /*IsExtraneousCopy=*/false);
7853 break;
7854
7856 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7857 /*IsExtraneousCopy=*/true);
7858 break;
7859
7860 case SK_UserConversion: {
7861 // We have a user-defined conversion that invokes either a constructor
7862 // or a conversion function.
7866 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
7867 bool CreatedObject = false;
7868 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
7869 // Build a call to the selected constructor.
7870 SmallVector<Expr*, 8> ConstructorArgs;
7871 SourceLocation Loc = CurInit.get()->getBeginLoc();
7872
7873 // Determine the arguments required to actually perform the constructor
7874 // call.
7875 Expr *Arg = CurInit.get();
7876 if (S.CompleteConstructorCall(Constructor, Step->Type,
7877 MultiExprArg(&Arg, 1), Loc,
7878 ConstructorArgs))
7879 return ExprError();
7880
7881 // Build an expression that constructs a temporary.
7882 CurInit = S.BuildCXXConstructExpr(
7883 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
7884 HadMultipleCandidates,
7885 /*ListInit*/ false,
7886 /*StdInitListInit*/ false,
7887 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7888 if (CurInit.isInvalid())
7889 return ExprError();
7890
7891 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7892 Entity);
7893 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7894 return ExprError();
7895
7896 CastKind = CK_ConstructorConversion;
7897 CreatedObject = true;
7898 } else {
7899 // Build a call to the conversion function.
7900 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
7901 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
7902 FoundFn);
7903 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7904 return ExprError();
7905
7906 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7907 HadMultipleCandidates);
7908 if (CurInit.isInvalid())
7909 return ExprError();
7910
7911 CastKind = CK_UserDefinedConversion;
7912 CreatedObject = Conversion->getReturnType()->isRecordType();
7913 }
7914
7915 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7916 return ExprError();
7917
7918 CurInit = ImplicitCastExpr::Create(
7919 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
7920 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
7921
7922 if (shouldBindAsTemporary(Entity))
7923 // The overall entity is temporary, so this expression should be
7924 // destroyed at the end of its full-expression.
7925 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7926 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7927 // The object outlasts the full-expression, but we need to prepare for
7928 // a destructor being run on it.
7929 // FIXME: It makes no sense to do this here. This should happen
7930 // regardless of how we initialized the entity.
7931 QualType T = CurInit.get()->getType();
7932 if (const RecordType *Record = T->getAs<RecordType>()) {
7934 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
7936 S.PDiag(diag::err_access_dtor_temp) << T);
7938 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
7939 return ExprError();
7940 }
7941 }
7942 break;
7943 }
7944
7948 // Perform a qualification conversion; these can never go wrong.
7949 ExprValueKind VK =
7951 ? VK_LValue
7953 : VK_PRValue);
7954 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
7955 break;
7956 }
7957
7959 assert(CurInit.get()->isLValue() &&
7960 "function reference should be lvalue");
7961 CurInit =
7962 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
7963 break;
7964
7965 case SK_AtomicConversion: {
7966 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
7967 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7968 CK_NonAtomicToAtomic, VK_PRValue);
7969 break;
7970 }
7971
7974 if (const auto *FromPtrType =
7975 CurInit.get()->getType()->getAs<PointerType>()) {
7976 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
7977 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
7978 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
7979 // Do not check static casts here because they are checked earlier
7980 // in Sema::ActOnCXXNamedCast()
7981 if (!Kind.isStaticCast()) {
7982 S.Diag(CurInit.get()->getExprLoc(),
7983 diag::warn_noderef_to_dereferenceable_pointer)
7984 << CurInit.get()->getSourceRange();
7985 }
7986 }
7987 }
7988 }
7989 Expr *Init = CurInit.get();
7991 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
7992 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
7993 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
7995 ExprResult CurInitExprRes = S.PerformImplicitConversion(
7996 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
7997 if (CurInitExprRes.isInvalid())
7998 return ExprError();
7999
8001
8002 CurInit = CurInitExprRes;
8003
8005 S.getLangOpts().CPlusPlus)
8006 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8007 CurInit.get());
8008
8009 break;
8010 }
8011
8012 case SK_ListInitialization: {
8013 if (checkAbstractType(Step->Type))
8014 return ExprError();
8015
8016 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8017 // If we're not initializing the top-level entity, we need to create an
8018 // InitializeTemporary entity for our target type.
8019 QualType Ty = Step->Type;
8020 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8022 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
8023 InitListChecker PerformInitList(S, InitEntity,
8024 InitList, Ty, /*VerifyOnly=*/false,
8025 /*TreatUnavailableAsInvalid=*/false);
8026 if (PerformInitList.HadError())
8027 return ExprError();
8028
8029 // Hack: We must update *ResultType if available in order to set the
8030 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8031 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8032 if (ResultType &&
8033 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8034 if ((*ResultType)->isRValueReferenceType())
8036 else if ((*ResultType)->isLValueReferenceType())
8038 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8039 *ResultType = Ty;
8040 }
8041
8042 InitListExpr *StructuredInitList =
8043 PerformInitList.getFullyStructuredList();
8044 CurInit.get();
8045 CurInit = shouldBindAsTemporary(InitEntity)
8046 ? S.MaybeBindToTemporary(StructuredInitList)
8047 : StructuredInitList;
8048 break;
8049 }
8050
8052 if (checkAbstractType(Step->Type))
8053 return ExprError();
8054
8055 // When an initializer list is passed for a parameter of type "reference
8056 // to object", we don't get an EK_Temporary entity, but instead an
8057 // EK_Parameter entity with reference type.
8058 // FIXME: This is a hack. What we really should do is create a user
8059 // conversion step for this case, but this makes it considerably more
8060 // complicated. For now, this will do.
8062 Entity.getType().getNonReferenceType());
8063 bool UseTemporary = Entity.getType()->isReferenceType();
8064 assert(Args.size() == 1 && "expected a single argument for list init");
8065 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8066 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8067 << InitList->getSourceRange();
8068 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8069 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8070 Entity,
8071 Kind, Arg, *Step,
8072 ConstructorInitRequiresZeroInit,
8073 /*IsListInitialization*/true,
8074 /*IsStdInitListInit*/false,
8075 InitList->getLBraceLoc(),
8076 InitList->getRBraceLoc());
8077 break;
8078 }
8079
8080 case SK_UnwrapInitList:
8081 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8082 break;
8083
8084 case SK_RewrapInitList: {
8085 Expr *E = CurInit.get();
8087 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8088 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8089 ILE->setSyntacticForm(Syntactic);
8090 ILE->setType(E->getType());
8091 ILE->setValueKind(E->getValueKind());
8092 CurInit = ILE;
8093 break;
8094 }
8095
8098 if (checkAbstractType(Step->Type))
8099 return ExprError();
8100
8101 // When an initializer list is passed for a parameter of type "reference
8102 // to object", we don't get an EK_Temporary entity, but instead an
8103 // EK_Parameter entity with reference type.
8104 // FIXME: This is a hack. What we really should do is create a user
8105 // conversion step for this case, but this makes it considerably more
8106 // complicated. For now, this will do.
8108 Entity.getType().getNonReferenceType());
8109 bool UseTemporary = Entity.getType()->isReferenceType();
8110 bool IsStdInitListInit =
8112 Expr *Source = CurInit.get();
8113 SourceRange Range = Kind.hasParenOrBraceRange()
8114 ? Kind.getParenOrBraceRange()
8115 : SourceRange();
8117 S, UseTemporary ? TempEntity : Entity, Kind,
8118 Source ? MultiExprArg(Source) : Args, *Step,
8119 ConstructorInitRequiresZeroInit,
8120 /*IsListInitialization*/ IsStdInitListInit,
8121 /*IsStdInitListInitialization*/ IsStdInitListInit,
8122 /*LBraceLoc*/ Range.getBegin(),
8123 /*RBraceLoc*/ Range.getEnd());
8124 break;
8125 }
8126
8127 case SK_ZeroInitialization: {
8128 step_iterator NextStep = Step;
8129 ++NextStep;
8130 if (NextStep != StepEnd &&
8131 (NextStep->Kind == SK_ConstructorInitialization ||
8132 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8133 // The need for zero-initialization is recorded directly into
8134 // the call to the object's constructor within the next step.
8135 ConstructorInitRequiresZeroInit = true;
8136 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8137 S.getLangOpts().CPlusPlus &&
8138 !Kind.isImplicitValueInit()) {
8139 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8140 if (!TSInfo)
8142 Kind.getRange().getBegin());
8143
8144 CurInit = new (S.Context) CXXScalarValueInitExpr(
8145 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8146 Kind.getRange().getEnd());
8147 } else {
8148 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8149 }
8150 break;
8151 }
8152
8153 case SK_CAssignment: {
8154 QualType SourceType = CurInit.get()->getType();
8155 Expr *Init = CurInit.get();
8156
8157 // Save off the initial CurInit in case we need to emit a diagnostic
8158 ExprResult InitialCurInit = Init;
8163 if (Result.isInvalid())
8164 return ExprError();
8165 CurInit = Result;
8166
8167 // If this is a call, allow conversion to a transparent union.
8168 ExprResult CurInitExprRes = CurInit;
8169 if (ConvTy != Sema::Compatible &&
8170 Entity.isParameterKind() &&
8173 ConvTy = Sema::Compatible;
8174 if (CurInitExprRes.isInvalid())
8175 return ExprError();
8176 CurInit = CurInitExprRes;
8177
8178 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8179 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8180 CurInit.get());
8181
8182 // C23 6.7.1p6: If an object or subobject declared with storage-class
8183 // specifier constexpr has pointer, integer, or arithmetic type, any
8184 // explicit initializer value for it shall be null, an integer
8185 // constant expression, or an arithmetic constant expression,
8186 // respectively.
8188 if (Entity.getType()->getAs<PointerType>() &&
8189 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8190 !ER.Val.isNullPointer()) {
8191 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8192 }
8193 }
8194
8195 bool Complained;
8196 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8197 Step->Type, SourceType,
8198 InitialCurInit.get(),
8199 getAssignmentAction(Entity, true),
8200 &Complained)) {
8201 PrintInitLocationNote(S, Entity);
8202 return ExprError();
8203 } else if (Complained)
8204 PrintInitLocationNote(S, Entity);
8205 break;
8206 }
8207
8208 case SK_StringInit: {
8209 QualType Ty = Step->Type;
8210 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8211 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8212 S.Context.getAsArrayType(Ty), S,
8213 S.getLangOpts().C23 &&
8215 break;
8216 }
8217
8219 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8220 CK_ObjCObjectLValueCast,
8221 CurInit.get()->getValueKind());
8222 break;
8223
8224 case SK_ArrayLoopIndex: {
8225 Expr *Cur = CurInit.get();
8226 Expr *BaseExpr = new (S.Context)
8227 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8228 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8229 Expr *IndexExpr =
8232 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8233 ArrayLoopCommonExprs.push_back(BaseExpr);
8234 break;
8235 }
8236
8237 case SK_ArrayLoopInit: {
8238 assert(!ArrayLoopCommonExprs.empty() &&
8239 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8240 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8241 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8242 CurInit.get());
8243 break;
8244 }
8245
8246 case SK_GNUArrayInit:
8247 // Okay: we checked everything before creating this step. Note that
8248 // this is a GNU extension.
8249 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8250 << Step->Type << CurInit.get()->getType()
8251 << CurInit.get()->getSourceRange();
8253 [[fallthrough]];
8254 case SK_ArrayInit:
8255 // If the destination type is an incomplete array type, update the
8256 // type accordingly.
8257 if (ResultType) {
8258 if (const IncompleteArrayType *IncompleteDest
8260 if (const ConstantArrayType *ConstantSource
8261 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8262 *ResultType = S.Context.getConstantArrayType(
8263 IncompleteDest->getElementType(), ConstantSource->getSize(),
8264 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8265 }
8266 }
8267 }
8268 break;
8269
8271 // Okay: we checked everything before creating this step. Note that
8272 // this is a GNU extension.
8273 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8274 << CurInit.get()->getSourceRange();
8275 break;
8276
8279 checkIndirectCopyRestoreSource(S, CurInit.get());
8280 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8281 CurInit.get(), Step->Type,
8283 break;
8284
8286 CurInit = ImplicitCastExpr::Create(
8287 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8289 break;
8290
8291 case SK_StdInitializerList: {
8292 S.Diag(CurInit.get()->getExprLoc(),
8293 diag::warn_cxx98_compat_initializer_list_init)
8294 << CurInit.get()->getSourceRange();
8295
8296 // Materialize the temporary into memory.
8298 CurInit.get()->getType(), CurInit.get(),
8299 /*BoundToLvalueReference=*/false);
8300
8301 // Wrap it in a construction of a std::initializer_list<T>.
8302 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8303
8304 if (!Step->Type->isDependentType()) {
8305 QualType ElementType;
8306 [[maybe_unused]] bool IsStdInitializerList =
8307 S.isStdInitializerList(Step->Type, &ElementType);
8308 assert(IsStdInitializerList &&
8309 "StdInitializerList step to non-std::initializer_list");
8310 const CXXRecordDecl *Record =
8312 assert(Record && Record->isCompleteDefinition() &&
8313 "std::initializer_list should have already be "
8314 "complete/instantiated by this point");
8315
8316 auto InvalidType = [&] {
8317 S.Diag(Record->getLocation(),
8318 diag::err_std_initializer_list_malformed)
8320 return ExprError();
8321 };
8322
8323 if (Record->isUnion() || Record->getNumBases() != 0 ||
8324 Record->isPolymorphic())
8325 return InvalidType();
8326
8327 RecordDecl::field_iterator Field = Record->field_begin();
8328 if (Field == Record->field_end())
8329 return InvalidType();
8330
8331 // Start pointer
8332 if (!Field->getType()->isPointerType() ||
8333 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8334 ElementType.withConst()))
8335 return InvalidType();
8336
8337 if (++Field == Record->field_end())
8338 return InvalidType();
8339
8340 // Size or end pointer
8341 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8342 if (!S.Context.hasSameType(PT->getPointeeType(),
8343 ElementType.withConst()))
8344 return InvalidType();
8345 } else {
8346 if (Field->isBitField() ||
8347 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8348 return InvalidType();
8349 }
8350
8351 if (++Field != Record->field_end())
8352 return InvalidType();
8353 }
8354
8355 // Bind the result, in case the library has given initializer_list a
8356 // non-trivial destructor.
8357 if (shouldBindAsTemporary(Entity))
8358 CurInit = S.MaybeBindToTemporary(CurInit.get());
8359 break;
8360 }
8361
8362 case SK_OCLSamplerInit: {
8363 // Sampler initialization have 5 cases:
8364 // 1. function argument passing
8365 // 1a. argument is a file-scope variable
8366 // 1b. argument is a function-scope variable
8367 // 1c. argument is one of caller function's parameters
8368 // 2. variable initialization
8369 // 2a. initializing a file-scope variable
8370 // 2b. initializing a function-scope variable
8371 //
8372 // For file-scope variables, since they cannot be initialized by function
8373 // call of __translate_sampler_initializer in LLVM IR, their references
8374 // need to be replaced by a cast from their literal initializers to
8375 // sampler type. Since sampler variables can only be used in function
8376 // calls as arguments, we only need to replace them when handling the
8377 // argument passing.
8378 assert(Step->Type->isSamplerT() &&
8379 "Sampler initialization on non-sampler type.");
8380 Expr *Init = CurInit.get()->IgnoreParens();
8381 QualType SourceType = Init->getType();
8382 // Case 1
8383 if (Entity.isParameterKind()) {
8384 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8385 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8386 << SourceType;
8387 break;
8388 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8389 auto Var = cast<VarDecl>(DRE->getDecl());
8390 // Case 1b and 1c
8391 // No cast from integer to sampler is needed.
8392 if (!Var->hasGlobalStorage()) {
8393 CurInit = ImplicitCastExpr::Create(
8394 S.Context, Step->Type, CK_LValueToRValue, Init,
8395 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8396 break;
8397 }
8398 // Case 1a
8399 // For function call with a file-scope sampler variable as argument,
8400 // get the integer literal.
8401 // Do not diagnose if the file-scope variable does not have initializer
8402 // since this has already been diagnosed when parsing the variable
8403 // declaration.
8404 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8405 break;
8406 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8407 Var->getInit()))->getSubExpr();
8408 SourceType = Init->getType();
8409 }
8410 } else {
8411 // Case 2
8412 // Check initializer is 32 bit integer constant.
8413 // If the initializer is taken from global variable, do not diagnose since
8414 // this has already been done when parsing the variable declaration.
8415 if (!Init->isConstantInitializer(S.Context, false))
8416 break;
8417
8418 if (!SourceType->isIntegerType() ||
8419 32 != S.Context.getIntWidth(SourceType)) {
8420 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8421 << SourceType;
8422 break;
8423 }
8424
8425 Expr::EvalResult EVResult;
8426 Init->EvaluateAsInt(EVResult, S.Context);
8427 llvm::APSInt Result = EVResult.Val.getInt();
8428 const uint64_t SamplerValue = Result.getLimitedValue();
8429 // 32-bit value of sampler's initializer is interpreted as
8430 // bit-field with the following structure:
8431 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8432 // |31 6|5 4|3 1| 0|
8433 // This structure corresponds to enum values of sampler properties
8434 // defined in SPIR spec v1.2 and also opencl-c.h
8435 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8436 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8437 if (FilterMode != 1 && FilterMode != 2 &&
8439 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8440 S.Diag(Kind.getLocation(),
8441 diag::warn_sampler_initializer_invalid_bits)
8442 << "Filter Mode";
8443 if (AddressingMode > 4)
8444 S.Diag(Kind.getLocation(),
8445 diag::warn_sampler_initializer_invalid_bits)
8446 << "Addressing Mode";
8447 }
8448
8449 // Cases 1a, 2a and 2b
8450 // Insert cast from integer to sampler.
8452 CK_IntToOCLSampler);
8453 break;
8454 }
8455 case SK_OCLZeroOpaqueType: {
8456 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8458 "Wrong type for initialization of OpenCL opaque type.");
8459
8460 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8461 CK_ZeroToOCLOpaqueType,
8462 CurInit.get()->getValueKind());
8463 break;
8464 }
8466 CurInit = nullptr;
8467 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8468 /*VerifyOnly=*/false, &CurInit);
8469 if (CurInit.get() && ResultType)
8470 *ResultType = CurInit.get()->getType();
8471 if (shouldBindAsTemporary(Entity))
8472 CurInit = S.MaybeBindToTemporary(CurInit.get());
8473 break;
8474 }
8475 }
8476 }
8477
8478 Expr *Init = CurInit.get();
8479 if (!Init)
8480 return ExprError();
8481
8482 // Check whether the initializer has a shorter lifetime than the initialized
8483 // entity, and if not, either lifetime-extend or warn as appropriate.
8484 S.checkInitializerLifetime(Entity, Init);
8485
8486 // Diagnose non-fatal problems with the completed initialization.
8487 if (InitializedEntity::EntityKind EK = Entity.getKind();
8490 cast<FieldDecl>(Entity.getDecl())->isBitField())
8491 S.CheckBitFieldInitialization(Kind.getLocation(),
8492 cast<FieldDecl>(Entity.getDecl()), Init);
8493
8494 // Check for std::move on construction.
8497
8498 return Init;
8499}
8500
8501/// Somewhere within T there is an uninitialized reference subobject.
8502/// Dig it out and diagnose it.
8504 QualType T) {
8505 if (T->isReferenceType()) {
8506 S.Diag(Loc, diag::err_reference_without_init)
8507 << T.getNonReferenceType();
8508 return true;
8509 }
8510
8512 if (!RD || !RD->hasUninitializedReferenceMember())
8513 return false;
8514
8515 for (const auto *FI : RD->fields()) {
8516 if (FI->isUnnamedBitField())
8517 continue;
8518
8519 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8520 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8521 return true;
8522 }
8523 }
8524
8525 for (const auto &BI : RD->bases()) {
8526 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8527 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8528 return true;
8529 }
8530 }
8531
8532 return false;
8533}
8534
8535
8536//===----------------------------------------------------------------------===//
8537// Diagnose initialization failures
8538//===----------------------------------------------------------------------===//
8539
8540/// Emit notes associated with an initialization that failed due to a
8541/// "simple" conversion failure.
8542static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8543 Expr *op) {
8544 QualType destType = entity.getType();
8545 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8547
8548 // Emit a possible note about the conversion failing because the
8549 // operand is a message send with a related result type.
8551
8552 // Emit a possible note about a return failing because we're
8553 // expecting a related result type.
8554 if (entity.getKind() == InitializedEntity::EK_Result)
8556 }
8557 QualType fromType = op->getType();
8558 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8559 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8560 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8561 auto *destDecl = destType->getPointeeCXXRecordDecl();
8562 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8563 destDecl->getDeclKind() == Decl::CXXRecord &&
8564 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8565 !fromDecl->hasDefinition() &&
8566 destPointeeType.getQualifiers().compatiblyIncludes(
8567 fromPointeeType.getQualifiers()))
8568 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8569 << S.getASTContext().getTagDeclType(fromDecl)
8570 << S.getASTContext().getTagDeclType(destDecl);
8571}
8572
8573static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8574 InitListExpr *InitList) {
8575 QualType DestType = Entity.getType();
8576
8577 QualType E;
8578 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8580 E.withConst(),
8581 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8582 InitList->getNumInits()),
8584 InitializedEntity HiddenArray =
8586 return diagnoseListInit(S, HiddenArray, InitList);
8587 }
8588
8589 if (DestType->isReferenceType()) {
8590 // A list-initialization failure for a reference means that we tried to
8591 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8592 // inner initialization failed.
8593 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8595 SourceLocation Loc = InitList->getBeginLoc();
8596 if (auto *D = Entity.getDecl())
8597 Loc = D->getLocation();
8598 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8599 return;
8600 }
8601
8602 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8603 /*VerifyOnly=*/false,
8604 /*TreatUnavailableAsInvalid=*/false);
8605 assert(DiagnoseInitList.HadError() &&
8606 "Inconsistent init list check result.");
8607}
8608
8610 const InitializedEntity &Entity,
8611 const InitializationKind &Kind,
8612 ArrayRef<Expr *> Args) {
8613 if (!Failed())
8614 return false;
8615
8616 QualType DestType = Entity.getType();
8617
8618 // When we want to diagnose only one element of a braced-init-list,
8619 // we need to factor it out.
8620 Expr *OnlyArg;
8621 if (Args.size() == 1) {
8622 auto *List = dyn_cast<InitListExpr>(Args[0]);
8623 if (List && List->getNumInits() == 1)
8624 OnlyArg = List->getInit(0);
8625 else
8626 OnlyArg = Args[0];
8627
8628 if (OnlyArg->getType() == S.Context.OverloadTy) {
8631 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
8632 Found)) {
8633 if (Expr *Resolved =
8634 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
8635 OnlyArg = Resolved;
8636 }
8637 }
8638 }
8639 else
8640 OnlyArg = nullptr;
8641
8642 switch (Failure) {
8644 // FIXME: Customize for the initialized entity?
8645 if (Args.empty()) {
8646 // Dig out the reference subobject which is uninitialized and diagnose it.
8647 // If this is value-initialization, this could be nested some way within
8648 // the target type.
8649 assert(Kind.getKind() == InitializationKind::IK_Value ||
8650 DestType->isReferenceType());
8651 bool Diagnosed =
8652 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8653 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8654 (void)Diagnosed;
8655 } else // FIXME: diagnostic below could be better!
8656 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
8657 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8658 break;
8660 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8661 << 1 << Entity.getType() << Args[0]->getSourceRange();
8662 break;
8663
8665 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
8666 break;
8668 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8669 break;
8671 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8672 break;
8674 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8675 break;
8677 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8678 break;
8680 S.Diag(Kind.getLocation(),
8681 diag::err_array_init_incompat_wide_string_into_wchar);
8682 break;
8684 S.Diag(Kind.getLocation(),
8685 diag::err_array_init_plain_string_into_char8_t);
8686 S.Diag(Args.front()->getBeginLoc(),
8687 diag::note_array_init_plain_string_into_char8_t)
8688 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
8689 break;
8691 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
8692 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
8693 break;
8696 S.Diag(Kind.getLocation(),
8697 (Failure == FK_ArrayTypeMismatch
8698 ? diag::err_array_init_different_type
8699 : diag::err_array_init_non_constant_array))
8700 << DestType.getNonReferenceType()
8701 << OnlyArg->getType()
8702 << Args[0]->getSourceRange();
8703 break;
8704
8706 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8707 << Args[0]->getSourceRange();
8708 break;
8709
8713 DestType.getNonReferenceType(),
8714 true,
8715 Found);
8716 break;
8717 }
8718
8720 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8721 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8722 OnlyArg->getBeginLoc());
8723 break;
8724 }
8725
8728 switch (FailedOverloadResult) {
8729 case OR_Ambiguous:
8730
8731 FailedCandidateSet.NoteCandidates(
8733 Kind.getLocation(),
8735 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8736 << OnlyArg->getType() << DestType
8737 << Args[0]->getSourceRange())
8738 : (S.PDiag(diag::err_ref_init_ambiguous)
8739 << DestType << OnlyArg->getType()
8740 << Args[0]->getSourceRange())),
8741 S, OCD_AmbiguousCandidates, Args);
8742 break;
8743
8744 case OR_No_Viable_Function: {
8745 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
8746 if (!S.RequireCompleteType(Kind.getLocation(),
8747 DestType.getNonReferenceType(),
8748 diag::err_typecheck_nonviable_condition_incomplete,
8749 OnlyArg->getType(), Args[0]->getSourceRange()))
8750 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
8751 << (Entity.getKind() == InitializedEntity::EK_Result)
8752 << OnlyArg->getType() << Args[0]->getSourceRange()
8753 << DestType.getNonReferenceType();
8754
8755 FailedCandidateSet.NoteCandidates(S, Args, Cands);
8756 break;
8757 }
8758 case OR_Deleted: {
8761 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8762
8763 StringLiteral *Msg = Best->Function->getDeletedMessage();
8764 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
8765 << OnlyArg->getType() << DestType.getNonReferenceType()
8766 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
8767 << Args[0]->getSourceRange();
8768 if (Ovl == OR_Deleted) {
8769 S.NoteDeletedFunction(Best->Function);
8770 } else {
8771 llvm_unreachable("Inconsistent overload resolution?");
8772 }
8773 break;
8774 }
8775
8776 case OR_Success:
8777 llvm_unreachable("Conversion did not fail!");
8778 }
8779 break;
8780
8782 if (isa<InitListExpr>(Args[0])) {
8783 S.Diag(Kind.getLocation(),
8784 diag::err_lvalue_reference_bind_to_initlist)
8786 << DestType.getNonReferenceType()
8787 << Args[0]->getSourceRange();
8788 break;
8789 }
8790 [[fallthrough]];
8791
8793 S.Diag(Kind.getLocation(),
8795 ? diag::err_lvalue_reference_bind_to_temporary
8796 : diag::err_lvalue_reference_bind_to_unrelated)
8798 << DestType.getNonReferenceType()
8799 << OnlyArg->getType()
8800 << Args[0]->getSourceRange();
8801 break;
8802
8804 // We don't necessarily have an unambiguous source bit-field.
8805 FieldDecl *BitField = Args[0]->getSourceBitField();
8806 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8807 << DestType.isVolatileQualified()
8808 << (BitField ? BitField->getDeclName() : DeclarationName())
8809 << (BitField != nullptr)
8810 << Args[0]->getSourceRange();
8811 if (BitField)
8812 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8813 break;
8814 }
8815
8817 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8818 << DestType.isVolatileQualified()
8819 << Args[0]->getSourceRange();
8820 break;
8821
8823 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
8824 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
8825 break;
8826
8828 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
8829 << DestType.getNonReferenceType() << OnlyArg->getType()
8830 << Args[0]->getSourceRange();
8831 break;
8832
8834 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
8835 << DestType << Args[0]->getSourceRange();
8836 break;
8837
8839 QualType SourceType = OnlyArg->getType();
8840 QualType NonRefType = DestType.getNonReferenceType();
8841 Qualifiers DroppedQualifiers =
8842 SourceType.getQualifiers() - NonRefType.getQualifiers();
8843
8844 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
8845 SourceType.getQualifiers()))
8846 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8847 << NonRefType << SourceType << 1 /*addr space*/
8848 << Args[0]->getSourceRange();
8849 else if (DroppedQualifiers.hasQualifiers())
8850 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8851 << NonRefType << SourceType << 0 /*cv quals*/
8852 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
8853 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
8854 else
8855 // FIXME: Consider decomposing the type and explaining which qualifiers
8856 // were dropped where, or on which level a 'const' is missing, etc.
8857 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8858 << NonRefType << SourceType << 2 /*incompatible quals*/
8859 << Args[0]->getSourceRange();
8860 break;
8861 }
8862
8864 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8865 << DestType.getNonReferenceType()
8866 << DestType.getNonReferenceType()->isIncompleteType()
8867 << OnlyArg->isLValue()
8868 << OnlyArg->getType()
8869 << Args[0]->getSourceRange();
8870 emitBadConversionNotes(S, Entity, Args[0]);
8871 break;
8872
8873 case FK_ConversionFailed: {
8874 QualType FromType = OnlyArg->getType();
8875 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
8876 << (int)Entity.getKind()
8877 << DestType
8878 << OnlyArg->isLValue()
8879 << FromType
8880 << Args[0]->getSourceRange();
8881 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8882 S.Diag(Kind.getLocation(), PDiag);
8883 emitBadConversionNotes(S, Entity, Args[0]);
8884 break;
8885 }
8886
8888 // No-op. This error has already been reported.
8889 break;
8890
8892 SourceRange R;
8893
8894 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
8895 if (InitList && InitList->getNumInits() >= 1) {
8896 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
8897 } else {
8898 assert(Args.size() > 1 && "Expected multiple initializers!");
8899 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
8900 }
8901
8903 if (Kind.isCStyleOrFunctionalCast())
8904 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8905 << R;
8906 else
8907 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8908 << /*scalar=*/2 << R;
8909 break;
8910 }
8911
8913 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8914 << 0 << Entity.getType() << Args[0]->getSourceRange();
8915 break;
8916
8918 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8919 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8920 break;
8921
8923 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8924 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8925 break;
8926
8929 SourceRange ArgsRange;
8930 if (Args.size())
8931 ArgsRange =
8932 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8933
8934 if (Failure == FK_ListConstructorOverloadFailed) {
8935 assert(Args.size() == 1 &&
8936 "List construction from other than 1 argument.");
8937 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8938 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
8939 }
8940
8941 // FIXME: Using "DestType" for the entity we're printing is probably
8942 // bad.
8943 switch (FailedOverloadResult) {
8944 case OR_Ambiguous:
8945 FailedCandidateSet.NoteCandidates(
8946 PartialDiagnosticAt(Kind.getLocation(),
8947 S.PDiag(diag::err_ovl_ambiguous_init)
8948 << DestType << ArgsRange),
8949 S, OCD_AmbiguousCandidates, Args);
8950 break;
8951
8953 if (Kind.getKind() == InitializationKind::IK_Default &&
8954 (Entity.getKind() == InitializedEntity::EK_Base ||
8957 isa<CXXConstructorDecl>(S.CurContext)) {
8958 // This is implicit default initialization of a member or
8959 // base within a constructor. If no viable function was
8960 // found, notify the user that they need to explicitly
8961 // initialize this base/member.
8962 CXXConstructorDecl *Constructor
8963 = cast<CXXConstructorDecl>(S.CurContext);
8964 const CXXRecordDecl *InheritedFrom = nullptr;
8965 if (auto Inherited = Constructor->getInheritedConstructor())
8966 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
8967 if (Entity.getKind() == InitializedEntity::EK_Base) {
8968 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
8969 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8970 << S.Context.getTypeDeclType(Constructor->getParent())
8971 << /*base=*/0
8972 << Entity.getType()
8973 << InheritedFrom;
8974
8975 RecordDecl *BaseDecl
8976 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
8977 ->getDecl();
8978 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8979 << S.Context.getTagDeclType(BaseDecl);
8980 } else {
8981 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
8982 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8983 << S.Context.getTypeDeclType(Constructor->getParent())
8984 << /*member=*/1
8985 << Entity.getName()
8986 << InheritedFrom;
8987 S.Diag(Entity.getDecl()->getLocation(),
8988 diag::note_member_declared_at);
8989
8990 if (const RecordType *Record
8991 = Entity.getType()->getAs<RecordType>())
8992 S.Diag(Record->getDecl()->getLocation(),
8993 diag::note_previous_decl)
8994 << S.Context.getTagDeclType(Record->getDecl());
8995 }
8996 break;
8997 }
8998
8999 FailedCandidateSet.NoteCandidates(
9001 Kind.getLocation(),
9002 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9003 << DestType << ArgsRange),
9004 S, OCD_AllCandidates, Args);
9005 break;
9006
9007 case OR_Deleted: {
9010 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9011 if (Ovl != OR_Deleted) {
9012 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9013 << DestType << ArgsRange;
9014 llvm_unreachable("Inconsistent overload resolution?");
9015 break;
9016 }
9017
9018 // If this is a defaulted or implicitly-declared function, then
9019 // it was implicitly deleted. Make it clear that the deletion was
9020 // implicit.
9021 if (S.isImplicitlyDeleted(Best->Function))
9022 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9023 << llvm::to_underlying(
9024 S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)))
9025 << DestType << ArgsRange;
9026 else {
9027 StringLiteral *Msg = Best->Function->getDeletedMessage();
9028 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9029 << DestType << (Msg != nullptr)
9030 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9031 }
9032
9033 S.NoteDeletedFunction(Best->Function);
9034 break;
9035 }
9036
9037 case OR_Success:
9038 llvm_unreachable("Conversion did not fail!");
9039 }
9040 }
9041 break;
9042
9044 if (Entity.getKind() == InitializedEntity::EK_Member &&
9045 isa<CXXConstructorDecl>(S.CurContext)) {
9046 // This is implicit default-initialization of a const member in
9047 // a constructor. Complain that it needs to be explicitly
9048 // initialized.
9049 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9050 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9051 << (Constructor->getInheritedConstructor() ? 2 :
9052 Constructor->isImplicit() ? 1 : 0)
9053 << S.Context.getTypeDeclType(Constructor->getParent())
9054 << /*const=*/1
9055 << Entity.getName();
9056 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9057 << Entity.getName();
9058 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9059 VD && VD->isConstexpr()) {
9060 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9061 << VD;
9062 } else {
9063 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9064 << DestType << (bool)DestType->getAs<RecordType>();
9065 }
9066 break;
9067
9068 case FK_Incomplete:
9069 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9070 diag::err_init_incomplete_type);
9071 break;
9072
9074 // Run the init list checker again to emit diagnostics.
9075 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9076 diagnoseListInit(S, Entity, InitList);
9077 break;
9078 }
9079
9080 case FK_PlaceholderType: {
9081 // FIXME: Already diagnosed!
9082 break;
9083 }
9084
9086 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9087 << Args[0]->getSourceRange();
9090 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9091 (void)Ovl;
9092 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9093 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9094 S.Diag(CtorDecl->getLocation(),
9095 diag::note_explicit_ctor_deduction_guide_here) << false;
9096 break;
9097 }
9098
9100 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9101 /*VerifyOnly=*/false);
9102 break;
9103
9105 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9106 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9107 << Entity.getType() << InitList->getSourceRange();
9108 break;
9109 }
9110
9111 PrintInitLocationNote(S, Entity);
9112 return true;
9113}
9114
9115void InitializationSequence::dump(raw_ostream &OS) const {
9116 switch (SequenceKind) {
9117 case FailedSequence: {
9118 OS << "Failed sequence: ";
9119 switch (Failure) {
9121 OS << "too many initializers for reference";
9122 break;
9123
9125 OS << "parenthesized list init for reference";
9126 break;
9127
9129 OS << "array requires initializer list";
9130 break;
9131
9133 OS << "address of unaddressable function was taken";
9134 break;
9135
9137 OS << "array requires initializer list or string literal";
9138 break;
9139
9141 OS << "array requires initializer list or wide string literal";
9142 break;
9143
9145 OS << "narrow string into wide char array";
9146 break;
9147
9149 OS << "wide string into char array";
9150 break;
9151
9153 OS << "incompatible wide string into wide char array";
9154 break;
9155
9157 OS << "plain string literal into char8_t array";
9158 break;
9159
9161 OS << "u8 string literal into char array";
9162 break;
9163
9165 OS << "array type mismatch";
9166 break;
9167
9169 OS << "non-constant array initializer";
9170 break;
9171
9173 OS << "address of overloaded function failed";
9174 break;
9175
9177 OS << "overload resolution for reference initialization failed";
9178 break;
9179
9181 OS << "non-const lvalue reference bound to temporary";
9182 break;
9183
9185 OS << "non-const lvalue reference bound to bit-field";
9186 break;
9187
9189 OS << "non-const lvalue reference bound to vector element";
9190 break;
9191
9193 OS << "non-const lvalue reference bound to matrix element";
9194 break;
9195
9197 OS << "non-const lvalue reference bound to unrelated type";
9198 break;
9199
9201 OS << "rvalue reference bound to an lvalue";
9202 break;
9203
9205 OS << "reference initialization drops qualifiers";
9206 break;
9207
9209 OS << "reference with mismatching address space bound to temporary";
9210 break;
9211
9213 OS << "reference initialization failed";
9214 break;
9215
9217 OS << "conversion failed";
9218 break;
9219
9221 OS << "conversion from property failed";
9222 break;
9223
9225 OS << "too many initializers for scalar";
9226 break;
9227
9229 OS << "parenthesized list init for reference";
9230 break;
9231
9233 OS << "referencing binding to initializer list";
9234 break;
9235
9237 OS << "initializer list for non-aggregate, non-scalar type";
9238 break;
9239
9241 OS << "overloading failed for user-defined conversion";
9242 break;
9243
9245 OS << "constructor overloading failed";
9246 break;
9247
9249 OS << "default initialization of a const variable";
9250 break;
9251
9252 case FK_Incomplete:
9253 OS << "initialization of incomplete type";
9254 break;
9255
9257 OS << "list initialization checker failure";
9258 break;
9259
9261 OS << "variable length array has an initializer";
9262 break;
9263
9264 case FK_PlaceholderType:
9265 OS << "initializer expression isn't contextually valid";
9266 break;
9267
9269 OS << "list constructor overloading failed";
9270 break;
9271
9273 OS << "list copy initialization chose explicit constructor";
9274 break;
9275
9277 OS << "parenthesized list initialization failed";
9278 break;
9279
9281 OS << "designated initializer for non-aggregate type";
9282 break;
9283 }
9284 OS << '\n';
9285 return;
9286 }
9287
9288 case DependentSequence:
9289 OS << "Dependent sequence\n";
9290 return;
9291
9292 case NormalSequence:
9293 OS << "Normal sequence: ";
9294 break;
9295 }
9296
9297 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9298 if (S != step_begin()) {
9299 OS << " -> ";
9300 }
9301
9302 switch (S->Kind) {
9304 OS << "resolve address of overloaded function";
9305 break;
9306
9308 OS << "derived-to-base (prvalue)";
9309 break;
9310
9312 OS << "derived-to-base (xvalue)";
9313 break;
9314
9316 OS << "derived-to-base (lvalue)";
9317 break;
9318
9319 case SK_BindReference:
9320 OS << "bind reference to lvalue";
9321 break;
9322
9324 OS << "bind reference to a temporary";
9325 break;
9326
9327 case SK_FinalCopy:
9328 OS << "final copy in class direct-initialization";
9329 break;
9330
9332 OS << "extraneous C++03 copy to temporary";
9333 break;
9334
9335 case SK_UserConversion:
9336 OS << "user-defined conversion via " << *S->Function.Function;
9337 break;
9338
9340 OS << "qualification conversion (prvalue)";
9341 break;
9342
9344 OS << "qualification conversion (xvalue)";
9345 break;
9346
9348 OS << "qualification conversion (lvalue)";
9349 break;
9350
9352 OS << "function reference conversion";
9353 break;
9354
9356 OS << "non-atomic-to-atomic conversion";
9357 break;
9358
9360 OS << "implicit conversion sequence (";
9361 S->ICS->dump(); // FIXME: use OS
9362 OS << ")";
9363 break;
9364
9366 OS << "implicit conversion sequence with narrowing prohibited (";
9367 S->ICS->dump(); // FIXME: use OS
9368 OS << ")";
9369 break;
9370
9372 OS << "list aggregate initialization";
9373 break;
9374
9375 case SK_UnwrapInitList:
9376 OS << "unwrap reference initializer list";
9377 break;
9378
9379 case SK_RewrapInitList:
9380 OS << "rewrap reference initializer list";
9381 break;
9382
9384 OS << "constructor initialization";
9385 break;
9386
9388 OS << "list initialization via constructor";
9389 break;
9390
9392 OS << "zero initialization";
9393 break;
9394
9395 case SK_CAssignment:
9396 OS << "C assignment";
9397 break;
9398
9399 case SK_StringInit:
9400 OS << "string initialization";
9401 break;
9402
9404 OS << "Objective-C object conversion";
9405 break;
9406
9407 case SK_ArrayLoopIndex:
9408 OS << "indexing for array initialization loop";
9409 break;
9410
9411 case SK_ArrayLoopInit:
9412 OS << "array initialization loop";
9413 break;
9414
9415 case SK_ArrayInit:
9416 OS << "array initialization";
9417 break;
9418
9419 case SK_GNUArrayInit:
9420 OS << "array initialization (GNU extension)";
9421 break;
9422
9424 OS << "parenthesized array initialization";
9425 break;
9426
9428 OS << "pass by indirect copy and restore";
9429 break;
9430
9432 OS << "pass by indirect restore";
9433 break;
9434
9436 OS << "Objective-C object retension";
9437 break;
9438
9440 OS << "std::initializer_list from initializer list";
9441 break;
9442
9444 OS << "list initialization from std::initializer_list";
9445 break;
9446
9447 case SK_OCLSamplerInit:
9448 OS << "OpenCL sampler_t from integer constant";
9449 break;
9450
9452 OS << "OpenCL opaque type from zero";
9453 break;
9455 OS << "initialization from a parenthesized list of values";
9456 break;
9457 }
9458
9459 OS << " [" << S->Type << ']';
9460 }
9461
9462 OS << '\n';
9463}
9464
9466 dump(llvm::errs());
9467}
9468
9470 const ImplicitConversionSequence &ICS,
9471 QualType PreNarrowingType,
9472 QualType EntityType,
9473 const Expr *PostInit) {
9474 const StandardConversionSequence *SCS = nullptr;
9475 switch (ICS.getKind()) {
9477 SCS = &ICS.Standard;
9478 break;
9480 SCS = &ICS.UserDefined.After;
9481 break;
9486 return;
9487 }
9488
9489 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9490 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9491 unsigned DiagID;
9492 auto &L = S.getLangOpts();
9493 if (L.CPlusPlus11 &&
9494 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9495 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9496 else
9497 DiagID = WarnDiagID;
9498 return S.Diag(PostInit->getBeginLoc(), DiagID)
9499 << PostInit->getSourceRange();
9500 };
9501
9502 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9503 APValue ConstantValue;
9504 QualType ConstantType;
9505 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9506 ConstantType)) {
9507 case NK_Not_Narrowing:
9509 // No narrowing occurred.
9510 return;
9511
9512 case NK_Type_Narrowing: {
9513 // This was a floating-to-integer conversion, which is always considered a
9514 // narrowing conversion even if the value is a constant and can be
9515 // represented exactly as an integer.
9516 QualType T = EntityType.getNonReferenceType();
9517 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9518 diag::ext_init_list_type_narrowing_const_reference,
9519 diag::warn_init_list_type_narrowing)
9520 << PreNarrowingType.getLocalUnqualifiedType()
9521 << T.getLocalUnqualifiedType();
9522 break;
9523 }
9524
9525 case NK_Constant_Narrowing: {
9526 // A constant value was narrowed.
9527 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9528 diag::ext_init_list_constant_narrowing,
9529 diag::ext_init_list_constant_narrowing_const_reference,
9530 diag::warn_init_list_constant_narrowing)
9531 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9533 break;
9534 }
9535
9536 case NK_Variable_Narrowing: {
9537 // A variable's value may have been narrowed.
9538 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9539 diag::ext_init_list_variable_narrowing,
9540 diag::ext_init_list_variable_narrowing_const_reference,
9541 diag::warn_init_list_variable_narrowing)
9542 << PreNarrowingType.getLocalUnqualifiedType()
9544 break;
9545 }
9546 }
9547
9548 SmallString<128> StaticCast;
9549 llvm::raw_svector_ostream OS(StaticCast);
9550 OS << "static_cast<";
9551 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9552 // It's important to use the typedef's name if there is one so that the
9553 // fixit doesn't break code using types like int64_t.
9554 //
9555 // FIXME: This will break if the typedef requires qualification. But
9556 // getQualifiedNameAsString() includes non-machine-parsable components.
9557 OS << *TT->getDecl();
9558 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9559 OS << BT->getName(S.getLangOpts());
9560 else {
9561 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9562 // with a broken cast.
9563 return;
9564 }
9565 OS << ">(";
9566 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9567 << PostInit->getSourceRange()
9568 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9570 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9571}
9572
9574 QualType ToType, Expr *Init) {
9575 assert(S.getLangOpts().C23);
9577 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
9578 Sema::AllowedExplicit::None,
9579 /*InOverloadResolution*/ false,
9580 /*CStyle*/ false,
9581 /*AllowObjCWritebackConversion=*/false);
9582
9583 if (!ICS.isStandard())
9584 return;
9585
9586 APValue Value;
9587 QualType PreNarrowingType;
9588 // Reuse C++ narrowing check.
9589 switch (ICS.Standard.getNarrowingKind(
9590 S.Context, Init, Value, PreNarrowingType,
9591 /*IgnoreFloatToIntegralConversion*/ false)) {
9592 // The value doesn't fit.
9594 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
9595 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
9596 return;
9597
9598 // Conversion to a narrower type.
9599 case NK_Type_Narrowing:
9600 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
9601 << ToType << FromType;
9602 return;
9603
9604 // Since we only reuse narrowing check for C23 constexpr variables here, we're
9605 // not really interested in these cases.
9608 case NK_Not_Narrowing:
9609 return;
9610 }
9611 llvm_unreachable("unhandled case in switch");
9612}
9613
9615 Sema &SemaRef, QualType &TT) {
9616 assert(SemaRef.getLangOpts().C23);
9617 // character that string literal contains fits into TT - target type.
9618 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
9619 QualType CharType = AT->getElementType();
9620 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
9621 bool isUnsigned = CharType->isUnsignedIntegerType();
9622 llvm::APSInt Value(BitWidth, isUnsigned);
9623 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
9624 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
9625 Value = C;
9626 if (Value != C) {
9627 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
9628 diag::err_c23_constexpr_init_not_representable)
9629 << C << CharType;
9630 return;
9631 }
9632 }
9633 return;
9634}
9635
9636//===----------------------------------------------------------------------===//
9637// Initialization helper functions
9638//===----------------------------------------------------------------------===//
9639bool
9641 ExprResult Init) {
9642 if (Init.isInvalid())
9643 return false;
9644
9645 Expr *InitE = Init.get();
9646 assert(InitE && "No initialization expression");
9647
9648 InitializationKind Kind =
9650 InitializationSequence Seq(*this, Entity, Kind, InitE);
9651 return !Seq.Failed();
9652}
9653
9656 SourceLocation EqualLoc,
9658 bool TopLevelOfInitList,
9659 bool AllowExplicit) {
9660 if (Init.isInvalid())
9661 return ExprError();
9662
9663 Expr *InitE = Init.get();
9664 assert(InitE && "No initialization expression?");
9665
9666 if (EqualLoc.isInvalid())
9667 EqualLoc = InitE->getBeginLoc();
9668
9670 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9671 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
9672
9673 // Prevent infinite recursion when performing parameter copy-initialization.
9674 const bool ShouldTrackCopy =
9675 Entity.isParameterKind() && Seq.isConstructorInitialization();
9676 if (ShouldTrackCopy) {
9677 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
9678 Seq.SetOverloadFailure(
9681
9682 // Try to give a meaningful diagnostic note for the problematic
9683 // constructor.
9684 const auto LastStep = Seq.step_end() - 1;
9685 assert(LastStep->Kind ==
9687 const FunctionDecl *Function = LastStep->Function.Function;
9688 auto Candidate =
9689 llvm::find_if(Seq.getFailedCandidateSet(),
9690 [Function](const OverloadCandidate &Candidate) -> bool {
9691 return Candidate.Viable &&
9692 Candidate.Function == Function &&
9693 Candidate.Conversions.size() > 0;
9694 });
9695 if (Candidate != Seq.getFailedCandidateSet().end() &&
9696 Function->getNumParams() > 0) {
9697 Candidate->Viable = false;
9700 InitE,
9701 Function->getParamDecl(0)->getType());
9702 }
9703 }
9704 CurrentParameterCopyTypes.push_back(Entity.getType());
9705 }
9706
9707 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
9708
9709 if (ShouldTrackCopy)
9710 CurrentParameterCopyTypes.pop_back();
9711
9712 return Result;
9713}
9714
9715/// Determine whether RD is, or is derived from, a specialization of CTD.
9717 ClassTemplateDecl *CTD) {
9718 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9719 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9720 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9721 };
9722 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9723}
9724
9726 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9727 const InitializationKind &Kind, MultiExprArg Inits) {
9728 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9729 TSInfo->getType()->getContainedDeducedType());
9730 assert(DeducedTST && "not a deduced template specialization type");
9731
9732 auto TemplateName = DeducedTST->getTemplateName();
9734 return SubstAutoTypeDependent(TSInfo->getType());
9735
9736 // We can only perform deduction for class templates or alias templates.
9737 auto *Template =
9738 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9739 TemplateDecl *LookupTemplateDecl = Template;
9740 if (!Template) {
9741 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
9743 Diag(Kind.getLocation(),
9744 diag::warn_cxx17_compat_ctad_for_alias_templates);
9745 LookupTemplateDecl = AliasTemplate;
9746 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
9747 ->getUnderlyingType()
9748 .getCanonicalType();
9749 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
9750 // of the form
9751 // [typename] [nested-name-specifier] [template] simple-template-id
9752 if (const auto *TST =
9753 UnderlyingType->getAs<TemplateSpecializationType>()) {
9754 Template = dyn_cast_or_null<ClassTemplateDecl>(
9755 TST->getTemplateName().getAsTemplateDecl());
9756 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
9757 // Cases where template arguments in the RHS of the alias are not
9758 // dependent. e.g.
9759 // using AliasFoo = Foo<bool>;
9760 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
9761 RT->getAsCXXRecordDecl()))
9762 Template = CTSD->getSpecializedTemplate();
9763 }
9764 }
9765 }
9766 if (!Template) {
9767 Diag(Kind.getLocation(),
9768 diag::err_deduced_non_class_or_alias_template_specialization_type)
9770 if (auto *TD = TemplateName.getAsTemplateDecl())
9772 return QualType();
9773 }
9774
9775 // Can't deduce from dependent arguments.
9777 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9778 diag::warn_cxx14_compat_class_template_argument_deduction)
9779 << TSInfo->getTypeLoc().getSourceRange() << 0;
9780 return SubstAutoTypeDependent(TSInfo->getType());
9781 }
9782
9783 // FIXME: Perform "exact type" matching first, per CWG discussion?
9784 // Or implement this via an implied 'T(T) -> T' deduction guide?
9785
9786 // Look up deduction guides, including those synthesized from constructors.
9787 //
9788 // C++1z [over.match.class.deduct]p1:
9789 // A set of functions and function templates is formed comprising:
9790 // - For each constructor of the class template designated by the
9791 // template-name, a function template [...]
9792 // - For each deduction-guide, a function or function template [...]
9793 DeclarationNameInfo NameInfo(
9795 TSInfo->getTypeLoc().getEndLoc());
9796 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9797 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
9798
9799 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9800 // clear on this, but they're not found by name so access does not apply.
9801 Guides.suppressDiagnostics();
9802
9803 // Figure out if this is list-initialization.
9805 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9806 ? dyn_cast<InitListExpr>(Inits[0])
9807 : nullptr;
9808
9809 // C++1z [over.match.class.deduct]p1:
9810 // Initialization and overload resolution are performed as described in
9811 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9812 // (as appropriate for the type of initialization performed) for an object
9813 // of a hypothetical class type, where the selected functions and function
9814 // templates are considered to be the constructors of that class type
9815 //
9816 // Since we know we're initializing a class type of a type unrelated to that
9817 // of the initializer, this reduces to something fairly reasonable.
9818 OverloadCandidateSet Candidates(Kind.getLocation(),
9821
9822 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
9823
9824 // Return true if the candidate is added successfully, false otherwise.
9825 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
9827 DeclAccessPair FoundDecl,
9828 bool OnlyListConstructors,
9829 bool AllowAggregateDeductionCandidate) {
9830 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9831 // For copy-initialization, the candidate functions are all the
9832 // converting constructors (12.3.1) of that class.
9833 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9834 // The converting constructors of T are candidate functions.
9835 if (!AllowExplicit) {
9836 // Overload resolution checks whether the deduction guide is declared
9837 // explicit for us.
9838
9839 // When looking for a converting constructor, deduction guides that
9840 // could never be called with one argument are not interesting to
9841 // check or note.
9842 if (GD->getMinRequiredArguments() > 1 ||
9843 (GD->getNumParams() == 0 && !GD->isVariadic()))
9844 return;
9845 }
9846
9847 // C++ [over.match.list]p1.1: (first phase list initialization)
9848 // Initially, the candidate functions are the initializer-list
9849 // constructors of the class T
9850 if (OnlyListConstructors && !isInitListConstructor(GD))
9851 return;
9852
9853 if (!AllowAggregateDeductionCandidate &&
9854 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
9855 return;
9856
9857 // C++ [over.match.list]p1.2: (second phase list initialization)
9858 // the candidate functions are all the constructors of the class T
9859 // C++ [over.match.ctor]p1: (all other cases)
9860 // the candidate functions are all the constructors of the class of
9861 // the object being initialized
9862
9863 // C++ [over.best.ics]p4:
9864 // When [...] the constructor [...] is a candidate by
9865 // - [over.match.copy] (in all cases)
9866 if (TD) {
9867 SmallVector<Expr *, 8> TmpInits;
9868 for (Expr *E : Inits)
9869 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
9870 TmpInits.push_back(DI->getInit());
9871 else
9872 TmpInits.push_back(E);
9874 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
9875 /*SuppressUserConversions=*/false,
9876 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
9877 /*PO=*/{}, AllowAggregateDeductionCandidate);
9878 } else {
9879 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
9880 /*SuppressUserConversions=*/false,
9881 /*PartialOverloading=*/false, AllowExplicit);
9882 }
9883 };
9884
9885 bool FoundDeductionGuide = false;
9886
9887 auto TryToResolveOverload =
9888 [&](bool OnlyListConstructors) -> OverloadingResult {
9890 bool HasAnyDeductionGuide = false;
9891
9892 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
9893 auto *Pattern = Template;
9894 while (Pattern->getInstantiatedFromMemberTemplate()) {
9895 if (Pattern->isMemberSpecialization())
9896 break;
9897 Pattern = Pattern->getInstantiatedFromMemberTemplate();
9898 }
9899
9900 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
9901 if (!(RD->getDefinition() && RD->isAggregate()))
9902 return;
9904 SmallVector<QualType, 8> ElementTypes;
9905
9906 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
9907 if (!CheckInitList.HadError()) {
9908 // C++ [over.match.class.deduct]p1.8:
9909 // if e_i is of array type and x_i is a braced-init-list, T_i is an
9910 // rvalue reference to the declared type of e_i and
9911 // C++ [over.match.class.deduct]p1.9:
9912 // if e_i is of array type and x_i is a string-literal, T_i is an
9913 // lvalue reference to the const-qualified declared type of e_i and
9914 // C++ [over.match.class.deduct]p1.10:
9915 // otherwise, T_i is the declared type of e_i
9916 for (int I = 0, E = ListInit->getNumInits();
9917 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
9918 if (ElementTypes[I]->isArrayType()) {
9919 if (isa<InitListExpr, DesignatedInitExpr>(ListInit->getInit(I)))
9920 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
9921 else if (isa<StringLiteral>(
9922 ListInit->getInit(I)->IgnoreParenImpCasts()))
9923 ElementTypes[I] =
9924 Context.getLValueReferenceType(ElementTypes[I].withConst());
9925 }
9926
9927 if (FunctionTemplateDecl *TD =
9929 LookupTemplateDecl, ElementTypes,
9930 TSInfo->getTypeLoc().getEndLoc())) {
9931 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
9932 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
9933 OnlyListConstructors,
9934 /*AllowAggregateDeductionCandidate=*/true);
9935 HasAnyDeductionGuide = true;
9936 }
9937 }
9938 };
9939
9940 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9941 NamedDecl *D = (*I)->getUnderlyingDecl();
9942 if (D->isInvalidDecl())
9943 continue;
9944
9945 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9946 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
9947 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9948 if (!GD)
9949 continue;
9950
9951 if (!GD->isImplicit())
9952 HasAnyDeductionGuide = true;
9953
9954 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
9955 /*AllowAggregateDeductionCandidate=*/false);
9956 }
9957
9958 // C++ [over.match.class.deduct]p1.4:
9959 // if C is defined and its definition satisfies the conditions for an
9960 // aggregate class ([dcl.init.aggr]) with the assumption that any
9961 // dependent base class has no virtual functions and no virtual base
9962 // classes, and the initializer is a non-empty braced-init-list or
9963 // parenthesized expression-list, and there are no deduction-guides for
9964 // C, the set contains an additional function template, called the
9965 // aggregate deduction candidate, defined as follows.
9966 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
9967 if (ListInit && ListInit->getNumInits()) {
9968 SynthesizeAggrGuide(ListInit);
9969 } else if (Inits.size()) { // parenthesized expression-list
9970 // Inits are expressions inside the parentheses. We don't have
9971 // the parentheses source locations, use the begin/end of Inits as the
9972 // best heuristic.
9973 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
9974 Inits, Inits.back()->getEndLoc());
9975 SynthesizeAggrGuide(&TempListInit);
9976 }
9977 }
9978
9979 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
9980
9981 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9982 };
9983
9985
9986 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9987 // try initializer-list constructors.
9988 if (ListInit) {
9989 bool TryListConstructors = true;
9990
9991 // Try list constructors unless the list is empty and the class has one or
9992 // more default constructors, in which case those constructors win.
9993 if (!ListInit->getNumInits()) {
9994 for (NamedDecl *D : Guides) {
9995 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9996 if (FD && FD->getMinRequiredArguments() == 0) {
9997 TryListConstructors = false;
9998 break;
9999 }
10000 }
10001 } else if (ListInit->getNumInits() == 1) {
10002 // C++ [over.match.class.deduct]:
10003 // As an exception, the first phase in [over.match.list] (considering
10004 // initializer-list constructors) is omitted if the initializer list
10005 // consists of a single expression of type cv U, where U is a
10006 // specialization of C or a class derived from a specialization of C.
10007 Expr *E = ListInit->getInit(0);
10008 auto *RD = E->getType()->getAsCXXRecordDecl();
10009 if (!isa<InitListExpr>(E) && RD &&
10010 isCompleteType(Kind.getLocation(), E->getType()) &&
10012 TryListConstructors = false;
10013 }
10014
10015 if (TryListConstructors)
10016 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10017 // Then unwrap the initializer list and try again considering all
10018 // constructors.
10019 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10020 }
10021
10022 // If list-initialization fails, or if we're doing any other kind of
10023 // initialization, we (eventually) consider constructors.
10025 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10026
10027 switch (Result) {
10028 case OR_Ambiguous:
10029 // FIXME: For list-initialization candidates, it'd usually be better to
10030 // list why they were not viable when given the initializer list itself as
10031 // an argument.
10032 Candidates.NoteCandidates(
10034 Kind.getLocation(),
10035 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10036 << TemplateName),
10037 *this, OCD_AmbiguousCandidates, Inits);
10038 return QualType();
10039
10040 case OR_No_Viable_Function: {
10041 CXXRecordDecl *Primary =
10042 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10043 bool Complete =
10044 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10045 Candidates.NoteCandidates(
10047 Kind.getLocation(),
10048 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10049 : diag::err_deduced_class_template_incomplete)
10050 << TemplateName << !Guides.empty()),
10051 *this, OCD_AllCandidates, Inits);
10052 return QualType();
10053 }
10054
10055 case OR_Deleted: {
10056 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10057 // like we ever get here; attempts to trigger this seem to yield a
10058 // generic c'all to deleted function' diagnostic instead.
10059 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10060 << TemplateName;
10061 NoteDeletedFunction(Best->Function);
10062 return QualType();
10063 }
10064
10065 case OR_Success:
10066 // C++ [over.match.list]p1:
10067 // In copy-list-initialization, if an explicit constructor is chosen, the
10068 // initialization is ill-formed.
10069 if (Kind.isCopyInit() && ListInit &&
10070 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10071 bool IsDeductionGuide = !Best->Function->isImplicit();
10072 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10073 << TemplateName << IsDeductionGuide;
10074 Diag(Best->Function->getLocation(),
10075 diag::note_explicit_ctor_deduction_guide_here)
10076 << IsDeductionGuide;
10077 return QualType();
10078 }
10079
10080 // Make sure we didn't select an unusable deduction guide, and mark it
10081 // as referenced.
10082 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10083 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10084 break;
10085 }
10086
10087 // C++ [dcl.type.class.deduct]p1:
10088 // The placeholder is replaced by the return type of the function selected
10089 // by overload resolution for class template deduction.
10091 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10092 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10093 diag::warn_cxx14_compat_class_template_argument_deduction)
10094 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10095
10096 // Warn if CTAD was used on a type that does not have any user-defined
10097 // deduction guides.
10098 if (!FoundDeductionGuide) {
10099 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10100 diag::warn_ctad_maybe_unsupported)
10101 << TemplateName;
10102 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10103 }
10104
10105 return DeducedType;
10106}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
const Decl * D
Expr * E
static bool isRValueRef(QualType ParamType)
Definition: Consumed.cpp:181
Defines the clang::Expr interface and subclasses for C++ expressions.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:558
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
Definition: SemaInit.cpp:6274
static void updateStringLiteralType(Expr *E, QualType Ty)
Update the type of a string literal, including any surrounding parentheses, to match the type of the ...
Definition: SemaInit.cpp:175
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition: SemaInit.cpp:187
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition: SemaInit.cpp:196
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, SourceRange Braces)
Warn that Entity was of scalar type and was initialized by a single-element braced initializer list.
Definition: SemaInit.cpp:1205
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
Definition: SemaInit.cpp:6846
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
Definition: SemaInit.cpp:6879
static bool hasAnyDesignatedInits(const InitListExpr *IL)
Definition: SemaInit.cpp:1008
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
Definition: SemaInit.cpp:6156
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
Definition: SemaInit.cpp:2611
static ExprResult CopyObject(Sema &S, QualType T, const InitializedEntity &Entity, ExprResult CurInit, bool IsExtraneousCopy)
Make a (potentially elidable) temporary copy of the object provided by the given initializer by calli...
Definition: SemaInit.cpp:6937
static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
Definition: SemaInit.cpp:6757
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
Definition: SemaInit.cpp:5597
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
Definition: SemaInit.cpp:7353
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
Definition: SemaInit.cpp:9614
static void CheckCXX98CompatAccessibleCopy(Sema &S, const InitializedEntity &Entity, Expr *CurInitExpr)
Check whether elidable copy construction for binding a reference to a temporary would have succeeded ...
Definition: SemaInit.cpp:7088
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
Definition: SemaInit.cpp:9716
static bool canInitializeArrayWithEmbedDataString(ArrayRef< Expr * > ExprList, const InitializedEntity &Entity, ASTContext &Context)
Definition: SemaInit.cpp:2000
static bool TryInitializerListConstruction(Sema &S, InitListExpr *List, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
When initializing from init list via constructor, handle initialization of an object of type std::ini...
Definition: SemaInit.cpp:4182
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, ASTContext &Context)
Check whether the array of type AT can be initialized by the Init expression by means of string initi...
Definition: SemaInit.cpp:75
StringInitFailureKind
Definition: SemaInit.cpp:61
@ SIF_None
Definition: SemaInit.cpp:62
@ SIF_PlainStringIntoUTF8Char
Definition: SemaInit.cpp:67
@ SIF_IncompatWideStringIntoWideChar
Definition: SemaInit.cpp:65
@ SIF_UTF8StringIntoPlainChar
Definition: SemaInit.cpp:66
@ SIF_NarrowStringIntoWideChar
Definition: SemaInit.cpp:63
@ SIF_Other
Definition: SemaInit.cpp:68
@ SIF_WideStringIntoChar
Definition: SemaInit.cpp:64
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
Definition: SemaInit.cpp:5559
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6203
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
Definition: SemaInit.cpp:4122
static ExprResult CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value)
Check that the given Index expression is a valid array designator value.
Definition: SemaInit.cpp:3461
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
Definition: SemaInit.cpp:6285
static bool IsZeroInitializer(Expr *Initializer, Sema &S)
Definition: SemaInit.cpp:6216
static void TryReferenceInitializationCore(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, QualType cv1T1, QualType T1, Qualifiers T1Quals, QualType cv2T2, QualType T2, Qualifiers T2Quals, InitializationSequence &Sequence, bool TopLevelOfInitList)
Reference initialization without resolving overloaded functions.
Definition: SemaInit.cpp:5148
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
Definition: SemaInit.cpp:9573
static void ExpandAnonymousFieldDesignator(Sema &SemaRef, DesignatedInitExpr *DIE, unsigned DesigIdx, IndirectFieldDecl *IndirectField)
Expand a field designator that refers to a member of an anonymous struct or union into a series of fi...
Definition: SemaInit.cpp:2583
static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList=nullptr)
Attempt value initialization (C++ [dcl.init]p7).
Definition: SemaInit.cpp:5481
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5853
static OverloadingResult ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, MultiExprArg Args, OverloadCandidateSet &CandidateSet, QualType DestType, DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, bool IsListInit, bool RequireActualConstructor, bool SecondStepOfCopyInit=false)
Definition: SemaInit.cpp:4230
static void TryListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization (C++0x [dcl.init.list])
Definition: SemaInit.cpp:4708
static void TryStringLiteralInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence)
Attempt character array initialization from a string literal (C++ [dcl.init.string],...
Definition: SemaInit.cpp:5472
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, Sema &SemaRef)
Check if the type of a class element has an accessible destructor, and marks it referenced.
Definition: SemaInit.cpp:1982
static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt reference initialization (C++0x [dcl.init.ref])
Definition: SemaInit.cpp:5110
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
Definition: SemaInit.cpp:9469
static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, const ArrayType *Source)
Determine whether we have compatible array types for the purposes of GNU by-copy array initialization...
Definition: SemaInit.cpp:6140
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, bool CheckC23ConstexprInit=false)
Definition: SemaInit.cpp:214
static bool isExplicitTemporary(const InitializedEntity &Entity, const InitializationKind &Kind, unsigned NumArgs)
Returns true if the parameters describe a constructor initialization of an explicit temporary object,...
Definition: SemaInit.cpp:7164
static bool isNonReferenceableGLValue(Expr *E)
Determine whether an expression is a non-referenceable glvalue (one to which a reference can never bi...
Definition: SemaInit.cpp:5139
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6221
static bool IsWideCharCompatible(QualType T, ASTContext &Context)
Check whether T is compatible with a wide character type (wchar_t, char16_t or char32_t).
Definition: SemaInit.cpp:51
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
Definition: SemaInit.cpp:8573
static OverloadingResult TryRefInitWithConversionFunction(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, bool AllowRValues, bool IsLValueRef, InitializationSequence &Sequence)
Try a reference initialization that involves calling a conversion function.
Definition: SemaInit.cpp:4925
static void TryConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, QualType DestArrayType, InitializationSequence &Sequence, bool IsListInit=false, bool IsInitListCopy=false)
Attempt initialization by constructor (C++ [dcl.init]), which enumerates the constructors of the init...
Definition: SemaInit.cpp:4344
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, Expr *op)
Emit notes associated with an initialization that failed due to a "simple" conversion failure.
Definition: SemaInit.cpp:8542
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity)
Determine whether Entity is an entity for which it is idiomatic to elide the braces in aggregate init...
Definition: SemaInit.cpp:1082
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Definition: SemaInit.cpp:4142
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
Definition: SemaInit.cpp:6122
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
Definition: SemaInit.cpp:6812
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
Definition: SemaInit.cpp:4560
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
Definition: SemaInit.cpp:6052
@ IIK_okay
Definition: SemaInit.cpp:6052
@ IIK_nonlocal
Definition: SemaInit.cpp:6052
@ IIK_nonscalar
Definition: SemaInit.cpp:6052
static ExprResult PerformConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, const InitializationSequence::Step &Step, bool &ConstructorInitRequiresZeroInit, bool IsListInitialization, bool IsStdInitListInitialization, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
Definition: SemaInit.cpp:7189
static void TryReferenceListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization of a reference.
Definition: SemaInit.cpp:4605
static bool isLibstdcxxPointerReturnFalseHack(Sema &S, const InitializedEntity &Entity, const Expr *Init)
An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, a function with a pointer...
Definition: SemaInit.cpp:6040
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, const ConstructorInfo &Info)
Determine if the constructor has the signature of a copy or move constructor for the type T of the cl...
Definition: SemaInit.cpp:4217
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
Definition: SemaInit.cpp:8503
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
Definition: SemaInit.cpp:6055
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
__device__ int
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isNullPointer() const
Definition: APValue.cpp:1010
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
QualType getRecordType(const RecordDecl *Decl) const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType Char16Ty
Definition: ASTContext.h:1126
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2831
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1128
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
CanQualType OverloadTy
Definition: ASTContext.h:1147
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CanQualType OCLSamplerTy
Definition: ASTContext.h:1156
CanQualType VoidTy
Definition: ASTContext.h:1119
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2828
CanQualType Char32Ty
Definition: ASTContext.h:1127
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1847
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2398
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5756
Represents a loop initializing the elements of an array.
Definition: Expr.h:5703
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
QualType getElementType() const
Definition: Type.h:3578
This class is used for builtin types like 'int'.
Definition: Type.h:3023
Kind getKind() const
Definition: Type.h:3071
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1689
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1609
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1686
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2781
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2618
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2811
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2906
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1956
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition: ExprCXX.cpp:1934
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasUninitializedReferenceMember() const
Whether this class or any of its subobjects has any members of reference type which would make value-...
Definition: DeclCXX.h:1163
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1396
base_class_range bases()
Definition: DeclCXX.h:620
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1872
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
llvm::iterator_range< base_class_iterator > base_class_range
Definition: DeclCXX.h:616
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:618
bool forallBases(ForallBasesCallback BaseMatches) const
Determines if the given callback holds for all the direct or indirect base classes of this type.
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2181
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
static CXXTemporaryObjectExpr * Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef< Expr * > Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization)
Definition: ExprCXX.cpp:1126
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3021
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
bool isCallToStdMove() const
Definition: Expr.cpp:3521
Expr * getCallee()
Definition: Expr.h:2980
SourceLocation getRParenLoc() const
Definition: Expr.h:3145
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
SourceLocation getBegin() const
Declaration of a class template.
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
QualType getElementType() const
Definition: Type.h:3144
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:218
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3680
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
virtual std::unique_ptr< CorrectionCandidateCallback > clone()=0
Clone this CorrectionCandidateCallback.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2307
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:2025
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1463
ValueDecl * getDecl()
Definition: Expr.h:1333
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:455
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool hasAttr() const
Definition: DeclBase.h:584
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6341
Represents a single C99 designator.
Definition: Expr.h:5327
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:5489
SourceLocation getFieldLoc() const
Definition: Expr.h:5435
SourceLocation getDotLoc() const
Definition: Expr.h:5430
Represents a C99 designated initializer expression.
Definition: Expr.h:5284
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition: Expr.h:5544
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:4672
void setInit(Expr *init)
Definition: Expr.h:5556
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:5566
llvm::MutableArrayRef< Designator > designators()
Definition: Expr.h:5517
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition: Expr.h:5548
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:4667
void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last)
Replaces the designator at index Idx with the series of designators in [First, Last).
Definition: Expr.cpp:4679
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4605
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4662
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:5525
Expr * getInit() const
Retrieve the initializer value.
Definition: Expr.h:5552
unsigned size() const
Returns the number of designators in this initializer.
Definition: Expr.h:5514
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4641
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4658
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition: Expr.h:5539
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition: Expr.h:5564
InitListExpr * getUpdater() const
Definition: Expr.h:5671
Designation - Represent a full designation, which is a sequence of designators.
Definition: Designator.h:208
const Designator & getDesignator(unsigned Idx) const
Definition: Designator.h:219
unsigned getNumDesignators() const
Definition: Designator.h:218
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
Definition: Designator.h:115
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Represents a reference to #emded data.
Definition: Expr.h:4867
StringLiteral * getDataStringLiteral() const
Definition: Expr.h:4884
EmbedDataStorage * getData() const
Definition: Expr.h:4885
SourceLocation getLocation() const
Definition: Expr.h:4880
size_t getDataElementCount() const
Definition: Expr.h:4888
RAII object that enters a new expression evaluation context.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:4156
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3058
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3290
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3567
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3204
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3941
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToMatrixElement() const
Returns whether this expression refers to a matrix element.
Definition: Expr.h:507
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4113
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3191
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4630
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4652
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3124
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3699
QualType getReturnType() const
Definition: Decl.h:2717
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
One of these records is kept for each identifier that is lexed.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:618
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition: Overload.h:766
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5792
Represents a C array with an unspecified size.
Definition: Type.h:3751
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
chain_iterator chain_end() const
Definition: Decl.h:3344
chain_iterator chain_begin() const
Definition: Decl.h:3343
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition: Decl.h:3338
Describes an C or C++ initializer list.
Definition: Expr.h:5039
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:5143
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:5209
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition: Expr.h:5105
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5146
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2443
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2403
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:5158
unsigned getNumInits() const
Definition: Expr.h:5069
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2477
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:5095
SourceLocation getLBraceLoc() const
Definition: Expr.h:5193
Expr * updateInit(const ASTContext &C, unsigned Init, Expr *expr)
Updates the initializer at index Init with the new expression expr, and returns the old expression at...
Definition: Expr.cpp:2407
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2419
InitListExpr * getSyntacticForm() const
Definition: Expr.h:5205
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:5133
SourceLocation getRBraceLoc() const
Definition: Expr.h:5195
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5085
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:2466
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2495
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:5164
bool isSyntacticForm() const
Definition: Expr.h:5202
ArrayRef< Expr * > inits()
Definition: Expr.h:5079
void setRBraceLoc(SourceLocation Loc)
Definition: Expr.h:5196
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:5219
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:5072
Describes the kind of initialization being performed, along with location information for tokens rela...
@ IK_DirectList
Direct list-initialization.
@ IK_Value
Value initialization.
@ IK_Direct
Direct initialization.
@ IK_Copy
Copy initialization.
@ IK_Default
Default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
A single step in the initialization sequence.
StepKind Kind
The kind of conversion or initialization step we are taking.
InitListExpr * WrappingSyntacticList
When Kind = SK_RewrapInitList, the syntactic form of the wrapping list.
ImplicitConversionSequence * ICS
When Kind = SK_ConversionSequence, the implicit conversion sequence.
struct F Function
When Kind == SK_ResolvedOverloadedFunction or Kind == SK_UserConversion, the function that the expres...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
void AddListInitializationStep(QualType T)
Add a list-initialization step.
Definition: SemaInit.cpp:3976
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7521
void AddStringInitStep(QualType T)
Add a string init step.
Definition: SemaInit.cpp:4011
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
Definition: SemaInit.cpp:4066
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
Definition: SemaInit.cpp:3983
@ SK_StdInitializerListConstructorCall
Perform initialization via a constructor taking a single std::initializer_list argument.
@ SK_AtomicConversion
Perform a conversion adding _Atomic to a type.
@ SK_ObjCObjectConversion
An initialization that "converts" an Objective-C object (not a point to an object) to another Objecti...
@ SK_GNUArrayInit
Array initialization (from an array rvalue) as a GNU extension.
@ SK_CastDerivedToBaseLValue
Perform a derived-to-base cast, producing an lvalue.
@ SK_ProduceObjCObject
Produce an Objective-C object pointer.
@ SK_FunctionReferenceConversion
Perform a function reference conversion, see [dcl.init.ref]p4.
@ SK_BindReference
Reference binding to an lvalue.
@ SK_ArrayLoopInit
Array initialization by elementwise copy.
@ SK_ConstructorInitialization
Perform initialization via a constructor.
@ SK_OCLSamplerInit
Initialize an OpenCL sampler from an integer.
@ SK_StringInit
Initialization by string.
@ SK_ZeroInitialization
Zero-initialize the object.
@ SK_CastDerivedToBaseXValue
Perform a derived-to-base cast, producing an xvalue.
@ SK_QualificationConversionXValue
Perform a qualification conversion, producing an xvalue.
@ SK_UserConversion
Perform a user-defined conversion, either via a conversion function or via a constructor.
@ SK_CastDerivedToBasePRValue
Perform a derived-to-base cast, producing an rvalue.
@ SK_BindReferenceToTemporary
Reference binding to a temporary.
@ SK_PassByIndirectRestore
Pass an object by indirect restore.
@ SK_ParenthesizedArrayInit
Array initialization from a parenthesized initializer list.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
@ SK_ArrayInit
Array initialization (from an array rvalue).
@ SK_ExtraneousCopyToTemporary
An optional copy of a temporary object to another temporary object, which is permitted (but not requi...
@ SK_ArrayLoopIndex
Array indexing for initialization by elementwise copy.
@ SK_ConversionSequenceNoNarrowing
Perform an implicit conversion sequence without narrowing.
@ SK_RewrapInitList
Rewrap the single-element initializer list for a reference.
@ SK_ConstructorInitializationFromList
Perform initialization via a constructor, taking arguments from a single InitListExpr.
@ SK_PassByIndirectCopyRestore
Pass an object by indirect copy-and-restore.
@ SK_ResolveAddressOfOverloadedFunction
Resolve the address of an overloaded function to a specific function declaration.
@ SK_UnwrapInitList
Unwrap the single-element initializer list for a reference.
@ SK_FinalCopy
Direct-initialization from a reference-related object in the final stage of class copy-initialization...
@ SK_QualificationConversionLValue
Perform a qualification conversion, producing an lvalue.
@ SK_StdInitializerList
Construct a std::initializer_list from an initializer list.
@ SK_QualificationConversionPRValue
Perform a qualification conversion, producing a prvalue.
@ SK_ConversionSequence
Perform an implicit conversion sequence.
@ SK_ListInitialization
Perform list-initialization without a constructor.
@ SK_OCLZeroOpaqueType
Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero.
void AddUserConversionStep(FunctionDecl *Function, DeclAccessPair FoundDecl, QualType T, bool HadMultipleCandidates)
Add a new step invoking a conversion function, which is either a constructor or a conversion function...
Definition: SemaInit.cpp:3919
void SetZeroInitializationFixit(const std::string &Fixit, SourceLocation L)
Call for initializations are invalid but that would be valid zero initialzations if Fixit was applied...
InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList=false, bool TreatUnavailableAsInvalid=true)
Try to perform initialization of the given entity, creating a record of the steps required to perform...
Definition: SemaInit.cpp:6263
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
Definition: SemaInit.cpp:3932
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
Definition: SemaInit.cpp:3951
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
Definition: SemaInit.cpp:3882
FailureKind getFailureKind() const
Determine why initialization failed.
void InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
Definition: SemaInit.cpp:6319
void AddParenthesizedListInitStep(QualType T)
Definition: SemaInit.cpp:4087
void SetFailed(FailureKind Failure)
Note that this initialization sequence failed.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3810
void AddOCLZeroOpaqueTypeStep(QualType T)
Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.) from a zero constant.
Definition: SemaInit.cpp:4080
void AddFinalCopy(QualType T)
Add a new step that makes a copy of the input to an object of the given type, as the final step in cl...
Definition: SemaInit.cpp:3904
void setSequenceKind(enum SequenceKind SK)
Set the kind of sequence computed.
void AddObjCObjectConversionStep(QualType T)
Add an Objective-C object conversion step, which is always a no-op.
Definition: SemaInit.cpp:4018
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
Definition: SemaInit.cpp:4109
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
Definition: SemaInit.cpp:4043
void AddExtraneousCopyToTemporary(QualType T)
Add a new step that makes an extraneous copy of the input to a temporary of the same class type.
Definition: SemaInit.cpp:3911
void setIncompleteTypeFailure(QualType IncompleteType)
Note that this initialization sequence failed due to an incomplete type.
void AddOCLSamplerInitStep(QualType T)
Add a step to initialize an OpenCL sampler from an integer constant.
Definition: SemaInit.cpp:4073
void AddCAssignmentStep(QualType T)
Add a C assignment step.
Definition: SemaInit.cpp:4004
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
Definition: SemaInit.cpp:4050
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic)
Add steps to unwrap a initializer list for a reference around a single element and rewrap it at the e...
Definition: SemaInit.cpp:4094
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8609
bool Failed() const
Determine whether the initialization sequence is invalid.
void AddAtomicConversionStep(QualType Ty)
Add a new step that performs conversion from non-atomic to atomic type.
Definition: SemaInit.cpp:3958
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
Definition: SemaInit.cpp:9465
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
Definition: SemaInit.cpp:3965
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
Definition: SemaInit.cpp:3997
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
Definition: SemaInit.cpp:4059
enum SequenceKind getKind() const
Determine the kind of initialization sequence computed.
SequenceKind
Describes the kind of initialization sequence computed.
@ NormalSequence
A normal sequence.
@ FailedSequence
A failed initialization sequence.
@ DependentSequence
A dependent initialization, which could not be type-checked due to the presence of dependent types or...
void AddReferenceBindingStep(QualType T, bool BindingTemporary)
Add a new step binding a reference to an object.
Definition: SemaInit.cpp:3896
FailureKind
Describes why initialization failed.
@ FK_UserConversionOverloadFailed
Overloading for a user-defined conversion failed.
@ FK_NarrowStringIntoWideCharArray
Initializing a wide char array with narrow string literal.
@ FK_ArrayTypeMismatch
Array type mismatch.
@ FK_ParenthesizedListInitForReference
Reference initialized from a parenthesized initializer list.
@ FK_NonConstLValueReferenceBindingToVectorElement
Non-const lvalue reference binding to a vector element.
@ FK_ReferenceInitDropsQualifiers
Reference binding drops qualifiers.
@ FK_InitListBadDestinationType
Initialization of some unused destination type with an initializer list.
@ FK_ConversionFromPropertyFailed
Implicit conversion failed.
@ FK_NonConstLValueReferenceBindingToUnrelated
Non-const lvalue reference binding to an lvalue of unrelated type.
@ FK_ListConstructorOverloadFailed
Overloading for list-initialization by constructor failed.
@ FK_ReferenceInitFailed
Reference binding failed.
@ FK_ArrayNeedsInitList
Array must be initialized with an initializer list.
@ FK_PlainStringIntoUTF8Char
Initializing char8_t array with plain string literal.
@ FK_NonConstantArrayInit
Non-constant array initializer.
@ FK_NonConstLValueReferenceBindingToTemporary
Non-const lvalue reference binding to a temporary.
@ FK_ConversionFailed
Implicit conversion failed.
@ FK_ArrayNeedsInitListOrStringLiteral
Array must be initialized with an initializer list or a string literal.
@ FK_ParenthesizedListInitForScalar
Scalar initialized from a parenthesized initializer list.
@ FK_PlaceholderType
Initializer has a placeholder type which cannot be resolved by initialization.
@ FK_IncompatWideStringIntoWideChar
Initializing wide char array with incompatible wide string literal.
@ FK_NonConstLValueReferenceBindingToMatrixElement
Non-const lvalue reference binding to a matrix element.
@ FK_TooManyInitsForReference
Too many initializers provided for a reference.
@ FK_NonConstLValueReferenceBindingToBitfield
Non-const lvalue reference binding to a bit-field.
@ FK_ReferenceAddrspaceMismatchTemporary
Reference with mismatching address space binding to temporary.
@ FK_ListInitializationFailed
List initialization failed at some point.
@ FK_TooManyInitsForScalar
Too many initializers for scalar.
@ FK_AddressOfOverloadFailed
Cannot resolve the address of an overloaded function.
@ FK_VariableLengthArrayHasInitializer
Variable-length array must not have an initializer.
@ FK_ArrayNeedsInitListOrWideStringLiteral
Array must be initialized with an initializer list or a wide string literal.
@ FK_RValueReferenceBindingToLValue
Rvalue reference binding to an lvalue.
@ FK_Incomplete
Initialization of an incomplete type.
@ FK_WideStringIntoCharArray
Initializing char array with wide string literal.
@ FK_ExplicitConstructor
List-copy-initialization chose an explicit constructor.
@ FK_ReferenceInitOverloadFailed
Overloading due to reference initialization failed.
@ FK_ConstructorOverloadFailed
Overloading for initialization by constructor failed.
@ FK_ReferenceBindingToInitList
Reference initialization from an initializer list.
@ FK_DefaultInitOfConst
Default-initialization of a 'const' object.
@ FK_ParenthesizedListInitFailed
Parenthesized list initialization failed at some point.
@ FK_AddressOfUnaddressableFunction
Trying to take the address of a function that doesn't support having its address taken.
@ FK_UTF8StringIntoPlainChar
Initializing char array with UTF-8 string literal.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
Definition: SemaInit.cpp:3799
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
Definition: SemaInit.cpp:4032
void AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates)
Add a new step in the initialization that resolves the address of an overloaded function to a specifi...
Definition: SemaInit.cpp:3870
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
Definition: SemaInit.cpp:4025
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3864
SmallVectorImpl< Step >::const_iterator step_iterator
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:3580
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
VD Variable
When Kind == EK_Variable, EK_Member, EK_Binding, or EK_TemplateParameter, the variable,...
EntityKind getKind() const
Determine the kind of initialization.
DeclarationName getName() const
Retrieve the name of the entity being initialized.
Definition: SemaInit.cpp:3592
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
Definition: SemaInit.cpp:3630
bool isImplicitMemberInitializer() const
Is this the implicit initialization of a member of a class from a defaulted constructor?
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index.
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda.
bool isParamOrTemplateParamKind() const
llvm::PointerIntPair< const CXXBaseSpecifier *, 1 > Base
When Kind == EK_Base, the base specifier that provides the base class.
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
Definition: SemaInit.cpp:3664
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
Definition: SemaInit.cpp:3745
EntityKind
Specifies the kind of entity being initialized.
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
static InitializedEntity InitializeMemberFromParenAggInit(FieldDecl *Member)
Create the initialization entity for a member subobject initialized via parenthesized aggregate init.
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, or EK_ComplexElement, the index of the array or vecto...
bool isVariableLengthArrayNew() const
Determine whether this is an array new with an unknown bound.
llvm::PointerIntPair< ParmVarDecl *, 1 > Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the integer indicating whether the parameter is "con...
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call.
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6612
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3472
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4727
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4752
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represent a C++ namespace.
Definition: Decl.h:547
Represents a place-holder for an object not to be initialized by anything.
Definition: Expr.h:5612
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1575
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition: Overload.h:1247
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1029
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:1024
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
Represents a parameter to a function.
Definition: Decl.h:1722
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7839
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3476
QualType withConst() const
Definition: Type.h:1166
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1232
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7951
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7871
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
void addAddressSpace(LangAS space)
Definition: Type.h:584
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
bool hasConst() const
Definition: Type.h:444
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition: Type.h:633
bool hasAddressSpace() const
Definition: Type.h:557
Qualifiers withoutAddressSpace() const
Definition: Type.h:525
void removeAddressSpace()
Definition: Type.h:583
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:422
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
bool hasVolatile() const
Definition: Type.h:454
bool hasObjCLifetime() const
Definition: Type.h:531
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:732
LangAS getAddressSpace() const
Definition: Type.h:558
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3490
Represents a struct/union/class.
Definition: Decl.h:4145
bool hasFlexibleArrayMember() const
Definition: Decl.h:4178
field_iterator field_end() const
Definition: Decl.h:4354
field_range fields() const
Definition: Decl.h:4351
bool isRandomized() const
Definition: Decl.h:4295
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4336
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4348
bool field_empty() const
Definition: Decl.h:4359
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
bool isSpelledAsLValue() const
Definition: Type.h:3441
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1318
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5845
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:169
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition: Sema.h:10139
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10142
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10148
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10146
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16940
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
Definition: SemaInit.cpp:3478
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1710
ASTContext & Context
Definition: Sema.h:962
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition: Sema.cpp:626
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1164
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
@ AllowFold
Definition: Sema.h:7265
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
ASTContext & getASTContext() const
Definition: Sema.h:560
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9505
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:702
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7837
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition: Sema.h:8694
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:553
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
Definition: SemaInit.cpp:7502
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17299
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7484
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:73
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6487
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9557
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9725
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7804
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7465
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7599
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7601
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7680
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1288
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20717
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
SourceManager & getSourceManager() const
Definition: Sema.h:558
AssignmentAction
Definition: Sema.h:6495
@ AA_Returning
Definition: Sema.h:6498
@ AA_Passing_CFAudited
Definition: Sema.h:6503
@ AA_Initializing
Definition: Sema.h:6500
@ AA_Converting
Definition: Sema.h:6499
@ AA_Passing
Definition: Sema.h:6497
@ AA_Casting
Definition: Sema.h:6502
@ AA_Sending
Definition: Sema.h:6501
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20001
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5453
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14938
@ CTK_ErrorRecovery
Definition: Sema.h:9409
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3444
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5102
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
Definition: SemaInit.cpp:7338
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:8882
SourceManager & SourceMgr
Definition: Sema.h:965
DiagnosticsEngine & Diags
Definition: Sema.h:964
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:554
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9655
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5527
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:574
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:16607
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:17862
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:9640
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
void setFromType(QualType T)
Definition: Overload.h:381
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
void setAllToTypes(QualType T)
Definition: Overload.h:388
QualType getToType(unsigned Idx) const
Definition: Overload.h:398
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
unsigned getLength() const
Definition: Expr.h:1895
StringLiteralKind getKind() const
Definition: Expr.h:1898
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition: Expr.h:1884
StringRef getString() const
Definition: Expr.h:1855
bool isUnion() const
Definition: Decl.h:3767
bool isBigEndian() const
Definition: TargetInfo.h:1665
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isDependent() const
Determines whether this is a dependent template name.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6480
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8497
bool isIncompleteArrayType() const
Definition: Type.h:8083
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool isRValueReferenceType() const
Definition: Type.h:8029
bool isConstantArrayType() const
Definition: Type.h:8079
bool isArrayType() const
Definition: Type.h:8075
bool isCharType() const
Definition: Type.cpp:2089
bool isPointerType() const
Definition: Type.h:8003
bool isArrayParameterType() const
Definition: Type.h:8091
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isScalarType() const
Definition: Type.h:8418
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1867
bool isChar8Type() const
Definition: Type.cpp:2105
bool isSizelessBuiltinType() const
Definition: Type.cpp:2441
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isExtVectorType() const
Definition: Type.h:8119
bool isOCLIntelSubgroupAVCType() const
Definition: Type.h:8251
bool isLValueReferenceType() const
Definition: Type.h:8025
bool isOpenCLSpecificType() const
Definition: Type.h:8266
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isAnyComplexType() const
Definition: Type.h:8111
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
bool isQueueT() const
Definition: Type.h:8222
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isAtomicType() const
Definition: Type.h:8158
bool isFunctionProtoType() const
Definition: Type.h:2528
bool isObjCObjectType() const
Definition: Type.h:8149
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8593
bool isEventT() const
Definition: Type.h:8214
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isVectorType() const
Definition: Type.h:8115
bool isFloatingType() const
Definition: Type.cpp:2249
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2196
bool isSamplerT() const
Definition: Type.h:8210
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
bool isObjCRetainableType() const
Definition: Type.cpp:4950
bool isUnionType() const
Definition: Type.cpp:671
Simple class containing the result of Sema::CorrectTypo.
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
const Expr * getInit() const
Definition: Decl.h:1316
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3795
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
VectorKind getVectorKind() const
Definition: Type.h:4041
QualType getElementType() const
Definition: Type.h:4035
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2242
void checkExprLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus11
Definition: LangStandard.h:57
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ ovl_fail_bad_conversion
Definition: Overload.h:801
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
CXXConstructionKind
Definition: ExprCXX.h:1538
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:329
@ Result
The result type of a method or function.
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
Expr * IgnoreParensSingleStep(Expr *E)
Definition: IgnoreExpr.h:150
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1273
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Braces
New-expression has a C++11 list-initializer.
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:414
@ Implicit
An implicit conversion.
@ CStyleCast
A C-style cast.
@ OtherCast
A cast other than a C-style cast.
@ FunctionalCast
A functional-style cast.
@ AS_public
Definition: Specifiers.h:124
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
unsigned long uint64_t
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
CXXConstructorDecl * Constructor
Definition: Overload.h:1265
DeclAccessPair FoundDecl
Definition: Overload.h:1264
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:901
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:937
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:895
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10156
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451