xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaInit.cpp (revision 700637cbb5e582861067a11aaca4d053546871d2)
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"
14 #include "clang/AST/ASTContext.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"
19 #include "clang/AST/IgnoreExpr.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Designator.h"
26 #include "clang/Sema/EnterExpressionEvaluationContext.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Ownership.h"
30 #include "clang/Sema/SemaHLSL.h"
31 #include "clang/Sema/SemaObjC.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/FoldingSet.h"
34 #include "llvm/ADT/PointerIntPair.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 
40 using namespace clang;
41 
42 //===----------------------------------------------------------------------===//
43 // Sema Initialization Checking
44 //===----------------------------------------------------------------------===//
45 
46 /// Check whether T is compatible with a wide character type (wchar_t,
47 /// char16_t or char32_t).
IsWideCharCompatible(QualType T,ASTContext & Context)48 static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
49   if (Context.typesAreCompatible(Context.getWideCharType(), T))
50     return true;
51   if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
52     return Context.typesAreCompatible(Context.Char16Ty, T) ||
53            Context.typesAreCompatible(Context.Char32Ty, T);
54   }
55   return false;
56 }
57 
58 enum StringInitFailureKind {
59   SIF_None,
60   SIF_NarrowStringIntoWideChar,
61   SIF_WideStringIntoChar,
62   SIF_IncompatWideStringIntoWideChar,
63   SIF_UTF8StringIntoPlainChar,
64   SIF_PlainStringIntoUTF8Char,
65   SIF_Other
66 };
67 
68 /// Check whether the array of type AT can be initialized by the Init
69 /// expression by means of string initialization. Returns SIF_None if so,
70 /// otherwise returns a StringInitFailureKind that describes why the
71 /// initialization would not work.
IsStringInit(Expr * Init,const ArrayType * AT,ASTContext & Context)72 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
73                                           ASTContext &Context) {
74   if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
75     return SIF_Other;
76 
77   // See if this is a string literal or @encode.
78   Init = Init->IgnoreParens();
79 
80   // Handle @encode, which is a narrow string.
81   if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
82     return SIF_None;
83 
84   // Otherwise we can only handle string literals.
85   StringLiteral *SL = dyn_cast<StringLiteral>(Init);
86   if (!SL)
87     return SIF_Other;
88 
89   const QualType ElemTy =
90       Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
91 
92   auto IsCharOrUnsignedChar = [](const QualType &T) {
93     const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
94     return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
95   };
96 
97   switch (SL->getKind()) {
98   case StringLiteralKind::UTF8:
99     // char8_t array can be initialized with a UTF-8 string.
100     // - C++20 [dcl.init.string] (DR)
101     //   Additionally, an array of char or unsigned char may be initialized
102     //   by a UTF-8 string literal.
103     if (ElemTy->isChar8Type() ||
104         (Context.getLangOpts().Char8 &&
105          IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
106       return SIF_None;
107     [[fallthrough]];
108   case StringLiteralKind::Ordinary:
109   case StringLiteralKind::Binary:
110     // char array can be initialized with a narrow string.
111     // Only allow char x[] = "foo";  not char x[] = L"foo";
112     if (ElemTy->isCharType())
113       return (SL->getKind() == StringLiteralKind::UTF8 &&
114               Context.getLangOpts().Char8)
115                  ? SIF_UTF8StringIntoPlainChar
116                  : SIF_None;
117     if (ElemTy->isChar8Type())
118       return SIF_PlainStringIntoUTF8Char;
119     if (IsWideCharCompatible(ElemTy, Context))
120       return SIF_NarrowStringIntoWideChar;
121     return SIF_Other;
122   // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
123   // "An array with element type compatible with a qualified or unqualified
124   // version of wchar_t, char16_t, or char32_t may be initialized by a wide
125   // string literal with the corresponding encoding prefix (L, u, or U,
126   // respectively), optionally enclosed in braces.
127   case StringLiteralKind::UTF16:
128     if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
129       return SIF_None;
130     if (ElemTy->isCharType() || ElemTy->isChar8Type())
131       return SIF_WideStringIntoChar;
132     if (IsWideCharCompatible(ElemTy, Context))
133       return SIF_IncompatWideStringIntoWideChar;
134     return SIF_Other;
135   case StringLiteralKind::UTF32:
136     if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
137       return SIF_None;
138     if (ElemTy->isCharType() || ElemTy->isChar8Type())
139       return SIF_WideStringIntoChar;
140     if (IsWideCharCompatible(ElemTy, Context))
141       return SIF_IncompatWideStringIntoWideChar;
142     return SIF_Other;
143   case StringLiteralKind::Wide:
144     if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
145       return SIF_None;
146     if (ElemTy->isCharType() || ElemTy->isChar8Type())
147       return SIF_WideStringIntoChar;
148     if (IsWideCharCompatible(ElemTy, Context))
149       return SIF_IncompatWideStringIntoWideChar;
150     return SIF_Other;
151   case StringLiteralKind::Unevaluated:
152     assert(false && "Unevaluated string literal in initialization");
153     break;
154   }
155 
156   llvm_unreachable("missed a StringLiteral kind?");
157 }
158 
IsStringInit(Expr * init,QualType declType,ASTContext & Context)159 static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
160                                           ASTContext &Context) {
161   const ArrayType *arrayType = Context.getAsArrayType(declType);
162   if (!arrayType)
163     return SIF_Other;
164   return IsStringInit(init, arrayType, Context);
165 }
166 
IsStringInit(Expr * Init,const ArrayType * AT)167 bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
168   return ::IsStringInit(Init, AT, Context) == SIF_None;
169 }
170 
171 /// Update the type of a string literal, including any surrounding parentheses,
172 /// to match the type of the object which it is initializing.
updateStringLiteralType(Expr * E,QualType Ty)173 static void updateStringLiteralType(Expr *E, QualType Ty) {
174   while (true) {
175     E->setType(Ty);
176     E->setValueKind(VK_PRValue);
177     if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
178       break;
179     E = IgnoreParensSingleStep(E);
180   }
181 }
182 
183 /// Fix a compound literal initializing an array so it's correctly marked
184 /// as an rvalue.
updateGNUCompoundLiteralRValue(Expr * E)185 static void updateGNUCompoundLiteralRValue(Expr *E) {
186   while (true) {
187     E->setValueKind(VK_PRValue);
188     if (isa<CompoundLiteralExpr>(E))
189       break;
190     E = IgnoreParensSingleStep(E);
191   }
192 }
193 
initializingConstexprVariable(const InitializedEntity & Entity)194 static bool initializingConstexprVariable(const InitializedEntity &Entity) {
195   Decl *D = Entity.getDecl();
196   const InitializedEntity *Parent = &Entity;
197 
198   while (Parent) {
199     D = Parent->getDecl();
200     Parent = Parent->getParent();
201   }
202 
203   if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
204     return true;
205 
206   return false;
207 }
208 
209 static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
210                                                Sema &SemaRef, QualType &TT);
211 
CheckStringInit(Expr * Str,QualType & DeclT,const ArrayType * AT,Sema & S,const InitializedEntity & Entity,bool CheckC23ConstexprInit=false)212 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
213                             Sema &S, const InitializedEntity &Entity,
214                             bool CheckC23ConstexprInit = false) {
215   // Get the length of the string as parsed.
216   auto *ConstantArrayTy =
217       cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
218   uint64_t StrLength = ConstantArrayTy->getZExtSize();
219 
220   if (CheckC23ConstexprInit)
221     if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
222       CheckC23ConstexprInitStringLiteral(SL, S, DeclT);
223 
224   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
225     // C99 6.7.8p14. We have an array of character type with unknown size
226     // being initialized to a string literal.
227     llvm::APInt ConstVal(32, StrLength);
228     // Return a new array type (C99 6.7.8p22).
229     DeclT = S.Context.getConstantArrayType(
230         IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
231     updateStringLiteralType(Str, DeclT);
232     return;
233   }
234 
235   const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
236   uint64_t ArrayLen = CAT->getZExtSize();
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 > ArrayLen)
253       S.Diag(Str->getBeginLoc(),
254              diag::err_initializer_string_for_char_array_too_long)
255           << ArrayLen << StrLength << Str->getSourceRange();
256   } else {
257     // C99 6.7.8p14.
258     if (StrLength - 1 > ArrayLen)
259       S.Diag(Str->getBeginLoc(),
260              diag::ext_initializer_string_for_char_array_too_long)
261           << Str->getSourceRange();
262     else if (StrLength - 1 == ArrayLen) {
263       // In C, if the string literal is null-terminated explicitly, e.g., `char
264       // a[4] = "ABC\0"`, there should be no warning:
265       const auto *SL = dyn_cast<StringLiteral>(Str->IgnoreParens());
266       bool IsSLSafe = SL && SL->getLength() > 0 &&
267                       SL->getCodeUnit(SL->getLength() - 1) == 0;
268 
269       if (!IsSLSafe) {
270         // If the entity being initialized has the nonstring attribute, then
271         // silence the "missing nonstring" diagnostic. If there's no entity,
272         // check whether we're initializing an array of arrays; if so, walk the
273         // parents to find an entity.
274         auto FindCorrectEntity =
275             [](const InitializedEntity *Entity) -> const ValueDecl * {
276           while (Entity) {
277             if (const ValueDecl *VD = Entity->getDecl())
278               return VD;
279             if (!Entity->getType()->isArrayType())
280               return nullptr;
281             Entity = Entity->getParent();
282           }
283 
284           return nullptr;
285         };
286         if (const ValueDecl *D = FindCorrectEntity(&Entity);
287             !D || !D->hasAttr<NonStringAttr>())
288           S.Diag(
289               Str->getBeginLoc(),
290               diag::
291                   warn_initializer_string_for_char_array_too_long_no_nonstring)
292               << ArrayLen << StrLength << Str->getSourceRange();
293       }
294       // Always emit the C++ compatibility diagnostic.
295       S.Diag(Str->getBeginLoc(),
296              diag::warn_initializer_string_for_char_array_too_long_for_cpp)
297           << ArrayLen << StrLength << Str->getSourceRange();
298     }
299   }
300 
301   // Set the type to the actual size that we are initializing.  If we have
302   // something like:
303   //   char x[1] = "foo";
304   // then this will set the string literal's type to char[1].
305   updateStringLiteralType(Str, DeclT);
306 }
307 
emitUninitializedExplicitInitFields(Sema & S,const RecordDecl * R)308 void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R) {
309   for (const FieldDecl *Field : R->fields()) {
310     if (Field->hasAttr<ExplicitInitAttr>())
311       S.Diag(Field->getLocation(), diag::note_entity_declared_at) << Field;
312   }
313 }
314 
315 //===----------------------------------------------------------------------===//
316 // Semantic checking for initializer lists.
317 //===----------------------------------------------------------------------===//
318 
319 namespace {
320 
321 /// Semantic checking for initializer lists.
322 ///
323 /// The InitListChecker class contains a set of routines that each
324 /// handle the initialization of a certain kind of entity, e.g.,
325 /// arrays, vectors, struct/union types, scalars, etc. The
326 /// InitListChecker itself performs a recursive walk of the subobject
327 /// structure of the type to be initialized, while stepping through
328 /// the initializer list one element at a time. The IList and Index
329 /// parameters to each of the Check* routines contain the active
330 /// (syntactic) initializer list and the index into that initializer
331 /// list that represents the current initializer. Each routine is
332 /// responsible for moving that Index forward as it consumes elements.
333 ///
334 /// Each Check* routine also has a StructuredList/StructuredIndex
335 /// arguments, which contains the current "structured" (semantic)
336 /// initializer list and the index into that initializer list where we
337 /// are copying initializers as we map them over to the semantic
338 /// list. Once we have completed our recursive walk of the subobject
339 /// structure, we will have constructed a full semantic initializer
340 /// list.
341 ///
342 /// C99 designators cause changes in the initializer list traversal,
343 /// because they make the initialization "jump" into a specific
344 /// subobject and then continue the initialization from that
345 /// point. CheckDesignatedInitializer() recursively steps into the
346 /// designated subobject and manages backing out the recursion to
347 /// initialize the subobjects after the one designated.
348 ///
349 /// If an initializer list contains any designators, we build a placeholder
350 /// structured list even in 'verify only' mode, so that we can track which
351 /// elements need 'empty' initializtion.
352 class InitListChecker {
353   Sema &SemaRef;
354   bool hadError = false;
355   bool VerifyOnly; // No diagnostics.
356   bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
357   bool InOverloadResolution;
358   InitListExpr *FullyStructuredList = nullptr;
359   NoInitExpr *DummyExpr = nullptr;
360   SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
361   EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
362   unsigned CurEmbedIndex = 0;
363 
getDummyInit()364   NoInitExpr *getDummyInit() {
365     if (!DummyExpr)
366       DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
367     return DummyExpr;
368   }
369 
370   void CheckImplicitInitList(const InitializedEntity &Entity,
371                              InitListExpr *ParentIList, QualType T,
372                              unsigned &Index, InitListExpr *StructuredList,
373                              unsigned &StructuredIndex);
374   void CheckExplicitInitList(const InitializedEntity &Entity,
375                              InitListExpr *IList, QualType &T,
376                              InitListExpr *StructuredList,
377                              bool TopLevelObject = false);
378   void CheckListElementTypes(const InitializedEntity &Entity,
379                              InitListExpr *IList, QualType &DeclType,
380                              bool SubobjectIsDesignatorContext,
381                              unsigned &Index,
382                              InitListExpr *StructuredList,
383                              unsigned &StructuredIndex,
384                              bool TopLevelObject = false);
385   void CheckSubElementType(const InitializedEntity &Entity,
386                            InitListExpr *IList, QualType ElemType,
387                            unsigned &Index,
388                            InitListExpr *StructuredList,
389                            unsigned &StructuredIndex,
390                            bool DirectlyDesignated = false);
391   void CheckComplexType(const InitializedEntity &Entity,
392                         InitListExpr *IList, QualType DeclType,
393                         unsigned &Index,
394                         InitListExpr *StructuredList,
395                         unsigned &StructuredIndex);
396   void CheckScalarType(const InitializedEntity &Entity,
397                        InitListExpr *IList, QualType DeclType,
398                        unsigned &Index,
399                        InitListExpr *StructuredList,
400                        unsigned &StructuredIndex);
401   void CheckReferenceType(const InitializedEntity &Entity,
402                           InitListExpr *IList, QualType DeclType,
403                           unsigned &Index,
404                           InitListExpr *StructuredList,
405                           unsigned &StructuredIndex);
406   void CheckVectorType(const InitializedEntity &Entity,
407                        InitListExpr *IList, QualType DeclType, unsigned &Index,
408                        InitListExpr *StructuredList,
409                        unsigned &StructuredIndex);
410   void CheckStructUnionTypes(const InitializedEntity &Entity,
411                              InitListExpr *IList, QualType DeclType,
412                              CXXRecordDecl::base_class_const_range Bases,
413                              RecordDecl::field_iterator Field,
414                              bool SubobjectIsDesignatorContext, unsigned &Index,
415                              InitListExpr *StructuredList,
416                              unsigned &StructuredIndex,
417                              bool TopLevelObject = false);
418   void CheckArrayType(const InitializedEntity &Entity,
419                       InitListExpr *IList, QualType &DeclType,
420                       llvm::APSInt elementIndex,
421                       bool SubobjectIsDesignatorContext, unsigned &Index,
422                       InitListExpr *StructuredList,
423                       unsigned &StructuredIndex);
424   bool CheckDesignatedInitializer(const InitializedEntity &Entity,
425                                   InitListExpr *IList, DesignatedInitExpr *DIE,
426                                   unsigned DesigIdx,
427                                   QualType &CurrentObjectType,
428                                   RecordDecl::field_iterator *NextField,
429                                   llvm::APSInt *NextElementIndex,
430                                   unsigned &Index,
431                                   InitListExpr *StructuredList,
432                                   unsigned &StructuredIndex,
433                                   bool FinishSubobjectInit,
434                                   bool TopLevelObject);
435   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
436                                            QualType CurrentObjectType,
437                                            InitListExpr *StructuredList,
438                                            unsigned StructuredIndex,
439                                            SourceRange InitRange,
440                                            bool IsFullyOverwritten = false);
441   void UpdateStructuredListElement(InitListExpr *StructuredList,
442                                    unsigned &StructuredIndex,
443                                    Expr *expr);
444   InitListExpr *createInitListExpr(QualType CurrentObjectType,
445                                    SourceRange InitRange,
446                                    unsigned ExpectedNumInits);
447   int numArrayElements(QualType DeclType);
448   int numStructUnionElements(QualType DeclType);
449   static RecordDecl *getRecordDecl(QualType DeclType);
450 
451   ExprResult PerformEmptyInit(SourceLocation Loc,
452                               const InitializedEntity &Entity);
453 
454   /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
diagnoseInitOverride(Expr * OldInit,SourceRange NewInitRange,bool UnionOverride=false,bool FullyOverwritten=true)455   void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
456                             bool UnionOverride = false,
457                             bool FullyOverwritten = true) {
458     // Overriding an initializer via a designator is valid with C99 designated
459     // initializers, but ill-formed with C++20 designated initializers.
460     unsigned DiagID =
461         SemaRef.getLangOpts().CPlusPlus
462             ? (UnionOverride ? diag::ext_initializer_union_overrides
463                              : diag::ext_initializer_overrides)
464             : diag::warn_initializer_overrides;
465 
466     if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
467       // In overload resolution, we have to strictly enforce the rules, and so
468       // don't allow any overriding of prior initializers. This matters for a
469       // case such as:
470       //
471       //   union U { int a, b; };
472       //   struct S { int a, b; };
473       //   void f(U), f(S);
474       //
475       // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
476       // consistency, we disallow all overriding of prior initializers in
477       // overload resolution, not only overriding of union members.
478       hadError = true;
479     } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
480       // If we'll be keeping around the old initializer but overwriting part of
481       // the object it initialized, and that object is not trivially
482       // destructible, this can leak. Don't allow that, not even as an
483       // extension.
484       //
485       // FIXME: It might be reasonable to allow this in cases where the part of
486       // the initializer that we're overriding has trivial destruction.
487       DiagID = diag::err_initializer_overrides_destructed;
488     } else if (!OldInit->getSourceRange().isValid()) {
489       // We need to check on source range validity because the previous
490       // initializer does not have to be an explicit initializer. e.g.,
491       //
492       // struct P { int a, b; };
493       // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
494       //
495       // There is an overwrite taking place because the first braced initializer
496       // list "{ .a = 2 }" already provides value for .p.b (which is zero).
497       //
498       // Such overwrites are harmless, so we don't diagnose them. (Note that in
499       // C++, this cannot be reached unless we've already seen and diagnosed a
500       // different conformance issue, such as a mixture of designated and
501       // non-designated initializers or a multi-level designator.)
502       return;
503     }
504 
505     if (!VerifyOnly) {
506       SemaRef.Diag(NewInitRange.getBegin(), DiagID)
507           << NewInitRange << FullyOverwritten << OldInit->getType();
508       SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
509           << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
510           << OldInit->getSourceRange();
511     }
512   }
513 
514   // Explanation on the "FillWithNoInit" mode:
515   //
516   // Assume we have the following definitions (Case#1):
517   // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
518   // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
519   //
520   // l.lp.x[1][0..1] should not be filled with implicit initializers because the
521   // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
522   //
523   // But if we have (Case#2):
524   // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
525   //
526   // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
527   // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
528   //
529   // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
530   // in the InitListExpr, the "holes" in Case#1 are filled not with empty
531   // initializers but with special "NoInitExpr" place holders, which tells the
532   // CodeGen not to generate any initializers for these parts.
533   void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
534                               const InitializedEntity &ParentEntity,
535                               InitListExpr *ILE, bool &RequiresSecondPass,
536                               bool FillWithNoInit);
537   void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
538                                const InitializedEntity &ParentEntity,
539                                InitListExpr *ILE, bool &RequiresSecondPass,
540                                bool FillWithNoInit = false);
541   void FillInEmptyInitializations(const InitializedEntity &Entity,
542                                   InitListExpr *ILE, bool &RequiresSecondPass,
543                                   InitListExpr *OuterILE, unsigned OuterIndex,
544                                   bool FillWithNoInit = false);
545   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
546                               Expr *InitExpr, FieldDecl *Field,
547                               bool TopLevelObject);
548   void CheckEmptyInitializable(const InitializedEntity &Entity,
549                                SourceLocation Loc);
550 
HandleEmbed(EmbedExpr * Embed,const InitializedEntity & Entity)551   Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
552     Expr *Result = nullptr;
553     // Undrestand which part of embed we'd like to reference.
554     if (!CurEmbed) {
555       CurEmbed = Embed;
556       CurEmbedIndex = 0;
557     }
558     // Reference just one if we're initializing a single scalar.
559     uint64_t ElsCount = 1;
560     // Otherwise try to fill whole array with embed data.
561     if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
562       unsigned ArrIndex = Entity.getElementIndex();
563       auto *AType =
564           SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
565       assert(AType && "expected array type when initializing array");
566       ElsCount = Embed->getDataElementCount();
567       if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
568         ElsCount = std::min(CAType->getSize().getZExtValue() - ArrIndex,
569                             ElsCount - CurEmbedIndex);
570       if (ElsCount == Embed->getDataElementCount()) {
571         CurEmbed = nullptr;
572         CurEmbedIndex = 0;
573         return Embed;
574       }
575     }
576 
577     Result = new (SemaRef.Context)
578         EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
579                   CurEmbedIndex, ElsCount);
580     CurEmbedIndex += ElsCount;
581     if (CurEmbedIndex >= Embed->getDataElementCount()) {
582       CurEmbed = nullptr;
583       CurEmbedIndex = 0;
584     }
585     return Result;
586   }
587 
588 public:
589   InitListChecker(
590       Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
591       bool VerifyOnly, bool TreatUnavailableAsInvalid,
592       bool InOverloadResolution = false,
593       SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
InitListChecker(Sema & S,const InitializedEntity & Entity,InitListExpr * IL,QualType & T,SmallVectorImpl<QualType> & AggrDeductionCandidateParamTypes)594   InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
595                   QualType &T,
596                   SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
597       : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
598                         /*TreatUnavailableAsInvalid=*/false,
599                         /*InOverloadResolution=*/false,
600                         &AggrDeductionCandidateParamTypes) {}
601 
HadError()602   bool HadError() { return hadError; }
603 
604   // Retrieves the fully-structured initializer list used for
605   // semantic analysis and code generation.
getFullyStructuredList() const606   InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
607 };
608 
609 } // end anonymous namespace
610 
PerformEmptyInit(SourceLocation Loc,const InitializedEntity & Entity)611 ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
612                                              const InitializedEntity &Entity) {
613   InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
614                                                             true);
615   MultiExprArg SubInit;
616   Expr *InitExpr;
617   InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc);
618 
619   // C++ [dcl.init.aggr]p7:
620   //   If there are fewer initializer-clauses in the list than there are
621   //   members in the aggregate, then each member not explicitly initialized
622   //   ...
623   bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
624       Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
625   if (EmptyInitList) {
626     // C++1y / DR1070:
627     //   shall be initialized [...] from an empty initializer list.
628     //
629     // We apply the resolution of this DR to C++11 but not C++98, since C++98
630     // does not have useful semantics for initialization from an init list.
631     // We treat this as copy-initialization, because aggregate initialization
632     // always performs copy-initialization on its elements.
633     //
634     // Only do this if we're initializing a class type, to avoid filling in
635     // the initializer list where possible.
636     InitExpr = VerifyOnly ? &DummyInitList
637                           : new (SemaRef.Context)
638                                 InitListExpr(SemaRef.Context, Loc, {}, Loc);
639     InitExpr->setType(SemaRef.Context.VoidTy);
640     SubInit = InitExpr;
641     Kind = InitializationKind::CreateCopy(Loc, Loc);
642   } else {
643     // C++03:
644     //   shall be value-initialized.
645   }
646 
647   InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
648   // HACK: libstdc++ prior to 4.9 marks the vector default constructor
649   // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic
650   // in that case. stlport does so too.
651   // Look for std::__debug for libstdc++, and for std:: for stlport.
652   // This is effectively a compiler-side implementation of LWG2193.
653   if (!InitSeq && EmptyInitList &&
654       InitSeq.getFailureKind() ==
655           InitializationSequence::FK_ExplicitConstructor &&
656       SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
657     OverloadCandidateSet::iterator Best;
658     OverloadingResult O =
659         InitSeq.getFailedCandidateSet()
660             .BestViableFunction(SemaRef, Kind.getLocation(), Best);
661     (void)O;
662     assert(O == OR_Success && "Inconsistent overload resolution");
663     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
664     CXXRecordDecl *R = CtorDecl->getParent();
665 
666     if (CtorDecl->getMinRequiredArguments() == 0 &&
667         CtorDecl->isExplicit() && R->getDeclName() &&
668         SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
669       bool IsInStd = false;
670       for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
671            ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
672         if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
673           IsInStd = true;
674       }
675 
676       if (IsInStd && llvm::StringSwitch<bool>(R->getName())
677               .Cases("basic_string", "deque", "forward_list", true)
678               .Cases("list", "map", "multimap", "multiset", true)
679               .Cases("priority_queue", "queue", "set", "stack", true)
680               .Cases("unordered_map", "unordered_set", "vector", true)
681               .Default(false)) {
682         InitSeq.InitializeFrom(
683             SemaRef, Entity,
684             InitializationKind::CreateValue(Loc, Loc, Loc, true),
685             MultiExprArg(), /*TopLevelOfInitList=*/false,
686             TreatUnavailableAsInvalid);
687         // Emit a warning for this.  System header warnings aren't shown
688         // by default, but people working on system headers should see it.
689         if (!VerifyOnly) {
690           SemaRef.Diag(CtorDecl->getLocation(),
691                        diag::warn_invalid_initializer_from_system_header);
692           if (Entity.getKind() == InitializedEntity::EK_Member)
693             SemaRef.Diag(Entity.getDecl()->getLocation(),
694                          diag::note_used_in_initialization_here);
695           else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
696             SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
697         }
698       }
699     }
700   }
701   if (!InitSeq) {
702     if (!VerifyOnly) {
703       InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
704       if (Entity.getKind() == InitializedEntity::EK_Member)
705         SemaRef.Diag(Entity.getDecl()->getLocation(),
706                      diag::note_in_omitted_aggregate_initializer)
707           << /*field*/1 << Entity.getDecl();
708       else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
709         bool IsTrailingArrayNewMember =
710             Entity.getParent() &&
711             Entity.getParent()->isVariableLengthArrayNew();
712         SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
713           << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
714           << Entity.getElementIndex();
715       }
716     }
717     hadError = true;
718     return ExprError();
719   }
720 
721   return VerifyOnly ? ExprResult()
722                     : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
723 }
724 
CheckEmptyInitializable(const InitializedEntity & Entity,SourceLocation Loc)725 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
726                                               SourceLocation Loc) {
727   // If we're building a fully-structured list, we'll check this at the end
728   // once we know which elements are actually initialized. Otherwise, we know
729   // that there are no designators so we can just check now.
730   if (FullyStructuredList)
731     return;
732   PerformEmptyInit(Loc, Entity);
733 }
734 
FillInEmptyInitForBase(unsigned Init,const CXXBaseSpecifier & Base,const InitializedEntity & ParentEntity,InitListExpr * ILE,bool & RequiresSecondPass,bool FillWithNoInit)735 void InitListChecker::FillInEmptyInitForBase(
736     unsigned Init, const CXXBaseSpecifier &Base,
737     const InitializedEntity &ParentEntity, InitListExpr *ILE,
738     bool &RequiresSecondPass, bool FillWithNoInit) {
739   InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
740       SemaRef.Context, &Base, false, &ParentEntity);
741 
742   if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
743     ExprResult BaseInit = FillWithNoInit
744                               ? new (SemaRef.Context) NoInitExpr(Base.getType())
745                               : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
746     if (BaseInit.isInvalid()) {
747       hadError = true;
748       return;
749     }
750 
751     if (!VerifyOnly) {
752       assert(Init < ILE->getNumInits() && "should have been expanded");
753       ILE->setInit(Init, BaseInit.getAs<Expr>());
754     }
755   } else if (InitListExpr *InnerILE =
756                  dyn_cast<InitListExpr>(ILE->getInit(Init))) {
757     FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
758                                ILE, Init, FillWithNoInit);
759   } else if (DesignatedInitUpdateExpr *InnerDIUE =
760                dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
761     FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
762                                RequiresSecondPass, ILE, Init,
763                                /*FillWithNoInit =*/true);
764   }
765 }
766 
FillInEmptyInitForField(unsigned Init,FieldDecl * Field,const InitializedEntity & ParentEntity,InitListExpr * ILE,bool & RequiresSecondPass,bool FillWithNoInit)767 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
768                                         const InitializedEntity &ParentEntity,
769                                               InitListExpr *ILE,
770                                               bool &RequiresSecondPass,
771                                               bool FillWithNoInit) {
772   SourceLocation Loc = ILE->getEndLoc();
773   unsigned NumInits = ILE->getNumInits();
774   InitializedEntity MemberEntity
775     = InitializedEntity::InitializeMember(Field, &ParentEntity);
776 
777   if (Init >= NumInits || !ILE->getInit(Init)) {
778     if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
779       if (!RType->getDecl()->isUnion())
780         assert((Init < NumInits || VerifyOnly) &&
781                "This ILE should have been expanded");
782 
783     if (FillWithNoInit) {
784       assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
785       Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
786       if (Init < NumInits)
787         ILE->setInit(Init, Filler);
788       else
789         ILE->updateInit(SemaRef.Context, Init, Filler);
790       return;
791     }
792 
793     if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() &&
794         !SemaRef.isUnevaluatedContext()) {
795       SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init)
796           << /* Var-in-Record */ 0 << Field;
797       SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at)
798           << Field;
799     }
800 
801     // C++1y [dcl.init.aggr]p7:
802     //   If there are fewer initializer-clauses in the list than there are
803     //   members in the aggregate, then each member not explicitly initialized
804     //   shall be initialized from its brace-or-equal-initializer [...]
805     if (Field->hasInClassInitializer()) {
806       if (VerifyOnly)
807         return;
808 
809       ExprResult DIE;
810       {
811         // Enter a default initializer rebuild context, then we can support
812         // lifetime extension of temporary created by aggregate initialization
813         // using a default member initializer.
814         // CWG1815 (https://wg21.link/CWG1815).
815         EnterExpressionEvaluationContext RebuildDefaultInit(
816             SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
817         SemaRef.currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
818             true;
819         SemaRef.currentEvaluationContext().DelayedDefaultInitializationContext =
820             SemaRef.parentEvaluationContext()
821                 .DelayedDefaultInitializationContext;
822         SemaRef.currentEvaluationContext().InLifetimeExtendingContext =
823             SemaRef.parentEvaluationContext().InLifetimeExtendingContext;
824         DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
825       }
826       if (DIE.isInvalid()) {
827         hadError = true;
828         return;
829       }
830       SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
831       if (Init < NumInits)
832         ILE->setInit(Init, DIE.get());
833       else {
834         ILE->updateInit(SemaRef.Context, Init, DIE.get());
835         RequiresSecondPass = true;
836       }
837       return;
838     }
839 
840     if (Field->getType()->isReferenceType()) {
841       if (!VerifyOnly) {
842         // C++ [dcl.init.aggr]p9:
843         //   If an incomplete or empty initializer-list leaves a
844         //   member of reference type uninitialized, the program is
845         //   ill-formed.
846         SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
847             << Field->getType()
848             << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
849                    ->getSourceRange();
850         SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
851       }
852       hadError = true;
853       return;
854     }
855 
856     ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
857     if (MemberInit.isInvalid()) {
858       hadError = true;
859       return;
860     }
861 
862     if (hadError || VerifyOnly) {
863       // Do nothing
864     } else if (Init < NumInits) {
865       ILE->setInit(Init, MemberInit.getAs<Expr>());
866     } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
867       // Empty initialization requires a constructor call, so
868       // extend the initializer list to include the constructor
869       // call and make a note that we'll need to take another pass
870       // through the initializer list.
871       ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
872       RequiresSecondPass = true;
873     }
874   } else if (InitListExpr *InnerILE
875                = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
876     FillInEmptyInitializations(MemberEntity, InnerILE,
877                                RequiresSecondPass, ILE, Init, FillWithNoInit);
878   } else if (DesignatedInitUpdateExpr *InnerDIUE =
879                  dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
880     FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
881                                RequiresSecondPass, ILE, Init,
882                                /*FillWithNoInit =*/true);
883   }
884 }
885 
886 /// Recursively replaces NULL values within the given initializer list
887 /// with expressions that perform value-initialization of the
888 /// appropriate type, and finish off the InitListExpr formation.
889 void
FillInEmptyInitializations(const InitializedEntity & Entity,InitListExpr * ILE,bool & RequiresSecondPass,InitListExpr * OuterILE,unsigned OuterIndex,bool FillWithNoInit)890 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
891                                             InitListExpr *ILE,
892                                             bool &RequiresSecondPass,
893                                             InitListExpr *OuterILE,
894                                             unsigned OuterIndex,
895                                             bool FillWithNoInit) {
896   assert((ILE->getType() != SemaRef.Context.VoidTy) &&
897          "Should not have void type");
898 
899   // We don't need to do any checks when just filling NoInitExprs; that can't
900   // fail.
901   if (FillWithNoInit && VerifyOnly)
902     return;
903 
904   // If this is a nested initializer list, we might have changed its contents
905   // (and therefore some of its properties, such as instantiation-dependence)
906   // while filling it in. Inform the outer initializer list so that its state
907   // can be updated to match.
908   // FIXME: We should fully build the inner initializers before constructing
909   // the outer InitListExpr instead of mutating AST nodes after they have
910   // been used as subexpressions of other nodes.
911   struct UpdateOuterILEWithUpdatedInit {
912     InitListExpr *Outer;
913     unsigned OuterIndex;
914     ~UpdateOuterILEWithUpdatedInit() {
915       if (Outer)
916         Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
917     }
918   } UpdateOuterRAII = {OuterILE, OuterIndex};
919 
920   // A transparent ILE is not performing aggregate initialization and should
921   // not be filled in.
922   if (ILE->isTransparent())
923     return;
924 
925   if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
926     const RecordDecl *RDecl = RType->getDecl();
927     if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
928       FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
929                               RequiresSecondPass, FillWithNoInit);
930     } else {
931       assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
932               !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
933              "We should have computed initialized fields already");
934       // The fields beyond ILE->getNumInits() are default initialized, so in
935       // order to leave them uninitialized, the ILE is expanded and the extra
936       // fields are then filled with NoInitExpr.
937       unsigned NumElems = numStructUnionElements(ILE->getType());
938       if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
939         ++NumElems;
940       if (!VerifyOnly && ILE->getNumInits() < NumElems)
941         ILE->resizeInits(SemaRef.Context, NumElems);
942 
943       unsigned Init = 0;
944 
945       if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
946         for (auto &Base : CXXRD->bases()) {
947           if (hadError)
948             return;
949 
950           FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
951                                  FillWithNoInit);
952           ++Init;
953         }
954       }
955 
956       for (auto *Field : RDecl->fields()) {
957         if (Field->isUnnamedBitField())
958           continue;
959 
960         if (hadError)
961           return;
962 
963         FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
964                                 FillWithNoInit);
965         if (hadError)
966           return;
967 
968         ++Init;
969 
970         // Only look at the first initialization of a union.
971         if (RDecl->isUnion())
972           break;
973       }
974     }
975 
976     return;
977   }
978 
979   QualType ElementType;
980 
981   InitializedEntity ElementEntity = Entity;
982   unsigned NumInits = ILE->getNumInits();
983   uint64_t NumElements = NumInits;
984   if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
985     ElementType = AType->getElementType();
986     if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
987       NumElements = CAType->getZExtSize();
988     // For an array new with an unknown bound, ask for one additional element
989     // in order to populate the array filler.
990     if (Entity.isVariableLengthArrayNew())
991       ++NumElements;
992     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
993                                                          0, Entity);
994   } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
995     ElementType = VType->getElementType();
996     NumElements = VType->getNumElements();
997     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
998                                                          0, Entity);
999   } else
1000     ElementType = ILE->getType();
1001 
1002   bool SkipEmptyInitChecks = false;
1003   for (uint64_t Init = 0; Init != NumElements; ++Init) {
1004     if (hadError)
1005       return;
1006 
1007     if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
1008         ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
1009       ElementEntity.setElementIndex(Init);
1010 
1011     if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
1012       return;
1013 
1014     Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
1015     if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1016       ILE->setInit(Init, ILE->getArrayFiller());
1017     else if (!InitExpr && !ILE->hasArrayFiller()) {
1018       // In VerifyOnly mode, there's no point performing empty initialization
1019       // more than once.
1020       if (SkipEmptyInitChecks)
1021         continue;
1022 
1023       Expr *Filler = nullptr;
1024 
1025       if (FillWithNoInit)
1026         Filler = new (SemaRef.Context) NoInitExpr(ElementType);
1027       else {
1028         ExprResult ElementInit =
1029             PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
1030         if (ElementInit.isInvalid()) {
1031           hadError = true;
1032           return;
1033         }
1034 
1035         Filler = ElementInit.getAs<Expr>();
1036       }
1037 
1038       if (hadError) {
1039         // Do nothing
1040       } else if (VerifyOnly) {
1041         SkipEmptyInitChecks = true;
1042       } else if (Init < NumInits) {
1043         // For arrays, just set the expression used for value-initialization
1044         // of the "holes" in the array.
1045         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
1046           ILE->setArrayFiller(Filler);
1047         else
1048           ILE->setInit(Init, Filler);
1049       } else {
1050         // For arrays, just set the expression used for value-initialization
1051         // of the rest of elements and exit.
1052         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
1053           ILE->setArrayFiller(Filler);
1054           return;
1055         }
1056 
1057         if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
1058           // Empty initialization requires a constructor call, so
1059           // extend the initializer list to include the constructor
1060           // call and make a note that we'll need to take another pass
1061           // through the initializer list.
1062           ILE->updateInit(SemaRef.Context, Init, Filler);
1063           RequiresSecondPass = true;
1064         }
1065       }
1066     } else if (InitListExpr *InnerILE
1067                  = dyn_cast_or_null<InitListExpr>(InitExpr)) {
1068       FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
1069                                  ILE, Init, FillWithNoInit);
1070     } else if (DesignatedInitUpdateExpr *InnerDIUE =
1071                    dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1072       FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1073                                  RequiresSecondPass, ILE, Init,
1074                                  /*FillWithNoInit =*/true);
1075     }
1076   }
1077 }
1078 
hasAnyDesignatedInits(const InitListExpr * IL)1079 static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1080   for (const Stmt *Init : *IL)
1081     if (isa_and_nonnull<DesignatedInitExpr>(Init))
1082       return true;
1083   return false;
1084 }
1085 
InitListChecker(Sema & S,const InitializedEntity & Entity,InitListExpr * IL,QualType & T,bool VerifyOnly,bool TreatUnavailableAsInvalid,bool InOverloadResolution,SmallVectorImpl<QualType> * AggrDeductionCandidateParamTypes)1086 InitListChecker::InitListChecker(
1087     Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1088     bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1089     SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1090     : SemaRef(S), VerifyOnly(VerifyOnly),
1091       TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1092       InOverloadResolution(InOverloadResolution),
1093       AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1094   if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1095     FullyStructuredList =
1096         createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
1097 
1098     // FIXME: Check that IL isn't already the semantic form of some other
1099     // InitListExpr. If it is, we'd create a broken AST.
1100     if (!VerifyOnly)
1101       FullyStructuredList->setSyntacticForm(IL);
1102   }
1103 
1104   CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1105                         /*TopLevelObject=*/true);
1106 
1107   if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1108     bool RequiresSecondPass = false;
1109     FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1110                                /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1111     if (RequiresSecondPass && !hadError)
1112       FillInEmptyInitializations(Entity, FullyStructuredList,
1113                                  RequiresSecondPass, nullptr, 0);
1114   }
1115   if (hadError && FullyStructuredList)
1116     FullyStructuredList->markError();
1117 }
1118 
numArrayElements(QualType DeclType)1119 int InitListChecker::numArrayElements(QualType DeclType) {
1120   // FIXME: use a proper constant
1121   int maxElements = 0x7FFFFFFF;
1122   if (const ConstantArrayType *CAT =
1123         SemaRef.Context.getAsConstantArrayType(DeclType)) {
1124     maxElements = static_cast<int>(CAT->getZExtSize());
1125   }
1126   return maxElements;
1127 }
1128 
numStructUnionElements(QualType DeclType)1129 int InitListChecker::numStructUnionElements(QualType DeclType) {
1130   RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1131   int InitializableMembers = 0;
1132   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1133     InitializableMembers += CXXRD->getNumBases();
1134   for (const auto *Field : structDecl->fields())
1135     if (!Field->isUnnamedBitField())
1136       ++InitializableMembers;
1137 
1138   if (structDecl->isUnion())
1139     return std::min(InitializableMembers, 1);
1140   return InitializableMembers - structDecl->hasFlexibleArrayMember();
1141 }
1142 
getRecordDecl(QualType DeclType)1143 RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1144   if (const auto *RT = DeclType->getAs<RecordType>())
1145     return RT->getDecl();
1146   if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1147     return Inject->getDecl();
1148   return nullptr;
1149 }
1150 
1151 /// Determine whether Entity is an entity for which it is idiomatic to elide
1152 /// the braces in aggregate initialization.
isIdiomaticBraceElisionEntity(const InitializedEntity & Entity)1153 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1154   // Recursive initialization of the one and only field within an aggregate
1155   // class is considered idiomatic. This case arises in particular for
1156   // initialization of std::array, where the C++ standard suggests the idiom of
1157   //
1158   //   std::array<T, N> arr = {1, 2, 3};
1159   //
1160   // (where std::array is an aggregate struct containing a single array field.
1161 
1162   if (!Entity.getParent())
1163     return false;
1164 
1165   // Allows elide brace initialization for aggregates with empty base.
1166   if (Entity.getKind() == InitializedEntity::EK_Base) {
1167     auto *ParentRD =
1168         Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1169     CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1170     return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1171   }
1172 
1173   // Allow brace elision if the only subobject is a field.
1174   if (Entity.getKind() == InitializedEntity::EK_Member) {
1175     auto *ParentRD =
1176         Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1177     if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1178       if (CXXRD->getNumBases()) {
1179         return false;
1180       }
1181     }
1182     auto FieldIt = ParentRD->field_begin();
1183     assert(FieldIt != ParentRD->field_end() &&
1184            "no fields but have initializer for member?");
1185     return ++FieldIt == ParentRD->field_end();
1186   }
1187 
1188   return false;
1189 }
1190 
1191 /// Check whether the range of the initializer \p ParentIList from element
1192 /// \p Index onwards can be used to initialize an object of type \p T. Update
1193 /// \p Index to indicate how many elements of the list were consumed.
1194 ///
1195 /// This also fills in \p StructuredList, from element \p StructuredIndex
1196 /// onwards, with the fully-braced, desugared form of the initialization.
CheckImplicitInitList(const InitializedEntity & Entity,InitListExpr * ParentIList,QualType T,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)1197 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1198                                             InitListExpr *ParentIList,
1199                                             QualType T, unsigned &Index,
1200                                             InitListExpr *StructuredList,
1201                                             unsigned &StructuredIndex) {
1202   int maxElements = 0;
1203 
1204   if (T->isArrayType())
1205     maxElements = numArrayElements(T);
1206   else if (T->isRecordType())
1207     maxElements = numStructUnionElements(T);
1208   else if (T->isVectorType())
1209     maxElements = T->castAs<VectorType>()->getNumElements();
1210   else
1211     llvm_unreachable("CheckImplicitInitList(): Illegal type");
1212 
1213   if (maxElements == 0) {
1214     if (!VerifyOnly)
1215       SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1216                    diag::err_implicit_empty_initializer);
1217     ++Index;
1218     hadError = true;
1219     return;
1220   }
1221 
1222   // Build a structured initializer list corresponding to this subobject.
1223   InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1224       ParentIList, Index, T, StructuredList, StructuredIndex,
1225       SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1226                   ParentIList->getSourceRange().getEnd()));
1227   unsigned StructuredSubobjectInitIndex = 0;
1228 
1229   // Check the element types and build the structural subobject.
1230   unsigned StartIndex = Index;
1231   CheckListElementTypes(Entity, ParentIList, T,
1232                         /*SubobjectIsDesignatorContext=*/false, Index,
1233                         StructuredSubobjectInitList,
1234                         StructuredSubobjectInitIndex);
1235 
1236   if (StructuredSubobjectInitList) {
1237     StructuredSubobjectInitList->setType(T);
1238 
1239     unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1240     // Update the structured sub-object initializer so that it's ending
1241     // range corresponds with the end of the last initializer it used.
1242     if (EndIndex < ParentIList->getNumInits() &&
1243         ParentIList->getInit(EndIndex)) {
1244       SourceLocation EndLoc
1245         = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1246       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1247     }
1248 
1249     // Complain about missing braces.
1250     if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1251         !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1252         !isIdiomaticBraceElisionEntity(Entity)) {
1253       SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1254                    diag::warn_missing_braces)
1255           << StructuredSubobjectInitList->getSourceRange()
1256           << FixItHint::CreateInsertion(
1257                  StructuredSubobjectInitList->getBeginLoc(), "{")
1258           << FixItHint::CreateInsertion(
1259                  SemaRef.getLocForEndOfToken(
1260                      StructuredSubobjectInitList->getEndLoc()),
1261                  "}");
1262     }
1263 
1264     // Warn if this type won't be an aggregate in future versions of C++.
1265     auto *CXXRD = T->getAsCXXRecordDecl();
1266     if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1267       SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1268                    diag::warn_cxx20_compat_aggregate_init_with_ctors)
1269           << StructuredSubobjectInitList->getSourceRange() << T;
1270     }
1271   }
1272 }
1273 
1274 /// Warn that \p Entity was of scalar type and was initialized by a
1275 /// single-element braced initializer list.
warnBracedScalarInit(Sema & S,const InitializedEntity & Entity,SourceRange Braces)1276 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1277                                  SourceRange Braces) {
1278   // Don't warn during template instantiation. If the initialization was
1279   // non-dependent, we warned during the initial parse; otherwise, the
1280   // type might not be scalar in some uses of the template.
1281   if (S.inTemplateInstantiation())
1282     return;
1283 
1284   unsigned DiagID = 0;
1285 
1286   switch (Entity.getKind()) {
1287   case InitializedEntity::EK_VectorElement:
1288   case InitializedEntity::EK_ComplexElement:
1289   case InitializedEntity::EK_ArrayElement:
1290   case InitializedEntity::EK_Parameter:
1291   case InitializedEntity::EK_Parameter_CF_Audited:
1292   case InitializedEntity::EK_TemplateParameter:
1293   case InitializedEntity::EK_Result:
1294   case InitializedEntity::EK_ParenAggInitMember:
1295     // Extra braces here are suspicious.
1296     DiagID = diag::warn_braces_around_init;
1297     break;
1298 
1299   case InitializedEntity::EK_Member:
1300     // Warn on aggregate initialization but not on ctor init list or
1301     // default member initializer.
1302     if (Entity.getParent())
1303       DiagID = diag::warn_braces_around_init;
1304     break;
1305 
1306   case InitializedEntity::EK_Variable:
1307   case InitializedEntity::EK_LambdaCapture:
1308     // No warning, might be direct-list-initialization.
1309     // FIXME: Should we warn for copy-list-initialization in these cases?
1310     break;
1311 
1312   case InitializedEntity::EK_New:
1313   case InitializedEntity::EK_Temporary:
1314   case InitializedEntity::EK_CompoundLiteralInit:
1315     // No warning, braces are part of the syntax of the underlying construct.
1316     break;
1317 
1318   case InitializedEntity::EK_RelatedResult:
1319     // No warning, we already warned when initializing the result.
1320     break;
1321 
1322   case InitializedEntity::EK_Exception:
1323   case InitializedEntity::EK_Base:
1324   case InitializedEntity::EK_Delegating:
1325   case InitializedEntity::EK_BlockElement:
1326   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1327   case InitializedEntity::EK_Binding:
1328   case InitializedEntity::EK_StmtExprResult:
1329     llvm_unreachable("unexpected braced scalar init");
1330   }
1331 
1332   if (DiagID) {
1333     S.Diag(Braces.getBegin(), DiagID)
1334         << Entity.getType()->isSizelessBuiltinType() << Braces
1335         << FixItHint::CreateRemoval(Braces.getBegin())
1336         << FixItHint::CreateRemoval(Braces.getEnd());
1337   }
1338 }
1339 
1340 /// Check whether the initializer \p IList (that was written with explicit
1341 /// braces) can be used to initialize an object of type \p T.
1342 ///
1343 /// This also fills in \p StructuredList with the fully-braced, desugared
1344 /// form of the initialization.
CheckExplicitInitList(const InitializedEntity & Entity,InitListExpr * IList,QualType & T,InitListExpr * StructuredList,bool TopLevelObject)1345 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1346                                             InitListExpr *IList, QualType &T,
1347                                             InitListExpr *StructuredList,
1348                                             bool TopLevelObject) {
1349   unsigned Index = 0, StructuredIndex = 0;
1350   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1351                         Index, StructuredList, StructuredIndex, TopLevelObject);
1352   if (StructuredList) {
1353     QualType ExprTy = T;
1354     if (!ExprTy->isArrayType())
1355       ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1356     if (!VerifyOnly)
1357       IList->setType(ExprTy);
1358     StructuredList->setType(ExprTy);
1359   }
1360   if (hadError)
1361     return;
1362 
1363   // Don't complain for incomplete types, since we'll get an error elsewhere.
1364   if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) {
1365     // We have leftover initializers
1366     bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1367           (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1368     hadError = ExtraInitsIsError;
1369     if (VerifyOnly) {
1370       return;
1371     } else if (StructuredIndex == 1 &&
1372                IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1373                    SIF_None) {
1374       unsigned DK =
1375           ExtraInitsIsError
1376               ? diag::err_excess_initializers_in_char_array_initializer
1377               : diag::ext_excess_initializers_in_char_array_initializer;
1378       SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1379           << IList->getInit(Index)->getSourceRange();
1380     } else if (T->isSizelessBuiltinType()) {
1381       unsigned DK = ExtraInitsIsError
1382                         ? diag::err_excess_initializers_for_sizeless_type
1383                         : diag::ext_excess_initializers_for_sizeless_type;
1384       SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1385           << T << IList->getInit(Index)->getSourceRange();
1386     } else {
1387       int initKind = T->isArrayType() ? 0 :
1388                      T->isVectorType() ? 1 :
1389                      T->isScalarType() ? 2 :
1390                      T->isUnionType() ? 3 :
1391                      4;
1392 
1393       unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1394                                       : diag::ext_excess_initializers;
1395       SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1396           << initKind << IList->getInit(Index)->getSourceRange();
1397     }
1398   }
1399 
1400   if (!VerifyOnly) {
1401     if (T->isScalarType() && IList->getNumInits() == 1 &&
1402         !isa<InitListExpr>(IList->getInit(0)))
1403       warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1404 
1405     // Warn if this is a class type that won't be an aggregate in future
1406     // versions of C++.
1407     auto *CXXRD = T->getAsCXXRecordDecl();
1408     if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1409       // Don't warn if there's an equivalent default constructor that would be
1410       // used instead.
1411       bool HasEquivCtor = false;
1412       if (IList->getNumInits() == 0) {
1413         auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1414         HasEquivCtor = CD && !CD->isDeleted();
1415       }
1416 
1417       if (!HasEquivCtor) {
1418         SemaRef.Diag(IList->getBeginLoc(),
1419                      diag::warn_cxx20_compat_aggregate_init_with_ctors)
1420             << IList->getSourceRange() << T;
1421       }
1422     }
1423   }
1424 }
1425 
CheckListElementTypes(const InitializedEntity & Entity,InitListExpr * IList,QualType & DeclType,bool SubobjectIsDesignatorContext,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool TopLevelObject)1426 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1427                                             InitListExpr *IList,
1428                                             QualType &DeclType,
1429                                             bool SubobjectIsDesignatorContext,
1430                                             unsigned &Index,
1431                                             InitListExpr *StructuredList,
1432                                             unsigned &StructuredIndex,
1433                                             bool TopLevelObject) {
1434   if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1435     // Explicitly braced initializer for complex type can be real+imaginary
1436     // parts.
1437     CheckComplexType(Entity, IList, DeclType, Index,
1438                      StructuredList, StructuredIndex);
1439   } else if (DeclType->isScalarType()) {
1440     CheckScalarType(Entity, IList, DeclType, Index,
1441                     StructuredList, StructuredIndex);
1442   } else if (DeclType->isVectorType()) {
1443     CheckVectorType(Entity, IList, DeclType, Index,
1444                     StructuredList, StructuredIndex);
1445   } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1446     auto Bases =
1447         CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1448                                         CXXRecordDecl::base_class_const_iterator());
1449     if (DeclType->isRecordType()) {
1450       assert(DeclType->isAggregateType() &&
1451              "non-aggregate records should be handed in CheckSubElementType");
1452       if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1453         Bases = CXXRD->bases();
1454     } else {
1455       Bases = cast<CXXRecordDecl>(RD)->bases();
1456     }
1457     CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1458                           SubobjectIsDesignatorContext, Index, StructuredList,
1459                           StructuredIndex, TopLevelObject);
1460   } else if (DeclType->isArrayType()) {
1461     llvm::APSInt Zero(
1462                     SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1463                     false);
1464     CheckArrayType(Entity, IList, DeclType, Zero,
1465                    SubobjectIsDesignatorContext, Index,
1466                    StructuredList, StructuredIndex);
1467   } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1468     // This type is invalid, issue a diagnostic.
1469     ++Index;
1470     if (!VerifyOnly)
1471       SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1472           << DeclType;
1473     hadError = true;
1474   } else if (DeclType->isReferenceType()) {
1475     CheckReferenceType(Entity, IList, DeclType, Index,
1476                        StructuredList, StructuredIndex);
1477   } else if (DeclType->isObjCObjectType()) {
1478     if (!VerifyOnly)
1479       SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1480     hadError = true;
1481   } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1482              DeclType->isSizelessBuiltinType()) {
1483     // Checks for scalar type are sufficient for these types too.
1484     CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1485                     StructuredIndex);
1486   } else if (DeclType->isDependentType()) {
1487     // C++ [over.match.class.deduct]p1.5:
1488     //   brace elision is not considered for any aggregate element that has a
1489     //   dependent non-array type or an array type with a value-dependent bound
1490     ++Index;
1491     assert(AggrDeductionCandidateParamTypes);
1492     AggrDeductionCandidateParamTypes->push_back(DeclType);
1493   } else {
1494     if (!VerifyOnly)
1495       SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1496           << DeclType;
1497     hadError = true;
1498   }
1499 }
1500 
CheckSubElementType(const InitializedEntity & Entity,InitListExpr * IList,QualType ElemType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool DirectlyDesignated)1501 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1502                                           InitListExpr *IList,
1503                                           QualType ElemType,
1504                                           unsigned &Index,
1505                                           InitListExpr *StructuredList,
1506                                           unsigned &StructuredIndex,
1507                                           bool DirectlyDesignated) {
1508   Expr *expr = IList->getInit(Index);
1509 
1510   if (ElemType->isReferenceType())
1511     return CheckReferenceType(Entity, IList, ElemType, Index,
1512                               StructuredList, StructuredIndex);
1513 
1514   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1515     if (SubInitList->getNumInits() == 1 &&
1516         IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1517         SIF_None) {
1518       // FIXME: It would be more faithful and no less correct to include an
1519       // InitListExpr in the semantic form of the initializer list in this case.
1520       expr = SubInitList->getInit(0);
1521     }
1522     // Nested aggregate initialization and C++ initialization are handled later.
1523   } else if (isa<ImplicitValueInitExpr>(expr)) {
1524     // This happens during template instantiation when we see an InitListExpr
1525     // that we've already checked once.
1526     assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1527            "found implicit initialization for the wrong type");
1528     UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1529     ++Index;
1530     return;
1531   }
1532 
1533   if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1534     // C++ [dcl.init.aggr]p2:
1535     //   Each member is copy-initialized from the corresponding
1536     //   initializer-clause.
1537 
1538     // FIXME: Better EqualLoc?
1539     InitializationKind Kind =
1540         InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1541 
1542     // Vector elements can be initialized from other vectors in which case
1543     // we need initialization entity with a type of a vector (and not a vector
1544     // element!) initializing multiple vector elements.
1545     auto TmpEntity =
1546         (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1547             ? InitializedEntity::InitializeTemporary(ElemType)
1548             : Entity;
1549 
1550     if (TmpEntity.getType()->isDependentType()) {
1551       // C++ [over.match.class.deduct]p1.5:
1552       //   brace elision is not considered for any aggregate element that has a
1553       //   dependent non-array type or an array type with a value-dependent
1554       //   bound
1555       assert(AggrDeductionCandidateParamTypes);
1556 
1557       // In the presence of a braced-init-list within the initializer, we should
1558       // not perform brace-elision, even if brace elision would otherwise be
1559       // applicable. For example, given:
1560       //
1561       // template <class T> struct Foo {
1562       //   T t[2];
1563       // };
1564       //
1565       // Foo t = {{1, 2}};
1566       //
1567       // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1568       // {{1, 2}}.
1569       if (isa<InitListExpr, DesignatedInitExpr>(expr) ||
1570           !isa_and_present<ConstantArrayType>(
1571               SemaRef.Context.getAsArrayType(ElemType))) {
1572         ++Index;
1573         AggrDeductionCandidateParamTypes->push_back(ElemType);
1574         return;
1575       }
1576     } else {
1577       InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1578                                  /*TopLevelOfInitList*/ true);
1579       // C++14 [dcl.init.aggr]p13:
1580       //   If the assignment-expression can initialize a member, the member is
1581       //   initialized. Otherwise [...] brace elision is assumed
1582       //
1583       // Brace elision is never performed if the element is not an
1584       // assignment-expression.
1585       if (Seq || isa<InitListExpr>(expr)) {
1586         if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1587           expr = HandleEmbed(Embed, Entity);
1588         }
1589         if (!VerifyOnly) {
1590           ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1591           if (Result.isInvalid())
1592             hadError = true;
1593 
1594           UpdateStructuredListElement(StructuredList, StructuredIndex,
1595                                       Result.getAs<Expr>());
1596         } else if (!Seq) {
1597           hadError = true;
1598         } else if (StructuredList) {
1599           UpdateStructuredListElement(StructuredList, StructuredIndex,
1600                                       getDummyInit());
1601         }
1602         if (!CurEmbed)
1603           ++Index;
1604         if (AggrDeductionCandidateParamTypes)
1605           AggrDeductionCandidateParamTypes->push_back(ElemType);
1606         return;
1607       }
1608     }
1609 
1610     // Fall through for subaggregate initialization
1611   } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1612     // FIXME: Need to handle atomic aggregate types with implicit init lists.
1613     return CheckScalarType(Entity, IList, ElemType, Index,
1614                            StructuredList, StructuredIndex);
1615   } else if (const ArrayType *arrayType =
1616                  SemaRef.Context.getAsArrayType(ElemType)) {
1617     // arrayType can be incomplete if we're initializing a flexible
1618     // array member.  There's nothing we can do with the completed
1619     // type here, though.
1620 
1621     if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1622       // FIXME: Should we do this checking in verify-only mode?
1623       if (!VerifyOnly)
1624         CheckStringInit(expr, ElemType, arrayType, SemaRef, Entity,
1625                         SemaRef.getLangOpts().C23 &&
1626                             initializingConstexprVariable(Entity));
1627       if (StructuredList)
1628         UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1629       ++Index;
1630       return;
1631     }
1632 
1633     // Fall through for subaggregate initialization.
1634 
1635   } else {
1636     assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1637             ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1638            "Unexpected type");
1639 
1640     // C99 6.7.8p13:
1641     //
1642     //   The initializer for a structure or union object that has
1643     //   automatic storage duration shall be either an initializer
1644     //   list as described below, or a single expression that has
1645     //   compatible structure or union type. In the latter case, the
1646     //   initial value of the object, including unnamed members, is
1647     //   that of the expression.
1648     ExprResult ExprRes = expr;
1649     if (SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
1650                                                  !VerifyOnly) !=
1651         AssignConvertType::Incompatible) {
1652       if (ExprRes.isInvalid())
1653         hadError = true;
1654       else {
1655         ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1656         if (ExprRes.isInvalid())
1657           hadError = true;
1658       }
1659       UpdateStructuredListElement(StructuredList, StructuredIndex,
1660                                   ExprRes.getAs<Expr>());
1661       ++Index;
1662       return;
1663     }
1664     ExprRes.get();
1665     // Fall through for subaggregate initialization
1666   }
1667 
1668   // C++ [dcl.init.aggr]p12:
1669   //
1670   //   [...] Otherwise, if the member is itself a non-empty
1671   //   subaggregate, brace elision is assumed and the initializer is
1672   //   considered for the initialization of the first member of
1673   //   the subaggregate.
1674   // OpenCL vector initializer is handled elsewhere.
1675   if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1676       ElemType->isAggregateType()) {
1677     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1678                           StructuredIndex);
1679     ++StructuredIndex;
1680 
1681     // In C++20, brace elision is not permitted for a designated initializer.
1682     if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1683       if (InOverloadResolution)
1684         hadError = true;
1685       if (!VerifyOnly) {
1686         SemaRef.Diag(expr->getBeginLoc(),
1687                      diag::ext_designated_init_brace_elision)
1688             << expr->getSourceRange()
1689             << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1690             << FixItHint::CreateInsertion(
1691                    SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1692       }
1693     }
1694   } else {
1695     if (!VerifyOnly) {
1696       // We cannot initialize this element, so let PerformCopyInitialization
1697       // produce the appropriate diagnostic. We already checked that this
1698       // initialization will fail.
1699       ExprResult Copy =
1700           SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1701                                             /*TopLevelOfInitList=*/true);
1702       (void)Copy;
1703       assert(Copy.isInvalid() &&
1704              "expected non-aggregate initialization to fail");
1705     }
1706     hadError = true;
1707     ++Index;
1708     ++StructuredIndex;
1709   }
1710 }
1711 
CheckComplexType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)1712 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1713                                        InitListExpr *IList, QualType DeclType,
1714                                        unsigned &Index,
1715                                        InitListExpr *StructuredList,
1716                                        unsigned &StructuredIndex) {
1717   assert(Index == 0 && "Index in explicit init list must be zero");
1718 
1719   // As an extension, clang supports complex initializers, which initialize
1720   // a complex number component-wise.  When an explicit initializer list for
1721   // a complex number contains two initializers, this extension kicks in:
1722   // it expects the initializer list to contain two elements convertible to
1723   // the element type of the complex type. The first element initializes
1724   // the real part, and the second element intitializes the imaginary part.
1725 
1726   if (IList->getNumInits() < 2)
1727     return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1728                            StructuredIndex);
1729 
1730   // This is an extension in C.  (The builtin _Complex type does not exist
1731   // in the C++ standard.)
1732   if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1733     SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1734         << IList->getSourceRange();
1735 
1736   // Initialize the complex number.
1737   QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1738   InitializedEntity ElementEntity =
1739     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1740 
1741   for (unsigned i = 0; i < 2; ++i) {
1742     ElementEntity.setElementIndex(Index);
1743     CheckSubElementType(ElementEntity, IList, elementType, Index,
1744                         StructuredList, StructuredIndex);
1745   }
1746 }
1747 
CheckScalarType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)1748 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1749                                       InitListExpr *IList, QualType DeclType,
1750                                       unsigned &Index,
1751                                       InitListExpr *StructuredList,
1752                                       unsigned &StructuredIndex) {
1753   if (Index >= IList->getNumInits()) {
1754     if (!VerifyOnly) {
1755       if (SemaRef.getLangOpts().CPlusPlus) {
1756         if (DeclType->isSizelessBuiltinType())
1757           SemaRef.Diag(IList->getBeginLoc(),
1758                        SemaRef.getLangOpts().CPlusPlus11
1759                            ? diag::warn_cxx98_compat_empty_sizeless_initializer
1760                            : diag::err_empty_sizeless_initializer)
1761               << DeclType << IList->getSourceRange();
1762         else
1763           SemaRef.Diag(IList->getBeginLoc(),
1764                        SemaRef.getLangOpts().CPlusPlus11
1765                            ? diag::warn_cxx98_compat_empty_scalar_initializer
1766                            : diag::err_empty_scalar_initializer)
1767               << IList->getSourceRange();
1768       }
1769     }
1770     hadError =
1771         SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1772     ++Index;
1773     ++StructuredIndex;
1774     return;
1775   }
1776 
1777   Expr *expr = IList->getInit(Index);
1778   if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1779     // FIXME: This is invalid, and accepting it causes overload resolution
1780     // to pick the wrong overload in some corner cases.
1781     if (!VerifyOnly)
1782       SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1783           << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1784 
1785     CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1786                     StructuredIndex);
1787     return;
1788   } else if (isa<DesignatedInitExpr>(expr)) {
1789     if (!VerifyOnly)
1790       SemaRef.Diag(expr->getBeginLoc(),
1791                    diag::err_designator_for_scalar_or_sizeless_init)
1792           << DeclType->isSizelessBuiltinType() << DeclType
1793           << expr->getSourceRange();
1794     hadError = true;
1795     ++Index;
1796     ++StructuredIndex;
1797     return;
1798   } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1799     expr = HandleEmbed(Embed, Entity);
1800   }
1801 
1802   ExprResult Result;
1803   if (VerifyOnly) {
1804     if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1805       Result = getDummyInit();
1806     else
1807       Result = ExprError();
1808   } else {
1809     Result =
1810         SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1811                                           /*TopLevelOfInitList=*/true);
1812   }
1813 
1814   Expr *ResultExpr = nullptr;
1815 
1816   if (Result.isInvalid())
1817     hadError = true; // types weren't compatible.
1818   else {
1819     ResultExpr = Result.getAs<Expr>();
1820 
1821     if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1822       // The type was promoted, update initializer list.
1823       // FIXME: Why are we updating the syntactic init list?
1824       IList->setInit(Index, ResultExpr);
1825     }
1826   }
1827 
1828   UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1829   if (!CurEmbed)
1830     ++Index;
1831   if (AggrDeductionCandidateParamTypes)
1832     AggrDeductionCandidateParamTypes->push_back(DeclType);
1833 }
1834 
CheckReferenceType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)1835 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1836                                          InitListExpr *IList, QualType DeclType,
1837                                          unsigned &Index,
1838                                          InitListExpr *StructuredList,
1839                                          unsigned &StructuredIndex) {
1840   if (Index >= IList->getNumInits()) {
1841     // FIXME: It would be wonderful if we could point at the actual member. In
1842     // general, it would be useful to pass location information down the stack,
1843     // so that we know the location (or decl) of the "current object" being
1844     // initialized.
1845     if (!VerifyOnly)
1846       SemaRef.Diag(IList->getBeginLoc(),
1847                    diag::err_init_reference_member_uninitialized)
1848           << DeclType << IList->getSourceRange();
1849     hadError = true;
1850     ++Index;
1851     ++StructuredIndex;
1852     return;
1853   }
1854 
1855   Expr *expr = IList->getInit(Index);
1856   if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1857     if (!VerifyOnly)
1858       SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1859           << DeclType << IList->getSourceRange();
1860     hadError = true;
1861     ++Index;
1862     ++StructuredIndex;
1863     return;
1864   }
1865 
1866   ExprResult Result;
1867   if (VerifyOnly) {
1868     if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1869       Result = getDummyInit();
1870     else
1871       Result = ExprError();
1872   } else {
1873     Result =
1874         SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1875                                           /*TopLevelOfInitList=*/true);
1876   }
1877 
1878   if (Result.isInvalid())
1879     hadError = true;
1880 
1881   expr = Result.getAs<Expr>();
1882   // FIXME: Why are we updating the syntactic init list?
1883   if (!VerifyOnly && expr)
1884     IList->setInit(Index, expr);
1885 
1886   UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1887   ++Index;
1888   if (AggrDeductionCandidateParamTypes)
1889     AggrDeductionCandidateParamTypes->push_back(DeclType);
1890 }
1891 
CheckVectorType(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)1892 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1893                                       InitListExpr *IList, QualType DeclType,
1894                                       unsigned &Index,
1895                                       InitListExpr *StructuredList,
1896                                       unsigned &StructuredIndex) {
1897   const VectorType *VT = DeclType->castAs<VectorType>();
1898   unsigned maxElements = VT->getNumElements();
1899   unsigned numEltsInit = 0;
1900   QualType elementType = VT->getElementType();
1901 
1902   if (Index >= IList->getNumInits()) {
1903     // Make sure the element type can be value-initialized.
1904     CheckEmptyInitializable(
1905         InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1906         IList->getEndLoc());
1907     return;
1908   }
1909 
1910   if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1911     // If the initializing element is a vector, try to copy-initialize
1912     // instead of breaking it apart (which is doomed to failure anyway).
1913     Expr *Init = IList->getInit(Index);
1914     if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1915       ExprResult Result;
1916       if (VerifyOnly) {
1917         if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1918           Result = getDummyInit();
1919         else
1920           Result = ExprError();
1921       } else {
1922         Result =
1923             SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1924                                               /*TopLevelOfInitList=*/true);
1925       }
1926 
1927       Expr *ResultExpr = nullptr;
1928       if (Result.isInvalid())
1929         hadError = true; // types weren't compatible.
1930       else {
1931         ResultExpr = Result.getAs<Expr>();
1932 
1933         if (ResultExpr != Init && !VerifyOnly) {
1934           // The type was promoted, update initializer list.
1935           // FIXME: Why are we updating the syntactic init list?
1936           IList->setInit(Index, ResultExpr);
1937         }
1938       }
1939       UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1940       ++Index;
1941       if (AggrDeductionCandidateParamTypes)
1942         AggrDeductionCandidateParamTypes->push_back(elementType);
1943       return;
1944     }
1945 
1946     InitializedEntity ElementEntity =
1947       InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1948 
1949     for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1950       // Don't attempt to go past the end of the init list
1951       if (Index >= IList->getNumInits()) {
1952         CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1953         break;
1954       }
1955 
1956       ElementEntity.setElementIndex(Index);
1957       CheckSubElementType(ElementEntity, IList, elementType, Index,
1958                           StructuredList, StructuredIndex);
1959     }
1960 
1961     if (VerifyOnly)
1962       return;
1963 
1964     bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1965     const VectorType *T = Entity.getType()->castAs<VectorType>();
1966     if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1967                         T->getVectorKind() == VectorKind::NeonPoly)) {
1968       // The ability to use vector initializer lists is a GNU vector extension
1969       // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1970       // endian machines it works fine, however on big endian machines it
1971       // exhibits surprising behaviour:
1972       //
1973       //   uint32x2_t x = {42, 64};
1974       //   return vget_lane_u32(x, 0); // Will return 64.
1975       //
1976       // Because of this, explicitly call out that it is non-portable.
1977       //
1978       SemaRef.Diag(IList->getBeginLoc(),
1979                    diag::warn_neon_vector_initializer_non_portable);
1980 
1981       const char *typeCode;
1982       unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1983 
1984       if (elementType->isFloatingType())
1985         typeCode = "f";
1986       else if (elementType->isSignedIntegerType())
1987         typeCode = "s";
1988       else if (elementType->isUnsignedIntegerType())
1989         typeCode = "u";
1990       else if (elementType->isMFloat8Type())
1991         typeCode = "mf";
1992       else
1993         llvm_unreachable("Invalid element type!");
1994 
1995       SemaRef.Diag(IList->getBeginLoc(),
1996                    SemaRef.Context.getTypeSize(VT) > 64
1997                        ? diag::note_neon_vector_initializer_non_portable_q
1998                        : diag::note_neon_vector_initializer_non_portable)
1999           << typeCode << typeSize;
2000     }
2001 
2002     return;
2003   }
2004 
2005   InitializedEntity ElementEntity =
2006     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2007 
2008   // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2009   for (unsigned i = 0; i < maxElements; ++i) {
2010     // Don't attempt to go past the end of the init list
2011     if (Index >= IList->getNumInits())
2012       break;
2013 
2014     ElementEntity.setElementIndex(Index);
2015 
2016     QualType IType = IList->getInit(Index)->getType();
2017     if (!IType->isVectorType()) {
2018       CheckSubElementType(ElementEntity, IList, elementType, Index,
2019                           StructuredList, StructuredIndex);
2020       ++numEltsInit;
2021     } else {
2022       QualType VecType;
2023       const VectorType *IVT = IType->castAs<VectorType>();
2024       unsigned numIElts = IVT->getNumElements();
2025 
2026       if (IType->isExtVectorType())
2027         VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2028       else
2029         VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2030                                                 IVT->getVectorKind());
2031       CheckSubElementType(ElementEntity, IList, VecType, Index,
2032                           StructuredList, StructuredIndex);
2033       numEltsInit += numIElts;
2034     }
2035   }
2036 
2037   // OpenCL and HLSL require all elements to be initialized.
2038   if (numEltsInit != maxElements) {
2039     if (!VerifyOnly)
2040       SemaRef.Diag(IList->getBeginLoc(),
2041                    diag::err_vector_incorrect_num_elements)
2042           << (numEltsInit < maxElements) << maxElements << numEltsInit
2043           << /*initialization*/ 0;
2044     hadError = true;
2045   }
2046 }
2047 
2048 /// Check if the type of a class element has an accessible destructor, and marks
2049 /// it referenced. Returns true if we shouldn't form a reference to the
2050 /// destructor.
2051 ///
2052 /// Aggregate initialization requires a class element's destructor be
2053 /// accessible per 11.6.1 [dcl.init.aggr]:
2054 ///
2055 /// The destructor for each element of class type is potentially invoked
2056 /// (15.4 [class.dtor]) from the context where the aggregate initialization
2057 /// occurs.
checkDestructorReference(QualType ElementType,SourceLocation Loc,Sema & SemaRef)2058 static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
2059                                      Sema &SemaRef) {
2060   auto *CXXRD = ElementType->getAsCXXRecordDecl();
2061   if (!CXXRD)
2062     return false;
2063 
2064   CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
2065   if (!Destructor)
2066     return false;
2067 
2068   SemaRef.CheckDestructorAccess(Loc, Destructor,
2069                                 SemaRef.PDiag(diag::err_access_dtor_temp)
2070                                 << ElementType);
2071   SemaRef.MarkFunctionReferenced(Loc, Destructor);
2072   return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2073 }
2074 
2075 static bool
canInitializeArrayWithEmbedDataString(ArrayRef<Expr * > ExprList,const InitializedEntity & Entity,ASTContext & Context)2076 canInitializeArrayWithEmbedDataString(ArrayRef<Expr *> ExprList,
2077                                       const InitializedEntity &Entity,
2078                                       ASTContext &Context) {
2079   QualType InitType = Entity.getType();
2080   const InitializedEntity *Parent = &Entity;
2081 
2082   while (Parent) {
2083     InitType = Parent->getType();
2084     Parent = Parent->getParent();
2085   }
2086 
2087   // Only one initializer, it's an embed and the types match;
2088   EmbedExpr *EE =
2089       ExprList.size() == 1
2090           ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2091           : nullptr;
2092   if (!EE)
2093     return false;
2094 
2095   if (InitType->isArrayType()) {
2096     const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2097     StringLiteral *SL = EE->getDataStringLiteral();
2098     return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2099   }
2100   return false;
2101 }
2102 
CheckArrayType(const InitializedEntity & Entity,InitListExpr * IList,QualType & DeclType,llvm::APSInt elementIndex,bool SubobjectIsDesignatorContext,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex)2103 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2104                                      InitListExpr *IList, QualType &DeclType,
2105                                      llvm::APSInt elementIndex,
2106                                      bool SubobjectIsDesignatorContext,
2107                                      unsigned &Index,
2108                                      InitListExpr *StructuredList,
2109                                      unsigned &StructuredIndex) {
2110   const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2111 
2112   if (!VerifyOnly) {
2113     if (checkDestructorReference(arrayType->getElementType(),
2114                                  IList->getEndLoc(), SemaRef)) {
2115       hadError = true;
2116       return;
2117     }
2118   }
2119 
2120   if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2121                                             SemaRef.Context)) {
2122     EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2123     IList->setInit(0, Embed->getDataStringLiteral());
2124   }
2125 
2126   // Check for the special-case of initializing an array with a string.
2127   if (Index < IList->getNumInits()) {
2128     if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2129         SIF_None) {
2130       // We place the string literal directly into the resulting
2131       // initializer list. This is the only place where the structure
2132       // of the structured initializer list doesn't match exactly,
2133       // because doing so would involve allocating one character
2134       // constant for each string.
2135       // FIXME: Should we do these checks in verify-only mode too?
2136       if (!VerifyOnly)
2137         CheckStringInit(
2138             IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2139             SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2140       if (StructuredList) {
2141         UpdateStructuredListElement(StructuredList, StructuredIndex,
2142                                     IList->getInit(Index));
2143         StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2144       }
2145       ++Index;
2146       if (AggrDeductionCandidateParamTypes)
2147         AggrDeductionCandidateParamTypes->push_back(DeclType);
2148       return;
2149     }
2150   }
2151   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2152     // Check for VLAs; in standard C it would be possible to check this
2153     // earlier, but I don't know where clang accepts VLAs (gcc accepts
2154     // them in all sorts of strange places).
2155     bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2156     if (!VerifyOnly) {
2157       // C23 6.7.10p4: An entity of variable length array type shall not be
2158       // initialized except by an empty initializer.
2159       //
2160       // The C extension warnings are issued from ParseBraceInitializer() and
2161       // do not need to be issued here. However, we continue to issue an error
2162       // in the case there are initializers or we are compiling C++. We allow
2163       // use of VLAs in C++, but it's not clear we want to allow {} to zero
2164       // init a VLA in C++ in all cases (such as with non-trivial constructors).
2165       // FIXME: should we allow this construct in C++ when it makes sense to do
2166       // so?
2167       if (HasErr)
2168         SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2169                      diag::err_variable_object_no_init)
2170             << VAT->getSizeExpr()->getSourceRange();
2171     }
2172     hadError = HasErr;
2173     ++Index;
2174     ++StructuredIndex;
2175     return;
2176   }
2177 
2178   // We might know the maximum number of elements in advance.
2179   llvm::APSInt maxElements(elementIndex.getBitWidth(),
2180                            elementIndex.isUnsigned());
2181   bool maxElementsKnown = false;
2182   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2183     maxElements = CAT->getSize();
2184     elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2185     elementIndex.setIsUnsigned(maxElements.isUnsigned());
2186     maxElementsKnown = true;
2187   }
2188 
2189   QualType elementType = arrayType->getElementType();
2190   while (Index < IList->getNumInits()) {
2191     Expr *Init = IList->getInit(Index);
2192     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2193       // If we're not the subobject that matches up with the '{' for
2194       // the designator, we shouldn't be handling the
2195       // designator. Return immediately.
2196       if (!SubobjectIsDesignatorContext)
2197         return;
2198 
2199       // Handle this designated initializer. elementIndex will be
2200       // updated to be the next array element we'll initialize.
2201       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2202                                      DeclType, nullptr, &elementIndex, Index,
2203                                      StructuredList, StructuredIndex, true,
2204                                      false)) {
2205         hadError = true;
2206         continue;
2207       }
2208 
2209       if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2210         maxElements = maxElements.extend(elementIndex.getBitWidth());
2211       else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2212         elementIndex = elementIndex.extend(maxElements.getBitWidth());
2213       elementIndex.setIsUnsigned(maxElements.isUnsigned());
2214 
2215       // If the array is of incomplete type, keep track of the number of
2216       // elements in the initializer.
2217       if (!maxElementsKnown && elementIndex > maxElements)
2218         maxElements = elementIndex;
2219 
2220       continue;
2221     }
2222 
2223     // If we know the maximum number of elements, and we've already
2224     // hit it, stop consuming elements in the initializer list.
2225     if (maxElementsKnown && elementIndex == maxElements)
2226       break;
2227 
2228     InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2229         SemaRef.Context, StructuredIndex, Entity);
2230     ElementEntity.setElementIndex(elementIndex.getExtValue());
2231 
2232     unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2233     // Check this element.
2234     CheckSubElementType(ElementEntity, IList, elementType, Index,
2235                         StructuredList, StructuredIndex);
2236     ++elementIndex;
2237     if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2238       if (CurEmbed) {
2239         elementIndex =
2240             elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2241       } else {
2242         auto Embed = cast<EmbedExpr>(Init);
2243         elementIndex = elementIndex + Embed->getDataElementCount() -
2244                        EmbedElementIndexBeforeInit - 1;
2245       }
2246     }
2247 
2248     // If the array is of incomplete type, keep track of the number of
2249     // elements in the initializer.
2250     if (!maxElementsKnown && elementIndex > maxElements)
2251       maxElements = elementIndex;
2252   }
2253   if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2254     // If this is an incomplete array type, the actual type needs to
2255     // be calculated here.
2256     llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2257     if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2258       // Sizing an array implicitly to zero is not allowed by ISO C,
2259       // but is supported by GNU.
2260       SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2261     }
2262 
2263     DeclType = SemaRef.Context.getConstantArrayType(
2264         elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2265   }
2266   if (!hadError) {
2267     // If there are any members of the array that get value-initialized, check
2268     // that is possible. That happens if we know the bound and don't have
2269     // enough elements, or if we're performing an array new with an unknown
2270     // bound.
2271     if ((maxElementsKnown && elementIndex < maxElements) ||
2272         Entity.isVariableLengthArrayNew())
2273       CheckEmptyInitializable(
2274           InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
2275           IList->getEndLoc());
2276   }
2277 }
2278 
CheckFlexibleArrayInit(const InitializedEntity & Entity,Expr * InitExpr,FieldDecl * Field,bool TopLevelObject)2279 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2280                                              Expr *InitExpr,
2281                                              FieldDecl *Field,
2282                                              bool TopLevelObject) {
2283   // Handle GNU flexible array initializers.
2284   unsigned FlexArrayDiag;
2285   if (isa<InitListExpr>(InitExpr) &&
2286       cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2287     // Empty flexible array init always allowed as an extension
2288     FlexArrayDiag = diag::ext_flexible_array_init;
2289   } else if (!TopLevelObject) {
2290     // Disallow flexible array init on non-top-level object
2291     FlexArrayDiag = diag::err_flexible_array_init;
2292   } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2293     // Disallow flexible array init on anything which is not a variable.
2294     FlexArrayDiag = diag::err_flexible_array_init;
2295   } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2296     // Disallow flexible array init on local variables.
2297     FlexArrayDiag = diag::err_flexible_array_init;
2298   } else {
2299     // Allow other cases.
2300     FlexArrayDiag = diag::ext_flexible_array_init;
2301   }
2302 
2303   if (!VerifyOnly) {
2304     SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2305         << InitExpr->getBeginLoc();
2306     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2307       << Field;
2308   }
2309 
2310   return FlexArrayDiag != diag::ext_flexible_array_init;
2311 }
2312 
isInitializedStructuredList(const InitListExpr * StructuredList)2313 static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2314   return StructuredList && StructuredList->getNumInits() == 1U;
2315 }
2316 
CheckStructUnionTypes(const InitializedEntity & Entity,InitListExpr * IList,QualType DeclType,CXXRecordDecl::base_class_const_range Bases,RecordDecl::field_iterator Field,bool SubobjectIsDesignatorContext,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool TopLevelObject)2317 void InitListChecker::CheckStructUnionTypes(
2318     const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2319     CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,
2320     bool SubobjectIsDesignatorContext, unsigned &Index,
2321     InitListExpr *StructuredList, unsigned &StructuredIndex,
2322     bool TopLevelObject) {
2323   const RecordDecl *RD = getRecordDecl(DeclType);
2324 
2325   // If the record is invalid, some of it's members are invalid. To avoid
2326   // confusion, we forgo checking the initializer for the entire record.
2327   if (RD->isInvalidDecl()) {
2328     // Assume it was supposed to consume a single initializer.
2329     ++Index;
2330     hadError = true;
2331     return;
2332   }
2333 
2334   if (RD->isUnion() && IList->getNumInits() == 0) {
2335     if (!VerifyOnly)
2336       for (FieldDecl *FD : RD->fields()) {
2337         QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2338         if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2339           hadError = true;
2340           return;
2341         }
2342       }
2343 
2344     // If there's a default initializer, use it.
2345     if (isa<CXXRecordDecl>(RD) &&
2346         cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2347       if (!StructuredList)
2348         return;
2349       for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2350            Field != FieldEnd; ++Field) {
2351         if (Field->hasInClassInitializer() ||
2352             (Field->isAnonymousStructOrUnion() &&
2353              Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
2354           StructuredList->setInitializedFieldInUnion(*Field);
2355           // FIXME: Actually build a CXXDefaultInitExpr?
2356           return;
2357         }
2358       }
2359       llvm_unreachable("Couldn't find in-class initializer");
2360     }
2361 
2362     // Value-initialize the first member of the union that isn't an unnamed
2363     // bitfield.
2364     for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2365          Field != FieldEnd; ++Field) {
2366       if (!Field->isUnnamedBitField()) {
2367         CheckEmptyInitializable(
2368             InitializedEntity::InitializeMember(*Field, &Entity),
2369             IList->getEndLoc());
2370         if (StructuredList)
2371           StructuredList->setInitializedFieldInUnion(*Field);
2372         break;
2373       }
2374     }
2375     return;
2376   }
2377 
2378   bool InitializedSomething = false;
2379 
2380   // If we have any base classes, they are initialized prior to the fields.
2381   for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2382     auto &Base = *I;
2383     Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2384 
2385     // Designated inits always initialize fields, so if we see one, all
2386     // remaining base classes have no explicit initializer.
2387     if (isa_and_nonnull<DesignatedInitExpr>(Init))
2388       Init = nullptr;
2389 
2390     // C++ [over.match.class.deduct]p1.6:
2391     //   each non-trailing aggregate element that is a pack expansion is assumed
2392     //   to correspond to no elements of the initializer list, and (1.7) a
2393     //   trailing aggregate element that is a pack expansion is assumed to
2394     //   correspond to all remaining elements of the initializer list (if any).
2395 
2396     // C++ [over.match.class.deduct]p1.9:
2397     //   ... except that additional parameter packs of the form P_j... are
2398     //   inserted into the parameter list in their original aggregate element
2399     //   position corresponding to each non-trailing aggregate element of
2400     //   type P_j that was skipped because it was a parameter pack, and the
2401     //   trailing sequence of parameters corresponding to a trailing
2402     //   aggregate element that is a pack expansion (if any) is replaced
2403     //   by a single parameter of the form T_n....
2404     if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2405       AggrDeductionCandidateParamTypes->push_back(
2406           SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2407 
2408       // Trailing pack expansion
2409       if (I + 1 == E && RD->field_empty()) {
2410         if (Index < IList->getNumInits())
2411           Index = IList->getNumInits();
2412         return;
2413       }
2414 
2415       continue;
2416     }
2417 
2418     SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2419     InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2420         SemaRef.Context, &Base, false, &Entity);
2421     if (Init) {
2422       CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2423                           StructuredList, StructuredIndex);
2424       InitializedSomething = true;
2425     } else {
2426       CheckEmptyInitializable(BaseEntity, InitLoc);
2427     }
2428 
2429     if (!VerifyOnly)
2430       if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2431         hadError = true;
2432         return;
2433       }
2434   }
2435 
2436   // If structDecl is a forward declaration, this loop won't do
2437   // anything except look at designated initializers; That's okay,
2438   // because an error should get printed out elsewhere. It might be
2439   // worthwhile to skip over the rest of the initializer, though.
2440   RecordDecl::field_iterator FieldEnd = RD->field_end();
2441   size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2442     return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2443   });
2444   bool HasDesignatedInit = false;
2445 
2446   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2447 
2448   while (Index < IList->getNumInits()) {
2449     Expr *Init = IList->getInit(Index);
2450     SourceLocation InitLoc = Init->getBeginLoc();
2451 
2452     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2453       // If we're not the subobject that matches up with the '{' for
2454       // the designator, we shouldn't be handling the
2455       // designator. Return immediately.
2456       if (!SubobjectIsDesignatorContext)
2457         return;
2458 
2459       HasDesignatedInit = true;
2460 
2461       // Handle this designated initializer. Field will be updated to
2462       // the next field that we'll be initializing.
2463       bool DesignatedInitFailed = CheckDesignatedInitializer(
2464           Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2465           StructuredList, StructuredIndex, true, TopLevelObject);
2466       if (DesignatedInitFailed)
2467         hadError = true;
2468 
2469       // Find the field named by the designated initializer.
2470       DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2471       if (!VerifyOnly && D->isFieldDesignator()) {
2472         FieldDecl *F = D->getFieldDecl();
2473         InitializedFields.insert(F);
2474         if (!DesignatedInitFailed) {
2475           QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2476           if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2477             hadError = true;
2478             return;
2479           }
2480         }
2481       }
2482 
2483       InitializedSomething = true;
2484       continue;
2485     }
2486 
2487     // Check if this is an initializer of forms:
2488     //
2489     //   struct foo f = {};
2490     //   struct foo g = {0};
2491     //
2492     // These are okay for randomized structures. [C99 6.7.8p19]
2493     //
2494     // Also, if there is only one element in the structure, we allow something
2495     // like this, because it's really not randomized in the traditional sense.
2496     //
2497     //   struct foo h = {bar};
2498     auto IsZeroInitializer = [&](const Expr *I) {
2499       if (IList->getNumInits() == 1) {
2500         if (NumRecordDecls == 1)
2501           return true;
2502         if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2503           return IL->getValue().isZero();
2504       }
2505       return false;
2506     };
2507 
2508     // Don't allow non-designated initializers on randomized structures.
2509     if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2510       if (!VerifyOnly)
2511         SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2512       hadError = true;
2513       break;
2514     }
2515 
2516     if (Field == FieldEnd) {
2517       // We've run out of fields. We're done.
2518       break;
2519     }
2520 
2521     // We've already initialized a member of a union. We can stop entirely.
2522     if (InitializedSomething && RD->isUnion())
2523       return;
2524 
2525     // Stop if we've hit a flexible array member.
2526     if (Field->getType()->isIncompleteArrayType())
2527       break;
2528 
2529     if (Field->isUnnamedBitField()) {
2530       // Don't initialize unnamed bitfields, e.g. "int : 20;"
2531       ++Field;
2532       continue;
2533     }
2534 
2535     // Make sure we can use this declaration.
2536     bool InvalidUse;
2537     if (VerifyOnly)
2538       InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2539     else
2540       InvalidUse = SemaRef.DiagnoseUseOfDecl(
2541           *Field, IList->getInit(Index)->getBeginLoc());
2542     if (InvalidUse) {
2543       ++Index;
2544       ++Field;
2545       hadError = true;
2546       continue;
2547     }
2548 
2549     if (!VerifyOnly) {
2550       QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2551       if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2552         hadError = true;
2553         return;
2554       }
2555     }
2556 
2557     InitializedEntity MemberEntity =
2558       InitializedEntity::InitializeMember(*Field, &Entity);
2559     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2560                         StructuredList, StructuredIndex);
2561     InitializedSomething = true;
2562     InitializedFields.insert(*Field);
2563     if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2564       // Initialize the first field within the union.
2565       StructuredList->setInitializedFieldInUnion(*Field);
2566     }
2567 
2568     ++Field;
2569   }
2570 
2571   // Emit warnings for missing struct field initializers.
2572   // This check is disabled for designated initializers in C.
2573   // This matches gcc behaviour.
2574   bool IsCDesignatedInitializer =
2575       HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2576   if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2577       !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2578       !IsCDesignatedInitializer) {
2579     // It is possible we have one or more unnamed bitfields remaining.
2580     // Find first (if any) named field and emit warning.
2581     for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2582                                                            : Field,
2583                                     end = RD->field_end();
2584          it != end; ++it) {
2585       if (HasDesignatedInit && InitializedFields.count(*it))
2586         continue;
2587 
2588       if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2589           !it->getType()->isIncompleteArrayType()) {
2590         auto Diag = HasDesignatedInit
2591                         ? diag::warn_missing_designated_field_initializers
2592                         : diag::warn_missing_field_initializers;
2593         SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2594         break;
2595       }
2596     }
2597   }
2598 
2599   // Check that any remaining fields can be value-initialized if we're not
2600   // building a structured list. (If we are, we'll check this later.)
2601   if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2602       !Field->getType()->isIncompleteArrayType()) {
2603     for (; Field != FieldEnd && !hadError; ++Field) {
2604       if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2605         CheckEmptyInitializable(
2606             InitializedEntity::InitializeMember(*Field, &Entity),
2607             IList->getEndLoc());
2608     }
2609   }
2610 
2611   // Check that the types of the remaining fields have accessible destructors.
2612   if (!VerifyOnly) {
2613     // If the initializer expression has a designated initializer, check the
2614     // elements for which a designated initializer is not provided too.
2615     RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2616                                                      : Field;
2617     for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2618       QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2619       if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2620         hadError = true;
2621         return;
2622       }
2623     }
2624   }
2625 
2626   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2627       Index >= IList->getNumInits())
2628     return;
2629 
2630   if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2631                              TopLevelObject)) {
2632     hadError = true;
2633     ++Index;
2634     return;
2635   }
2636 
2637   InitializedEntity MemberEntity =
2638     InitializedEntity::InitializeMember(*Field, &Entity);
2639 
2640   if (isa<InitListExpr>(IList->getInit(Index)) ||
2641       AggrDeductionCandidateParamTypes)
2642     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2643                         StructuredList, StructuredIndex);
2644   else
2645     CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2646                           StructuredList, StructuredIndex);
2647 
2648   if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2649     // Initialize the first field within the union.
2650     StructuredList->setInitializedFieldInUnion(*Field);
2651   }
2652 }
2653 
2654 /// Expand a field designator that refers to a member of an
2655 /// anonymous struct or union into a series of field designators that
2656 /// refers to the field within the appropriate subobject.
2657 ///
ExpandAnonymousFieldDesignator(Sema & SemaRef,DesignatedInitExpr * DIE,unsigned DesigIdx,IndirectFieldDecl * IndirectField)2658 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2659                                            DesignatedInitExpr *DIE,
2660                                            unsigned DesigIdx,
2661                                            IndirectFieldDecl *IndirectField) {
2662   typedef DesignatedInitExpr::Designator Designator;
2663 
2664   // Build the replacement designators.
2665   SmallVector<Designator, 4> Replacements;
2666   for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2667        PE = IndirectField->chain_end(); PI != PE; ++PI) {
2668     if (PI + 1 == PE)
2669       Replacements.push_back(Designator::CreateFieldDesignator(
2670           (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2671           DIE->getDesignator(DesigIdx)->getFieldLoc()));
2672     else
2673       Replacements.push_back(Designator::CreateFieldDesignator(
2674           (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2675     assert(isa<FieldDecl>(*PI));
2676     Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2677   }
2678 
2679   // Expand the current designator into the set of replacement
2680   // designators, so we have a full subobject path down to where the
2681   // member of the anonymous struct/union is actually stored.
2682   DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2683                         &Replacements[0] + Replacements.size());
2684 }
2685 
CloneDesignatedInitExpr(Sema & SemaRef,DesignatedInitExpr * DIE)2686 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2687                                                    DesignatedInitExpr *DIE) {
2688   unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2689   SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2690   for (unsigned I = 0; I < NumIndexExprs; ++I)
2691     IndexExprs[I] = DIE->getSubExpr(I + 1);
2692   return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2693                                     IndexExprs,
2694                                     DIE->getEqualOrColonLoc(),
2695                                     DIE->usesGNUSyntax(), DIE->getInit());
2696 }
2697 
2698 namespace {
2699 
2700 // Callback to only accept typo corrections that are for field members of
2701 // the given struct or union.
2702 class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2703  public:
FieldInitializerValidatorCCC(const RecordDecl * RD)2704   explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2705       : Record(RD) {}
2706 
ValidateCandidate(const TypoCorrection & candidate)2707   bool ValidateCandidate(const TypoCorrection &candidate) override {
2708     FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2709     return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2710   }
2711 
clone()2712   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2713     return std::make_unique<FieldInitializerValidatorCCC>(*this);
2714   }
2715 
2716  private:
2717   const RecordDecl *Record;
2718 };
2719 
2720 } // end anonymous namespace
2721 
2722 /// Check the well-formedness of a C99 designated initializer.
2723 ///
2724 /// Determines whether the designated initializer @p DIE, which
2725 /// resides at the given @p Index within the initializer list @p
2726 /// IList, is well-formed for a current object of type @p DeclType
2727 /// (C99 6.7.8). The actual subobject that this designator refers to
2728 /// within the current subobject is returned in either
2729 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2730 ///
2731 /// @param IList  The initializer list in which this designated
2732 /// initializer occurs.
2733 ///
2734 /// @param DIE The designated initializer expression.
2735 ///
2736 /// @param DesigIdx  The index of the current designator.
2737 ///
2738 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2739 /// into which the designation in @p DIE should refer.
2740 ///
2741 /// @param NextField  If non-NULL and the first designator in @p DIE is
2742 /// a field, this will be set to the field declaration corresponding
2743 /// to the field named by the designator. On input, this is expected to be
2744 /// the next field that would be initialized in the absence of designation,
2745 /// if the complete object being initialized is a struct.
2746 ///
2747 /// @param NextElementIndex  If non-NULL and the first designator in @p
2748 /// DIE is an array designator or GNU array-range designator, this
2749 /// will be set to the last index initialized by this designator.
2750 ///
2751 /// @param Index  Index into @p IList where the designated initializer
2752 /// @p DIE occurs.
2753 ///
2754 /// @param StructuredList  The initializer list expression that
2755 /// describes all of the subobject initializers in the order they'll
2756 /// actually be initialized.
2757 ///
2758 /// @returns true if there was an error, false otherwise.
2759 bool
CheckDesignatedInitializer(const InitializedEntity & Entity,InitListExpr * IList,DesignatedInitExpr * DIE,unsigned DesigIdx,QualType & CurrentObjectType,RecordDecl::field_iterator * NextField,llvm::APSInt * NextElementIndex,unsigned & Index,InitListExpr * StructuredList,unsigned & StructuredIndex,bool FinishSubobjectInit,bool TopLevelObject)2760 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2761                                             InitListExpr *IList,
2762                                             DesignatedInitExpr *DIE,
2763                                             unsigned DesigIdx,
2764                                             QualType &CurrentObjectType,
2765                                           RecordDecl::field_iterator *NextField,
2766                                             llvm::APSInt *NextElementIndex,
2767                                             unsigned &Index,
2768                                             InitListExpr *StructuredList,
2769                                             unsigned &StructuredIndex,
2770                                             bool FinishSubobjectInit,
2771                                             bool TopLevelObject) {
2772   if (DesigIdx == DIE->size()) {
2773     // C++20 designated initialization can result in direct-list-initialization
2774     // of the designated subobject. This is the only way that we can end up
2775     // performing direct initialization as part of aggregate initialization, so
2776     // it needs special handling.
2777     if (DIE->isDirectInit()) {
2778       Expr *Init = DIE->getInit();
2779       assert(isa<InitListExpr>(Init) &&
2780              "designator result in direct non-list initialization?");
2781       InitializationKind Kind = InitializationKind::CreateDirectList(
2782           DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2783       InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2784                                  /*TopLevelOfInitList*/ true);
2785       if (StructuredList) {
2786         ExprResult Result = VerifyOnly
2787                                 ? getDummyInit()
2788                                 : Seq.Perform(SemaRef, Entity, Kind, Init);
2789         UpdateStructuredListElement(StructuredList, StructuredIndex,
2790                                     Result.get());
2791       }
2792       ++Index;
2793       if (AggrDeductionCandidateParamTypes)
2794         AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2795       return !Seq;
2796     }
2797 
2798     // Check the actual initialization for the designated object type.
2799     bool prevHadError = hadError;
2800 
2801     // Temporarily remove the designator expression from the
2802     // initializer list that the child calls see, so that we don't try
2803     // to re-process the designator.
2804     unsigned OldIndex = Index;
2805     auto *OldDIE =
2806         dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2807     if (!OldDIE)
2808       OldDIE = DIE;
2809     IList->setInit(OldIndex, OldDIE->getInit());
2810 
2811     CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2812                         StructuredIndex, /*DirectlyDesignated=*/true);
2813 
2814     // Restore the designated initializer expression in the syntactic
2815     // form of the initializer list.
2816     if (IList->getInit(OldIndex) != OldDIE->getInit())
2817       OldDIE->setInit(IList->getInit(OldIndex));
2818     IList->setInit(OldIndex, OldDIE);
2819 
2820     return hadError && !prevHadError;
2821   }
2822 
2823   DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2824   bool IsFirstDesignator = (DesigIdx == 0);
2825   if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2826     // Determine the structural initializer list that corresponds to the
2827     // current subobject.
2828     if (IsFirstDesignator)
2829       StructuredList = FullyStructuredList;
2830     else {
2831       Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2832           StructuredList->getInit(StructuredIndex) : nullptr;
2833       if (!ExistingInit && StructuredList->hasArrayFiller())
2834         ExistingInit = StructuredList->getArrayFiller();
2835 
2836       if (!ExistingInit)
2837         StructuredList = getStructuredSubobjectInit(
2838             IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2839             SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2840       else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2841         StructuredList = Result;
2842       else {
2843         // We are creating an initializer list that initializes the
2844         // subobjects of the current object, but there was already an
2845         // initialization that completely initialized the current
2846         // subobject, e.g., by a compound literal:
2847         //
2848         // struct X { int a, b; };
2849         // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2850         //
2851         // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2852         // designated initializer re-initializes only its current object
2853         // subobject [0].b.
2854         diagnoseInitOverride(ExistingInit,
2855                              SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2856                              /*UnionOverride=*/false,
2857                              /*FullyOverwritten=*/false);
2858 
2859         if (!VerifyOnly) {
2860           if (DesignatedInitUpdateExpr *E =
2861                   dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2862             StructuredList = E->getUpdater();
2863           else {
2864             DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2865                 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2866                                          ExistingInit, DIE->getEndLoc());
2867             StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2868             StructuredList = DIUE->getUpdater();
2869           }
2870         } else {
2871           // We don't need to track the structured representation of a
2872           // designated init update of an already-fully-initialized object in
2873           // verify-only mode. The only reason we would need the structure is
2874           // to determine where the uninitialized "holes" are, and in this
2875           // case, we know there aren't any and we can't introduce any.
2876           StructuredList = nullptr;
2877         }
2878       }
2879     }
2880   }
2881 
2882   if (D->isFieldDesignator()) {
2883     // C99 6.7.8p7:
2884     //
2885     //   If a designator has the form
2886     //
2887     //      . identifier
2888     //
2889     //   then the current object (defined below) shall have
2890     //   structure or union type and the identifier shall be the
2891     //   name of a member of that type.
2892     RecordDecl *RD = getRecordDecl(CurrentObjectType);
2893     if (!RD) {
2894       SourceLocation Loc = D->getDotLoc();
2895       if (Loc.isInvalid())
2896         Loc = D->getFieldLoc();
2897       if (!VerifyOnly)
2898         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2899           << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2900       ++Index;
2901       return true;
2902     }
2903 
2904     FieldDecl *KnownField = D->getFieldDecl();
2905     if (!KnownField) {
2906       const IdentifierInfo *FieldName = D->getFieldName();
2907       ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2908       if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2909         KnownField = FD;
2910       } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2911         // In verify mode, don't modify the original.
2912         if (VerifyOnly)
2913           DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2914         ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2915         D = DIE->getDesignator(DesigIdx);
2916         KnownField = cast<FieldDecl>(*IFD->chain_begin());
2917       }
2918       if (!KnownField) {
2919         if (VerifyOnly) {
2920           ++Index;
2921           return true;  // No typo correction when just trying this out.
2922         }
2923 
2924         // We found a placeholder variable
2925         if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2926                                                       FieldName)) {
2927           ++Index;
2928           return true;
2929         }
2930         // Name lookup found something, but it wasn't a field.
2931         if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2932             !Lookup.empty()) {
2933           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2934               << FieldName;
2935           SemaRef.Diag(Lookup.front()->getLocation(),
2936                        diag::note_field_designator_found);
2937           ++Index;
2938           return true;
2939         }
2940 
2941         // Name lookup didn't find anything.
2942         // Determine whether this was a typo for another field name.
2943         FieldInitializerValidatorCCC CCC(RD);
2944         if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2945                 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2946                 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2947                 CorrectTypoKind::ErrorRecovery, RD)) {
2948           SemaRef.diagnoseTypo(
2949               Corrected,
2950               SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2951                 << FieldName << CurrentObjectType);
2952           KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2953           hadError = true;
2954         } else {
2955           // Typo correction didn't find anything.
2956           SourceLocation Loc = D->getFieldLoc();
2957 
2958           // The loc can be invalid with a "null" designator (i.e. an anonymous
2959           // union/struct). Do our best to approximate the location.
2960           if (Loc.isInvalid())
2961             Loc = IList->getBeginLoc();
2962 
2963           SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2964             << FieldName << CurrentObjectType << DIE->getSourceRange();
2965           ++Index;
2966           return true;
2967         }
2968       }
2969     }
2970 
2971     unsigned NumBases = 0;
2972     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2973       NumBases = CXXRD->getNumBases();
2974 
2975     unsigned FieldIndex = NumBases;
2976 
2977     for (auto *FI : RD->fields()) {
2978       if (FI->isUnnamedBitField())
2979         continue;
2980       if (declaresSameEntity(KnownField, FI)) {
2981         KnownField = FI;
2982         break;
2983       }
2984       ++FieldIndex;
2985     }
2986 
2987     RecordDecl::field_iterator Field =
2988         RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2989 
2990     // All of the fields of a union are located at the same place in
2991     // the initializer list.
2992     if (RD->isUnion()) {
2993       FieldIndex = 0;
2994       if (StructuredList) {
2995         FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2996         if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2997           assert(StructuredList->getNumInits() == 1
2998                  && "A union should never have more than one initializer!");
2999 
3000           Expr *ExistingInit = StructuredList->getInit(0);
3001           if (ExistingInit) {
3002             // We're about to throw away an initializer, emit warning.
3003             diagnoseInitOverride(
3004                 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3005                 /*UnionOverride=*/true,
3006                 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3007                                                                      : true);
3008           }
3009 
3010           // remove existing initializer
3011           StructuredList->resizeInits(SemaRef.Context, 0);
3012           StructuredList->setInitializedFieldInUnion(nullptr);
3013         }
3014 
3015         StructuredList->setInitializedFieldInUnion(*Field);
3016       }
3017     }
3018 
3019     // Make sure we can use this declaration.
3020     bool InvalidUse;
3021     if (VerifyOnly)
3022       InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3023     else
3024       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3025     if (InvalidUse) {
3026       ++Index;
3027       return true;
3028     }
3029 
3030     // C++20 [dcl.init.list]p3:
3031     //   The ordered identifiers in the designators of the designated-
3032     //   initializer-list shall form a subsequence of the ordered identifiers
3033     //   in the direct non-static data members of T.
3034     //
3035     // Note that this is not a condition on forming the aggregate
3036     // initialization, only on actually performing initialization,
3037     // so it is not checked in VerifyOnly mode.
3038     //
3039     // FIXME: This is the only reordering diagnostic we produce, and it only
3040     // catches cases where we have a top-level field designator that jumps
3041     // backwards. This is the only such case that is reachable in an
3042     // otherwise-valid C++20 program, so is the only case that's required for
3043     // conformance, but for consistency, we should diagnose all the other
3044     // cases where a designator takes us backwards too.
3045     if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3046         NextField &&
3047         (*NextField == RD->field_end() ||
3048          (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3049       // Find the field that we just initialized.
3050       FieldDecl *PrevField = nullptr;
3051       for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3052         if (FI->isUnnamedBitField())
3053           continue;
3054         if (*NextField != RD->field_end() &&
3055             declaresSameEntity(*FI, **NextField))
3056           break;
3057         PrevField = *FI;
3058       }
3059 
3060       if (PrevField &&
3061           PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3062         SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3063                      diag::ext_designated_init_reordered)
3064             << KnownField << PrevField << DIE->getSourceRange();
3065 
3066         unsigned OldIndex = StructuredIndex - 1;
3067         if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3068           if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3069             SemaRef.Diag(PrevInit->getBeginLoc(),
3070                          diag::note_previous_field_init)
3071                 << PrevField << PrevInit->getSourceRange();
3072           }
3073         }
3074       }
3075     }
3076 
3077 
3078     // Update the designator with the field declaration.
3079     if (!VerifyOnly)
3080       D->setFieldDecl(*Field);
3081 
3082     // Make sure that our non-designated initializer list has space
3083     // for a subobject corresponding to this field.
3084     if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3085       StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3086 
3087     // This designator names a flexible array member.
3088     if (Field->getType()->isIncompleteArrayType()) {
3089       bool Invalid = false;
3090       if ((DesigIdx + 1) != DIE->size()) {
3091         // We can't designate an object within the flexible array
3092         // member (because GCC doesn't allow it).
3093         if (!VerifyOnly) {
3094           DesignatedInitExpr::Designator *NextD
3095             = DIE->getDesignator(DesigIdx + 1);
3096           SemaRef.Diag(NextD->getBeginLoc(),
3097                        diag::err_designator_into_flexible_array_member)
3098               << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3099           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3100             << *Field;
3101         }
3102         Invalid = true;
3103       }
3104 
3105       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3106           !isa<StringLiteral>(DIE->getInit())) {
3107         // The initializer is not an initializer list.
3108         if (!VerifyOnly) {
3109           SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3110                        diag::err_flexible_array_init_needs_braces)
3111               << DIE->getInit()->getSourceRange();
3112           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3113             << *Field;
3114         }
3115         Invalid = true;
3116       }
3117 
3118       // Check GNU flexible array initializer.
3119       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3120                                              TopLevelObject))
3121         Invalid = true;
3122 
3123       if (Invalid) {
3124         ++Index;
3125         return true;
3126       }
3127 
3128       // Initialize the array.
3129       bool prevHadError = hadError;
3130       unsigned newStructuredIndex = FieldIndex;
3131       unsigned OldIndex = Index;
3132       IList->setInit(Index, DIE->getInit());
3133 
3134       InitializedEntity MemberEntity =
3135         InitializedEntity::InitializeMember(*Field, &Entity);
3136       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3137                           StructuredList, newStructuredIndex);
3138 
3139       IList->setInit(OldIndex, DIE);
3140       if (hadError && !prevHadError) {
3141         ++Field;
3142         ++FieldIndex;
3143         if (NextField)
3144           *NextField = Field;
3145         StructuredIndex = FieldIndex;
3146         return true;
3147       }
3148     } else {
3149       // Recurse to check later designated subobjects.
3150       QualType FieldType = Field->getType();
3151       unsigned newStructuredIndex = FieldIndex;
3152 
3153       InitializedEntity MemberEntity =
3154         InitializedEntity::InitializeMember(*Field, &Entity);
3155       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3156                                      FieldType, nullptr, nullptr, Index,
3157                                      StructuredList, newStructuredIndex,
3158                                      FinishSubobjectInit, false))
3159         return true;
3160     }
3161 
3162     // Find the position of the next field to be initialized in this
3163     // subobject.
3164     ++Field;
3165     ++FieldIndex;
3166 
3167     // If this the first designator, our caller will continue checking
3168     // the rest of this struct/class/union subobject.
3169     if (IsFirstDesignator) {
3170       if (Field != RD->field_end() && Field->isUnnamedBitField())
3171         ++Field;
3172 
3173       if (NextField)
3174         *NextField = Field;
3175 
3176       StructuredIndex = FieldIndex;
3177       return false;
3178     }
3179 
3180     if (!FinishSubobjectInit)
3181       return false;
3182 
3183     // We've already initialized something in the union; we're done.
3184     if (RD->isUnion())
3185       return hadError;
3186 
3187     // Check the remaining fields within this class/struct/union subobject.
3188     bool prevHadError = hadError;
3189 
3190     auto NoBases =
3191         CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
3192                                         CXXRecordDecl::base_class_iterator());
3193     CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3194                           false, Index, StructuredList, FieldIndex);
3195     return hadError && !prevHadError;
3196   }
3197 
3198   // C99 6.7.8p6:
3199   //
3200   //   If a designator has the form
3201   //
3202   //      [ constant-expression ]
3203   //
3204   //   then the current object (defined below) shall have array
3205   //   type and the expression shall be an integer constant
3206   //   expression. If the array is of unknown size, any
3207   //   nonnegative value is valid.
3208   //
3209   // Additionally, cope with the GNU extension that permits
3210   // designators of the form
3211   //
3212   //      [ constant-expression ... constant-expression ]
3213   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3214   if (!AT) {
3215     if (!VerifyOnly)
3216       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3217         << CurrentObjectType;
3218     ++Index;
3219     return true;
3220   }
3221 
3222   Expr *IndexExpr = nullptr;
3223   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3224   if (D->isArrayDesignator()) {
3225     IndexExpr = DIE->getArrayIndex(*D);
3226     DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3227     DesignatedEndIndex = DesignatedStartIndex;
3228   } else {
3229     assert(D->isArrayRangeDesignator() && "Need array-range designator");
3230 
3231     DesignatedStartIndex =
3232       DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
3233     DesignatedEndIndex =
3234       DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
3235     IndexExpr = DIE->getArrayRangeEnd(*D);
3236 
3237     // Codegen can't handle evaluating array range designators that have side
3238     // effects, because we replicate the AST value for each initialized element.
3239     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3240     // elements with something that has a side effect, so codegen can emit an
3241     // "error unsupported" error instead of miscompiling the app.
3242     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3243         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3244       FullyStructuredList->sawArrayRangeDesignator();
3245   }
3246 
3247   if (isa<ConstantArrayType>(AT)) {
3248     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3249     DesignatedStartIndex
3250       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3251     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3252     DesignatedEndIndex
3253       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3254     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3255     if (DesignatedEndIndex >= MaxElements) {
3256       if (!VerifyOnly)
3257         SemaRef.Diag(IndexExpr->getBeginLoc(),
3258                      diag::err_array_designator_too_large)
3259             << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3260             << IndexExpr->getSourceRange();
3261       ++Index;
3262       return true;
3263     }
3264   } else {
3265     unsigned DesignatedIndexBitWidth =
3266       ConstantArrayType::getMaxSizeBits(SemaRef.Context);
3267     DesignatedStartIndex =
3268       DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3269     DesignatedEndIndex =
3270       DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3271     DesignatedStartIndex.setIsUnsigned(true);
3272     DesignatedEndIndex.setIsUnsigned(true);
3273   }
3274 
3275   bool IsStringLiteralInitUpdate =
3276       StructuredList && StructuredList->isStringLiteralInit();
3277   if (IsStringLiteralInitUpdate && VerifyOnly) {
3278     // We're just verifying an update to a string literal init. We don't need
3279     // to split the string up into individual characters to do that.
3280     StructuredList = nullptr;
3281   } else if (IsStringLiteralInitUpdate) {
3282     // We're modifying a string literal init; we have to decompose the string
3283     // so we can modify the individual characters.
3284     ASTContext &Context = SemaRef.Context;
3285     Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3286 
3287     // Compute the character type
3288     QualType CharTy = AT->getElementType();
3289 
3290     // Compute the type of the integer literals.
3291     QualType PromotedCharTy = CharTy;
3292     if (Context.isPromotableIntegerType(CharTy))
3293       PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3294     unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3295 
3296     if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3297       // Get the length of the string.
3298       uint64_t StrLen = SL->getLength();
3299       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3300         StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3301       StructuredList->resizeInits(Context, StrLen);
3302 
3303       // Build a literal for each character in the string, and put them into
3304       // the init list.
3305       for (unsigned i = 0, e = StrLen; i != e; ++i) {
3306         llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3307         Expr *Init = new (Context) IntegerLiteral(
3308             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3309         if (CharTy != PromotedCharTy)
3310           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3311                                           Init, nullptr, VK_PRValue,
3312                                           FPOptionsOverride());
3313         StructuredList->updateInit(Context, i, Init);
3314       }
3315     } else {
3316       ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3317       std::string Str;
3318       Context.getObjCEncodingForType(E->getEncodedType(), Str);
3319 
3320       // Get the length of the string.
3321       uint64_t StrLen = Str.size();
3322       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3323         StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3324       StructuredList->resizeInits(Context, StrLen);
3325 
3326       // Build a literal for each character in the string, and put them into
3327       // the init list.
3328       for (unsigned i = 0, e = StrLen; i != e; ++i) {
3329         llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3330         Expr *Init = new (Context) IntegerLiteral(
3331             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3332         if (CharTy != PromotedCharTy)
3333           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3334                                           Init, nullptr, VK_PRValue,
3335                                           FPOptionsOverride());
3336         StructuredList->updateInit(Context, i, Init);
3337       }
3338     }
3339   }
3340 
3341   // Make sure that our non-designated initializer list has space
3342   // for a subobject corresponding to this array element.
3343   if (StructuredList &&
3344       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3345     StructuredList->resizeInits(SemaRef.Context,
3346                                 DesignatedEndIndex.getZExtValue() + 1);
3347 
3348   // Repeatedly perform subobject initializations in the range
3349   // [DesignatedStartIndex, DesignatedEndIndex].
3350 
3351   // Move to the next designator
3352   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3353   unsigned OldIndex = Index;
3354 
3355   InitializedEntity ElementEntity =
3356     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3357 
3358   while (DesignatedStartIndex <= DesignatedEndIndex) {
3359     // Recurse to check later designated subobjects.
3360     QualType ElementType = AT->getElementType();
3361     Index = OldIndex;
3362 
3363     ElementEntity.setElementIndex(ElementIndex);
3364     if (CheckDesignatedInitializer(
3365             ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3366             nullptr, Index, StructuredList, ElementIndex,
3367             FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3368             false))
3369       return true;
3370 
3371     // Move to the next index in the array that we'll be initializing.
3372     ++DesignatedStartIndex;
3373     ElementIndex = DesignatedStartIndex.getZExtValue();
3374   }
3375 
3376   // If this the first designator, our caller will continue checking
3377   // the rest of this array subobject.
3378   if (IsFirstDesignator) {
3379     if (NextElementIndex)
3380       *NextElementIndex = DesignatedStartIndex;
3381     StructuredIndex = ElementIndex;
3382     return false;
3383   }
3384 
3385   if (!FinishSubobjectInit)
3386     return false;
3387 
3388   // Check the remaining elements within this array subobject.
3389   bool prevHadError = hadError;
3390   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3391                  /*SubobjectIsDesignatorContext=*/false, Index,
3392                  StructuredList, ElementIndex);
3393   return hadError && !prevHadError;
3394 }
3395 
3396 // Get the structured initializer list for a subobject of type
3397 // @p CurrentObjectType.
3398 InitListExpr *
getStructuredSubobjectInit(InitListExpr * IList,unsigned Index,QualType CurrentObjectType,InitListExpr * StructuredList,unsigned StructuredIndex,SourceRange InitRange,bool IsFullyOverwritten)3399 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3400                                             QualType CurrentObjectType,
3401                                             InitListExpr *StructuredList,
3402                                             unsigned StructuredIndex,
3403                                             SourceRange InitRange,
3404                                             bool IsFullyOverwritten) {
3405   if (!StructuredList)
3406     return nullptr;
3407 
3408   Expr *ExistingInit = nullptr;
3409   if (StructuredIndex < StructuredList->getNumInits())
3410     ExistingInit = StructuredList->getInit(StructuredIndex);
3411 
3412   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3413     // There might have already been initializers for subobjects of the current
3414     // object, but a subsequent initializer list will overwrite the entirety
3415     // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3416     //
3417     // struct P { char x[6]; };
3418     // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3419     //
3420     // The first designated initializer is ignored, and l.x is just "f".
3421     if (!IsFullyOverwritten)
3422       return Result;
3423 
3424   if (ExistingInit) {
3425     // We are creating an initializer list that initializes the
3426     // subobjects of the current object, but there was already an
3427     // initialization that completely initialized the current
3428     // subobject:
3429     //
3430     // struct X { int a, b; };
3431     // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3432     //
3433     // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3434     // designated initializer overwrites the [0].b initializer
3435     // from the prior initialization.
3436     //
3437     // When the existing initializer is an expression rather than an
3438     // initializer list, we cannot decompose and update it in this way.
3439     // For example:
3440     //
3441     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3442     //
3443     // This case is handled by CheckDesignatedInitializer.
3444     diagnoseInitOverride(ExistingInit, InitRange);
3445   }
3446 
3447   unsigned ExpectedNumInits = 0;
3448   if (Index < IList->getNumInits()) {
3449     if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3450       ExpectedNumInits = Init->getNumInits();
3451     else
3452       ExpectedNumInits = IList->getNumInits() - Index;
3453   }
3454 
3455   InitListExpr *Result =
3456       createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3457 
3458   // Link this new initializer list into the structured initializer
3459   // lists.
3460   StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3461   return Result;
3462 }
3463 
3464 InitListExpr *
createInitListExpr(QualType CurrentObjectType,SourceRange InitRange,unsigned ExpectedNumInits)3465 InitListChecker::createInitListExpr(QualType CurrentObjectType,
3466                                     SourceRange InitRange,
3467                                     unsigned ExpectedNumInits) {
3468   InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3469       SemaRef.Context, InitRange.getBegin(), {}, InitRange.getEnd());
3470 
3471   QualType ResultType = CurrentObjectType;
3472   if (!ResultType->isArrayType())
3473     ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3474   Result->setType(ResultType);
3475 
3476   // Pre-allocate storage for the structured initializer list.
3477   unsigned NumElements = 0;
3478 
3479   if (const ArrayType *AType
3480       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3481     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3482       NumElements = CAType->getZExtSize();
3483       // Simple heuristic so that we don't allocate a very large
3484       // initializer with many empty entries at the end.
3485       if (NumElements > ExpectedNumInits)
3486         NumElements = 0;
3487     }
3488   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3489     NumElements = VType->getNumElements();
3490   } else if (CurrentObjectType->isRecordType()) {
3491     NumElements = numStructUnionElements(CurrentObjectType);
3492   } else if (CurrentObjectType->isDependentType()) {
3493     NumElements = 1;
3494   }
3495 
3496   Result->reserveInits(SemaRef.Context, NumElements);
3497 
3498   return Result;
3499 }
3500 
3501 /// Update the initializer at index @p StructuredIndex within the
3502 /// structured initializer list to the value @p expr.
UpdateStructuredListElement(InitListExpr * StructuredList,unsigned & StructuredIndex,Expr * expr)3503 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3504                                                   unsigned &StructuredIndex,
3505                                                   Expr *expr) {
3506   // No structured initializer list to update
3507   if (!StructuredList)
3508     return;
3509 
3510   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3511                                                   StructuredIndex, expr)) {
3512     // This initializer overwrites a previous initializer.
3513     // No need to diagnose when `expr` is nullptr because a more relevant
3514     // diagnostic has already been issued and this diagnostic is potentially
3515     // noise.
3516     if (expr)
3517       diagnoseInitOverride(PrevInit, expr->getSourceRange());
3518   }
3519 
3520   ++StructuredIndex;
3521 }
3522 
CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity & Entity,InitListExpr * From)3523 bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3524     const InitializedEntity &Entity, InitListExpr *From) {
3525   QualType Type = Entity.getType();
3526   InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3527                         /*TreatUnavailableAsInvalid=*/false,
3528                         /*InOverloadResolution=*/true);
3529   return !Check.HadError();
3530 }
3531 
3532 /// Check that the given Index expression is a valid array designator
3533 /// value. This is essentially just a wrapper around
3534 /// VerifyIntegerConstantExpression that also checks for negative values
3535 /// and produces a reasonable diagnostic if there is a
3536 /// failure. Returns the index expression, possibly with an implicit cast
3537 /// added, on success.  If everything went okay, Value will receive the
3538 /// value of the constant expression.
3539 static ExprResult
CheckArrayDesignatorExpr(Sema & S,Expr * Index,llvm::APSInt & Value)3540 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3541   SourceLocation Loc = Index->getBeginLoc();
3542 
3543   // Make sure this is an integer constant expression.
3544   ExprResult Result =
3545       S.VerifyIntegerConstantExpression(Index, &Value, AllowFoldKind::Allow);
3546   if (Result.isInvalid())
3547     return Result;
3548 
3549   if (Value.isSigned() && Value.isNegative())
3550     return S.Diag(Loc, diag::err_array_designator_negative)
3551            << toString(Value, 10) << Index->getSourceRange();
3552 
3553   Value.setIsUnsigned(true);
3554   return Result;
3555 }
3556 
ActOnDesignatedInitializer(Designation & Desig,SourceLocation EqualOrColonLoc,bool GNUSyntax,ExprResult Init)3557 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3558                                             SourceLocation EqualOrColonLoc,
3559                                             bool GNUSyntax,
3560                                             ExprResult Init) {
3561   typedef DesignatedInitExpr::Designator ASTDesignator;
3562 
3563   bool Invalid = false;
3564   SmallVector<ASTDesignator, 32> Designators;
3565   SmallVector<Expr *, 32> InitExpressions;
3566 
3567   // Build designators and check array designator expressions.
3568   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3569     const Designator &D = Desig.getDesignator(Idx);
3570 
3571     if (D.isFieldDesignator()) {
3572       Designators.push_back(ASTDesignator::CreateFieldDesignator(
3573           D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3574     } else if (D.isArrayDesignator()) {
3575       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3576       llvm::APSInt IndexValue;
3577       if (!Index->isTypeDependent() && !Index->isValueDependent())
3578         Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3579       if (!Index)
3580         Invalid = true;
3581       else {
3582         Designators.push_back(ASTDesignator::CreateArrayDesignator(
3583             InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3584         InitExpressions.push_back(Index);
3585       }
3586     } else if (D.isArrayRangeDesignator()) {
3587       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3588       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3589       llvm::APSInt StartValue;
3590       llvm::APSInt EndValue;
3591       bool StartDependent = StartIndex->isTypeDependent() ||
3592                             StartIndex->isValueDependent();
3593       bool EndDependent = EndIndex->isTypeDependent() ||
3594                           EndIndex->isValueDependent();
3595       if (!StartDependent)
3596         StartIndex =
3597             CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3598       if (!EndDependent)
3599         EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3600 
3601       if (!StartIndex || !EndIndex)
3602         Invalid = true;
3603       else {
3604         // Make sure we're comparing values with the same bit width.
3605         if (StartDependent || EndDependent) {
3606           // Nothing to compute.
3607         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3608           EndValue = EndValue.extend(StartValue.getBitWidth());
3609         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3610           StartValue = StartValue.extend(EndValue.getBitWidth());
3611 
3612         if (!StartDependent && !EndDependent && EndValue < StartValue) {
3613           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3614             << toString(StartValue, 10) << toString(EndValue, 10)
3615             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3616           Invalid = true;
3617         } else {
3618           Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3619               InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3620               D.getRBracketLoc()));
3621           InitExpressions.push_back(StartIndex);
3622           InitExpressions.push_back(EndIndex);
3623         }
3624       }
3625     }
3626   }
3627 
3628   if (Invalid || Init.isInvalid())
3629     return ExprError();
3630 
3631   return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3632                                     EqualOrColonLoc, GNUSyntax,
3633                                     Init.getAs<Expr>());
3634 }
3635 
3636 //===----------------------------------------------------------------------===//
3637 // Initialization entity
3638 //===----------------------------------------------------------------------===//
3639 
InitializedEntity(ASTContext & Context,unsigned Index,const InitializedEntity & Parent)3640 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3641                                      const InitializedEntity &Parent)
3642   : Parent(&Parent), Index(Index)
3643 {
3644   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3645     Kind = EK_ArrayElement;
3646     Type = AT->getElementType();
3647   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3648     Kind = EK_VectorElement;
3649     Type = VT->getElementType();
3650   } else {
3651     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3652     assert(CT && "Unexpected type");
3653     Kind = EK_ComplexElement;
3654     Type = CT->getElementType();
3655   }
3656 }
3657 
3658 InitializedEntity
InitializeBase(ASTContext & Context,const CXXBaseSpecifier * Base,bool IsInheritedVirtualBase,const InitializedEntity * Parent)3659 InitializedEntity::InitializeBase(ASTContext &Context,
3660                                   const CXXBaseSpecifier *Base,
3661                                   bool IsInheritedVirtualBase,
3662                                   const InitializedEntity *Parent) {
3663   InitializedEntity Result;
3664   Result.Kind = EK_Base;
3665   Result.Parent = Parent;
3666   Result.Base = {Base, IsInheritedVirtualBase};
3667   Result.Type = Base->getType();
3668   return Result;
3669 }
3670 
getName() const3671 DeclarationName InitializedEntity::getName() const {
3672   switch (getKind()) {
3673   case EK_Parameter:
3674   case EK_Parameter_CF_Audited: {
3675     ParmVarDecl *D = Parameter.getPointer();
3676     return (D ? D->getDeclName() : DeclarationName());
3677   }
3678 
3679   case EK_Variable:
3680   case EK_Member:
3681   case EK_ParenAggInitMember:
3682   case EK_Binding:
3683   case EK_TemplateParameter:
3684     return Variable.VariableOrMember->getDeclName();
3685 
3686   case EK_LambdaCapture:
3687     return DeclarationName(Capture.VarID);
3688 
3689   case EK_Result:
3690   case EK_StmtExprResult:
3691   case EK_Exception:
3692   case EK_New:
3693   case EK_Temporary:
3694   case EK_Base:
3695   case EK_Delegating:
3696   case EK_ArrayElement:
3697   case EK_VectorElement:
3698   case EK_ComplexElement:
3699   case EK_BlockElement:
3700   case EK_LambdaToBlockConversionBlockElement:
3701   case EK_CompoundLiteralInit:
3702   case EK_RelatedResult:
3703     return DeclarationName();
3704   }
3705 
3706   llvm_unreachable("Invalid EntityKind!");
3707 }
3708 
getDecl() const3709 ValueDecl *InitializedEntity::getDecl() const {
3710   switch (getKind()) {
3711   case EK_Variable:
3712   case EK_Member:
3713   case EK_ParenAggInitMember:
3714   case EK_Binding:
3715   case EK_TemplateParameter:
3716     return Variable.VariableOrMember;
3717 
3718   case EK_Parameter:
3719   case EK_Parameter_CF_Audited:
3720     return Parameter.getPointer();
3721 
3722   case EK_Result:
3723   case EK_StmtExprResult:
3724   case EK_Exception:
3725   case EK_New:
3726   case EK_Temporary:
3727   case EK_Base:
3728   case EK_Delegating:
3729   case EK_ArrayElement:
3730   case EK_VectorElement:
3731   case EK_ComplexElement:
3732   case EK_BlockElement:
3733   case EK_LambdaToBlockConversionBlockElement:
3734   case EK_LambdaCapture:
3735   case EK_CompoundLiteralInit:
3736   case EK_RelatedResult:
3737     return nullptr;
3738   }
3739 
3740   llvm_unreachable("Invalid EntityKind!");
3741 }
3742 
allowsNRVO() const3743 bool InitializedEntity::allowsNRVO() const {
3744   switch (getKind()) {
3745   case EK_Result:
3746   case EK_Exception:
3747     return LocAndNRVO.NRVO;
3748 
3749   case EK_StmtExprResult:
3750   case EK_Variable:
3751   case EK_Parameter:
3752   case EK_Parameter_CF_Audited:
3753   case EK_TemplateParameter:
3754   case EK_Member:
3755   case EK_ParenAggInitMember:
3756   case EK_Binding:
3757   case EK_New:
3758   case EK_Temporary:
3759   case EK_CompoundLiteralInit:
3760   case EK_Base:
3761   case EK_Delegating:
3762   case EK_ArrayElement:
3763   case EK_VectorElement:
3764   case EK_ComplexElement:
3765   case EK_BlockElement:
3766   case EK_LambdaToBlockConversionBlockElement:
3767   case EK_LambdaCapture:
3768   case EK_RelatedResult:
3769     break;
3770   }
3771 
3772   return false;
3773 }
3774 
dumpImpl(raw_ostream & OS) const3775 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3776   assert(getParent() != this);
3777   unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3778   for (unsigned I = 0; I != Depth; ++I)
3779     OS << "`-";
3780 
3781   switch (getKind()) {
3782   case EK_Variable: OS << "Variable"; break;
3783   case EK_Parameter: OS << "Parameter"; break;
3784   case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3785     break;
3786   case EK_TemplateParameter: OS << "TemplateParameter"; break;
3787   case EK_Result: OS << "Result"; break;
3788   case EK_StmtExprResult: OS << "StmtExprResult"; break;
3789   case EK_Exception: OS << "Exception"; break;
3790   case EK_Member:
3791   case EK_ParenAggInitMember:
3792     OS << "Member";
3793     break;
3794   case EK_Binding: OS << "Binding"; break;
3795   case EK_New: OS << "New"; break;
3796   case EK_Temporary: OS << "Temporary"; break;
3797   case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3798   case EK_RelatedResult: OS << "RelatedResult"; break;
3799   case EK_Base: OS << "Base"; break;
3800   case EK_Delegating: OS << "Delegating"; break;
3801   case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3802   case EK_VectorElement: OS << "VectorElement " << Index; break;
3803   case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3804   case EK_BlockElement: OS << "Block"; break;
3805   case EK_LambdaToBlockConversionBlockElement:
3806     OS << "Block (lambda)";
3807     break;
3808   case EK_LambdaCapture:
3809     OS << "LambdaCapture ";
3810     OS << DeclarationName(Capture.VarID);
3811     break;
3812   }
3813 
3814   if (auto *D = getDecl()) {
3815     OS << " ";
3816     D->printQualifiedName(OS);
3817   }
3818 
3819   OS << " '" << getType() << "'\n";
3820 
3821   return Depth + 1;
3822 }
3823 
dump() const3824 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3825   dumpImpl(llvm::errs());
3826 }
3827 
3828 //===----------------------------------------------------------------------===//
3829 // Initialization sequence
3830 //===----------------------------------------------------------------------===//
3831 
Destroy()3832 void InitializationSequence::Step::Destroy() {
3833   switch (Kind) {
3834   case SK_ResolveAddressOfOverloadedFunction:
3835   case SK_CastDerivedToBasePRValue:
3836   case SK_CastDerivedToBaseXValue:
3837   case SK_CastDerivedToBaseLValue:
3838   case SK_BindReference:
3839   case SK_BindReferenceToTemporary:
3840   case SK_FinalCopy:
3841   case SK_ExtraneousCopyToTemporary:
3842   case SK_UserConversion:
3843   case SK_QualificationConversionPRValue:
3844   case SK_QualificationConversionXValue:
3845   case SK_QualificationConversionLValue:
3846   case SK_FunctionReferenceConversion:
3847   case SK_AtomicConversion:
3848   case SK_ListInitialization:
3849   case SK_UnwrapInitList:
3850   case SK_RewrapInitList:
3851   case SK_ConstructorInitialization:
3852   case SK_ConstructorInitializationFromList:
3853   case SK_ZeroInitialization:
3854   case SK_CAssignment:
3855   case SK_StringInit:
3856   case SK_ObjCObjectConversion:
3857   case SK_ArrayLoopIndex:
3858   case SK_ArrayLoopInit:
3859   case SK_ArrayInit:
3860   case SK_GNUArrayInit:
3861   case SK_ParenthesizedArrayInit:
3862   case SK_PassByIndirectCopyRestore:
3863   case SK_PassByIndirectRestore:
3864   case SK_ProduceObjCObject:
3865   case SK_StdInitializerList:
3866   case SK_StdInitializerListConstructorCall:
3867   case SK_OCLSamplerInit:
3868   case SK_OCLZeroOpaqueType:
3869   case SK_ParenthesizedListInit:
3870     break;
3871 
3872   case SK_ConversionSequence:
3873   case SK_ConversionSequenceNoNarrowing:
3874     delete ICS;
3875   }
3876 }
3877 
isDirectReferenceBinding() const3878 bool InitializationSequence::isDirectReferenceBinding() const {
3879   // There can be some lvalue adjustments after the SK_BindReference step.
3880   for (const Step &S : llvm::reverse(Steps)) {
3881     if (S.Kind == SK_BindReference)
3882       return true;
3883     if (S.Kind == SK_BindReferenceToTemporary)
3884       return false;
3885   }
3886   return false;
3887 }
3888 
isAmbiguous() const3889 bool InitializationSequence::isAmbiguous() const {
3890   if (!Failed())
3891     return false;
3892 
3893   switch (getFailureKind()) {
3894   case FK_TooManyInitsForReference:
3895   case FK_ParenthesizedListInitForReference:
3896   case FK_ArrayNeedsInitList:
3897   case FK_ArrayNeedsInitListOrStringLiteral:
3898   case FK_ArrayNeedsInitListOrWideStringLiteral:
3899   case FK_NarrowStringIntoWideCharArray:
3900   case FK_WideStringIntoCharArray:
3901   case FK_IncompatWideStringIntoWideChar:
3902   case FK_PlainStringIntoUTF8Char:
3903   case FK_UTF8StringIntoPlainChar:
3904   case FK_AddressOfOverloadFailed: // FIXME: Could do better
3905   case FK_NonConstLValueReferenceBindingToTemporary:
3906   case FK_NonConstLValueReferenceBindingToBitfield:
3907   case FK_NonConstLValueReferenceBindingToVectorElement:
3908   case FK_NonConstLValueReferenceBindingToMatrixElement:
3909   case FK_NonConstLValueReferenceBindingToUnrelated:
3910   case FK_RValueReferenceBindingToLValue:
3911   case FK_ReferenceAddrspaceMismatchTemporary:
3912   case FK_ReferenceInitDropsQualifiers:
3913   case FK_ReferenceInitFailed:
3914   case FK_ConversionFailed:
3915   case FK_ConversionFromPropertyFailed:
3916   case FK_TooManyInitsForScalar:
3917   case FK_ParenthesizedListInitForScalar:
3918   case FK_ReferenceBindingToInitList:
3919   case FK_InitListBadDestinationType:
3920   case FK_DefaultInitOfConst:
3921   case FK_Incomplete:
3922   case FK_ArrayTypeMismatch:
3923   case FK_NonConstantArrayInit:
3924   case FK_ListInitializationFailed:
3925   case FK_VariableLengthArrayHasInitializer:
3926   case FK_PlaceholderType:
3927   case FK_ExplicitConstructor:
3928   case FK_AddressOfUnaddressableFunction:
3929   case FK_ParenthesizedListInitFailed:
3930   case FK_DesignatedInitForNonAggregate:
3931     return false;
3932 
3933   case FK_ReferenceInitOverloadFailed:
3934   case FK_UserConversionOverloadFailed:
3935   case FK_ConstructorOverloadFailed:
3936   case FK_ListConstructorOverloadFailed:
3937     return FailedOverloadResult == OR_Ambiguous;
3938   }
3939 
3940   llvm_unreachable("Invalid EntityKind!");
3941 }
3942 
isConstructorInitialization() const3943 bool InitializationSequence::isConstructorInitialization() const {
3944   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3945 }
3946 
3947 void
3948 InitializationSequence
AddAddressOverloadResolutionStep(FunctionDecl * Function,DeclAccessPair Found,bool HadMultipleCandidates)3949 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3950                                    DeclAccessPair Found,
3951                                    bool HadMultipleCandidates) {
3952   Step S;
3953   S.Kind = SK_ResolveAddressOfOverloadedFunction;
3954   S.Type = Function->getType();
3955   S.Function.HadMultipleCandidates = HadMultipleCandidates;
3956   S.Function.Function = Function;
3957   S.Function.FoundDecl = Found;
3958   Steps.push_back(S);
3959 }
3960 
AddDerivedToBaseCastStep(QualType BaseType,ExprValueKind VK)3961 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3962                                                       ExprValueKind VK) {
3963   Step S;
3964   switch (VK) {
3965   case VK_PRValue:
3966     S.Kind = SK_CastDerivedToBasePRValue;
3967     break;
3968   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3969   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3970   }
3971   S.Type = BaseType;
3972   Steps.push_back(S);
3973 }
3974 
AddReferenceBindingStep(QualType T,bool BindingTemporary)3975 void InitializationSequence::AddReferenceBindingStep(QualType T,
3976                                                      bool BindingTemporary) {
3977   Step S;
3978   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3979   S.Type = T;
3980   Steps.push_back(S);
3981 }
3982 
AddFinalCopy(QualType T)3983 void InitializationSequence::AddFinalCopy(QualType T) {
3984   Step S;
3985   S.Kind = SK_FinalCopy;
3986   S.Type = T;
3987   Steps.push_back(S);
3988 }
3989 
AddExtraneousCopyToTemporary(QualType T)3990 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3991   Step S;
3992   S.Kind = SK_ExtraneousCopyToTemporary;
3993   S.Type = T;
3994   Steps.push_back(S);
3995 }
3996 
3997 void
AddUserConversionStep(FunctionDecl * Function,DeclAccessPair FoundDecl,QualType T,bool HadMultipleCandidates)3998 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3999                                               DeclAccessPair FoundDecl,
4000                                               QualType T,
4001                                               bool HadMultipleCandidates) {
4002   Step S;
4003   S.Kind = SK_UserConversion;
4004   S.Type = T;
4005   S.Function.HadMultipleCandidates = HadMultipleCandidates;
4006   S.Function.Function = Function;
4007   S.Function.FoundDecl = FoundDecl;
4008   Steps.push_back(S);
4009 }
4010 
AddQualificationConversionStep(QualType Ty,ExprValueKind VK)4011 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
4012                                                             ExprValueKind VK) {
4013   Step S;
4014   S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4015   switch (VK) {
4016   case VK_PRValue:
4017     S.Kind = SK_QualificationConversionPRValue;
4018     break;
4019   case VK_XValue:
4020     S.Kind = SK_QualificationConversionXValue;
4021     break;
4022   case VK_LValue:
4023     S.Kind = SK_QualificationConversionLValue;
4024     break;
4025   }
4026   S.Type = Ty;
4027   Steps.push_back(S);
4028 }
4029 
AddFunctionReferenceConversionStep(QualType Ty)4030 void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
4031   Step S;
4032   S.Kind = SK_FunctionReferenceConversion;
4033   S.Type = Ty;
4034   Steps.push_back(S);
4035 }
4036 
AddAtomicConversionStep(QualType Ty)4037 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
4038   Step S;
4039   S.Kind = SK_AtomicConversion;
4040   S.Type = Ty;
4041   Steps.push_back(S);
4042 }
4043 
AddConversionSequenceStep(const ImplicitConversionSequence & ICS,QualType T,bool TopLevelOfInitList)4044 void InitializationSequence::AddConversionSequenceStep(
4045     const ImplicitConversionSequence &ICS, QualType T,
4046     bool TopLevelOfInitList) {
4047   Step S;
4048   S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4049                               : SK_ConversionSequence;
4050   S.Type = T;
4051   S.ICS = new ImplicitConversionSequence(ICS);
4052   Steps.push_back(S);
4053 }
4054 
AddListInitializationStep(QualType T)4055 void InitializationSequence::AddListInitializationStep(QualType T) {
4056   Step S;
4057   S.Kind = SK_ListInitialization;
4058   S.Type = T;
4059   Steps.push_back(S);
4060 }
4061 
AddConstructorInitializationStep(DeclAccessPair FoundDecl,CXXConstructorDecl * Constructor,QualType T,bool HadMultipleCandidates,bool FromInitList,bool AsInitList)4062 void InitializationSequence::AddConstructorInitializationStep(
4063     DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
4064     bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4065   Step S;
4066   S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4067                                      : SK_ConstructorInitializationFromList
4068                         : SK_ConstructorInitialization;
4069   S.Type = T;
4070   S.Function.HadMultipleCandidates = HadMultipleCandidates;
4071   S.Function.Function = Constructor;
4072   S.Function.FoundDecl = FoundDecl;
4073   Steps.push_back(S);
4074 }
4075 
AddZeroInitializationStep(QualType T)4076 void InitializationSequence::AddZeroInitializationStep(QualType T) {
4077   Step S;
4078   S.Kind = SK_ZeroInitialization;
4079   S.Type = T;
4080   Steps.push_back(S);
4081 }
4082 
AddCAssignmentStep(QualType T)4083 void InitializationSequence::AddCAssignmentStep(QualType T) {
4084   Step S;
4085   S.Kind = SK_CAssignment;
4086   S.Type = T;
4087   Steps.push_back(S);
4088 }
4089 
AddStringInitStep(QualType T)4090 void InitializationSequence::AddStringInitStep(QualType T) {
4091   Step S;
4092   S.Kind = SK_StringInit;
4093   S.Type = T;
4094   Steps.push_back(S);
4095 }
4096 
AddObjCObjectConversionStep(QualType T)4097 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
4098   Step S;
4099   S.Kind = SK_ObjCObjectConversion;
4100   S.Type = T;
4101   Steps.push_back(S);
4102 }
4103 
AddArrayInitStep(QualType T,bool IsGNUExtension)4104 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
4105   Step S;
4106   S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4107   S.Type = T;
4108   Steps.push_back(S);
4109 }
4110 
AddArrayInitLoopStep(QualType T,QualType EltT)4111 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
4112   Step S;
4113   S.Kind = SK_ArrayLoopIndex;
4114   S.Type = EltT;
4115   Steps.insert(Steps.begin(), S);
4116 
4117   S.Kind = SK_ArrayLoopInit;
4118   S.Type = T;
4119   Steps.push_back(S);
4120 }
4121 
AddParenthesizedArrayInitStep(QualType T)4122 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
4123   Step S;
4124   S.Kind = SK_ParenthesizedArrayInit;
4125   S.Type = T;
4126   Steps.push_back(S);
4127 }
4128 
AddPassByIndirectCopyRestoreStep(QualType type,bool shouldCopy)4129 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
4130                                                               bool shouldCopy) {
4131   Step s;
4132   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4133                        : SK_PassByIndirectRestore);
4134   s.Type = type;
4135   Steps.push_back(s);
4136 }
4137 
AddProduceObjCObjectStep(QualType T)4138 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
4139   Step S;
4140   S.Kind = SK_ProduceObjCObject;
4141   S.Type = T;
4142   Steps.push_back(S);
4143 }
4144 
AddStdInitializerListConstructionStep(QualType T)4145 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
4146   Step S;
4147   S.Kind = SK_StdInitializerList;
4148   S.Type = T;
4149   Steps.push_back(S);
4150 }
4151 
AddOCLSamplerInitStep(QualType T)4152 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
4153   Step S;
4154   S.Kind = SK_OCLSamplerInit;
4155   S.Type = T;
4156   Steps.push_back(S);
4157 }
4158 
AddOCLZeroOpaqueTypeStep(QualType T)4159 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
4160   Step S;
4161   S.Kind = SK_OCLZeroOpaqueType;
4162   S.Type = T;
4163   Steps.push_back(S);
4164 }
4165 
AddParenthesizedListInitStep(QualType T)4166 void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
4167   Step S;
4168   S.Kind = SK_ParenthesizedListInit;
4169   S.Type = T;
4170   Steps.push_back(S);
4171 }
4172 
AddUnwrapInitListInitStep(InitListExpr * Syntactic)4173 void InitializationSequence::AddUnwrapInitListInitStep(
4174     InitListExpr *Syntactic) {
4175   assert(Syntactic->getNumInits() == 1 &&
4176          "Can only unwrap trivial init lists.");
4177   Step S;
4178   S.Kind = SK_UnwrapInitList;
4179   S.Type = Syntactic->getInit(0)->getType();
4180   Steps.insert(Steps.begin(), S);
4181 }
4182 
RewrapReferenceInitList(QualType T,InitListExpr * Syntactic)4183 void InitializationSequence::RewrapReferenceInitList(QualType T,
4184                                                      InitListExpr *Syntactic) {
4185   assert(Syntactic->getNumInits() == 1 &&
4186          "Can only rewrap trivial init lists.");
4187   Step S;
4188   S.Kind = SK_UnwrapInitList;
4189   S.Type = Syntactic->getInit(0)->getType();
4190   Steps.insert(Steps.begin(), S);
4191 
4192   S.Kind = SK_RewrapInitList;
4193   S.Type = T;
4194   S.WrappingSyntacticList = Syntactic;
4195   Steps.push_back(S);
4196 }
4197 
SetOverloadFailure(FailureKind Failure,OverloadingResult Result)4198 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
4199                                                 OverloadingResult Result) {
4200   setSequenceKind(FailedSequence);
4201   this->Failure = Failure;
4202   this->FailedOverloadResult = Result;
4203 }
4204 
4205 //===----------------------------------------------------------------------===//
4206 // Attempt initialization
4207 //===----------------------------------------------------------------------===//
4208 
4209 /// Tries to add a zero initializer. Returns true if that worked.
4210 static bool
maybeRecoverWithZeroInitialization(Sema & S,InitializationSequence & Sequence,const InitializedEntity & Entity)4211 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
4212                                    const InitializedEntity &Entity) {
4213   if (Entity.getKind() != InitializedEntity::EK_Variable)
4214     return false;
4215 
4216   VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4217   if (VD->getInit() || VD->getEndLoc().isMacroID())
4218     return false;
4219 
4220   QualType VariableTy = VD->getType().getCanonicalType();
4221   SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
4222   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4223   if (!Init.empty()) {
4224     Sequence.AddZeroInitializationStep(Entity.getType());
4225     Sequence.SetZeroInitializationFixit(Init, Loc);
4226     return true;
4227   }
4228   return false;
4229 }
4230 
MaybeProduceObjCObject(Sema & S,InitializationSequence & Sequence,const InitializedEntity & Entity)4231 static void MaybeProduceObjCObject(Sema &S,
4232                                    InitializationSequence &Sequence,
4233                                    const InitializedEntity &Entity) {
4234   if (!S.getLangOpts().ObjCAutoRefCount) return;
4235 
4236   /// When initializing a parameter, produce the value if it's marked
4237   /// __attribute__((ns_consumed)).
4238   if (Entity.isParameterKind()) {
4239     if (!Entity.isParameterConsumed())
4240       return;
4241 
4242     assert(Entity.getType()->isObjCRetainableType() &&
4243            "consuming an object of unretainable type?");
4244     Sequence.AddProduceObjCObjectStep(Entity.getType());
4245 
4246   /// When initializing a return value, if the return type is a
4247   /// retainable type, then returns need to immediately retain the
4248   /// object.  If an autorelease is required, it will be done at the
4249   /// last instant.
4250   } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4251              Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
4252     if (!Entity.getType()->isObjCRetainableType())
4253       return;
4254 
4255     Sequence.AddProduceObjCObjectStep(Entity.getType());
4256   }
4257 }
4258 
4259 /// Initialize an array from another array
TryArrayCopy(Sema & S,const InitializationKind & Kind,const InitializedEntity & Entity,Expr * Initializer,QualType DestType,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)4260 static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4261                          const InitializedEntity &Entity, Expr *Initializer,
4262                          QualType DestType, InitializationSequence &Sequence,
4263                          bool TreatUnavailableAsInvalid) {
4264   // If source is a prvalue, use it directly.
4265   if (Initializer->isPRValue()) {
4266     Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4267     return;
4268   }
4269 
4270   // Emit element-at-a-time copy loop.
4271   InitializedEntity Element =
4272       InitializedEntity::InitializeElement(S.Context, 0, Entity);
4273   QualType InitEltT =
4274       S.Context.getAsArrayType(Initializer->getType())->getElementType();
4275   OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
4276                       Initializer->getValueKind(),
4277                       Initializer->getObjectKind());
4278   Expr *OVEAsExpr = &OVE;
4279   Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4280                           /*TopLevelOfInitList*/ false,
4281                           TreatUnavailableAsInvalid);
4282   if (Sequence)
4283     Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4284 }
4285 
4286 static void TryListInitialization(Sema &S,
4287                                   const InitializedEntity &Entity,
4288                                   const InitializationKind &Kind,
4289                                   InitListExpr *InitList,
4290                                   InitializationSequence &Sequence,
4291                                   bool TreatUnavailableAsInvalid);
4292 
4293 /// When initializing from init list via constructor, handle
4294 /// initialization of an object of type std::initializer_list<T>.
4295 ///
4296 /// \return true if we have handled initialization of an object of type
4297 /// std::initializer_list<T>, false otherwise.
TryInitializerListConstruction(Sema & S,InitListExpr * List,QualType DestType,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)4298 static bool TryInitializerListConstruction(Sema &S,
4299                                            InitListExpr *List,
4300                                            QualType DestType,
4301                                            InitializationSequence &Sequence,
4302                                            bool TreatUnavailableAsInvalid) {
4303   QualType E;
4304   if (!S.isStdInitializerList(DestType, &E))
4305     return false;
4306 
4307   if (!S.isCompleteType(List->getExprLoc(), E)) {
4308     Sequence.setIncompleteTypeFailure(E);
4309     return true;
4310   }
4311 
4312   // Try initializing a temporary array from the init list.
4313   QualType ArrayType = S.Context.getConstantArrayType(
4314       E.withConst(),
4315       llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4316                   List->getNumInitsWithEmbedExpanded()),
4317       nullptr, clang::ArraySizeModifier::Normal, 0);
4318   InitializedEntity HiddenArray =
4319       InitializedEntity::InitializeTemporary(ArrayType);
4320   InitializationKind Kind = InitializationKind::CreateDirectList(
4321       List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4322   TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4323                         TreatUnavailableAsInvalid);
4324   if (Sequence)
4325     Sequence.AddStdInitializerListConstructionStep(DestType);
4326   return true;
4327 }
4328 
4329 /// Determine if the constructor has the signature of a copy or move
4330 /// constructor for the type T of the class in which it was found. That is,
4331 /// determine if its first parameter is of type T or reference to (possibly
4332 /// cv-qualified) T.
hasCopyOrMoveCtorParam(ASTContext & Ctx,const ConstructorInfo & Info)4333 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
4334                                    const ConstructorInfo &Info) {
4335   if (Info.Constructor->getNumParams() == 0)
4336     return false;
4337 
4338   QualType ParmT =
4339       Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
4340   QualType ClassT =
4341       Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4342 
4343   return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4344 }
4345 
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)4346 static OverloadingResult ResolveConstructorOverload(
4347     Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4348     OverloadCandidateSet &CandidateSet, QualType DestType,
4349     DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,
4350     bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4351     bool IsListInit, bool RequireActualConstructor,
4352     bool SecondStepOfCopyInit = false) {
4353   CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
4354   CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4355 
4356   for (NamedDecl *D : Ctors) {
4357     auto Info = getConstructorInfo(D);
4358     if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4359       continue;
4360 
4361     if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4362       continue;
4363 
4364     // C++11 [over.best.ics]p4:
4365     //   ... and the constructor or user-defined conversion function is a
4366     //   candidate by
4367     //   - 13.3.1.3, when the argument is the temporary in the second step
4368     //     of a class copy-initialization, or
4369     //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4370     //   - the second phase of 13.3.1.7 when the initializer list has exactly
4371     //     one element that is itself an initializer list, and the target is
4372     //     the first parameter of a constructor of class X, and the conversion
4373     //     is to X or reference to (possibly cv-qualified X),
4374     //   user-defined conversion sequences are not considered.
4375     bool SuppressUserConversions =
4376         SecondStepOfCopyInit ||
4377         (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4378          hasCopyOrMoveCtorParam(S.Context, Info));
4379 
4380     if (Info.ConstructorTmpl)
4381       S.AddTemplateOverloadCandidate(
4382           Info.ConstructorTmpl, Info.FoundDecl,
4383           /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4384           /*PartialOverloading=*/false, AllowExplicit);
4385     else {
4386       // C++ [over.match.copy]p1:
4387       //   - When initializing a temporary to be bound to the first parameter
4388       //     of a constructor [for type T] that takes a reference to possibly
4389       //     cv-qualified T as its first argument, called with a single
4390       //     argument in the context of direct-initialization, explicit
4391       //     conversion functions are also considered.
4392       // FIXME: What if a constructor template instantiates to such a signature?
4393       bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4394                                Args.size() == 1 &&
4395                                hasCopyOrMoveCtorParam(S.Context, Info);
4396       S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4397                              CandidateSet, SuppressUserConversions,
4398                              /*PartialOverloading=*/false, AllowExplicit,
4399                              AllowExplicitConv);
4400     }
4401   }
4402 
4403   // FIXME: Work around a bug in C++17 guaranteed copy elision.
4404   //
4405   // When initializing an object of class type T by constructor
4406   // ([over.match.ctor]) or by list-initialization ([over.match.list])
4407   // from a single expression of class type U, conversion functions of
4408   // U that convert to the non-reference type cv T are candidates.
4409   // Explicit conversion functions are only candidates during
4410   // direct-initialization.
4411   //
4412   // Note: SecondStepOfCopyInit is only ever true in this case when
4413   // evaluating whether to produce a C++98 compatibility warning.
4414   if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4415       !RequireActualConstructor && !SecondStepOfCopyInit) {
4416     Expr *Initializer = Args[0];
4417     auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4418     if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4419       const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4420       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4421         NamedDecl *D = *I;
4422         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4423         D = D->getUnderlyingDecl();
4424 
4425         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4426         CXXConversionDecl *Conv;
4427         if (ConvTemplate)
4428           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4429         else
4430           Conv = cast<CXXConversionDecl>(D);
4431 
4432         if (ConvTemplate)
4433           S.AddTemplateConversionCandidate(
4434               ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4435               CandidateSet, AllowExplicit, AllowExplicit,
4436               /*AllowResultConversion*/ false);
4437         else
4438           S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4439                                    DestType, CandidateSet, AllowExplicit,
4440                                    AllowExplicit,
4441                                    /*AllowResultConversion*/ false);
4442       }
4443     }
4444   }
4445 
4446   // Perform overload resolution and return the result.
4447   return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4448 }
4449 
4450 /// Attempt initialization by constructor (C++ [dcl.init]), which
4451 /// enumerates the constructors of the initialized entity and performs overload
4452 /// resolution to select the best.
4453 /// \param DestType       The destination class type.
4454 /// \param DestArrayType  The destination type, which is either DestType or
4455 ///                       a (possibly multidimensional) array of DestType.
4456 /// \param IsListInit     Is this list-initialization?
4457 /// \param IsInitListCopy Is this non-list-initialization resulting from a
4458 ///                       list-initialization from {x} where x is the same
4459 ///                       aggregate type as the entity?
TryConstructorInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,QualType DestType,QualType DestArrayType,InitializationSequence & Sequence,bool IsListInit=false,bool IsInitListCopy=false)4460 static void TryConstructorInitialization(Sema &S,
4461                                          const InitializedEntity &Entity,
4462                                          const InitializationKind &Kind,
4463                                          MultiExprArg Args, QualType DestType,
4464                                          QualType DestArrayType,
4465                                          InitializationSequence &Sequence,
4466                                          bool IsListInit = false,
4467                                          bool IsInitListCopy = false) {
4468   assert(((!IsListInit && !IsInitListCopy) ||
4469           (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4470          "IsListInit/IsInitListCopy must come with a single initializer list "
4471          "argument.");
4472   InitListExpr *ILE =
4473       (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4474   MultiExprArg UnwrappedArgs =
4475       ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4476 
4477   // The type we're constructing needs to be complete.
4478   if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4479     Sequence.setIncompleteTypeFailure(DestType);
4480     return;
4481   }
4482 
4483   bool RequireActualConstructor =
4484       !(Entity.getKind() != InitializedEntity::EK_Base &&
4485         Entity.getKind() != InitializedEntity::EK_Delegating &&
4486         Entity.getKind() !=
4487             InitializedEntity::EK_LambdaToBlockConversionBlockElement);
4488 
4489   bool CopyElisionPossible = false;
4490   auto ElideConstructor = [&] {
4491     // Convert qualifications if necessary.
4492     Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4493     if (ILE)
4494       Sequence.RewrapReferenceInitList(DestType, ILE);
4495   };
4496 
4497   // C++17 [dcl.init]p17:
4498   //     - If the initializer expression is a prvalue and the cv-unqualified
4499   //       version of the source type is the same class as the class of the
4500   //       destination, the initializer expression is used to initialize the
4501   //       destination object.
4502   // Per DR (no number yet), this does not apply when initializing a base
4503   // class or delegating to another constructor from a mem-initializer.
4504   // ObjC++: Lambda captured by the block in the lambda to block conversion
4505   // should avoid copy elision.
4506   if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4507       UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4508       S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4509     if (ILE && !DestType->isAggregateType()) {
4510       // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4511       // Make this an elision if this won't call an initializer-list
4512       // constructor. (Always on an aggregate type or check constructors first.)
4513 
4514       // This effectively makes our resolution as follows. The parts in angle
4515       // brackets are additions.
4516       // C++17 [over.match.list]p(1.2):
4517       //   - If no viable initializer-list constructor is found <and the
4518       //     initializer list does not consist of exactly a single element with
4519       //     the same cv-unqualified class type as T>, [...]
4520       // C++17 [dcl.init.list]p(3.6):
4521       //   - Otherwise, if T is a class type, constructors are considered. The
4522       //     applicable constructors are enumerated and the best one is chosen
4523       //     through overload resolution. <If no constructor is found and the
4524       //     initializer list consists of exactly a single element with the same
4525       //     cv-unqualified class type as T, the object is initialized from that
4526       //     element (by copy-initialization for copy-list-initialization, or by
4527       //     direct-initialization for direct-list-initialization). Otherwise, >
4528       //     if a narrowing conversion [...]
4529       assert(!IsInitListCopy &&
4530              "IsInitListCopy only possible with aggregate types");
4531       CopyElisionPossible = true;
4532     } else {
4533       ElideConstructor();
4534       return;
4535     }
4536   }
4537 
4538   const RecordType *DestRecordType = DestType->getAs<RecordType>();
4539   assert(DestRecordType && "Constructor initialization requires record type");
4540   CXXRecordDecl *DestRecordDecl
4541     = cast<CXXRecordDecl>(DestRecordType->getDecl());
4542 
4543   // Build the candidate set directly in the initialization sequence
4544   // structure, so that it will persist if we fail.
4545   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4546 
4547   // Determine whether we are allowed to call explicit constructors or
4548   // explicit conversion operators.
4549   bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4550   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4551 
4552   //   - Otherwise, if T is a class type, constructors are considered. The
4553   //     applicable constructors are enumerated, and the best one is chosen
4554   //     through overload resolution.
4555   DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4556 
4557   OverloadingResult Result = OR_No_Viable_Function;
4558   OverloadCandidateSet::iterator Best;
4559   bool AsInitializerList = false;
4560 
4561   // C++11 [over.match.list]p1, per DR1467:
4562   //   When objects of non-aggregate type T are list-initialized, such that
4563   //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
4564   //   according to the rules in this section, overload resolution selects
4565   //   the constructor in two phases:
4566   //
4567   //   - Initially, the candidate functions are the initializer-list
4568   //     constructors of the class T and the argument list consists of the
4569   //     initializer list as a single argument.
4570   if (IsListInit) {
4571     AsInitializerList = true;
4572 
4573     // If the initializer list has no elements and T has a default constructor,
4574     // the first phase is omitted.
4575     if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4576       Result = ResolveConstructorOverload(
4577           S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4578           CopyInitialization, AllowExplicit,
4579           /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4580 
4581     if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4582       // No initializer list candidate
4583       ElideConstructor();
4584       return;
4585     }
4586   }
4587 
4588   // C++11 [over.match.list]p1:
4589   //   - If no viable initializer-list constructor is found, overload resolution
4590   //     is performed again, where the candidate functions are all the
4591   //     constructors of the class T and the argument list consists of the
4592   //     elements of the initializer list.
4593   if (Result == OR_No_Viable_Function) {
4594     AsInitializerList = false;
4595     Result = ResolveConstructorOverload(
4596         S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4597         Best, CopyInitialization, AllowExplicit,
4598         /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4599   }
4600   if (Result) {
4601     Sequence.SetOverloadFailure(
4602         IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4603                    : InitializationSequence::FK_ConstructorOverloadFailed,
4604         Result);
4605 
4606     if (Result != OR_Deleted)
4607       return;
4608   }
4609 
4610   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4611 
4612   // In C++17, ResolveConstructorOverload can select a conversion function
4613   // instead of a constructor.
4614   if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4615     // Add the user-defined conversion step that calls the conversion function.
4616     QualType ConvType = CD->getConversionType();
4617     assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4618            "should not have selected this conversion function");
4619     Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4620                                    HadMultipleCandidates);
4621     if (!S.Context.hasSameType(ConvType, DestType))
4622       Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4623     if (IsListInit)
4624       Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4625     return;
4626   }
4627 
4628   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4629   if (Result != OR_Deleted) {
4630     if (!IsListInit &&
4631         (Kind.getKind() == InitializationKind::IK_Default ||
4632          Kind.getKind() == InitializationKind::IK_Direct) &&
4633         !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4634         DestRecordDecl->isAggregate() &&
4635         DestRecordDecl->hasUninitializedExplicitInitFields() &&
4636         !S.isUnevaluatedContext()) {
4637       S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4638           << /* Var-in-Record */ 1 << DestRecordDecl;
4639       emitUninitializedExplicitInitFields(S, DestRecordDecl);
4640     }
4641 
4642     // C++11 [dcl.init]p6:
4643     //   If a program calls for the default initialization of an object
4644     //   of a const-qualified type T, T shall be a class type with a
4645     //   user-provided default constructor.
4646     // C++ core issue 253 proposal:
4647     //   If the implicit default constructor initializes all subobjects, no
4648     //   initializer should be required.
4649     // The 253 proposal is for example needed to process libstdc++ headers
4650     // in 5.x.
4651     if (Kind.getKind() == InitializationKind::IK_Default &&
4652         Entity.getType().isConstQualified()) {
4653       if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4654         if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4655           Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4656         return;
4657       }
4658     }
4659 
4660     // C++11 [over.match.list]p1:
4661     //   In copy-list-initialization, if an explicit constructor is chosen, the
4662     //   initializer is ill-formed.
4663     if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4664       Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4665       return;
4666     }
4667   }
4668 
4669   // [class.copy.elision]p3:
4670   // In some copy-initialization contexts, a two-stage overload resolution
4671   // is performed.
4672   // If the first overload resolution selects a deleted function, we also
4673   // need the initialization sequence to decide whether to perform the second
4674   // overload resolution.
4675   // For deleted functions in other contexts, there is no need to get the
4676   // initialization sequence.
4677   if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4678     return;
4679 
4680   // Add the constructor initialization step. Any cv-qualification conversion is
4681   // subsumed by the initialization.
4682   Sequence.AddConstructorInitializationStep(
4683       Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4684       IsListInit | IsInitListCopy, AsInitializerList);
4685 }
4686 
4687 static void TryOrBuildParenListInitialization(
4688     Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4689     ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4690     ExprResult *Result = nullptr);
4691 
4692 /// Attempt to initialize an object of a class type either by
4693 /// direct-initialization, or by copy-initialization from an
4694 /// expression of the same or derived class type. This corresponds
4695 /// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4696 ///
4697 /// \param IsAggrListInit Is this non-list-initialization being done as
4698 ///                       part of a list-initialization of an aggregate
4699 ///                       from a single expression of the same or
4700 ///                       derived class type (C++2c [dcl.init.list] p3.2)?
TryConstructorOrParenListInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,QualType DestType,InitializationSequence & Sequence,bool IsAggrListInit)4701 static void TryConstructorOrParenListInitialization(
4702     Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4703     MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4704     bool IsAggrListInit) {
4705   // C++2c [dcl.init.general] p16.6:
4706   //   * Otherwise, if the destination type is a class type:
4707   //     * If the initializer expression is a prvalue and
4708   //       the cv-unqualified version of the source type is the same
4709   //       as the destination type, the initializer expression is used
4710   //       to initialize the destination object.
4711   //     * Otherwise, if the initialization is direct-initialization,
4712   //       or if it is copy-initialization where the cv-unqualified
4713   //       version of the source type is the same as or is derived from
4714   //       the class of the destination type, constructors are considered.
4715   //       The applicable constructors are enumerated, and the best one
4716   //       is chosen through overload resolution. Then:
4717   //       * If overload resolution is successful, the selected
4718   //         constructor is called to initialize the object, with
4719   //         the initializer expression or expression-list as its
4720   //         argument(s).
4721   TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4722                                Sequence, /*IsListInit=*/false, IsAggrListInit);
4723 
4724   //       * Otherwise, if no constructor is viable, the destination type
4725   //         is an aggregate class, and the initializer is a parenthesized
4726   //         expression-list, the object is initialized as follows. [...]
4727   // Parenthesized initialization of aggregates is a C++20 feature.
4728   if (S.getLangOpts().CPlusPlus20 &&
4729       Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4730       Sequence.getFailureKind() ==
4731           InitializationSequence::FK_ConstructorOverloadFailed &&
4732       Sequence.getFailedOverloadResult() == OR_No_Viable_Function &&
4733       (IsAggrListInit || DestType->isAggregateType()))
4734     TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4735                                       /*VerifyOnly=*/true);
4736 
4737   //       * Otherwise, the initialization is ill-formed.
4738 }
4739 
4740 static bool
ResolveOverloadedFunctionForReferenceBinding(Sema & S,Expr * Initializer,QualType & SourceType,QualType & UnqualifiedSourceType,QualType UnqualifiedTargetType,InitializationSequence & Sequence)4741 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4742                                              Expr *Initializer,
4743                                              QualType &SourceType,
4744                                              QualType &UnqualifiedSourceType,
4745                                              QualType UnqualifiedTargetType,
4746                                              InitializationSequence &Sequence) {
4747   if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4748         S.Context.OverloadTy) {
4749     DeclAccessPair Found;
4750     bool HadMultipleCandidates = false;
4751     if (FunctionDecl *Fn
4752         = S.ResolveAddressOfOverloadedFunction(Initializer,
4753                                                UnqualifiedTargetType,
4754                                                false, Found,
4755                                                &HadMultipleCandidates)) {
4756       Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4757                                                 HadMultipleCandidates);
4758       SourceType = Fn->getType();
4759       UnqualifiedSourceType = SourceType.getUnqualifiedType();
4760     } else if (!UnqualifiedTargetType->isRecordType()) {
4761       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4762       return true;
4763     }
4764   }
4765   return false;
4766 }
4767 
4768 static void TryReferenceInitializationCore(Sema &S,
4769                                            const InitializedEntity &Entity,
4770                                            const InitializationKind &Kind,
4771                                            Expr *Initializer,
4772                                            QualType cv1T1, QualType T1,
4773                                            Qualifiers T1Quals,
4774                                            QualType cv2T2, QualType T2,
4775                                            Qualifiers T2Quals,
4776                                            InitializationSequence &Sequence,
4777                                            bool TopLevelOfInitList);
4778 
4779 static void TryValueInitialization(Sema &S,
4780                                    const InitializedEntity &Entity,
4781                                    const InitializationKind &Kind,
4782                                    InitializationSequence &Sequence,
4783                                    InitListExpr *InitList = nullptr);
4784 
4785 /// Attempt list initialization of a reference.
TryReferenceListInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitListExpr * InitList,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)4786 static void TryReferenceListInitialization(Sema &S,
4787                                            const InitializedEntity &Entity,
4788                                            const InitializationKind &Kind,
4789                                            InitListExpr *InitList,
4790                                            InitializationSequence &Sequence,
4791                                            bool TreatUnavailableAsInvalid) {
4792   // First, catch C++03 where this isn't possible.
4793   if (!S.getLangOpts().CPlusPlus11) {
4794     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4795     return;
4796   }
4797   // Can't reference initialize a compound literal.
4798   if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4799     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4800     return;
4801   }
4802 
4803   QualType DestType = Entity.getType();
4804   QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4805   Qualifiers T1Quals;
4806   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4807 
4808   // Reference initialization via an initializer list works thus:
4809   // If the initializer list consists of a single element that is
4810   // reference-related to the referenced type, bind directly to that element
4811   // (possibly creating temporaries).
4812   // Otherwise, initialize a temporary with the initializer list and
4813   // bind to that.
4814   if (InitList->getNumInits() == 1) {
4815     Expr *Initializer = InitList->getInit(0);
4816     QualType cv2T2 = S.getCompletedType(Initializer);
4817     Qualifiers T2Quals;
4818     QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4819 
4820     // If this fails, creating a temporary wouldn't work either.
4821     if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4822                                                      T1, Sequence))
4823       return;
4824 
4825     SourceLocation DeclLoc = Initializer->getBeginLoc();
4826     Sema::ReferenceCompareResult RefRelationship
4827       = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4828     if (RefRelationship >= Sema::Ref_Related) {
4829       // Try to bind the reference here.
4830       TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4831                                      T1Quals, cv2T2, T2, T2Quals, Sequence,
4832                                      /*TopLevelOfInitList=*/true);
4833       if (Sequence)
4834         Sequence.RewrapReferenceInitList(cv1T1, InitList);
4835       return;
4836     }
4837 
4838     // Update the initializer if we've resolved an overloaded function.
4839     if (Sequence.step_begin() != Sequence.step_end())
4840       Sequence.RewrapReferenceInitList(cv1T1, InitList);
4841   }
4842   // Perform address space compatibility check.
4843   QualType cv1T1IgnoreAS = cv1T1;
4844   if (T1Quals.hasAddressSpace()) {
4845     Qualifiers T2Quals;
4846     (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4847     if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4848       Sequence.SetFailed(
4849           InitializationSequence::FK_ReferenceInitDropsQualifiers);
4850       return;
4851     }
4852     // Ignore address space of reference type at this point and perform address
4853     // space conversion after the reference binding step.
4854     cv1T1IgnoreAS =
4855         S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4856   }
4857   // Not reference-related. Create a temporary and bind to that.
4858   InitializedEntity TempEntity =
4859       InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4860 
4861   TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4862                         TreatUnavailableAsInvalid);
4863   if (Sequence) {
4864     if (DestType->isRValueReferenceType() ||
4865         (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4866       if (S.getLangOpts().CPlusPlus20 &&
4867           isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4868           DestType->isRValueReferenceType()) {
4869         // C++20 [dcl.init.list]p3.10:
4870         // List-initialization of an object or reference of type T is defined as
4871         // follows:
4872         // ..., unless T is “reference to array of unknown bound of U”, in which
4873         // case the type of the prvalue is the type of x in the declaration U
4874         // x[] H, where H is the initializer list.
4875         Sequence.AddQualificationConversionStep(cv1T1, clang::VK_PRValue);
4876       }
4877       Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4878                                        /*BindingTemporary=*/true);
4879       if (T1Quals.hasAddressSpace())
4880         Sequence.AddQualificationConversionStep(
4881             cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4882     } else
4883       Sequence.SetFailed(
4884           InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4885   }
4886 }
4887 
4888 /// Attempt list initialization (C++0x [dcl.init.list])
TryListInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitListExpr * InitList,InitializationSequence & Sequence,bool TreatUnavailableAsInvalid)4889 static void TryListInitialization(Sema &S,
4890                                   const InitializedEntity &Entity,
4891                                   const InitializationKind &Kind,
4892                                   InitListExpr *InitList,
4893                                   InitializationSequence &Sequence,
4894                                   bool TreatUnavailableAsInvalid) {
4895   QualType DestType = Entity.getType();
4896 
4897   if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList))
4898     return;
4899 
4900   // C++ doesn't allow scalar initialization with more than one argument.
4901   // But C99 complex numbers are scalars and it makes sense there.
4902   if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4903       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4904     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4905     return;
4906   }
4907   if (DestType->isReferenceType()) {
4908     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4909                                    TreatUnavailableAsInvalid);
4910     return;
4911   }
4912 
4913   if (DestType->isRecordType() &&
4914       !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4915     Sequence.setIncompleteTypeFailure(DestType);
4916     return;
4917   }
4918 
4919   // C++20 [dcl.init.list]p3:
4920   // - If the braced-init-list contains a designated-initializer-list, T shall
4921   //   be an aggregate class. [...] Aggregate initialization is performed.
4922   //
4923   // We allow arrays here too in order to support array designators.
4924   //
4925   // FIXME: This check should precede the handling of reference initialization.
4926   // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4927   // as a tentative DR resolution.
4928   bool IsDesignatedInit = InitList->hasDesignatedInit();
4929   if (!DestType->isAggregateType() && IsDesignatedInit) {
4930     Sequence.SetFailed(
4931         InitializationSequence::FK_DesignatedInitForNonAggregate);
4932     return;
4933   }
4934 
4935   // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4936   // - If T is an aggregate class and the initializer list has a single element
4937   //   of type cv U, where U is T or a class derived from T, the object is
4938   //   initialized from that element (by copy-initialization for
4939   //   copy-list-initialization, or by direct-initialization for
4940   //   direct-list-initialization).
4941   // - Otherwise, if T is a character array and the initializer list has a
4942   //   single element that is an appropriately-typed string literal
4943   //   (8.5.2 [dcl.init.string]), initialization is performed as described
4944   //   in that section.
4945   // - Otherwise, if T is an aggregate, [...] (continue below).
4946   if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4947       !IsDesignatedInit) {
4948     if (DestType->isRecordType() && DestType->isAggregateType()) {
4949       QualType InitType = InitList->getInit(0)->getType();
4950       if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4951           S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4952         InitializationKind SubKind =
4953             Kind.getKind() == InitializationKind::IK_DirectList
4954                 ? InitializationKind::CreateDirect(Kind.getLocation(),
4955                                                    InitList->getLBraceLoc(),
4956                                                    InitList->getRBraceLoc())
4957                 : Kind;
4958         Expr *InitListAsExpr = InitList;
4959         TryConstructorOrParenListInitialization(
4960             S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
4961             /*IsAggrListInit=*/true);
4962         return;
4963       }
4964     }
4965     if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4966       Expr *SubInit[1] = {InitList->getInit(0)};
4967 
4968       // C++17 [dcl.struct.bind]p1:
4969       // ... If the assignment-expression in the initializer has array type A
4970       // and no ref-qualifier is present, e has type cv A and each element is
4971       // copy-initialized or direct-initialized from the corresponding element
4972       // of the assignment-expression as specified by the form of the
4973       // initializer. ...
4974       //
4975       // This is a special case not following list-initialization.
4976       if (isa<ConstantArrayType>(DestAT) &&
4977           Entity.getKind() == InitializedEntity::EK_Variable &&
4978           isa<DecompositionDecl>(Entity.getDecl())) {
4979         assert(
4980             S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
4981             "Deduced to other type?");
4982         assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
4983                "List-initialize structured bindings but not "
4984                "direct-list-initialization?");
4985         TryArrayCopy(S,
4986                      InitializationKind::CreateDirect(Kind.getLocation(),
4987                                                       InitList->getLBraceLoc(),
4988                                                       InitList->getRBraceLoc()),
4989                      Entity, SubInit[0], DestType, Sequence,
4990                      TreatUnavailableAsInvalid);
4991         if (Sequence)
4992           Sequence.AddUnwrapInitListInitStep(InitList);
4993         return;
4994       }
4995 
4996       if (!isa<VariableArrayType>(DestAT) &&
4997           IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4998         InitializationKind SubKind =
4999             Kind.getKind() == InitializationKind::IK_DirectList
5000                 ? InitializationKind::CreateDirect(Kind.getLocation(),
5001                                                    InitList->getLBraceLoc(),
5002                                                    InitList->getRBraceLoc())
5003                 : Kind;
5004         Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5005                                 /*TopLevelOfInitList*/ true,
5006                                 TreatUnavailableAsInvalid);
5007 
5008         // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5009         // the element is not an appropriately-typed string literal, in which
5010         // case we should proceed as in C++11 (below).
5011         if (Sequence) {
5012           Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5013           return;
5014         }
5015       }
5016     }
5017   }
5018 
5019   // C++11 [dcl.init.list]p3:
5020   //   - If T is an aggregate, aggregate initialization is performed.
5021   if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5022       (S.getLangOpts().CPlusPlus11 &&
5023        S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5024     if (S.getLangOpts().CPlusPlus11) {
5025       //   - Otherwise, if the initializer list has no elements and T is a
5026       //     class type with a default constructor, the object is
5027       //     value-initialized.
5028       if (InitList->getNumInits() == 0) {
5029         CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
5030         if (S.LookupDefaultConstructor(RD)) {
5031           TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5032           return;
5033         }
5034       }
5035 
5036       //   - Otherwise, if T is a specialization of std::initializer_list<E>,
5037       //     an initializer_list object constructed [...]
5038       if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5039                                          TreatUnavailableAsInvalid))
5040         return;
5041 
5042       //   - Otherwise, if T is a class type, constructors are considered.
5043       Expr *InitListAsExpr = InitList;
5044       TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5045                                    DestType, Sequence, /*InitListSyntax*/true);
5046     } else
5047       Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
5048     return;
5049   }
5050 
5051   if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5052       InitList->getNumInits() == 1) {
5053     Expr *E = InitList->getInit(0);
5054 
5055     //   - Otherwise, if T is an enumeration with a fixed underlying type,
5056     //     the initializer-list has a single element v, and the initialization
5057     //     is direct-list-initialization, the object is initialized with the
5058     //     value T(v); if a narrowing conversion is required to convert v to
5059     //     the underlying type of T, the program is ill-formed.
5060     auto *ET = DestType->getAs<EnumType>();
5061     if (S.getLangOpts().CPlusPlus17 &&
5062         Kind.getKind() == InitializationKind::IK_DirectList &&
5063         ET && ET->getDecl()->isFixed() &&
5064         !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5065         (E->getType()->isIntegralOrUnscopedEnumerationType() ||
5066          E->getType()->isFloatingType())) {
5067       // There are two ways that T(v) can work when T is an enumeration type.
5068       // If there is either an implicit conversion sequence from v to T or
5069       // a conversion function that can convert from v to T, then we use that.
5070       // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5071       // type, it is converted to the enumeration type via its underlying type.
5072       // There is no overlap possible between these two cases (except when the
5073       // source value is already of the destination type), and the first
5074       // case is handled by the general case for single-element lists below.
5075       ImplicitConversionSequence ICS;
5076       ICS.setStandard();
5077       ICS.Standard.setAsIdentityConversion();
5078       if (!E->isPRValue())
5079         ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5080       // If E is of a floating-point type, then the conversion is ill-formed
5081       // due to narrowing, but go through the motions in order to produce the
5082       // right diagnostic.
5083       ICS.Standard.Second = E->getType()->isFloatingType()
5084                                 ? ICK_Floating_Integral
5085                                 : ICK_Integral_Conversion;
5086       ICS.Standard.setFromType(E->getType());
5087       ICS.Standard.setToType(0, E->getType());
5088       ICS.Standard.setToType(1, DestType);
5089       ICS.Standard.setToType(2, DestType);
5090       Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5091                                          /*TopLevelOfInitList*/true);
5092       Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5093       return;
5094     }
5095 
5096     //   - Otherwise, if the initializer list has a single element of type E
5097     //     [...references are handled above...], the object or reference is
5098     //     initialized from that element (by copy-initialization for
5099     //     copy-list-initialization, or by direct-initialization for
5100     //     direct-list-initialization); if a narrowing conversion is required
5101     //     to convert the element to T, the program is ill-formed.
5102     //
5103     // Per core-24034, this is direct-initialization if we were performing
5104     // direct-list-initialization and copy-initialization otherwise.
5105     // We can't use InitListChecker for this, because it always performs
5106     // copy-initialization. This only matters if we might use an 'explicit'
5107     // conversion operator, or for the special case conversion of nullptr_t to
5108     // bool, so we only need to handle those cases.
5109     //
5110     // FIXME: Why not do this in all cases?
5111     Expr *Init = InitList->getInit(0);
5112     if (Init->getType()->isRecordType() ||
5113         (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5114       InitializationKind SubKind =
5115           Kind.getKind() == InitializationKind::IK_DirectList
5116               ? InitializationKind::CreateDirect(Kind.getLocation(),
5117                                                  InitList->getLBraceLoc(),
5118                                                  InitList->getRBraceLoc())
5119               : Kind;
5120       Expr *SubInit[1] = { Init };
5121       Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5122                               /*TopLevelOfInitList*/true,
5123                               TreatUnavailableAsInvalid);
5124       if (Sequence)
5125         Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5126       return;
5127     }
5128   }
5129 
5130   InitListChecker CheckInitList(S, Entity, InitList,
5131           DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5132   if (CheckInitList.HadError()) {
5133     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
5134     return;
5135   }
5136 
5137   // Add the list initialization step with the built init list.
5138   Sequence.AddListInitializationStep(DestType);
5139 }
5140 
5141 /// Try a reference initialization that involves calling a conversion
5142 /// function.
TryRefInitWithConversionFunction(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,bool AllowRValues,bool IsLValueRef,InitializationSequence & Sequence)5143 static OverloadingResult TryRefInitWithConversionFunction(
5144     Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5145     Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5146     InitializationSequence &Sequence) {
5147   QualType DestType = Entity.getType();
5148   QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5149   QualType T1 = cv1T1.getUnqualifiedType();
5150   QualType cv2T2 = Initializer->getType();
5151   QualType T2 = cv2T2.getUnqualifiedType();
5152 
5153   assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5154          "Must have incompatible references when binding via conversion");
5155 
5156   // Build the candidate set directly in the initialization sequence
5157   // structure, so that it will persist if we fail.
5158   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5159   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5160 
5161   // Determine whether we are allowed to call explicit conversion operators.
5162   // Note that none of [over.match.copy], [over.match.conv], nor
5163   // [over.match.ref] permit an explicit constructor to be chosen when
5164   // initializing a reference, not even for direct-initialization.
5165   bool AllowExplicitCtors = false;
5166   bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5167 
5168   const RecordType *T1RecordType = nullptr;
5169   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
5170       S.isCompleteType(Kind.getLocation(), T1)) {
5171     // The type we're converting to is a class type. Enumerate its constructors
5172     // to see if there is a suitable conversion.
5173     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
5174 
5175     for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5176       auto Info = getConstructorInfo(D);
5177       if (!Info.Constructor)
5178         continue;
5179 
5180       if (!Info.Constructor->isInvalidDecl() &&
5181           Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5182         if (Info.ConstructorTmpl)
5183           S.AddTemplateOverloadCandidate(
5184               Info.ConstructorTmpl, Info.FoundDecl,
5185               /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5186               /*SuppressUserConversions=*/true,
5187               /*PartialOverloading*/ false, AllowExplicitCtors);
5188         else
5189           S.AddOverloadCandidate(
5190               Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5191               /*SuppressUserConversions=*/true,
5192               /*PartialOverloading*/ false, AllowExplicitCtors);
5193       }
5194     }
5195   }
5196   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
5197     return OR_No_Viable_Function;
5198 
5199   const RecordType *T2RecordType = nullptr;
5200   if ((T2RecordType = T2->getAs<RecordType>()) &&
5201       S.isCompleteType(Kind.getLocation(), T2)) {
5202     // The type we're converting from is a class type, enumerate its conversion
5203     // functions.
5204     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
5205 
5206     const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5207     for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5208       NamedDecl *D = *I;
5209       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5210       if (isa<UsingShadowDecl>(D))
5211         D = cast<UsingShadowDecl>(D)->getTargetDecl();
5212 
5213       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5214       CXXConversionDecl *Conv;
5215       if (ConvTemplate)
5216         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5217       else
5218         Conv = cast<CXXConversionDecl>(D);
5219 
5220       // If the conversion function doesn't return a reference type,
5221       // it can't be considered for this conversion unless we're allowed to
5222       // consider rvalues.
5223       // FIXME: Do we need to make sure that we only consider conversion
5224       // candidates with reference-compatible results? That might be needed to
5225       // break recursion.
5226       if ((AllowRValues ||
5227            Conv->getConversionType()->isLValueReferenceType())) {
5228         if (ConvTemplate)
5229           S.AddTemplateConversionCandidate(
5230               ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5231               CandidateSet,
5232               /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5233         else
5234           S.AddConversionCandidate(
5235               Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5236               /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5237       }
5238     }
5239   }
5240   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
5241     return OR_No_Viable_Function;
5242 
5243   SourceLocation DeclLoc = Initializer->getBeginLoc();
5244 
5245   // Perform overload resolution. If it fails, return the failed result.
5246   OverloadCandidateSet::iterator Best;
5247   if (OverloadingResult Result
5248         = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5249     return Result;
5250 
5251   FunctionDecl *Function = Best->Function;
5252   // This is the overload that will be used for this initialization step if we
5253   // use this initialization. Mark it as referenced.
5254   Function->setReferenced();
5255 
5256   // Compute the returned type and value kind of the conversion.
5257   QualType cv3T3;
5258   if (isa<CXXConversionDecl>(Function))
5259     cv3T3 = Function->getReturnType();
5260   else
5261     cv3T3 = T1;
5262 
5263   ExprValueKind VK = VK_PRValue;
5264   if (cv3T3->isLValueReferenceType())
5265     VK = VK_LValue;
5266   else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5267     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5268   cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5269 
5270   // Add the user-defined conversion step.
5271   bool HadMultipleCandidates = (CandidateSet.size() > 1);
5272   Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5273                                  HadMultipleCandidates);
5274 
5275   // Determine whether we'll need to perform derived-to-base adjustments or
5276   // other conversions.
5277   Sema::ReferenceConversions RefConv;
5278   Sema::ReferenceCompareResult NewRefRelationship =
5279       S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5280 
5281   // Add the final conversion sequence, if necessary.
5282   if (NewRefRelationship == Sema::Ref_Incompatible) {
5283     assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5284            "should not have conversion after constructor");
5285 
5286     ImplicitConversionSequence ICS;
5287     ICS.setStandard();
5288     ICS.Standard = Best->FinalConversion;
5289     Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5290 
5291     // Every implicit conversion results in a prvalue, except for a glvalue
5292     // derived-to-base conversion, which we handle below.
5293     cv3T3 = ICS.Standard.getToType(2);
5294     VK = VK_PRValue;
5295   }
5296 
5297   //   If the converted initializer is a prvalue, its type T4 is adjusted to
5298   //   type "cv1 T4" and the temporary materialization conversion is applied.
5299   //
5300   // We adjust the cv-qualifications to match the reference regardless of
5301   // whether we have a prvalue so that the AST records the change. In this
5302   // case, T4 is "cv3 T3".
5303   QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5304   if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5305     Sequence.AddQualificationConversionStep(cv1T4, VK);
5306   Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5307   VK = IsLValueRef ? VK_LValue : VK_XValue;
5308 
5309   if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5310     Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5311   else if (RefConv & Sema::ReferenceConversions::ObjC)
5312     Sequence.AddObjCObjectConversionStep(cv1T1);
5313   else if (RefConv & Sema::ReferenceConversions::Function)
5314     Sequence.AddFunctionReferenceConversionStep(cv1T1);
5315   else if (RefConv & Sema::ReferenceConversions::Qualification) {
5316     if (!S.Context.hasSameType(cv1T4, cv1T1))
5317       Sequence.AddQualificationConversionStep(cv1T1, VK);
5318   }
5319 
5320   return OR_Success;
5321 }
5322 
5323 static void CheckCXX98CompatAccessibleCopy(Sema &S,
5324                                            const InitializedEntity &Entity,
5325                                            Expr *CurInitExpr);
5326 
5327 /// Attempt reference initialization (C++0x [dcl.init.ref])
TryReferenceInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,InitializationSequence & Sequence,bool TopLevelOfInitList)5328 static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,
5329                                        const InitializationKind &Kind,
5330                                        Expr *Initializer,
5331                                        InitializationSequence &Sequence,
5332                                        bool TopLevelOfInitList) {
5333   QualType DestType = Entity.getType();
5334   QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5335   Qualifiers T1Quals;
5336   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5337   QualType cv2T2 = S.getCompletedType(Initializer);
5338   Qualifiers T2Quals;
5339   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5340 
5341   // If the initializer is the address of an overloaded function, try
5342   // to resolve the overloaded function. If all goes well, T2 is the
5343   // type of the resulting function.
5344   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
5345                                                    T1, Sequence))
5346     return;
5347 
5348   // Delegate everything else to a subfunction.
5349   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5350                                  T1Quals, cv2T2, T2, T2Quals, Sequence,
5351                                  TopLevelOfInitList);
5352 }
5353 
5354 /// Determine whether an expression is a non-referenceable glvalue (one to
5355 /// which a reference can never bind). Attempting to bind a reference to
5356 /// such a glvalue will always create a temporary.
isNonReferenceableGLValue(Expr * E)5357 static bool isNonReferenceableGLValue(Expr *E) {
5358   return E->refersToBitField() || E->refersToVectorElement() ||
5359          E->refersToMatrixElement();
5360 }
5361 
5362 /// Reference initialization without resolving overloaded functions.
5363 ///
5364 /// We also can get here in C if we call a builtin which is declared as
5365 /// a function with a parameter of reference type (such as __builtin_va_end()).
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)5366 static void TryReferenceInitializationCore(Sema &S,
5367                                            const InitializedEntity &Entity,
5368                                            const InitializationKind &Kind,
5369                                            Expr *Initializer,
5370                                            QualType cv1T1, QualType T1,
5371                                            Qualifiers T1Quals,
5372                                            QualType cv2T2, QualType T2,
5373                                            Qualifiers T2Quals,
5374                                            InitializationSequence &Sequence,
5375                                            bool TopLevelOfInitList) {
5376   QualType DestType = Entity.getType();
5377   SourceLocation DeclLoc = Initializer->getBeginLoc();
5378 
5379   // Compute some basic properties of the types and the initializer.
5380   bool isLValueRef = DestType->isLValueReferenceType();
5381   bool isRValueRef = !isLValueRef;
5382   Expr::Classification InitCategory = Initializer->Classify(S.Context);
5383 
5384   Sema::ReferenceConversions RefConv;
5385   Sema::ReferenceCompareResult RefRelationship =
5386       S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5387 
5388   // C++0x [dcl.init.ref]p5:
5389   //   A reference to type "cv1 T1" is initialized by an expression of type
5390   //   "cv2 T2" as follows:
5391   //
5392   //     - If the reference is an lvalue reference and the initializer
5393   //       expression
5394   // Note the analogous bullet points for rvalue refs to functions. Because
5395   // there are no function rvalues in C++, rvalue refs to functions are treated
5396   // like lvalue refs.
5397   OverloadingResult ConvOvlResult = OR_Success;
5398   bool T1Function = T1->isFunctionType();
5399   if (isLValueRef || T1Function) {
5400     if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5401         (RefRelationship == Sema::Ref_Compatible ||
5402          (Kind.isCStyleOrFunctionalCast() &&
5403           RefRelationship == Sema::Ref_Related))) {
5404       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
5405       //     reference-compatible with "cv2 T2," or
5406       if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5407                      Sema::ReferenceConversions::ObjC)) {
5408         // If we're converting the pointee, add any qualifiers first;
5409         // these qualifiers must all be top-level, so just convert to "cv1 T2".
5410         if (RefConv & (Sema::ReferenceConversions::Qualification))
5411           Sequence.AddQualificationConversionStep(
5412               S.Context.getQualifiedType(T2, T1Quals),
5413               Initializer->getValueKind());
5414         if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5415           Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5416         else
5417           Sequence.AddObjCObjectConversionStep(cv1T1);
5418       } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5419         // Perform a (possibly multi-level) qualification conversion.
5420         Sequence.AddQualificationConversionStep(cv1T1,
5421                                                 Initializer->getValueKind());
5422       } else if (RefConv & Sema::ReferenceConversions::Function) {
5423         Sequence.AddFunctionReferenceConversionStep(cv1T1);
5424       }
5425 
5426       // We only create a temporary here when binding a reference to a
5427       // bit-field or vector element. Those cases are't supposed to be
5428       // handled by this bullet, but the outcome is the same either way.
5429       Sequence.AddReferenceBindingStep(cv1T1, false);
5430       return;
5431     }
5432 
5433     //     - has a class type (i.e., T2 is a class type), where T1 is not
5434     //       reference-related to T2, and can be implicitly converted to an
5435     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5436     //       with "cv3 T3" (this conversion is selected by enumerating the
5437     //       applicable conversion functions (13.3.1.6) and choosing the best
5438     //       one through overload resolution (13.3)),
5439     // If we have an rvalue ref to function type here, the rhs must be
5440     // an rvalue. DR1287 removed the "implicitly" here.
5441     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5442         (isLValueRef || InitCategory.isRValue())) {
5443       if (S.getLangOpts().CPlusPlus) {
5444         // Try conversion functions only for C++.
5445         ConvOvlResult = TryRefInitWithConversionFunction(
5446             S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5447             /*IsLValueRef*/ isLValueRef, Sequence);
5448         if (ConvOvlResult == OR_Success)
5449           return;
5450         if (ConvOvlResult != OR_No_Viable_Function)
5451           Sequence.SetOverloadFailure(
5452               InitializationSequence::FK_ReferenceInitOverloadFailed,
5453               ConvOvlResult);
5454       } else {
5455         ConvOvlResult = OR_No_Viable_Function;
5456       }
5457     }
5458   }
5459 
5460   //     - Otherwise, the reference shall be an lvalue reference to a
5461   //       non-volatile const type (i.e., cv1 shall be const), or the reference
5462   //       shall be an rvalue reference.
5463   //       For address spaces, we interpret this to mean that an addr space
5464   //       of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5465   if (isLValueRef &&
5466       !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5467         T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5468     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5469       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5470     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5471       Sequence.SetOverloadFailure(
5472                         InitializationSequence::FK_ReferenceInitOverloadFailed,
5473                                   ConvOvlResult);
5474     else if (!InitCategory.isLValue())
5475       Sequence.SetFailed(
5476           T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5477               ? InitializationSequence::
5478                     FK_NonConstLValueReferenceBindingToTemporary
5479               : InitializationSequence::FK_ReferenceInitDropsQualifiers);
5480     else {
5481       InitializationSequence::FailureKind FK;
5482       switch (RefRelationship) {
5483       case Sema::Ref_Compatible:
5484         if (Initializer->refersToBitField())
5485           FK = InitializationSequence::
5486               FK_NonConstLValueReferenceBindingToBitfield;
5487         else if (Initializer->refersToVectorElement())
5488           FK = InitializationSequence::
5489               FK_NonConstLValueReferenceBindingToVectorElement;
5490         else if (Initializer->refersToMatrixElement())
5491           FK = InitializationSequence::
5492               FK_NonConstLValueReferenceBindingToMatrixElement;
5493         else
5494           llvm_unreachable("unexpected kind of compatible initializer");
5495         break;
5496       case Sema::Ref_Related:
5497         FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5498         break;
5499       case Sema::Ref_Incompatible:
5500         FK = InitializationSequence::
5501             FK_NonConstLValueReferenceBindingToUnrelated;
5502         break;
5503       }
5504       Sequence.SetFailed(FK);
5505     }
5506     return;
5507   }
5508 
5509   //    - If the initializer expression
5510   //      - is an
5511   // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5512   // [1z]   rvalue (but not a bit-field) or
5513   //        function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5514   //
5515   // Note: functions are handled above and below rather than here...
5516   if (!T1Function &&
5517       (RefRelationship == Sema::Ref_Compatible ||
5518        (Kind.isCStyleOrFunctionalCast() &&
5519         RefRelationship == Sema::Ref_Related)) &&
5520       ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5521        (InitCategory.isPRValue() &&
5522         (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5523          T2->isArrayType())))) {
5524     ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5525     if (InitCategory.isPRValue() && T2->isRecordType()) {
5526       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5527       // compiler the freedom to perform a copy here or bind to the
5528       // object, while C++0x requires that we bind directly to the
5529       // object. Hence, we always bind to the object without making an
5530       // extra copy. However, in C++03 requires that we check for the
5531       // presence of a suitable copy constructor:
5532       //
5533       //   The constructor that would be used to make the copy shall
5534       //   be callable whether or not the copy is actually done.
5535       if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5536         Sequence.AddExtraneousCopyToTemporary(cv2T2);
5537       else if (S.getLangOpts().CPlusPlus11)
5538         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
5539     }
5540 
5541     // C++1z [dcl.init.ref]/5.2.1.2:
5542     //   If the converted initializer is a prvalue, its type T4 is adjusted
5543     //   to type "cv1 T4" and the temporary materialization conversion is
5544     //   applied.
5545     // Postpone address space conversions to after the temporary materialization
5546     // conversion to allow creating temporaries in the alloca address space.
5547     auto T1QualsIgnoreAS = T1Quals;
5548     auto T2QualsIgnoreAS = T2Quals;
5549     if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5550       T1QualsIgnoreAS.removeAddressSpace();
5551       T2QualsIgnoreAS.removeAddressSpace();
5552     }
5553     QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5554     if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5555       Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5556     Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5557     ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5558     // Add addr space conversion if required.
5559     if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5560       auto T4Quals = cv1T4.getQualifiers();
5561       T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5562       QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5563       Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5564       cv1T4 = cv1T4WithAS;
5565     }
5566 
5567     //   In any case, the reference is bound to the resulting glvalue (or to
5568     //   an appropriate base class subobject).
5569     if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5570       Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5571     else if (RefConv & Sema::ReferenceConversions::ObjC)
5572       Sequence.AddObjCObjectConversionStep(cv1T1);
5573     else if (RefConv & Sema::ReferenceConversions::Qualification) {
5574       if (!S.Context.hasSameType(cv1T4, cv1T1))
5575         Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5576     }
5577     return;
5578   }
5579 
5580   //       - has a class type (i.e., T2 is a class type), where T1 is not
5581   //         reference-related to T2, and can be implicitly converted to an
5582   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
5583   //         where "cv1 T1" is reference-compatible with "cv3 T3",
5584   //
5585   // DR1287 removes the "implicitly" here.
5586   if (T2->isRecordType()) {
5587     if (RefRelationship == Sema::Ref_Incompatible) {
5588       ConvOvlResult = TryRefInitWithConversionFunction(
5589           S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5590           /*IsLValueRef*/ isLValueRef, Sequence);
5591       if (ConvOvlResult)
5592         Sequence.SetOverloadFailure(
5593             InitializationSequence::FK_ReferenceInitOverloadFailed,
5594             ConvOvlResult);
5595 
5596       return;
5597     }
5598 
5599     if (RefRelationship == Sema::Ref_Compatible &&
5600         isRValueRef && InitCategory.isLValue()) {
5601       Sequence.SetFailed(
5602         InitializationSequence::FK_RValueReferenceBindingToLValue);
5603       return;
5604     }
5605 
5606     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5607     return;
5608   }
5609 
5610   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
5611   //        from the initializer expression using the rules for a non-reference
5612   //        copy-initialization (8.5). The reference is then bound to the
5613   //        temporary. [...]
5614 
5615   // Ignore address space of reference type at this point and perform address
5616   // space conversion after the reference binding step.
5617   QualType cv1T1IgnoreAS =
5618       T1Quals.hasAddressSpace()
5619           ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5620           : cv1T1;
5621 
5622   InitializedEntity TempEntity =
5623       InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5624 
5625   // FIXME: Why do we use an implicit conversion here rather than trying
5626   // copy-initialization?
5627   ImplicitConversionSequence ICS
5628     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5629                               /*SuppressUserConversions=*/false,
5630                               Sema::AllowedExplicit::None,
5631                               /*FIXME:InOverloadResolution=*/false,
5632                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5633                               /*AllowObjCWritebackConversion=*/false);
5634 
5635   if (ICS.isBad()) {
5636     // FIXME: Use the conversion function set stored in ICS to turn
5637     // this into an overloading ambiguity diagnostic. However, we need
5638     // to keep that set as an OverloadCandidateSet rather than as some
5639     // other kind of set.
5640     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5641       Sequence.SetOverloadFailure(
5642                         InitializationSequence::FK_ReferenceInitOverloadFailed,
5643                                   ConvOvlResult);
5644     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5645       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5646     else
5647       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5648     return;
5649   } else {
5650     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5651                                        TopLevelOfInitList);
5652   }
5653 
5654   //        [...] If T1 is reference-related to T2, cv1 must be the
5655   //        same cv-qualification as, or greater cv-qualification
5656   //        than, cv2; otherwise, the program is ill-formed.
5657   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5658   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5659   if (RefRelationship == Sema::Ref_Related &&
5660       ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5661        !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5662     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5663     return;
5664   }
5665 
5666   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
5667   //   reference, the initializer expression shall not be an lvalue.
5668   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5669       InitCategory.isLValue()) {
5670     Sequence.SetFailed(
5671                     InitializationSequence::FK_RValueReferenceBindingToLValue);
5672     return;
5673   }
5674 
5675   Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5676 
5677   if (T1Quals.hasAddressSpace()) {
5678     if (!Qualifiers::isAddressSpaceSupersetOf(
5679             T1Quals.getAddressSpace(), LangAS::Default, S.getASTContext())) {
5680       Sequence.SetFailed(
5681           InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5682       return;
5683     }
5684     Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5685                                                                : VK_XValue);
5686   }
5687 }
5688 
5689 /// Attempt character array initialization from a string literal
5690 /// (C++ [dcl.init.string], C99 6.7.8).
TryStringLiteralInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,Expr * Initializer,InitializationSequence & Sequence)5691 static void TryStringLiteralInitialization(Sema &S,
5692                                            const InitializedEntity &Entity,
5693                                            const InitializationKind &Kind,
5694                                            Expr *Initializer,
5695                                        InitializationSequence &Sequence) {
5696   Sequence.AddStringInitStep(Entity.getType());
5697 }
5698 
5699 /// Attempt value initialization (C++ [dcl.init]p7).
TryValueInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitializationSequence & Sequence,InitListExpr * InitList)5700 static void TryValueInitialization(Sema &S,
5701                                    const InitializedEntity &Entity,
5702                                    const InitializationKind &Kind,
5703                                    InitializationSequence &Sequence,
5704                                    InitListExpr *InitList) {
5705   assert((!InitList || InitList->getNumInits() == 0) &&
5706          "Shouldn't use value-init for non-empty init lists");
5707 
5708   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5709   //
5710   //   To value-initialize an object of type T means:
5711   QualType T = Entity.getType();
5712   assert(!T->isVoidType() && "Cannot value-init void");
5713 
5714   //     -- if T is an array type, then each element is value-initialized;
5715   T = S.Context.getBaseElementType(T);
5716 
5717   if (const RecordType *RT = T->getAs<RecordType>()) {
5718     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5719       bool NeedZeroInitialization = true;
5720       // C++98:
5721       // -- if T is a class type (clause 9) with a user-declared constructor
5722       //    (12.1), then the default constructor for T is called (and the
5723       //    initialization is ill-formed if T has no accessible default
5724       //    constructor);
5725       // C++11:
5726       // -- if T is a class type (clause 9) with either no default constructor
5727       //    (12.1 [class.ctor]) or a default constructor that is user-provided
5728       //    or deleted, then the object is default-initialized;
5729       //
5730       // Note that the C++11 rule is the same as the C++98 rule if there are no
5731       // defaulted or deleted constructors, so we just use it unconditionally.
5732       CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5733       if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5734         NeedZeroInitialization = false;
5735 
5736       // -- if T is a (possibly cv-qualified) non-union class type without a
5737       //    user-provided or deleted default constructor, then the object is
5738       //    zero-initialized and, if T has a non-trivial default constructor,
5739       //    default-initialized;
5740       // The 'non-union' here was removed by DR1502. The 'non-trivial default
5741       // constructor' part was removed by DR1507.
5742       if (NeedZeroInitialization)
5743         Sequence.AddZeroInitializationStep(Entity.getType());
5744 
5745       // C++03:
5746       // -- if T is a non-union class type without a user-declared constructor,
5747       //    then every non-static data member and base class component of T is
5748       //    value-initialized;
5749       // [...] A program that calls for [...] value-initialization of an
5750       // entity of reference type is ill-formed.
5751       //
5752       // C++11 doesn't need this handling, because value-initialization does not
5753       // occur recursively there, and the implicit default constructor is
5754       // defined as deleted in the problematic cases.
5755       if (!S.getLangOpts().CPlusPlus11 &&
5756           ClassDecl->hasUninitializedReferenceMember()) {
5757         Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5758         return;
5759       }
5760 
5761       // If this is list-value-initialization, pass the empty init list on when
5762       // building the constructor call. This affects the semantics of a few
5763       // things (such as whether an explicit default constructor can be called).
5764       Expr *InitListAsExpr = InitList;
5765       MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5766       bool InitListSyntax = InitList;
5767 
5768       // FIXME: Instead of creating a CXXConstructExpr of array type here,
5769       // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5770       return TryConstructorInitialization(
5771           S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5772     }
5773   }
5774 
5775   Sequence.AddZeroInitializationStep(Entity.getType());
5776 }
5777 
5778 /// Attempt default initialization (C++ [dcl.init]p6).
TryDefaultInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,InitializationSequence & Sequence)5779 static void TryDefaultInitialization(Sema &S,
5780                                      const InitializedEntity &Entity,
5781                                      const InitializationKind &Kind,
5782                                      InitializationSequence &Sequence) {
5783   assert(Kind.getKind() == InitializationKind::IK_Default);
5784 
5785   // C++ [dcl.init]p6:
5786   //   To default-initialize an object of type T means:
5787   //     - if T is an array type, each element is default-initialized;
5788   QualType DestType = S.Context.getBaseElementType(Entity.getType());
5789 
5790   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
5791   //       constructor for T is called (and the initialization is ill-formed if
5792   //       T has no accessible default constructor);
5793   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5794     TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5795                                  Entity.getType(), Sequence);
5796     return;
5797   }
5798 
5799   //     - otherwise, no initialization is performed.
5800 
5801   //   If a program calls for the default initialization of an object of
5802   //   a const-qualified type T, T shall be a class type with a user-provided
5803   //   default constructor.
5804   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5805     if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5806       Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5807     return;
5808   }
5809 
5810   // If the destination type has a lifetime property, zero-initialize it.
5811   if (DestType.getQualifiers().hasObjCLifetime()) {
5812     Sequence.AddZeroInitializationStep(Entity.getType());
5813     return;
5814   }
5815 }
5816 
TryOrBuildParenListInitialization(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,ArrayRef<Expr * > Args,InitializationSequence & Sequence,bool VerifyOnly,ExprResult * Result)5817 static void TryOrBuildParenListInitialization(
5818     Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5819     ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5820     ExprResult *Result) {
5821   unsigned EntityIndexToProcess = 0;
5822   SmallVector<Expr *, 4> InitExprs;
5823   QualType ResultType;
5824   Expr *ArrayFiller = nullptr;
5825   FieldDecl *InitializedFieldInUnion = nullptr;
5826 
5827   auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5828                                      const InitializationKind &SubKind,
5829                                      Expr *Arg, Expr **InitExpr = nullptr) {
5830     InitializationSequence IS = InitializationSequence(
5831         S, SubEntity, SubKind,
5832         Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5833 
5834     if (IS.Failed()) {
5835       if (!VerifyOnly) {
5836         IS.Diagnose(S, SubEntity, SubKind,
5837                     Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5838       } else {
5839         Sequence.SetFailed(
5840             InitializationSequence::FK_ParenthesizedListInitFailed);
5841       }
5842 
5843       return false;
5844     }
5845     if (!VerifyOnly) {
5846       ExprResult ER;
5847       ER = IS.Perform(S, SubEntity, SubKind,
5848                       Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5849 
5850       if (ER.isInvalid())
5851         return false;
5852 
5853       if (InitExpr)
5854         *InitExpr = ER.get();
5855       else
5856         InitExprs.push_back(ER.get());
5857     }
5858     return true;
5859   };
5860 
5861   if (const ArrayType *AT =
5862           S.getASTContext().getAsArrayType(Entity.getType())) {
5863     uint64_t ArrayLength;
5864     // C++ [dcl.init]p16.5
5865     //   if the destination type is an array, the object is initialized as
5866     //   follows. Let x1, . . . , xk be the elements of the expression-list. If
5867     //   the destination type is an array of unknown bound, it is defined as
5868     //   having k elements.
5869     if (const ConstantArrayType *CAT =
5870             S.getASTContext().getAsConstantArrayType(Entity.getType())) {
5871       ArrayLength = CAT->getZExtSize();
5872       ResultType = Entity.getType();
5873     } else if (const VariableArrayType *VAT =
5874                    S.getASTContext().getAsVariableArrayType(Entity.getType())) {
5875       // Braced-initialization of variable array types is not allowed, even if
5876       // the size is greater than or equal to the number of args, so we don't
5877       // allow them to be initialized via parenthesized aggregate initialization
5878       // either.
5879       const Expr *SE = VAT->getSizeExpr();
5880       S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5881           << SE->getSourceRange();
5882       return;
5883     } else {
5884       assert(Entity.getType()->isIncompleteArrayType());
5885       ArrayLength = Args.size();
5886     }
5887     EntityIndexToProcess = ArrayLength;
5888 
5889     //   ...the ith array element is copy-initialized with xi for each
5890     //   1 <= i <= k
5891     for (Expr *E : Args) {
5892       InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5893           S.getASTContext(), EntityIndexToProcess, Entity);
5894       InitializationKind SubKind = InitializationKind::CreateForInit(
5895           E->getExprLoc(), /*isDirectInit=*/false, E);
5896       if (!HandleInitializedEntity(SubEntity, SubKind, E))
5897         return;
5898     }
5899     //   ...and value-initialized for each k < i <= n;
5900     if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5901       InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5902           S.getASTContext(), Args.size(), Entity);
5903       InitializationKind SubKind = InitializationKind::CreateValue(
5904           Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5905       if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5906         return;
5907     }
5908 
5909     if (ResultType.isNull()) {
5910       ResultType = S.Context.getConstantArrayType(
5911           AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5912           /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5913     }
5914   } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5915     bool IsUnion = RT->isUnionType();
5916     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5917     if (RD->isInvalidDecl()) {
5918       // Exit early to avoid confusion when processing members.
5919       // We do the same for braced list initialization in
5920       // `CheckStructUnionTypes`.
5921       Sequence.SetFailed(
5922           clang::InitializationSequence::FK_ParenthesizedListInitFailed);
5923       return;
5924     }
5925 
5926     if (!IsUnion) {
5927       for (const CXXBaseSpecifier &Base : RD->bases()) {
5928         InitializedEntity SubEntity = InitializedEntity::InitializeBase(
5929             S.getASTContext(), &Base, false, &Entity);
5930         if (EntityIndexToProcess < Args.size()) {
5931           // C++ [dcl.init]p16.6.2.2.
5932           //   ...the object is initialized is follows. Let e1, ..., en be the
5933           //   elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5934           //   the elements of the expression-list...The element ei is
5935           //   copy-initialized with xi for 1 <= i <= k.
5936           Expr *E = Args[EntityIndexToProcess];
5937           InitializationKind SubKind = InitializationKind::CreateForInit(
5938               E->getExprLoc(), /*isDirectInit=*/false, E);
5939           if (!HandleInitializedEntity(SubEntity, SubKind, E))
5940             return;
5941         } else {
5942           // We've processed all of the args, but there are still base classes
5943           // that have to be initialized.
5944           // C++ [dcl.init]p17.6.2.2
5945           //   The remaining elements...otherwise are value initialzed
5946           InitializationKind SubKind = InitializationKind::CreateValue(
5947               Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5948               /*IsImplicit=*/true);
5949           if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5950             return;
5951         }
5952         EntityIndexToProcess++;
5953       }
5954     }
5955 
5956     for (FieldDecl *FD : RD->fields()) {
5957       // Unnamed bitfields should not be initialized at all, either with an arg
5958       // or by default.
5959       if (FD->isUnnamedBitField())
5960         continue;
5961 
5962       InitializedEntity SubEntity =
5963           InitializedEntity::InitializeMemberFromParenAggInit(FD);
5964 
5965       if (EntityIndexToProcess < Args.size()) {
5966         //   ...The element ei is copy-initialized with xi for 1 <= i <= k.
5967         Expr *E = Args[EntityIndexToProcess];
5968 
5969         // Incomplete array types indicate flexible array members. Do not allow
5970         // paren list initializations of structs with these members, as GCC
5971         // doesn't either.
5972         if (FD->getType()->isIncompleteArrayType()) {
5973           if (!VerifyOnly) {
5974             S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5975                 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5976             S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5977           }
5978           Sequence.SetFailed(
5979               InitializationSequence::FK_ParenthesizedListInitFailed);
5980           return;
5981         }
5982 
5983         InitializationKind SubKind = InitializationKind::CreateForInit(
5984             E->getExprLoc(), /*isDirectInit=*/false, E);
5985         if (!HandleInitializedEntity(SubEntity, SubKind, E))
5986           return;
5987 
5988         // Unions should have only one initializer expression, so we bail out
5989         // after processing the first field. If there are more initializers then
5990         // it will be caught when we later check whether EntityIndexToProcess is
5991         // less than Args.size();
5992         if (IsUnion) {
5993           InitializedFieldInUnion = FD;
5994           EntityIndexToProcess = 1;
5995           break;
5996         }
5997       } else {
5998         // We've processed all of the args, but there are still members that
5999         // have to be initialized.
6000         if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6001             !S.isUnevaluatedContext()) {
6002           S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6003               << /* Var-in-Record */ 0 << FD;
6004           S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6005         }
6006 
6007         if (FD->hasInClassInitializer()) {
6008           if (!VerifyOnly) {
6009             // C++ [dcl.init]p16.6.2.2
6010             //   The remaining elements are initialized with their default
6011             //   member initializers, if any
6012             ExprResult DIE = S.BuildCXXDefaultInitExpr(
6013                 Kind.getParenOrBraceRange().getEnd(), FD);
6014             if (DIE.isInvalid())
6015               return;
6016             S.checkInitializerLifetime(SubEntity, DIE.get());
6017             InitExprs.push_back(DIE.get());
6018           }
6019         } else {
6020           // C++ [dcl.init]p17.6.2.2
6021           //   The remaining elements...otherwise are value initialzed
6022           if (FD->getType()->isReferenceType()) {
6023             Sequence.SetFailed(
6024                 InitializationSequence::FK_ParenthesizedListInitFailed);
6025             if (!VerifyOnly) {
6026               SourceRange SR = Kind.getParenOrBraceRange();
6027               S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6028                   << FD->getType() << SR;
6029               S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6030             }
6031             return;
6032           }
6033           InitializationKind SubKind = InitializationKind::CreateValue(
6034               Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6035           if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6036             return;
6037         }
6038       }
6039       EntityIndexToProcess++;
6040     }
6041     ResultType = Entity.getType();
6042   }
6043 
6044   // Not all of the args have been processed, so there must've been more args
6045   // than were required to initialize the element.
6046   if (EntityIndexToProcess < Args.size()) {
6047     Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
6048     if (!VerifyOnly) {
6049       QualType T = Entity.getType();
6050       int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
6051       SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6052                                Args.back()->getEndLoc());
6053       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6054           << InitKind << ExcessInitSR;
6055     }
6056     return;
6057   }
6058 
6059   if (VerifyOnly) {
6060     Sequence.setSequenceKind(InitializationSequence::NormalSequence);
6061     Sequence.AddParenthesizedListInitStep(Entity.getType());
6062   } else if (Result) {
6063     SourceRange SR = Kind.getParenOrBraceRange();
6064     auto *CPLIE = CXXParenListInitExpr::Create(
6065         S.getASTContext(), InitExprs, ResultType, Args.size(),
6066         Kind.getLocation(), SR.getBegin(), SR.getEnd());
6067     if (ArrayFiller)
6068       CPLIE->setArrayFiller(ArrayFiller);
6069     if (InitializedFieldInUnion)
6070       CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6071     *Result = CPLIE;
6072     S.Diag(Kind.getLocation(),
6073            diag::warn_cxx17_compat_aggregate_init_paren_list)
6074         << Kind.getLocation() << SR << ResultType;
6075   }
6076 }
6077 
6078 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6079 /// which enumerates all conversion functions and performs overload resolution
6080 /// to select the best.
TryUserDefinedConversion(Sema & S,QualType DestType,const InitializationKind & Kind,Expr * Initializer,InitializationSequence & Sequence,bool TopLevelOfInitList)6081 static void TryUserDefinedConversion(Sema &S,
6082                                      QualType DestType,
6083                                      const InitializationKind &Kind,
6084                                      Expr *Initializer,
6085                                      InitializationSequence &Sequence,
6086                                      bool TopLevelOfInitList) {
6087   assert(!DestType->isReferenceType() && "References are handled elsewhere");
6088   QualType SourceType = Initializer->getType();
6089   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6090          "Must have a class type to perform a user-defined conversion");
6091 
6092   // Build the candidate set directly in the initialization sequence
6093   // structure, so that it will persist if we fail.
6094   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6095   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
6096   CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6097 
6098   // Determine whether we are allowed to call explicit constructors or
6099   // explicit conversion operators.
6100   bool AllowExplicit = Kind.AllowExplicit();
6101 
6102   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
6103     // The type we're converting to is a class type. Enumerate its constructors
6104     // to see if there is a suitable conversion.
6105     CXXRecordDecl *DestRecordDecl
6106       = cast<CXXRecordDecl>(DestRecordType->getDecl());
6107 
6108     // Try to complete the type we're converting to.
6109     if (S.isCompleteType(Kind.getLocation(), DestType)) {
6110       for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6111         auto Info = getConstructorInfo(D);
6112         if (!Info.Constructor)
6113           continue;
6114 
6115         if (!Info.Constructor->isInvalidDecl() &&
6116             Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6117           if (Info.ConstructorTmpl)
6118             S.AddTemplateOverloadCandidate(
6119                 Info.ConstructorTmpl, Info.FoundDecl,
6120                 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6121                 /*SuppressUserConversions=*/true,
6122                 /*PartialOverloading*/ false, AllowExplicit);
6123           else
6124             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6125                                    Initializer, CandidateSet,
6126                                    /*SuppressUserConversions=*/true,
6127                                    /*PartialOverloading*/ false, AllowExplicit);
6128         }
6129       }
6130     }
6131   }
6132 
6133   SourceLocation DeclLoc = Initializer->getBeginLoc();
6134 
6135   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
6136     // The type we're converting from is a class type, enumerate its conversion
6137     // functions.
6138 
6139     // We can only enumerate the conversion functions for a complete type; if
6140     // the type isn't complete, simply skip this step.
6141     if (S.isCompleteType(DeclLoc, SourceType)) {
6142       CXXRecordDecl *SourceRecordDecl
6143         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
6144 
6145       const auto &Conversions =
6146           SourceRecordDecl->getVisibleConversionFunctions();
6147       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6148         NamedDecl *D = *I;
6149         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
6150         if (isa<UsingShadowDecl>(D))
6151           D = cast<UsingShadowDecl>(D)->getTargetDecl();
6152 
6153         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6154         CXXConversionDecl *Conv;
6155         if (ConvTemplate)
6156           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6157         else
6158           Conv = cast<CXXConversionDecl>(D);
6159 
6160         if (ConvTemplate)
6161           S.AddTemplateConversionCandidate(
6162               ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6163               CandidateSet, AllowExplicit, AllowExplicit);
6164         else
6165           S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6166                                    DestType, CandidateSet, AllowExplicit,
6167                                    AllowExplicit);
6168       }
6169     }
6170   }
6171 
6172   // Perform overload resolution. If it fails, return the failed result.
6173   OverloadCandidateSet::iterator Best;
6174   if (OverloadingResult Result
6175         = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6176     Sequence.SetOverloadFailure(
6177         InitializationSequence::FK_UserConversionOverloadFailed, Result);
6178 
6179     // [class.copy.elision]p3:
6180     // In some copy-initialization contexts, a two-stage overload resolution
6181     // is performed.
6182     // If the first overload resolution selects a deleted function, we also
6183     // need the initialization sequence to decide whether to perform the second
6184     // overload resolution.
6185     if (!(Result == OR_Deleted &&
6186           Kind.getKind() == InitializationKind::IK_Copy))
6187       return;
6188   }
6189 
6190   FunctionDecl *Function = Best->Function;
6191   Function->setReferenced();
6192   bool HadMultipleCandidates = (CandidateSet.size() > 1);
6193 
6194   if (isa<CXXConstructorDecl>(Function)) {
6195     // Add the user-defined conversion step. Any cv-qualification conversion is
6196     // subsumed by the initialization. Per DR5, the created temporary is of the
6197     // cv-unqualified type of the destination.
6198     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6199                                    DestType.getUnqualifiedType(),
6200                                    HadMultipleCandidates);
6201 
6202     // C++14 and before:
6203     //   - if the function is a constructor, the call initializes a temporary
6204     //     of the cv-unqualified version of the destination type. The [...]
6205     //     temporary [...] is then used to direct-initialize, according to the
6206     //     rules above, the object that is the destination of the
6207     //     copy-initialization.
6208     // Note that this just performs a simple object copy from the temporary.
6209     //
6210     // C++17:
6211     //   - if the function is a constructor, the call is a prvalue of the
6212     //     cv-unqualified version of the destination type whose return object
6213     //     is initialized by the constructor. The call is used to
6214     //     direct-initialize, according to the rules above, the object that
6215     //     is the destination of the copy-initialization.
6216     // Therefore we need to do nothing further.
6217     //
6218     // FIXME: Mark this copy as extraneous.
6219     if (!S.getLangOpts().CPlusPlus17)
6220       Sequence.AddFinalCopy(DestType);
6221     else if (DestType.hasQualifiers())
6222       Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6223     return;
6224   }
6225 
6226   // Add the user-defined conversion step that calls the conversion function.
6227   QualType ConvType = Function->getCallResultType();
6228   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6229                                  HadMultipleCandidates);
6230 
6231   if (ConvType->getAs<RecordType>()) {
6232     //   The call is used to direct-initialize [...] the object that is the
6233     //   destination of the copy-initialization.
6234     //
6235     // In C++17, this does not call a constructor if we enter /17.6.1:
6236     //   - If the initializer expression is a prvalue and the cv-unqualified
6237     //     version of the source type is the same as the class of the
6238     //     destination [... do not make an extra copy]
6239     //
6240     // FIXME: Mark this copy as extraneous.
6241     if (!S.getLangOpts().CPlusPlus17 ||
6242         Function->getReturnType()->isReferenceType() ||
6243         !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6244       Sequence.AddFinalCopy(DestType);
6245     else if (!S.Context.hasSameType(ConvType, DestType))
6246       Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6247     return;
6248   }
6249 
6250   // If the conversion following the call to the conversion function
6251   // is interesting, add it as a separate step.
6252   assert(Best->HasFinalConversion);
6253   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6254       Best->FinalConversion.Third) {
6255     ImplicitConversionSequence ICS;
6256     ICS.setStandard();
6257     ICS.Standard = Best->FinalConversion;
6258     Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6259   }
6260 }
6261 
6262 /// The non-zero enum values here are indexes into diagnostic alternatives.
6263 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
6264 
6265 /// Determines whether this expression is an acceptable ICR source.
isInvalidICRSource(ASTContext & C,Expr * e,bool isAddressOf,bool & isWeakAccess)6266 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
6267                                          bool isAddressOf, bool &isWeakAccess) {
6268   // Skip parens.
6269   e = e->IgnoreParens();
6270 
6271   // Skip address-of nodes.
6272   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6273     if (op->getOpcode() == UO_AddrOf)
6274       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6275                                 isWeakAccess);
6276 
6277   // Skip certain casts.
6278   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6279     switch (ce->getCastKind()) {
6280     case CK_Dependent:
6281     case CK_BitCast:
6282     case CK_LValueBitCast:
6283     case CK_NoOp:
6284       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6285 
6286     case CK_ArrayToPointerDecay:
6287       return IIK_nonscalar;
6288 
6289     case CK_NullToPointer:
6290       return IIK_okay;
6291 
6292     default:
6293       break;
6294     }
6295 
6296   // If we have a declaration reference, it had better be a local variable.
6297   } else if (isa<DeclRefExpr>(e)) {
6298     // set isWeakAccess to true, to mean that there will be an implicit
6299     // load which requires a cleanup.
6300     if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
6301       isWeakAccess = true;
6302 
6303     if (!isAddressOf) return IIK_nonlocal;
6304 
6305     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6306     if (!var) return IIK_nonlocal;
6307 
6308     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6309 
6310   // If we have a conditional operator, check both sides.
6311   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6312     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6313                                                 isWeakAccess))
6314       return iik;
6315 
6316     return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6317 
6318   // These are never scalar.
6319   } else if (isa<ArraySubscriptExpr>(e)) {
6320     return IIK_nonscalar;
6321 
6322   // Otherwise, it needs to be a null pointer constant.
6323   } else {
6324     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
6325             ? IIK_okay : IIK_nonlocal);
6326   }
6327 
6328   return IIK_nonlocal;
6329 }
6330 
6331 /// Check whether the given expression is a valid operand for an
6332 /// indirect copy/restore.
checkIndirectCopyRestoreSource(Sema & S,Expr * src)6333 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
6334   assert(src->isPRValue());
6335   bool isWeakAccess = false;
6336   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6337   // If isWeakAccess to true, there will be an implicit
6338   // load which requires a cleanup.
6339   if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6340     S.Cleanup.setExprNeedsCleanups(true);
6341 
6342   if (iik == IIK_okay) return;
6343 
6344   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6345     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
6346     << src->getSourceRange();
6347 }
6348 
6349 /// Determine whether we have compatible array types for the
6350 /// purposes of GNU by-copy array initialization.
hasCompatibleArrayTypes(ASTContext & Context,const ArrayType * Dest,const ArrayType * Source)6351 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6352                                     const ArrayType *Source) {
6353   // If the source and destination array types are equivalent, we're
6354   // done.
6355   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6356     return true;
6357 
6358   // Make sure that the element types are the same.
6359   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6360     return false;
6361 
6362   // The only mismatch we allow is when the destination is an
6363   // incomplete array type and the source is a constant array type.
6364   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6365 }
6366 
tryObjCWritebackConversion(Sema & S,InitializationSequence & Sequence,const InitializedEntity & Entity,Expr * Initializer)6367 static bool tryObjCWritebackConversion(Sema &S,
6368                                        InitializationSequence &Sequence,
6369                                        const InitializedEntity &Entity,
6370                                        Expr *Initializer) {
6371   bool ArrayDecay = false;
6372   QualType ArgType = Initializer->getType();
6373   QualType ArgPointee;
6374   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6375     ArrayDecay = true;
6376     ArgPointee = ArgArrayType->getElementType();
6377     ArgType = S.Context.getPointerType(ArgPointee);
6378   }
6379 
6380   // Handle write-back conversion.
6381   QualType ConvertedArgType;
6382   if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6383                                           ConvertedArgType))
6384     return false;
6385 
6386   // We should copy unless we're passing to an argument explicitly
6387   // marked 'out'.
6388   bool ShouldCopy = true;
6389   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6390     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6391 
6392   // Do we need an lvalue conversion?
6393   if (ArrayDecay || Initializer->isGLValue()) {
6394     ImplicitConversionSequence ICS;
6395     ICS.setStandard();
6396     ICS.Standard.setAsIdentityConversion();
6397 
6398     QualType ResultType;
6399     if (ArrayDecay) {
6400       ICS.Standard.First = ICK_Array_To_Pointer;
6401       ResultType = S.Context.getPointerType(ArgPointee);
6402     } else {
6403       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
6404       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6405     }
6406 
6407     Sequence.AddConversionSequenceStep(ICS, ResultType);
6408   }
6409 
6410   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6411   return true;
6412 }
6413 
TryOCLSamplerInitialization(Sema & S,InitializationSequence & Sequence,QualType DestType,Expr * Initializer)6414 static bool TryOCLSamplerInitialization(Sema &S,
6415                                         InitializationSequence &Sequence,
6416                                         QualType DestType,
6417                                         Expr *Initializer) {
6418   if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6419       (!Initializer->isIntegerConstantExpr(S.Context) &&
6420       !Initializer->getType()->isSamplerT()))
6421     return false;
6422 
6423   Sequence.AddOCLSamplerInitStep(DestType);
6424   return true;
6425 }
6426 
IsZeroInitializer(const Expr * Init,ASTContext & Ctx)6427 static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6428   std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6429   return Value && Value->isZero();
6430 }
6431 
TryOCLZeroOpaqueTypeInitialization(Sema & S,InitializationSequence & Sequence,QualType DestType,Expr * Initializer)6432 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
6433                                                InitializationSequence &Sequence,
6434                                                QualType DestType,
6435                                                Expr *Initializer) {
6436   if (!S.getLangOpts().OpenCL)
6437     return false;
6438 
6439   //
6440   // OpenCL 1.2 spec, s6.12.10
6441   //
6442   // The event argument can also be used to associate the
6443   // async_work_group_copy with a previous async copy allowing
6444   // an event to be shared by multiple async copies; otherwise
6445   // event should be zero.
6446   //
6447   if (DestType->isEventT() || DestType->isQueueT()) {
6448     if (!IsZeroInitializer(Initializer, S.getASTContext()))
6449       return false;
6450 
6451     Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6452     return true;
6453   }
6454 
6455   // We should allow zero initialization for all types defined in the
6456   // cl_intel_device_side_avc_motion_estimation extension, except
6457   // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6458   if (S.getOpenCLOptions().isAvailableOption(
6459           "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6460       DestType->isOCLIntelSubgroupAVCType()) {
6461     if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6462         DestType->isOCLIntelSubgroupAVCMceResultType())
6463       return false;
6464     if (!IsZeroInitializer(Initializer, S.getASTContext()))
6465       return false;
6466 
6467     Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6468     return true;
6469   }
6470 
6471   return false;
6472 }
6473 
InitializationSequence(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,bool TopLevelOfInitList,bool TreatUnavailableAsInvalid)6474 InitializationSequence::InitializationSequence(
6475     Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6476     MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6477     : FailedOverloadResult(OR_Success),
6478       FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6479   InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6480                  TreatUnavailableAsInvalid);
6481 }
6482 
6483 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6484 /// address of that function, this returns true. Otherwise, it returns false.
isExprAnUnaddressableFunction(Sema & S,const Expr * E)6485 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6486   auto *DRE = dyn_cast<DeclRefExpr>(E);
6487   if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6488     return false;
6489 
6490   return !S.checkAddressOfFunctionIsAvailable(
6491       cast<FunctionDecl>(DRE->getDecl()));
6492 }
6493 
6494 /// Determine whether we can perform an elementwise array copy for this kind
6495 /// of entity.
canPerformArrayCopy(const InitializedEntity & Entity)6496 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6497   switch (Entity.getKind()) {
6498   case InitializedEntity::EK_LambdaCapture:
6499     // C++ [expr.prim.lambda]p24:
6500     //   For array members, the array elements are direct-initialized in
6501     //   increasing subscript order.
6502     return true;
6503 
6504   case InitializedEntity::EK_Variable:
6505     // C++ [dcl.decomp]p1:
6506     //   [...] each element is copy-initialized or direct-initialized from the
6507     //   corresponding element of the assignment-expression [...]
6508     return isa<DecompositionDecl>(Entity.getDecl());
6509 
6510   case InitializedEntity::EK_Member:
6511     // C++ [class.copy.ctor]p14:
6512     //   - if the member is an array, each element is direct-initialized with
6513     //     the corresponding subobject of x
6514     return Entity.isImplicitMemberInitializer();
6515 
6516   case InitializedEntity::EK_ArrayElement:
6517     // All the above cases are intended to apply recursively, even though none
6518     // of them actually say that.
6519     if (auto *E = Entity.getParent())
6520       return canPerformArrayCopy(*E);
6521     break;
6522 
6523   default:
6524     break;
6525   }
6526 
6527   return false;
6528 }
6529 
getConstField(const RecordDecl * RD)6530 static const FieldDecl *getConstField(const RecordDecl *RD) {
6531   assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6532   for (const FieldDecl *FD : RD->fields()) {
6533     // If the field is a flexible array member, we don't want to consider it
6534     // as a const field because there's no way to initialize the FAM anyway.
6535     const ASTContext &Ctx = FD->getASTContext();
6536     if (Decl::isFlexibleArrayMemberLike(
6537             Ctx, FD, FD->getType(),
6538             Ctx.getLangOpts().getStrictFlexArraysLevel(),
6539             /*IgnoreTemplateOrMacroSubstitution=*/true))
6540       continue;
6541 
6542     QualType QT = FD->getType();
6543     if (QT.isConstQualified())
6544       return FD;
6545     if (const auto *RD = QT->getAsRecordDecl()) {
6546       if (const FieldDecl *FD = getConstField(RD))
6547         return FD;
6548     }
6549   }
6550   return nullptr;
6551 }
6552 
InitializeFrom(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,bool TopLevelOfInitList,bool TreatUnavailableAsInvalid)6553 void InitializationSequence::InitializeFrom(Sema &S,
6554                                             const InitializedEntity &Entity,
6555                                             const InitializationKind &Kind,
6556                                             MultiExprArg Args,
6557                                             bool TopLevelOfInitList,
6558                                             bool TreatUnavailableAsInvalid) {
6559   ASTContext &Context = S.Context;
6560 
6561   // Eliminate non-overload placeholder types in the arguments.  We
6562   // need to do this before checking whether types are dependent
6563   // because lowering a pseudo-object expression might well give us
6564   // something of dependent type.
6565   for (unsigned I = 0, E = Args.size(); I != E; ++I)
6566     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6567       // FIXME: should we be doing this here?
6568       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6569       if (result.isInvalid()) {
6570         SetFailed(FK_PlaceholderType);
6571         return;
6572       }
6573       Args[I] = result.get();
6574     }
6575 
6576   // C++0x [dcl.init]p16:
6577   //   The semantics of initializers are as follows. The destination type is
6578   //   the type of the object or reference being initialized and the source
6579   //   type is the type of the initializer expression. The source type is not
6580   //   defined when the initializer is a braced-init-list or when it is a
6581   //   parenthesized list of expressions.
6582   QualType DestType = Entity.getType();
6583 
6584   if (DestType->isDependentType() ||
6585       Expr::hasAnyTypeDependentArguments(Args)) {
6586     SequenceKind = DependentSequence;
6587     return;
6588   }
6589 
6590   // Almost everything is a normal sequence.
6591   setSequenceKind(NormalSequence);
6592 
6593   QualType SourceType;
6594   Expr *Initializer = nullptr;
6595   if (Args.size() == 1) {
6596     Initializer = Args[0];
6597     if (S.getLangOpts().ObjC) {
6598       if (S.ObjC().CheckObjCBridgeRelatedConversions(
6599               Initializer->getBeginLoc(), DestType, Initializer->getType(),
6600               Initializer) ||
6601           S.ObjC().CheckConversionToObjCLiteral(DestType, Initializer))
6602         Args[0] = Initializer;
6603     }
6604     if (!isa<InitListExpr>(Initializer))
6605       SourceType = Initializer->getType();
6606   }
6607 
6608   //     - If the initializer is a (non-parenthesized) braced-init-list, the
6609   //       object is list-initialized (8.5.4).
6610   if (Kind.getKind() != InitializationKind::IK_Direct) {
6611     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6612       TryListInitialization(S, Entity, Kind, InitList, *this,
6613                             TreatUnavailableAsInvalid);
6614       return;
6615     }
6616   }
6617 
6618   if (!S.getLangOpts().CPlusPlus &&
6619       Kind.getKind() == InitializationKind::IK_Default) {
6620     if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6621       VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6622       if (Rec->hasUninitializedExplicitInitFields()) {
6623         if (Var && !Initializer && !S.isUnevaluatedContext()) {
6624           S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6625               << /* Var-in-Record */ 1 << Rec;
6626           emitUninitializedExplicitInitFields(S, Rec);
6627         }
6628       }
6629       // If the record has any members which are const (recursively checked),
6630       // then we want to diagnose those as being uninitialized if there is no
6631       // initializer present. However, we only do this for structure types, not
6632       // union types, because an unitialized field in a union is generally
6633       // reasonable, especially in C where unions can be used for type punning.
6634       if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6635         if (const FieldDecl *FD = getConstField(Rec)) {
6636           unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6637           if (Var->getStorageDuration() == SD_Static ||
6638               Var->getStorageDuration() == SD_Thread)
6639             DiagID = diag::warn_default_init_const_field;
6640 
6641           bool EmitCppCompat = !S.Diags.isIgnored(
6642               diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6643               Var->getLocation());
6644 
6645           S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6646           S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6647         }
6648       }
6649     }
6650   }
6651 
6652   //     - If the destination type is a reference type, see 8.5.3.
6653   if (DestType->isReferenceType()) {
6654     // C++0x [dcl.init.ref]p1:
6655     //   A variable declared to be a T& or T&&, that is, "reference to type T"
6656     //   (8.3.2), shall be initialized by an object, or function, of type T or
6657     //   by an object that can be converted into a T.
6658     // (Therefore, multiple arguments are not permitted.)
6659     if (Args.size() != 1)
6660       SetFailed(FK_TooManyInitsForReference);
6661     // C++17 [dcl.init.ref]p5:
6662     //   A reference [...] is initialized by an expression [...] as follows:
6663     // If the initializer is not an expression, presumably we should reject,
6664     // but the standard fails to actually say so.
6665     else if (isa<InitListExpr>(Args[0]))
6666       SetFailed(FK_ParenthesizedListInitForReference);
6667     else
6668       TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6669                                  TopLevelOfInitList);
6670     return;
6671   }
6672 
6673   //     - If the initializer is (), the object is value-initialized.
6674   if (Kind.getKind() == InitializationKind::IK_Value ||
6675       (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6676     TryValueInitialization(S, Entity, Kind, *this);
6677     return;
6678   }
6679 
6680   // Handle default initialization.
6681   if (Kind.getKind() == InitializationKind::IK_Default) {
6682     TryDefaultInitialization(S, Entity, Kind, *this);
6683     return;
6684   }
6685 
6686   //     - If the destination type is an array of characters, an array of
6687   //       char16_t, an array of char32_t, or an array of wchar_t, and the
6688   //       initializer is a string literal, see 8.5.2.
6689   //     - Otherwise, if the destination type is an array, the program is
6690   //       ill-formed.
6691   //     - Except in HLSL, where non-decaying array parameters behave like
6692   //       non-array types for initialization.
6693   if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6694     const ArrayType *DestAT = Context.getAsArrayType(DestType);
6695     if (Initializer && isa<VariableArrayType>(DestAT)) {
6696       SetFailed(FK_VariableLengthArrayHasInitializer);
6697       return;
6698     }
6699 
6700     if (Initializer) {
6701       switch (IsStringInit(Initializer, DestAT, Context)) {
6702       case SIF_None:
6703         TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6704         return;
6705       case SIF_NarrowStringIntoWideChar:
6706         SetFailed(FK_NarrowStringIntoWideCharArray);
6707         return;
6708       case SIF_WideStringIntoChar:
6709         SetFailed(FK_WideStringIntoCharArray);
6710         return;
6711       case SIF_IncompatWideStringIntoWideChar:
6712         SetFailed(FK_IncompatWideStringIntoWideChar);
6713         return;
6714       case SIF_PlainStringIntoUTF8Char:
6715         SetFailed(FK_PlainStringIntoUTF8Char);
6716         return;
6717       case SIF_UTF8StringIntoPlainChar:
6718         SetFailed(FK_UTF8StringIntoPlainChar);
6719         return;
6720       case SIF_Other:
6721         break;
6722       }
6723     }
6724 
6725     if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6726       QualType SrcType = Entity.getType();
6727       if (SrcType->isArrayParameterType())
6728         SrcType =
6729             cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6730       if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6731         TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6732                      TreatUnavailableAsInvalid);
6733         return;
6734       }
6735     }
6736 
6737     // Some kinds of initialization permit an array to be initialized from
6738     // another array of the same type, and perform elementwise initialization.
6739     if (Initializer && isa<ConstantArrayType>(DestAT) &&
6740         S.Context.hasSameUnqualifiedType(Initializer->getType(),
6741                                          Entity.getType()) &&
6742         canPerformArrayCopy(Entity)) {
6743       TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6744                    TreatUnavailableAsInvalid);
6745       return;
6746     }
6747 
6748     // Note: as an GNU C extension, we allow initialization of an
6749     // array from a compound literal that creates an array of the same
6750     // type, so long as the initializer has no side effects.
6751     if (!S.getLangOpts().CPlusPlus && Initializer &&
6752         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6753         Initializer->getType()->isArrayType()) {
6754       const ArrayType *SourceAT
6755         = Context.getAsArrayType(Initializer->getType());
6756       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6757         SetFailed(FK_ArrayTypeMismatch);
6758       else if (Initializer->HasSideEffects(S.Context))
6759         SetFailed(FK_NonConstantArrayInit);
6760       else {
6761         AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6762       }
6763     }
6764     // Note: as a GNU C++ extension, we allow list-initialization of a
6765     // class member of array type from a parenthesized initializer list.
6766     else if (S.getLangOpts().CPlusPlus &&
6767              Entity.getKind() == InitializedEntity::EK_Member &&
6768              isa_and_nonnull<InitListExpr>(Initializer)) {
6769       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6770                             *this, TreatUnavailableAsInvalid);
6771       AddParenthesizedArrayInitStep(DestType);
6772     } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6773                Kind.getKind() == InitializationKind::IK_Direct)
6774       TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6775                                         /*VerifyOnly=*/true);
6776     else if (DestAT->getElementType()->isCharType())
6777       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6778     else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6779       SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6780     else
6781       SetFailed(FK_ArrayNeedsInitList);
6782 
6783     return;
6784   }
6785 
6786   // Determine whether we should consider writeback conversions for
6787   // Objective-C ARC.
6788   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6789          Entity.isParameterKind();
6790 
6791   if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6792     return;
6793 
6794   // We're at the end of the line for C: it's either a write-back conversion
6795   // or it's a C assignment. There's no need to check anything else.
6796   if (!S.getLangOpts().CPlusPlus) {
6797     assert(Initializer && "Initializer must be non-null");
6798     // If allowed, check whether this is an Objective-C writeback conversion.
6799     if (allowObjCWritebackConversion &&
6800         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6801       return;
6802     }
6803 
6804     if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6805       return;
6806 
6807     // Handle initialization in C
6808     AddCAssignmentStep(DestType);
6809     MaybeProduceObjCObject(S, *this, Entity);
6810     return;
6811   }
6812 
6813   assert(S.getLangOpts().CPlusPlus);
6814 
6815   //     - If the destination type is a (possibly cv-qualified) class type:
6816   if (DestType->isRecordType()) {
6817     //     - If the initialization is direct-initialization, or if it is
6818     //       copy-initialization where the cv-unqualified version of the
6819     //       source type is the same class as, or a derived class of, the
6820     //       class of the destination, constructors are considered. [...]
6821     if (Kind.getKind() == InitializationKind::IK_Direct ||
6822         (Kind.getKind() == InitializationKind::IK_Copy &&
6823          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6824           (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6825                                           SourceType, DestType))))) {
6826       TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6827                                               *this, /*IsAggrListInit=*/false);
6828     } else {
6829       //     - Otherwise (i.e., for the remaining copy-initialization cases),
6830       //       user-defined conversion sequences that can convert from the
6831       //       source type to the destination type or (when a conversion
6832       //       function is used) to a derived class thereof are enumerated as
6833       //       described in 13.3.1.4, and the best one is chosen through
6834       //       overload resolution (13.3).
6835       assert(Initializer && "Initializer must be non-null");
6836       TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6837                                TopLevelOfInitList);
6838     }
6839     return;
6840   }
6841 
6842   assert(Args.size() >= 1 && "Zero-argument case handled above");
6843 
6844   // For HLSL ext vector types we allow list initialization behavior for C++
6845   // constructor syntax. This is accomplished by converting initialization
6846   // arguments an InitListExpr late.
6847   if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6848       (SourceType.isNull() ||
6849        !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6850 
6851     llvm::SmallVector<Expr *> InitArgs;
6852     for (auto *Arg : Args) {
6853       if (Arg->getType()->isExtVectorType()) {
6854         const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6855         unsigned Elm = VTy->getNumElements();
6856         for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6857           InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6858               Arg,
6859               IntegerLiteral::Create(
6860                   Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6861                   Context.IntTy, SourceLocation()),
6862               VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6863               SourceLocation()));
6864         }
6865       } else
6866         InitArgs.emplace_back(Arg);
6867     }
6868     InitListExpr *ILE = new (Context) InitListExpr(
6869         S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6870     Args[0] = ILE;
6871     AddListInitializationStep(DestType);
6872     return;
6873   }
6874 
6875   // The remaining cases all need a source type.
6876   if (Args.size() > 1) {
6877     SetFailed(FK_TooManyInitsForScalar);
6878     return;
6879   } else if (isa<InitListExpr>(Args[0])) {
6880     SetFailed(FK_ParenthesizedListInitForScalar);
6881     return;
6882   }
6883 
6884   //    - Otherwise, if the source type is a (possibly cv-qualified) class
6885   //      type, conversion functions are considered.
6886   if (!SourceType.isNull() && SourceType->isRecordType()) {
6887     assert(Initializer && "Initializer must be non-null");
6888     // For a conversion to _Atomic(T) from either T or a class type derived
6889     // from T, initialize the T object then convert to _Atomic type.
6890     bool NeedAtomicConversion = false;
6891     if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6892       if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6893           S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6894                           Atomic->getValueType())) {
6895         DestType = Atomic->getValueType();
6896         NeedAtomicConversion = true;
6897       }
6898     }
6899 
6900     TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6901                              TopLevelOfInitList);
6902     MaybeProduceObjCObject(S, *this, Entity);
6903     if (!Failed() && NeedAtomicConversion)
6904       AddAtomicConversionStep(Entity.getType());
6905     return;
6906   }
6907 
6908   //    - Otherwise, if the initialization is direct-initialization, the source
6909   //    type is std::nullptr_t, and the destination type is bool, the initial
6910   //    value of the object being initialized is false.
6911   if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6912       DestType->isBooleanType() &&
6913       Kind.getKind() == InitializationKind::IK_Direct) {
6914     AddConversionSequenceStep(
6915         ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
6916                                                      Initializer->isGLValue()),
6917         DestType);
6918     return;
6919   }
6920 
6921   //    - Otherwise, the initial value of the object being initialized is the
6922   //      (possibly converted) value of the initializer expression. Standard
6923   //      conversions (Clause 4) will be used, if necessary, to convert the
6924   //      initializer expression to the cv-unqualified version of the
6925   //      destination type; no user-defined conversions are considered.
6926 
6927   ImplicitConversionSequence ICS
6928     = S.TryImplicitConversion(Initializer, DestType,
6929                               /*SuppressUserConversions*/true,
6930                               Sema::AllowedExplicit::None,
6931                               /*InOverloadResolution*/ false,
6932                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6933                               allowObjCWritebackConversion);
6934 
6935   if (ICS.isStandard() &&
6936       ICS.Standard.Second == ICK_Writeback_Conversion) {
6937     // Objective-C ARC writeback conversion.
6938 
6939     // We should copy unless we're passing to an argument explicitly
6940     // marked 'out'.
6941     bool ShouldCopy = true;
6942     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6943       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6944 
6945     // If there was an lvalue adjustment, add it as a separate conversion.
6946     if (ICS.Standard.First == ICK_Array_To_Pointer ||
6947         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6948       ImplicitConversionSequence LvalueICS;
6949       LvalueICS.setStandard();
6950       LvalueICS.Standard.setAsIdentityConversion();
6951       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6952       LvalueICS.Standard.First = ICS.Standard.First;
6953       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6954     }
6955 
6956     AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6957   } else if (ICS.isBad()) {
6958     if (DeclAccessPair Found;
6959         Initializer->getType() == Context.OverloadTy &&
6960         !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
6961                                               /*Complain=*/false, Found))
6962       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
6963     else if (Initializer->getType()->isFunctionType() &&
6964              isExprAnUnaddressableFunction(S, Initializer))
6965       SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
6966     else
6967       SetFailed(InitializationSequence::FK_ConversionFailed);
6968   } else {
6969     AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6970 
6971     MaybeProduceObjCObject(S, *this, Entity);
6972   }
6973 }
6974 
~InitializationSequence()6975 InitializationSequence::~InitializationSequence() {
6976   for (auto &S : Steps)
6977     S.Destroy();
6978 }
6979 
6980 //===----------------------------------------------------------------------===//
6981 // Perform initialization
6982 //===----------------------------------------------------------------------===//
getAssignmentAction(const InitializedEntity & Entity,bool Diagnose=false)6983 static AssignmentAction getAssignmentAction(const InitializedEntity &Entity,
6984                                             bool Diagnose = false) {
6985   switch(Entity.getKind()) {
6986   case InitializedEntity::EK_Variable:
6987   case InitializedEntity::EK_New:
6988   case InitializedEntity::EK_Exception:
6989   case InitializedEntity::EK_Base:
6990   case InitializedEntity::EK_Delegating:
6991     return AssignmentAction::Initializing;
6992 
6993   case InitializedEntity::EK_Parameter:
6994     if (Entity.getDecl() &&
6995         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6996       return AssignmentAction::Sending;
6997 
6998     return AssignmentAction::Passing;
6999 
7000   case InitializedEntity::EK_Parameter_CF_Audited:
7001     if (Entity.getDecl() &&
7002       isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
7003       return AssignmentAction::Sending;
7004 
7005     return !Diagnose ? AssignmentAction::Passing
7006                      : AssignmentAction::Passing_CFAudited;
7007 
7008   case InitializedEntity::EK_Result:
7009   case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7010     return AssignmentAction::Returning;
7011 
7012   case InitializedEntity::EK_Temporary:
7013   case InitializedEntity::EK_RelatedResult:
7014     // FIXME: Can we tell apart casting vs. converting?
7015     return AssignmentAction::Casting;
7016 
7017   case InitializedEntity::EK_TemplateParameter:
7018     // This is really initialization, but refer to it as conversion for
7019     // consistency with CheckConvertedConstantExpression.
7020     return AssignmentAction::Converting;
7021 
7022   case InitializedEntity::EK_Member:
7023   case InitializedEntity::EK_ParenAggInitMember:
7024   case InitializedEntity::EK_Binding:
7025   case InitializedEntity::EK_ArrayElement:
7026   case InitializedEntity::EK_VectorElement:
7027   case InitializedEntity::EK_ComplexElement:
7028   case InitializedEntity::EK_BlockElement:
7029   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7030   case InitializedEntity::EK_LambdaCapture:
7031   case InitializedEntity::EK_CompoundLiteralInit:
7032     return AssignmentAction::Initializing;
7033   }
7034 
7035   llvm_unreachable("Invalid EntityKind!");
7036 }
7037 
7038 /// Whether we should bind a created object as a temporary when
7039 /// initializing the given entity.
shouldBindAsTemporary(const InitializedEntity & Entity)7040 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
7041   switch (Entity.getKind()) {
7042   case InitializedEntity::EK_ArrayElement:
7043   case InitializedEntity::EK_Member:
7044   case InitializedEntity::EK_ParenAggInitMember:
7045   case InitializedEntity::EK_Result:
7046   case InitializedEntity::EK_StmtExprResult:
7047   case InitializedEntity::EK_New:
7048   case InitializedEntity::EK_Variable:
7049   case InitializedEntity::EK_Base:
7050   case InitializedEntity::EK_Delegating:
7051   case InitializedEntity::EK_VectorElement:
7052   case InitializedEntity::EK_ComplexElement:
7053   case InitializedEntity::EK_Exception:
7054   case InitializedEntity::EK_BlockElement:
7055   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7056   case InitializedEntity::EK_LambdaCapture:
7057   case InitializedEntity::EK_CompoundLiteralInit:
7058   case InitializedEntity::EK_TemplateParameter:
7059     return false;
7060 
7061   case InitializedEntity::EK_Parameter:
7062   case InitializedEntity::EK_Parameter_CF_Audited:
7063   case InitializedEntity::EK_Temporary:
7064   case InitializedEntity::EK_RelatedResult:
7065   case InitializedEntity::EK_Binding:
7066     return true;
7067   }
7068 
7069   llvm_unreachable("missed an InitializedEntity kind?");
7070 }
7071 
7072 /// Whether the given entity, when initialized with an object
7073 /// created for that initialization, requires destruction.
shouldDestroyEntity(const InitializedEntity & Entity)7074 static bool shouldDestroyEntity(const InitializedEntity &Entity) {
7075   switch (Entity.getKind()) {
7076     case InitializedEntity::EK_Result:
7077     case InitializedEntity::EK_StmtExprResult:
7078     case InitializedEntity::EK_New:
7079     case InitializedEntity::EK_Base:
7080     case InitializedEntity::EK_Delegating:
7081     case InitializedEntity::EK_VectorElement:
7082     case InitializedEntity::EK_ComplexElement:
7083     case InitializedEntity::EK_BlockElement:
7084     case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7085     case InitializedEntity::EK_LambdaCapture:
7086       return false;
7087 
7088     case InitializedEntity::EK_Member:
7089     case InitializedEntity::EK_ParenAggInitMember:
7090     case InitializedEntity::EK_Binding:
7091     case InitializedEntity::EK_Variable:
7092     case InitializedEntity::EK_Parameter:
7093     case InitializedEntity::EK_Parameter_CF_Audited:
7094     case InitializedEntity::EK_TemplateParameter:
7095     case InitializedEntity::EK_Temporary:
7096     case InitializedEntity::EK_ArrayElement:
7097     case InitializedEntity::EK_Exception:
7098     case InitializedEntity::EK_CompoundLiteralInit:
7099     case InitializedEntity::EK_RelatedResult:
7100       return true;
7101   }
7102 
7103   llvm_unreachable("missed an InitializedEntity kind?");
7104 }
7105 
7106 /// Get the location at which initialization diagnostics should appear.
getInitializationLoc(const InitializedEntity & Entity,Expr * Initializer)7107 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
7108                                            Expr *Initializer) {
7109   switch (Entity.getKind()) {
7110   case InitializedEntity::EK_Result:
7111   case InitializedEntity::EK_StmtExprResult:
7112     return Entity.getReturnLoc();
7113 
7114   case InitializedEntity::EK_Exception:
7115     return Entity.getThrowLoc();
7116 
7117   case InitializedEntity::EK_Variable:
7118   case InitializedEntity::EK_Binding:
7119     return Entity.getDecl()->getLocation();
7120 
7121   case InitializedEntity::EK_LambdaCapture:
7122     return Entity.getCaptureLoc();
7123 
7124   case InitializedEntity::EK_ArrayElement:
7125   case InitializedEntity::EK_Member:
7126   case InitializedEntity::EK_ParenAggInitMember:
7127   case InitializedEntity::EK_Parameter:
7128   case InitializedEntity::EK_Parameter_CF_Audited:
7129   case InitializedEntity::EK_TemplateParameter:
7130   case InitializedEntity::EK_Temporary:
7131   case InitializedEntity::EK_New:
7132   case InitializedEntity::EK_Base:
7133   case InitializedEntity::EK_Delegating:
7134   case InitializedEntity::EK_VectorElement:
7135   case InitializedEntity::EK_ComplexElement:
7136   case InitializedEntity::EK_BlockElement:
7137   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7138   case InitializedEntity::EK_CompoundLiteralInit:
7139   case InitializedEntity::EK_RelatedResult:
7140     return Initializer->getBeginLoc();
7141   }
7142   llvm_unreachable("missed an InitializedEntity kind?");
7143 }
7144 
7145 /// Make a (potentially elidable) temporary copy of the object
7146 /// provided by the given initializer by calling the appropriate copy
7147 /// constructor.
7148 ///
7149 /// \param S The Sema object used for type-checking.
7150 ///
7151 /// \param T The type of the temporary object, which must either be
7152 /// the type of the initializer expression or a superclass thereof.
7153 ///
7154 /// \param Entity The entity being initialized.
7155 ///
7156 /// \param CurInit The initializer expression.
7157 ///
7158 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7159 /// is permitted in C++03 (but not C++0x) when binding a reference to
7160 /// an rvalue.
7161 ///
7162 /// \returns An expression that copies the initializer expression into
7163 /// a temporary object, or an error expression if a copy could not be
7164 /// created.
CopyObject(Sema & S,QualType T,const InitializedEntity & Entity,ExprResult CurInit,bool IsExtraneousCopy)7165 static ExprResult CopyObject(Sema &S,
7166                              QualType T,
7167                              const InitializedEntity &Entity,
7168                              ExprResult CurInit,
7169                              bool IsExtraneousCopy) {
7170   if (CurInit.isInvalid())
7171     return CurInit;
7172   // Determine which class type we're copying to.
7173   Expr *CurInitExpr = (Expr *)CurInit.get();
7174   CXXRecordDecl *Class = nullptr;
7175   if (const RecordType *Record = T->getAs<RecordType>())
7176     Class = cast<CXXRecordDecl>(Record->getDecl());
7177   if (!Class)
7178     return CurInit;
7179 
7180   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7181 
7182   // Make sure that the type we are copying is complete.
7183   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7184     return CurInit;
7185 
7186   // Perform overload resolution using the class's constructors. Per
7187   // C++11 [dcl.init]p16, second bullet for class types, this initialization
7188   // is direct-initialization.
7189   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7190   DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
7191 
7192   OverloadCandidateSet::iterator Best;
7193   switch (ResolveConstructorOverload(
7194       S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7195       /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7196       /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7197       /*RequireActualConstructor=*/false,
7198       /*SecondStepOfCopyInit=*/true)) {
7199   case OR_Success:
7200     break;
7201 
7202   case OR_No_Viable_Function:
7203     CandidateSet.NoteCandidates(
7204         PartialDiagnosticAt(
7205             Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7206                              ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7207                              : diag::err_temp_copy_no_viable)
7208                      << (int)Entity.getKind() << CurInitExpr->getType()
7209                      << CurInitExpr->getSourceRange()),
7210         S, OCD_AllCandidates, CurInitExpr);
7211     if (!IsExtraneousCopy || S.isSFINAEContext())
7212       return ExprError();
7213     return CurInit;
7214 
7215   case OR_Ambiguous:
7216     CandidateSet.NoteCandidates(
7217         PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7218                                      << (int)Entity.getKind()
7219                                      << CurInitExpr->getType()
7220                                      << CurInitExpr->getSourceRange()),
7221         S, OCD_AmbiguousCandidates, CurInitExpr);
7222     return ExprError();
7223 
7224   case OR_Deleted:
7225     S.Diag(Loc, diag::err_temp_copy_deleted)
7226       << (int)Entity.getKind() << CurInitExpr->getType()
7227       << CurInitExpr->getSourceRange();
7228     S.NoteDeletedFunction(Best->Function);
7229     return ExprError();
7230   }
7231 
7232   bool HadMultipleCandidates = CandidateSet.size() > 1;
7233 
7234   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
7235   SmallVector<Expr*, 8> ConstructorArgs;
7236   CurInit.get(); // Ownership transferred into MultiExprArg, below.
7237 
7238   S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7239                            IsExtraneousCopy);
7240 
7241   if (IsExtraneousCopy) {
7242     // If this is a totally extraneous copy for C++03 reference
7243     // binding purposes, just return the original initialization
7244     // expression. We don't generate an (elided) copy operation here
7245     // because doing so would require us to pass down a flag to avoid
7246     // infinite recursion, where each step adds another extraneous,
7247     // elidable copy.
7248 
7249     // Instantiate the default arguments of any extra parameters in
7250     // the selected copy constructor, as if we were going to create a
7251     // proper call to the copy constructor.
7252     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7253       ParmVarDecl *Parm = Constructor->getParamDecl(I);
7254       if (S.RequireCompleteType(Loc, Parm->getType(),
7255                                 diag::err_call_incomplete_argument))
7256         break;
7257 
7258       // Build the default argument expression; we don't actually care
7259       // if this succeeds or not, because this routine will complain
7260       // if there was a problem.
7261       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7262     }
7263 
7264     return CurInitExpr;
7265   }
7266 
7267   // Determine the arguments required to actually perform the
7268   // constructor call (we might have derived-to-base conversions, or
7269   // the copy constructor may have default arguments).
7270   if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7271                                 ConstructorArgs))
7272     return ExprError();
7273 
7274   // C++0x [class.copy]p32:
7275   //   When certain criteria are met, an implementation is allowed to
7276   //   omit the copy/move construction of a class object, even if the
7277   //   copy/move constructor and/or destructor for the object have
7278   //   side effects. [...]
7279   //     - when a temporary class object that has not been bound to a
7280   //       reference (12.2) would be copied/moved to a class object
7281   //       with the same cv-unqualified type, the copy/move operation
7282   //       can be omitted by constructing the temporary object
7283   //       directly into the target of the omitted copy/move
7284   //
7285   // Note that the other three bullets are handled elsewhere. Copy
7286   // elision for return statements and throw expressions are handled as part
7287   // of constructor initialization, while copy elision for exception handlers
7288   // is handled by the run-time.
7289   //
7290   // FIXME: If the function parameter is not the same type as the temporary, we
7291   // should still be able to elide the copy, but we don't have a way to
7292   // represent in the AST how much should be elided in this case.
7293   bool Elidable =
7294       CurInitExpr->isTemporaryObject(S.Context, Class) &&
7295       S.Context.hasSameUnqualifiedType(
7296           Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7297           CurInitExpr->getType());
7298 
7299   // Actually perform the constructor call.
7300   CurInit = S.BuildCXXConstructExpr(
7301       Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7302       HadMultipleCandidates,
7303       /*ListInit*/ false,
7304       /*StdInitListInit*/ false,
7305       /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7306 
7307   // If we're supposed to bind temporaries, do so.
7308   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7309     CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7310   return CurInit;
7311 }
7312 
7313 /// Check whether elidable copy construction for binding a reference to
7314 /// a temporary would have succeeded if we were building in C++98 mode, for
7315 /// -Wc++98-compat.
CheckCXX98CompatAccessibleCopy(Sema & S,const InitializedEntity & Entity,Expr * CurInitExpr)7316 static void CheckCXX98CompatAccessibleCopy(Sema &S,
7317                                            const InitializedEntity &Entity,
7318                                            Expr *CurInitExpr) {
7319   assert(S.getLangOpts().CPlusPlus11);
7320 
7321   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
7322   if (!Record)
7323     return;
7324 
7325   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7326   if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7327     return;
7328 
7329   // Find constructors which would have been considered.
7330   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7331   DeclContext::lookup_result Ctors =
7332       S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
7333 
7334   // Perform overload resolution.
7335   OverloadCandidateSet::iterator Best;
7336   OverloadingResult OR = ResolveConstructorOverload(
7337       S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7338       /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7339       /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7340       /*RequireActualConstructor=*/false,
7341       /*SecondStepOfCopyInit=*/true);
7342 
7343   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7344     << OR << (int)Entity.getKind() << CurInitExpr->getType()
7345     << CurInitExpr->getSourceRange();
7346 
7347   switch (OR) {
7348   case OR_Success:
7349     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7350                              Best->FoundDecl, Entity, Diag);
7351     // FIXME: Check default arguments as far as that's possible.
7352     break;
7353 
7354   case OR_No_Viable_Function:
7355     CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7356                                 OCD_AllCandidates, CurInitExpr);
7357     break;
7358 
7359   case OR_Ambiguous:
7360     CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7361                                 OCD_AmbiguousCandidates, CurInitExpr);
7362     break;
7363 
7364   case OR_Deleted:
7365     S.Diag(Loc, Diag);
7366     S.NoteDeletedFunction(Best->Function);
7367     break;
7368   }
7369 }
7370 
PrintInitLocationNote(Sema & S,const InitializedEntity & Entity)7371 void InitializationSequence::PrintInitLocationNote(Sema &S,
7372                                               const InitializedEntity &Entity) {
7373   if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7374     if (Entity.getDecl()->getLocation().isInvalid())
7375       return;
7376 
7377     if (Entity.getDecl()->getDeclName())
7378       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7379         << Entity.getDecl()->getDeclName();
7380     else
7381       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7382   }
7383   else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7384            Entity.getMethodDecl())
7385     S.Diag(Entity.getMethodDecl()->getLocation(),
7386            diag::note_method_return_type_change)
7387       << Entity.getMethodDecl()->getDeclName();
7388 }
7389 
7390 /// Returns true if the parameters describe a constructor initialization of
7391 /// an explicit temporary object, e.g. "Point(x, y)".
isExplicitTemporary(const InitializedEntity & Entity,const InitializationKind & Kind,unsigned NumArgs)7392 static bool isExplicitTemporary(const InitializedEntity &Entity,
7393                                 const InitializationKind &Kind,
7394                                 unsigned NumArgs) {
7395   switch (Entity.getKind()) {
7396   case InitializedEntity::EK_Temporary:
7397   case InitializedEntity::EK_CompoundLiteralInit:
7398   case InitializedEntity::EK_RelatedResult:
7399     break;
7400   default:
7401     return false;
7402   }
7403 
7404   switch (Kind.getKind()) {
7405   case InitializationKind::IK_DirectList:
7406     return true;
7407   // FIXME: Hack to work around cast weirdness.
7408   case InitializationKind::IK_Direct:
7409   case InitializationKind::IK_Value:
7410     return NumArgs != 1;
7411   default:
7412     return false;
7413   }
7414 }
7415 
7416 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)7417 PerformConstructorInitialization(Sema &S,
7418                                  const InitializedEntity &Entity,
7419                                  const InitializationKind &Kind,
7420                                  MultiExprArg Args,
7421                                  const InitializationSequence::Step& Step,
7422                                  bool &ConstructorInitRequiresZeroInit,
7423                                  bool IsListInitialization,
7424                                  bool IsStdInitListInitialization,
7425                                  SourceLocation LBraceLoc,
7426                                  SourceLocation RBraceLoc) {
7427   unsigned NumArgs = Args.size();
7428   CXXConstructorDecl *Constructor
7429     = cast<CXXConstructorDecl>(Step.Function.Function);
7430   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7431 
7432   // Build a call to the selected constructor.
7433   SmallVector<Expr*, 8> ConstructorArgs;
7434   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7435                          ? Kind.getEqualLoc()
7436                          : Kind.getLocation();
7437 
7438   if (Kind.getKind() == InitializationKind::IK_Default) {
7439     // Force even a trivial, implicit default constructor to be
7440     // semantically checked. We do this explicitly because we don't build
7441     // the definition for completely trivial constructors.
7442     assert(Constructor->getParent() && "No parent class for constructor.");
7443     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7444         Constructor->isTrivial() && !Constructor->isUsed(false)) {
7445       S.runWithSufficientStackSpace(Loc, [&] {
7446         S.DefineImplicitDefaultConstructor(Loc, Constructor);
7447       });
7448     }
7449   }
7450 
7451   ExprResult CurInit((Expr *)nullptr);
7452 
7453   // C++ [over.match.copy]p1:
7454   //   - When initializing a temporary to be bound to the first parameter
7455   //     of a constructor that takes a reference to possibly cv-qualified
7456   //     T as its first argument, called with a single argument in the
7457   //     context of direct-initialization, explicit conversion functions
7458   //     are also considered.
7459   bool AllowExplicitConv =
7460       Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7461       hasCopyOrMoveCtorParam(S.Context,
7462                              getConstructorInfo(Step.Function.FoundDecl));
7463 
7464   // A smart pointer constructed from a nullable pointer is nullable.
7465   if (NumArgs == 1 && !Kind.isExplicitCast())
7466     S.diagnoseNullableToNonnullConversion(
7467         Entity.getType(), Args.front()->getType(), Kind.getLocation());
7468 
7469   // Determine the arguments required to actually perform the constructor
7470   // call.
7471   if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7472                                 ConstructorArgs, AllowExplicitConv,
7473                                 IsListInitialization))
7474     return ExprError();
7475 
7476   if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7477     // An explicitly-constructed temporary, e.g., X(1, 2).
7478     if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7479       return ExprError();
7480 
7481     if (Kind.getKind() == InitializationKind::IK_Value &&
7482         Constructor->isImplicit()) {
7483       auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7484       if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7485         unsigned I = 0;
7486         for (const FieldDecl *FD : RD->fields()) {
7487           if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7488               !S.isUnevaluatedContext()) {
7489             S.Diag(Loc, diag::warn_field_requires_explicit_init)
7490                 << /* Var-in-Record */ 0 << FD;
7491             S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7492           }
7493           ++I;
7494         }
7495       }
7496     }
7497 
7498     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7499     if (!TSInfo)
7500       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7501     SourceRange ParenOrBraceRange =
7502         (Kind.getKind() == InitializationKind::IK_DirectList)
7503         ? SourceRange(LBraceLoc, RBraceLoc)
7504         : Kind.getParenOrBraceRange();
7505 
7506     CXXConstructorDecl *CalleeDecl = Constructor;
7507     if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7508             Step.Function.FoundDecl.getDecl())) {
7509       CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7510     }
7511     S.MarkFunctionReferenced(Loc, CalleeDecl);
7512 
7513     CurInit = S.CheckForImmediateInvocation(
7514         CXXTemporaryObjectExpr::Create(
7515             S.Context, CalleeDecl,
7516             Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7517             ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7518             IsListInitialization, IsStdInitListInitialization,
7519             ConstructorInitRequiresZeroInit),
7520         CalleeDecl);
7521   } else {
7522     CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;
7523 
7524     if (Entity.getKind() == InitializedEntity::EK_Base) {
7525       ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7526                           ? CXXConstructionKind::VirtualBase
7527                           : CXXConstructionKind::NonVirtualBase;
7528     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7529       ConstructKind = CXXConstructionKind::Delegating;
7530     }
7531 
7532     // Only get the parenthesis or brace range if it is a list initialization or
7533     // direct construction.
7534     SourceRange ParenOrBraceRange;
7535     if (IsListInitialization)
7536       ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7537     else if (Kind.getKind() == InitializationKind::IK_Direct)
7538       ParenOrBraceRange = Kind.getParenOrBraceRange();
7539 
7540     // If the entity allows NRVO, mark the construction as elidable
7541     // unconditionally.
7542     if (Entity.allowsNRVO())
7543       CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7544                                         Step.Function.FoundDecl,
7545                                         Constructor, /*Elidable=*/true,
7546                                         ConstructorArgs,
7547                                         HadMultipleCandidates,
7548                                         IsListInitialization,
7549                                         IsStdInitListInitialization,
7550                                         ConstructorInitRequiresZeroInit,
7551                                         ConstructKind,
7552                                         ParenOrBraceRange);
7553     else
7554       CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7555                                         Step.Function.FoundDecl,
7556                                         Constructor,
7557                                         ConstructorArgs,
7558                                         HadMultipleCandidates,
7559                                         IsListInitialization,
7560                                         IsStdInitListInitialization,
7561                                         ConstructorInitRequiresZeroInit,
7562                                         ConstructKind,
7563                                         ParenOrBraceRange);
7564   }
7565   if (CurInit.isInvalid())
7566     return ExprError();
7567 
7568   // Only check access if all of that succeeded.
7569   S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7570   if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7571     return ExprError();
7572 
7573   if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7574     if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
7575       return ExprError();
7576 
7577   if (shouldBindAsTemporary(Entity))
7578     CurInit = S.MaybeBindToTemporary(CurInit.get());
7579 
7580   return CurInit;
7581 }
7582 
checkInitializerLifetime(const InitializedEntity & Entity,Expr * Init)7583 void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7584                                     Expr *Init) {
7585   return sema::checkInitLifetime(*this, Entity, Init);
7586 }
7587 
7588 static void DiagnoseNarrowingInInitList(Sema &S,
7589                                         const ImplicitConversionSequence &ICS,
7590                                         QualType PreNarrowingType,
7591                                         QualType EntityType,
7592                                         const Expr *PostInit);
7593 
7594 static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7595                                             QualType ToType, Expr *Init);
7596 
7597 /// Provide warnings when std::move is used on construction.
CheckMoveOnConstruction(Sema & S,const Expr * InitExpr,bool IsReturnStmt)7598 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7599                                     bool IsReturnStmt) {
7600   if (!InitExpr)
7601     return;
7602 
7603   if (S.inTemplateInstantiation())
7604     return;
7605 
7606   QualType DestType = InitExpr->getType();
7607   if (!DestType->isRecordType())
7608     return;
7609 
7610   unsigned DiagID = 0;
7611   if (IsReturnStmt) {
7612     const CXXConstructExpr *CCE =
7613         dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7614     if (!CCE || CCE->getNumArgs() != 1)
7615       return;
7616 
7617     if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7618       return;
7619 
7620     InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7621   }
7622 
7623   // Find the std::move call and get the argument.
7624   const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7625   if (!CE || !CE->isCallToStdMove())
7626     return;
7627 
7628   const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7629 
7630   if (IsReturnStmt) {
7631     const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7632     if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7633       return;
7634 
7635     const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7636     if (!VD || !VD->hasLocalStorage())
7637       return;
7638 
7639     // __block variables are not moved implicitly.
7640     if (VD->hasAttr<BlocksAttr>())
7641       return;
7642 
7643     QualType SourceType = VD->getType();
7644     if (!SourceType->isRecordType())
7645       return;
7646 
7647     if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7648       return;
7649     }
7650 
7651     // If we're returning a function parameter, copy elision
7652     // is not possible.
7653     if (isa<ParmVarDecl>(VD))
7654       DiagID = diag::warn_redundant_move_on_return;
7655     else
7656       DiagID = diag::warn_pessimizing_move_on_return;
7657   } else {
7658     DiagID = diag::warn_pessimizing_move_on_initialization;
7659     const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7660     if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7661       return;
7662   }
7663 
7664   S.Diag(CE->getBeginLoc(), DiagID);
7665 
7666   // Get all the locations for a fix-it.  Don't emit the fix-it if any location
7667   // is within a macro.
7668   SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7669   if (CallBegin.isMacroID())
7670     return;
7671   SourceLocation RParen = CE->getRParenLoc();
7672   if (RParen.isMacroID())
7673     return;
7674   SourceLocation LParen;
7675   SourceLocation ArgLoc = Arg->getBeginLoc();
7676 
7677   // Special testing for the argument location.  Since the fix-it needs the
7678   // location right before the argument, the argument location can be in a
7679   // macro only if it is at the beginning of the macro.
7680   while (ArgLoc.isMacroID() &&
7681          S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
7682     ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
7683   }
7684 
7685   if (LParen.isMacroID())
7686     return;
7687 
7688   LParen = ArgLoc.getLocWithOffset(-1);
7689 
7690   S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7691       << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7692       << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7693 }
7694 
CheckForNullPointerDereference(Sema & S,const Expr * E)7695 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7696   // Check to see if we are dereferencing a null pointer.  If so, this is
7697   // undefined behavior, so warn about it.  This only handles the pattern
7698   // "*null", which is a very syntactic check.
7699   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7700     if (UO->getOpcode() == UO_Deref &&
7701         UO->getSubExpr()->IgnoreParenCasts()->
7702         isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7703     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7704                           S.PDiag(diag::warn_binding_null_to_reference)
7705                             << UO->getSubExpr()->getSourceRange());
7706   }
7707 }
7708 
7709 MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T,Expr * Temporary,bool BoundToLvalueReference)7710 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7711                                      bool BoundToLvalueReference) {
7712   auto MTE = new (Context)
7713       MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7714 
7715   // Order an ExprWithCleanups for lifetime marks.
7716   //
7717   // TODO: It'll be good to have a single place to check the access of the
7718   // destructor and generate ExprWithCleanups for various uses. Currently these
7719   // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7720   // but there may be a chance to merge them.
7721   Cleanup.setExprNeedsCleanups(false);
7722   if (isInLifetimeExtendingContext())
7723     currentEvaluationContext().ForRangeLifetimeExtendTemps.push_back(MTE);
7724   return MTE;
7725 }
7726 
TemporaryMaterializationConversion(Expr * E)7727 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7728   // In C++98, we don't want to implicitly create an xvalue. C11 added the
7729   // same rule, but C99 is broken without this behavior and so we treat the
7730   // change as applying to all C language modes.
7731   // FIXME: This means that AST consumers need to deal with "prvalues" that
7732   // denote materialized temporaries. Maybe we should add another ValueKind
7733   // for "xvalue pretending to be a prvalue" for C++98 support.
7734   if (!E->isPRValue() ||
7735       (!getLangOpts().CPlusPlus11 && getLangOpts().CPlusPlus))
7736     return E;
7737 
7738   // C++1z [conv.rval]/1: T shall be a complete type.
7739   // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7740   // If so, we should check for a non-abstract class type here too.
7741   QualType T = E->getType();
7742   if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7743     return ExprError();
7744 
7745   return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7746 }
7747 
PerformQualificationConversion(Expr * E,QualType Ty,ExprValueKind VK,CheckedConversionKind CCK)7748 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7749                                                 ExprValueKind VK,
7750                                                 CheckedConversionKind CCK) {
7751 
7752   CastKind CK = CK_NoOp;
7753 
7754   if (VK == VK_PRValue) {
7755     auto PointeeTy = Ty->getPointeeType();
7756     auto ExprPointeeTy = E->getType()->getPointeeType();
7757     if (!PointeeTy.isNull() &&
7758         PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7759       CK = CK_AddressSpaceConversion;
7760   } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7761     CK = CK_AddressSpaceConversion;
7762   }
7763 
7764   return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7765 }
7766 
Perform(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Args,QualType * ResultType)7767 ExprResult InitializationSequence::Perform(Sema &S,
7768                                            const InitializedEntity &Entity,
7769                                            const InitializationKind &Kind,
7770                                            MultiExprArg Args,
7771                                            QualType *ResultType) {
7772   if (Failed()) {
7773     Diagnose(S, Entity, Kind, Args);
7774     return ExprError();
7775   }
7776   if (!ZeroInitializationFixit.empty()) {
7777     const Decl *D = Entity.getDecl();
7778     const auto *VD = dyn_cast_or_null<VarDecl>(D);
7779     QualType DestType = Entity.getType();
7780 
7781     // The initialization would have succeeded with this fixit. Since the fixit
7782     // is on the error, we need to build a valid AST in this case, so this isn't
7783     // handled in the Failed() branch above.
7784     if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7785       // Use a more useful diagnostic for constexpr variables.
7786       S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7787           << VD
7788           << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7789                                         ZeroInitializationFixit);
7790     } else {
7791       unsigned DiagID = diag::err_default_init_const;
7792       if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7793         DiagID = diag::ext_default_init_const;
7794 
7795       S.Diag(Kind.getLocation(), DiagID)
7796           << DestType << (bool)DestType->getAs<RecordType>()
7797           << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7798                                         ZeroInitializationFixit);
7799     }
7800   }
7801 
7802   if (getKind() == DependentSequence) {
7803     // If the declaration is a non-dependent, incomplete array type
7804     // that has an initializer, then its type will be completed once
7805     // the initializer is instantiated.
7806     if (ResultType && !Entity.getType()->isDependentType() &&
7807         Args.size() == 1) {
7808       QualType DeclType = Entity.getType();
7809       if (const IncompleteArrayType *ArrayT
7810                            = S.Context.getAsIncompleteArrayType(DeclType)) {
7811         // FIXME: We don't currently have the ability to accurately
7812         // compute the length of an initializer list without
7813         // performing full type-checking of the initializer list
7814         // (since we have to determine where braces are implicitly
7815         // introduced and such).  So, we fall back to making the array
7816         // type a dependently-sized array type with no specified
7817         // bound.
7818         if (isa<InitListExpr>((Expr *)Args[0]))
7819           *ResultType = S.Context.getDependentSizedArrayType(
7820               ArrayT->getElementType(),
7821               /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7822               ArrayT->getIndexTypeCVRQualifiers());
7823       }
7824     }
7825     if (Kind.getKind() == InitializationKind::IK_Direct &&
7826         !Kind.isExplicitCast()) {
7827       // Rebuild the ParenListExpr.
7828       SourceRange ParenRange = Kind.getParenOrBraceRange();
7829       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7830                                   Args);
7831     }
7832     assert(Kind.getKind() == InitializationKind::IK_Copy ||
7833            Kind.isExplicitCast() ||
7834            Kind.getKind() == InitializationKind::IK_DirectList);
7835     return ExprResult(Args[0]);
7836   }
7837 
7838   // No steps means no initialization.
7839   if (Steps.empty())
7840     return ExprResult((Expr *)nullptr);
7841 
7842   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7843       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7844       !Entity.isParamOrTemplateParamKind()) {
7845     // Produce a C++98 compatibility warning if we are initializing a reference
7846     // from an initializer list. For parameters, we produce a better warning
7847     // elsewhere.
7848     Expr *Init = Args[0];
7849     S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7850         << Init->getSourceRange();
7851   }
7852 
7853   if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
7854       isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
7855     // Produce a Microsoft compatibility warning when initializing from a
7856     // predefined expression since MSVC treats predefined expressions as string
7857     // literals.
7858     Expr *Init = Args[0];
7859     S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
7860   }
7861 
7862   // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7863   QualType ETy = Entity.getType();
7864   bool HasGlobalAS = ETy.hasAddressSpace() &&
7865                      ETy.getAddressSpace() == LangAS::opencl_global;
7866 
7867   if (S.getLangOpts().OpenCLVersion >= 200 &&
7868       ETy->isAtomicType() && !HasGlobalAS &&
7869       Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7870     S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7871         << 1
7872         << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7873     return ExprError();
7874   }
7875 
7876   QualType DestType = Entity.getType().getNonReferenceType();
7877   // FIXME: Ugly hack around the fact that Entity.getType() is not
7878   // the same as Entity.getDecl()->getType() in cases involving type merging,
7879   //  and we want latter when it makes sense.
7880   if (ResultType)
7881     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
7882                                      Entity.getType();
7883 
7884   ExprResult CurInit((Expr *)nullptr);
7885   SmallVector<Expr*, 4> ArrayLoopCommonExprs;
7886 
7887   // HLSL allows vector initialization to function like list initialization, but
7888   // use the syntax of a C++-like constructor.
7889   bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
7890                           isa<InitListExpr>(Args[0]);
7891   (void)IsHLSLVectorInit;
7892 
7893   // For initialization steps that start with a single initializer,
7894   // grab the only argument out the Args and place it into the "current"
7895   // initializer.
7896   switch (Steps.front().Kind) {
7897   case SK_ResolveAddressOfOverloadedFunction:
7898   case SK_CastDerivedToBasePRValue:
7899   case SK_CastDerivedToBaseXValue:
7900   case SK_CastDerivedToBaseLValue:
7901   case SK_BindReference:
7902   case SK_BindReferenceToTemporary:
7903   case SK_FinalCopy:
7904   case SK_ExtraneousCopyToTemporary:
7905   case SK_UserConversion:
7906   case SK_QualificationConversionLValue:
7907   case SK_QualificationConversionXValue:
7908   case SK_QualificationConversionPRValue:
7909   case SK_FunctionReferenceConversion:
7910   case SK_AtomicConversion:
7911   case SK_ConversionSequence:
7912   case SK_ConversionSequenceNoNarrowing:
7913   case SK_ListInitialization:
7914   case SK_UnwrapInitList:
7915   case SK_RewrapInitList:
7916   case SK_CAssignment:
7917   case SK_StringInit:
7918   case SK_ObjCObjectConversion:
7919   case SK_ArrayLoopIndex:
7920   case SK_ArrayLoopInit:
7921   case SK_ArrayInit:
7922   case SK_GNUArrayInit:
7923   case SK_ParenthesizedArrayInit:
7924   case SK_PassByIndirectCopyRestore:
7925   case SK_PassByIndirectRestore:
7926   case SK_ProduceObjCObject:
7927   case SK_StdInitializerList:
7928   case SK_OCLSamplerInit:
7929   case SK_OCLZeroOpaqueType: {
7930     assert(Args.size() == 1 || IsHLSLVectorInit);
7931     CurInit = Args[0];
7932     if (!CurInit.get()) return ExprError();
7933     break;
7934   }
7935 
7936   case SK_ConstructorInitialization:
7937   case SK_ConstructorInitializationFromList:
7938   case SK_StdInitializerListConstructorCall:
7939   case SK_ZeroInitialization:
7940   case SK_ParenthesizedListInit:
7941     break;
7942   }
7943 
7944   // Promote from an unevaluated context to an unevaluated list context in
7945   // C++11 list-initialization; we need to instantiate entities usable in
7946   // constant expressions here in order to perform narrowing checks =(
7947   EnterExpressionEvaluationContext Evaluated(
7948       S, EnterExpressionEvaluationContext::InitList,
7949       isa_and_nonnull<InitListExpr>(CurInit.get()));
7950 
7951   // C++ [class.abstract]p2:
7952   //   no objects of an abstract class can be created except as subobjects
7953   //   of a class derived from it
7954   auto checkAbstractType = [&](QualType T) -> bool {
7955     if (Entity.getKind() == InitializedEntity::EK_Base ||
7956         Entity.getKind() == InitializedEntity::EK_Delegating)
7957       return false;
7958     return S.RequireNonAbstractType(Kind.getLocation(), T,
7959                                     diag::err_allocation_of_abstract_type);
7960   };
7961 
7962   // Walk through the computed steps for the initialization sequence,
7963   // performing the specified conversions along the way.
7964   bool ConstructorInitRequiresZeroInit = false;
7965   for (step_iterator Step = step_begin(), StepEnd = step_end();
7966        Step != StepEnd; ++Step) {
7967     if (CurInit.isInvalid())
7968       return ExprError();
7969 
7970     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
7971 
7972     switch (Step->Kind) {
7973     case SK_ResolveAddressOfOverloadedFunction:
7974       // Overload resolution determined which function invoke; update the
7975       // initializer to reflect that choice.
7976       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
7977       if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7978         return ExprError();
7979       CurInit = S.FixOverloadedFunctionReference(CurInit,
7980                                                  Step->Function.FoundDecl,
7981                                                  Step->Function.Function);
7982       // We might get back another placeholder expression if we resolved to a
7983       // builtin.
7984       if (!CurInit.isInvalid())
7985         CurInit = S.CheckPlaceholderExpr(CurInit.get());
7986       break;
7987 
7988     case SK_CastDerivedToBasePRValue:
7989     case SK_CastDerivedToBaseXValue:
7990     case SK_CastDerivedToBaseLValue: {
7991       // We have a derived-to-base cast that produces either an rvalue or an
7992       // lvalue. Perform that cast.
7993 
7994       CXXCastPath BasePath;
7995 
7996       // Casts to inaccessible base classes are allowed with C-style casts.
7997       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
7998       if (S.CheckDerivedToBaseConversion(
7999               SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8000               CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8001         return ExprError();
8002 
8003       ExprValueKind VK =
8004           Step->Kind == SK_CastDerivedToBaseLValue
8005               ? VK_LValue
8006               : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8007                                                           : VK_PRValue);
8008       CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8009                                          CK_DerivedToBase, CurInit.get(),
8010                                          &BasePath, VK, FPOptionsOverride());
8011       break;
8012     }
8013 
8014     case SK_BindReference:
8015       // Reference binding does not have any corresponding ASTs.
8016 
8017       // Check exception specifications
8018       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8019         return ExprError();
8020 
8021       // We don't check for e.g. function pointers here, since address
8022       // availability checks should only occur when the function first decays
8023       // into a pointer or reference.
8024       if (CurInit.get()->getType()->isFunctionProtoType()) {
8025         if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8026           if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8027             if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8028                                                      DRE->getBeginLoc()))
8029               return ExprError();
8030           }
8031         }
8032       }
8033 
8034       CheckForNullPointerDereference(S, CurInit.get());
8035       break;
8036 
8037     case SK_BindReferenceToTemporary: {
8038       // Make sure the "temporary" is actually an rvalue.
8039       assert(CurInit.get()->isPRValue() && "not a temporary");
8040 
8041       // Check exception specifications
8042       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8043         return ExprError();
8044 
8045       QualType MTETy = Step->Type;
8046 
8047       // When this is an incomplete array type (such as when this is
8048       // initializing an array of unknown bounds from an init list), use THAT
8049       // type instead so that we propagate the array bounds.
8050       if (MTETy->isIncompleteArrayType() &&
8051           !CurInit.get()->getType()->isIncompleteArrayType() &&
8052           S.Context.hasSameType(
8053               MTETy->getPointeeOrArrayElementType(),
8054               CurInit.get()->getType()->getPointeeOrArrayElementType()))
8055         MTETy = CurInit.get()->getType();
8056 
8057       // Materialize the temporary into memory.
8058       MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8059           MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8060       CurInit = MTE;
8061 
8062       // If we're extending this temporary to automatic storage duration -- we
8063       // need to register its cleanup during the full-expression's cleanups.
8064       if (MTE->getStorageDuration() == SD_Automatic &&
8065           MTE->getType().isDestructedType())
8066         S.Cleanup.setExprNeedsCleanups(true);
8067       break;
8068     }
8069 
8070     case SK_FinalCopy:
8071       if (checkAbstractType(Step->Type))
8072         return ExprError();
8073 
8074       // If the overall initialization is initializing a temporary, we already
8075       // bound our argument if it was necessary to do so. If not (if we're
8076       // ultimately initializing a non-temporary), our argument needs to be
8077       // bound since it's initializing a function parameter.
8078       // FIXME: This is a mess. Rationalize temporary destruction.
8079       if (!shouldBindAsTemporary(Entity))
8080         CurInit = S.MaybeBindToTemporary(CurInit.get());
8081       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8082                            /*IsExtraneousCopy=*/false);
8083       break;
8084 
8085     case SK_ExtraneousCopyToTemporary:
8086       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8087                            /*IsExtraneousCopy=*/true);
8088       break;
8089 
8090     case SK_UserConversion: {
8091       // We have a user-defined conversion that invokes either a constructor
8092       // or a conversion function.
8093       CastKind CastKind;
8094       FunctionDecl *Fn = Step->Function.Function;
8095       DeclAccessPair FoundFn = Step->Function.FoundDecl;
8096       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8097       bool CreatedObject = false;
8098       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8099         // Build a call to the selected constructor.
8100         SmallVector<Expr*, 8> ConstructorArgs;
8101         SourceLocation Loc = CurInit.get()->getBeginLoc();
8102 
8103         // Determine the arguments required to actually perform the constructor
8104         // call.
8105         Expr *Arg = CurInit.get();
8106         if (S.CompleteConstructorCall(Constructor, Step->Type,
8107                                       MultiExprArg(&Arg, 1), Loc,
8108                                       ConstructorArgs))
8109           return ExprError();
8110 
8111         // Build an expression that constructs a temporary.
8112         CurInit = S.BuildCXXConstructExpr(
8113             Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8114             HadMultipleCandidates,
8115             /*ListInit*/ false,
8116             /*StdInitListInit*/ false,
8117             /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8118         if (CurInit.isInvalid())
8119           return ExprError();
8120 
8121         S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8122                                  Entity);
8123         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8124           return ExprError();
8125 
8126         CastKind = CK_ConstructorConversion;
8127         CreatedObject = true;
8128       } else {
8129         // Build a call to the conversion function.
8130         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8131         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8132                                     FoundFn);
8133         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8134           return ExprError();
8135 
8136         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8137                                            HadMultipleCandidates);
8138         if (CurInit.isInvalid())
8139           return ExprError();
8140 
8141         CastKind = CK_UserDefinedConversion;
8142         CreatedObject = Conversion->getReturnType()->isRecordType();
8143       }
8144 
8145       if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8146         return ExprError();
8147 
8148       CurInit = ImplicitCastExpr::Create(
8149           S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8150           CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8151 
8152       if (shouldBindAsTemporary(Entity))
8153         // The overall entity is temporary, so this expression should be
8154         // destroyed at the end of its full-expression.
8155         CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8156       else if (CreatedObject && shouldDestroyEntity(Entity)) {
8157         // The object outlasts the full-expression, but we need to prepare for
8158         // a destructor being run on it.
8159         // FIXME: It makes no sense to do this here. This should happen
8160         // regardless of how we initialized the entity.
8161         QualType T = CurInit.get()->getType();
8162         if (const RecordType *Record = T->getAs<RecordType>()) {
8163           CXXDestructorDecl *Destructor
8164             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8165           S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8166                                   S.PDiag(diag::err_access_dtor_temp) << T);
8167           S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8168           if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8169             return ExprError();
8170         }
8171       }
8172       break;
8173     }
8174 
8175     case SK_QualificationConversionLValue:
8176     case SK_QualificationConversionXValue:
8177     case SK_QualificationConversionPRValue: {
8178       // Perform a qualification conversion; these can never go wrong.
8179       ExprValueKind VK =
8180           Step->Kind == SK_QualificationConversionLValue
8181               ? VK_LValue
8182               : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8183                                                                 : VK_PRValue);
8184       CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8185       break;
8186     }
8187 
8188     case SK_FunctionReferenceConversion:
8189       assert(CurInit.get()->isLValue() &&
8190              "function reference should be lvalue");
8191       CurInit =
8192           S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8193       break;
8194 
8195     case SK_AtomicConversion: {
8196       assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8197       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8198                                     CK_NonAtomicToAtomic, VK_PRValue);
8199       break;
8200     }
8201 
8202     case SK_ConversionSequence:
8203     case SK_ConversionSequenceNoNarrowing: {
8204       if (const auto *FromPtrType =
8205               CurInit.get()->getType()->getAs<PointerType>()) {
8206         if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8207           if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8208               !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8209             // Do not check static casts here because they are checked earlier
8210             // in Sema::ActOnCXXNamedCast()
8211             if (!Kind.isStaticCast()) {
8212               S.Diag(CurInit.get()->getExprLoc(),
8213                      diag::warn_noderef_to_dereferenceable_pointer)
8214                   << CurInit.get()->getSourceRange();
8215             }
8216           }
8217         }
8218       }
8219       Expr *Init = CurInit.get();
8220       CheckedConversionKind CCK =
8221           Kind.isCStyleCast()       ? CheckedConversionKind::CStyleCast
8222           : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8223           : Kind.isExplicitCast()   ? CheckedConversionKind::OtherCast
8224                                     : CheckedConversionKind::Implicit;
8225       ExprResult CurInitExprRes = S.PerformImplicitConversion(
8226           Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8227       if (CurInitExprRes.isInvalid())
8228         return ExprError();
8229 
8230       S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), Init);
8231 
8232       CurInit = CurInitExprRes;
8233 
8234       if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
8235           S.getLangOpts().CPlusPlus)
8236         DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8237                                     CurInit.get());
8238 
8239       break;
8240     }
8241 
8242     case SK_ListInitialization: {
8243       if (checkAbstractType(Step->Type))
8244         return ExprError();
8245 
8246       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8247       // If we're not initializing the top-level entity, we need to create an
8248       // InitializeTemporary entity for our target type.
8249       QualType Ty = Step->Type;
8250       bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8251       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
8252       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
8253       InitListChecker PerformInitList(S, InitEntity,
8254           InitList, Ty, /*VerifyOnly=*/false,
8255           /*TreatUnavailableAsInvalid=*/false);
8256       if (PerformInitList.HadError())
8257         return ExprError();
8258 
8259       // Hack: We must update *ResultType if available in order to set the
8260       // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8261       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8262       if (ResultType &&
8263           ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8264         if ((*ResultType)->isRValueReferenceType())
8265           Ty = S.Context.getRValueReferenceType(Ty);
8266         else if ((*ResultType)->isLValueReferenceType())
8267           Ty = S.Context.getLValueReferenceType(Ty,
8268             (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8269         *ResultType = Ty;
8270       }
8271 
8272       InitListExpr *StructuredInitList =
8273           PerformInitList.getFullyStructuredList();
8274       CurInit.get();
8275       CurInit = shouldBindAsTemporary(InitEntity)
8276           ? S.MaybeBindToTemporary(StructuredInitList)
8277           : StructuredInitList;
8278       break;
8279     }
8280 
8281     case SK_ConstructorInitializationFromList: {
8282       if (checkAbstractType(Step->Type))
8283         return ExprError();
8284 
8285       // When an initializer list is passed for a parameter of type "reference
8286       // to object", we don't get an EK_Temporary entity, but instead an
8287       // EK_Parameter entity with reference type.
8288       // FIXME: This is a hack. What we really should do is create a user
8289       // conversion step for this case, but this makes it considerably more
8290       // complicated. For now, this will do.
8291       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8292                                         Entity.getType().getNonReferenceType());
8293       bool UseTemporary = Entity.getType()->isReferenceType();
8294       assert(Args.size() == 1 && "expected a single argument for list init");
8295       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8296       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8297         << InitList->getSourceRange();
8298       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8299       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8300                                                                    Entity,
8301                                                  Kind, Arg, *Step,
8302                                                ConstructorInitRequiresZeroInit,
8303                                                /*IsListInitialization*/true,
8304                                                /*IsStdInitListInit*/false,
8305                                                InitList->getLBraceLoc(),
8306                                                InitList->getRBraceLoc());
8307       break;
8308     }
8309 
8310     case SK_UnwrapInitList:
8311       CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8312       break;
8313 
8314     case SK_RewrapInitList: {
8315       Expr *E = CurInit.get();
8316       InitListExpr *Syntactic = Step->WrappingSyntacticList;
8317       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8318           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8319       ILE->setSyntacticForm(Syntactic);
8320       ILE->setType(E->getType());
8321       ILE->setValueKind(E->getValueKind());
8322       CurInit = ILE;
8323       break;
8324     }
8325 
8326     case SK_ConstructorInitialization:
8327     case SK_StdInitializerListConstructorCall: {
8328       if (checkAbstractType(Step->Type))
8329         return ExprError();
8330 
8331       // When an initializer list is passed for a parameter of type "reference
8332       // to object", we don't get an EK_Temporary entity, but instead an
8333       // EK_Parameter entity with reference type.
8334       // FIXME: This is a hack. What we really should do is create a user
8335       // conversion step for this case, but this makes it considerably more
8336       // complicated. For now, this will do.
8337       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8338                                         Entity.getType().getNonReferenceType());
8339       bool UseTemporary = Entity.getType()->isReferenceType();
8340       bool IsStdInitListInit =
8341           Step->Kind == SK_StdInitializerListConstructorCall;
8342       Expr *Source = CurInit.get();
8343       SourceRange Range = Kind.hasParenOrBraceRange()
8344                               ? Kind.getParenOrBraceRange()
8345                               : SourceRange();
8346       CurInit = PerformConstructorInitialization(
8347           S, UseTemporary ? TempEntity : Entity, Kind,
8348           Source ? MultiExprArg(Source) : Args, *Step,
8349           ConstructorInitRequiresZeroInit,
8350           /*IsListInitialization*/ IsStdInitListInit,
8351           /*IsStdInitListInitialization*/ IsStdInitListInit,
8352           /*LBraceLoc*/ Range.getBegin(),
8353           /*RBraceLoc*/ Range.getEnd());
8354       break;
8355     }
8356 
8357     case SK_ZeroInitialization: {
8358       step_iterator NextStep = Step;
8359       ++NextStep;
8360       if (NextStep != StepEnd &&
8361           (NextStep->Kind == SK_ConstructorInitialization ||
8362            NextStep->Kind == SK_ConstructorInitializationFromList)) {
8363         // The need for zero-initialization is recorded directly into
8364         // the call to the object's constructor within the next step.
8365         ConstructorInitRequiresZeroInit = true;
8366       } else if (Kind.getKind() == InitializationKind::IK_Value &&
8367                  S.getLangOpts().CPlusPlus &&
8368                  !Kind.isImplicitValueInit()) {
8369         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8370         if (!TSInfo)
8371           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
8372                                                     Kind.getRange().getBegin());
8373 
8374         CurInit = new (S.Context) CXXScalarValueInitExpr(
8375             Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8376             Kind.getRange().getEnd());
8377       } else {
8378         CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8379         // Note the return value isn't used to return a ExprError() when
8380         // initialization fails . For struct initialization allows all field
8381         // assignments to be checked rather than bailing on the first error.
8382         S.BoundsSafetyCheckInitialization(Entity, Kind,
8383                                           AssignmentAction::Initializing,
8384                                           Step->Type, CurInit.get());
8385       }
8386       break;
8387     }
8388 
8389     case SK_CAssignment: {
8390       QualType SourceType = CurInit.get()->getType();
8391       Expr *Init = CurInit.get();
8392 
8393       // Save off the initial CurInit in case we need to emit a diagnostic
8394       ExprResult InitialCurInit = Init;
8395       ExprResult Result = Init;
8396       AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints(
8397           Step->Type, Result, true,
8398           Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
8399       if (Result.isInvalid())
8400         return ExprError();
8401       CurInit = Result;
8402 
8403       // If this is a call, allow conversion to a transparent union.
8404       ExprResult CurInitExprRes = CurInit;
8405       if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8406           S.CheckTransparentUnionArgumentConstraints(
8407               Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8408         ConvTy = AssignConvertType::Compatible;
8409       if (CurInitExprRes.isInvalid())
8410         return ExprError();
8411       CurInit = CurInitExprRes;
8412 
8413       if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8414         CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8415                                         CurInit.get());
8416 
8417         // C23 6.7.1p6: If an object or subobject declared with storage-class
8418         // specifier constexpr has pointer, integer, or arithmetic type, any
8419         // explicit initializer value for it shall be null, an integer
8420         // constant expression, or an arithmetic constant expression,
8421         // respectively.
8422         Expr::EvalResult ER;
8423         if (Entity.getType()->getAs<PointerType>() &&
8424             CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8425             !ER.Val.isNullPointer()) {
8426           S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8427         }
8428       }
8429 
8430       // Note the return value isn't used to return a ExprError() when
8431       // initialization fails. For struct initialization this allows all field
8432       // assignments to be checked rather than bailing on the first error.
8433       S.BoundsSafetyCheckInitialization(Entity, Kind,
8434                                         getAssignmentAction(Entity, true),
8435                                         Step->Type, InitialCurInit.get());
8436 
8437       bool Complained;
8438       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8439                                      Step->Type, SourceType,
8440                                      InitialCurInit.get(),
8441                                      getAssignmentAction(Entity, true),
8442                                      &Complained)) {
8443         PrintInitLocationNote(S, Entity);
8444         return ExprError();
8445       } else if (Complained)
8446         PrintInitLocationNote(S, Entity);
8447       break;
8448     }
8449 
8450     case SK_StringInit: {
8451       QualType Ty = Step->Type;
8452       bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8453       CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8454                       S.Context.getAsArrayType(Ty), S, Entity,
8455                       S.getLangOpts().C23 &&
8456                           initializingConstexprVariable(Entity));
8457       break;
8458     }
8459 
8460     case SK_ObjCObjectConversion:
8461       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8462                           CK_ObjCObjectLValueCast,
8463                           CurInit.get()->getValueKind());
8464       break;
8465 
8466     case SK_ArrayLoopIndex: {
8467       Expr *Cur = CurInit.get();
8468       Expr *BaseExpr = new (S.Context)
8469           OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8470                           Cur->getValueKind(), Cur->getObjectKind(), Cur);
8471       Expr *IndexExpr =
8472           new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8473       CurInit = S.CreateBuiltinArraySubscriptExpr(
8474           BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8475       ArrayLoopCommonExprs.push_back(BaseExpr);
8476       break;
8477     }
8478 
8479     case SK_ArrayLoopInit: {
8480       assert(!ArrayLoopCommonExprs.empty() &&
8481              "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8482       Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8483       CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8484                                                   CurInit.get());
8485       break;
8486     }
8487 
8488     case SK_GNUArrayInit:
8489       // Okay: we checked everything before creating this step. Note that
8490       // this is a GNU extension.
8491       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8492         << Step->Type << CurInit.get()->getType()
8493         << CurInit.get()->getSourceRange();
8494       updateGNUCompoundLiteralRValue(CurInit.get());
8495       [[fallthrough]];
8496     case SK_ArrayInit:
8497       // If the destination type is an incomplete array type, update the
8498       // type accordingly.
8499       if (ResultType) {
8500         if (const IncompleteArrayType *IncompleteDest
8501                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
8502           if (const ConstantArrayType *ConstantSource
8503                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8504             *ResultType = S.Context.getConstantArrayType(
8505                 IncompleteDest->getElementType(), ConstantSource->getSize(),
8506                 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8507           }
8508         }
8509       }
8510       break;
8511 
8512     case SK_ParenthesizedArrayInit:
8513       // Okay: we checked everything before creating this step. Note that
8514       // this is a GNU extension.
8515       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8516         << CurInit.get()->getSourceRange();
8517       break;
8518 
8519     case SK_PassByIndirectCopyRestore:
8520     case SK_PassByIndirectRestore:
8521       checkIndirectCopyRestoreSource(S, CurInit.get());
8522       CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8523           CurInit.get(), Step->Type,
8524           Step->Kind == SK_PassByIndirectCopyRestore);
8525       break;
8526 
8527     case SK_ProduceObjCObject:
8528       CurInit = ImplicitCastExpr::Create(
8529           S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8530           VK_PRValue, FPOptionsOverride());
8531       break;
8532 
8533     case SK_StdInitializerList: {
8534       S.Diag(CurInit.get()->getExprLoc(),
8535              diag::warn_cxx98_compat_initializer_list_init)
8536         << CurInit.get()->getSourceRange();
8537 
8538       // Materialize the temporary into memory.
8539       MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8540           CurInit.get()->getType(), CurInit.get(),
8541           /*BoundToLvalueReference=*/false);
8542 
8543       // Wrap it in a construction of a std::initializer_list<T>.
8544       CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8545 
8546       if (!Step->Type->isDependentType()) {
8547         QualType ElementType;
8548         [[maybe_unused]] bool IsStdInitializerList =
8549             S.isStdInitializerList(Step->Type, &ElementType);
8550         assert(IsStdInitializerList &&
8551                "StdInitializerList step to non-std::initializer_list");
8552         const CXXRecordDecl *Record =
8553             Step->Type->getAsCXXRecordDecl()->getDefinition();
8554         assert(Record && Record->isCompleteDefinition() &&
8555                "std::initializer_list should have already be "
8556                "complete/instantiated by this point");
8557 
8558         auto InvalidType = [&] {
8559           S.Diag(Record->getLocation(),
8560                  diag::err_std_initializer_list_malformed)
8561               << Step->Type.getUnqualifiedType();
8562           return ExprError();
8563         };
8564 
8565         if (Record->isUnion() || Record->getNumBases() != 0 ||
8566             Record->isPolymorphic())
8567           return InvalidType();
8568 
8569         RecordDecl::field_iterator Field = Record->field_begin();
8570         if (Field == Record->field_end())
8571           return InvalidType();
8572 
8573         // Start pointer
8574         if (!Field->getType()->isPointerType() ||
8575             !S.Context.hasSameType(Field->getType()->getPointeeType(),
8576                                    ElementType.withConst()))
8577           return InvalidType();
8578 
8579         if (++Field == Record->field_end())
8580           return InvalidType();
8581 
8582         // Size or end pointer
8583         if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8584           if (!S.Context.hasSameType(PT->getPointeeType(),
8585                                      ElementType.withConst()))
8586             return InvalidType();
8587         } else {
8588           if (Field->isBitField() ||
8589               !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8590             return InvalidType();
8591         }
8592 
8593         if (++Field != Record->field_end())
8594           return InvalidType();
8595       }
8596 
8597       // Bind the result, in case the library has given initializer_list a
8598       // non-trivial destructor.
8599       if (shouldBindAsTemporary(Entity))
8600         CurInit = S.MaybeBindToTemporary(CurInit.get());
8601       break;
8602     }
8603 
8604     case SK_OCLSamplerInit: {
8605       // Sampler initialization have 5 cases:
8606       //   1. function argument passing
8607       //      1a. argument is a file-scope variable
8608       //      1b. argument is a function-scope variable
8609       //      1c. argument is one of caller function's parameters
8610       //   2. variable initialization
8611       //      2a. initializing a file-scope variable
8612       //      2b. initializing a function-scope variable
8613       //
8614       // For file-scope variables, since they cannot be initialized by function
8615       // call of __translate_sampler_initializer in LLVM IR, their references
8616       // need to be replaced by a cast from their literal initializers to
8617       // sampler type. Since sampler variables can only be used in function
8618       // calls as arguments, we only need to replace them when handling the
8619       // argument passing.
8620       assert(Step->Type->isSamplerT() &&
8621              "Sampler initialization on non-sampler type.");
8622       Expr *Init = CurInit.get()->IgnoreParens();
8623       QualType SourceType = Init->getType();
8624       // Case 1
8625       if (Entity.isParameterKind()) {
8626         if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8627           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8628             << SourceType;
8629           break;
8630         } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8631           auto Var = cast<VarDecl>(DRE->getDecl());
8632           // Case 1b and 1c
8633           // No cast from integer to sampler is needed.
8634           if (!Var->hasGlobalStorage()) {
8635             CurInit = ImplicitCastExpr::Create(
8636                 S.Context, Step->Type, CK_LValueToRValue, Init,
8637                 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8638             break;
8639           }
8640           // Case 1a
8641           // For function call with a file-scope sampler variable as argument,
8642           // get the integer literal.
8643           // Do not diagnose if the file-scope variable does not have initializer
8644           // since this has already been diagnosed when parsing the variable
8645           // declaration.
8646           if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8647             break;
8648           Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8649             Var->getInit()))->getSubExpr();
8650           SourceType = Init->getType();
8651         }
8652       } else {
8653         // Case 2
8654         // Check initializer is 32 bit integer constant.
8655         // If the initializer is taken from global variable, do not diagnose since
8656         // this has already been done when parsing the variable declaration.
8657         if (!Init->isConstantInitializer(S.Context, false))
8658           break;
8659 
8660         if (!SourceType->isIntegerType() ||
8661             32 != S.Context.getIntWidth(SourceType)) {
8662           S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8663             << SourceType;
8664           break;
8665         }
8666 
8667         Expr::EvalResult EVResult;
8668         Init->EvaluateAsInt(EVResult, S.Context);
8669         llvm::APSInt Result = EVResult.Val.getInt();
8670         const uint64_t SamplerValue = Result.getLimitedValue();
8671         // 32-bit value of sampler's initializer is interpreted as
8672         // bit-field with the following structure:
8673         // |unspecified|Filter|Addressing Mode| Normalized Coords|
8674         // |31        6|5    4|3             1|                 0|
8675         // This structure corresponds to enum values of sampler properties
8676         // defined in SPIR spec v1.2 and also opencl-c.h
8677         unsigned AddressingMode  = (0x0E & SamplerValue) >> 1;
8678         unsigned FilterMode      = (0x30 & SamplerValue) >> 4;
8679         if (FilterMode != 1 && FilterMode != 2 &&
8680             !S.getOpenCLOptions().isAvailableOption(
8681                 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8682           S.Diag(Kind.getLocation(),
8683                  diag::warn_sampler_initializer_invalid_bits)
8684                  << "Filter Mode";
8685         if (AddressingMode > 4)
8686           S.Diag(Kind.getLocation(),
8687                  diag::warn_sampler_initializer_invalid_bits)
8688                  << "Addressing Mode";
8689       }
8690 
8691       // Cases 1a, 2a and 2b
8692       // Insert cast from integer to sampler.
8693       CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8694                                       CK_IntToOCLSampler);
8695       break;
8696     }
8697     case SK_OCLZeroOpaqueType: {
8698       assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8699               Step->Type->isOCLIntelSubgroupAVCType()) &&
8700              "Wrong type for initialization of OpenCL opaque type.");
8701 
8702       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8703                                     CK_ZeroToOCLOpaqueType,
8704                                     CurInit.get()->getValueKind());
8705       break;
8706     }
8707     case SK_ParenthesizedListInit: {
8708       CurInit = nullptr;
8709       TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8710                                         /*VerifyOnly=*/false, &CurInit);
8711       if (CurInit.get() && ResultType)
8712         *ResultType = CurInit.get()->getType();
8713       if (shouldBindAsTemporary(Entity))
8714         CurInit = S.MaybeBindToTemporary(CurInit.get());
8715       break;
8716     }
8717     }
8718   }
8719 
8720   Expr *Init = CurInit.get();
8721   if (!Init)
8722     return ExprError();
8723 
8724   // Check whether the initializer has a shorter lifetime than the initialized
8725   // entity, and if not, either lifetime-extend or warn as appropriate.
8726   S.checkInitializerLifetime(Entity, Init);
8727 
8728   // Diagnose non-fatal problems with the completed initialization.
8729   if (InitializedEntity::EntityKind EK = Entity.getKind();
8730       (EK == InitializedEntity::EK_Member ||
8731        EK == InitializedEntity::EK_ParenAggInitMember) &&
8732       cast<FieldDecl>(Entity.getDecl())->isBitField())
8733     S.CheckBitFieldInitialization(Kind.getLocation(),
8734                                   cast<FieldDecl>(Entity.getDecl()), Init);
8735 
8736   // Check for std::move on construction.
8737   CheckMoveOnConstruction(S, Init,
8738                           Entity.getKind() == InitializedEntity::EK_Result);
8739 
8740   return Init;
8741 }
8742 
8743 /// Somewhere within T there is an uninitialized reference subobject.
8744 /// Dig it out and diagnose it.
DiagnoseUninitializedReference(Sema & S,SourceLocation Loc,QualType T)8745 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8746                                            QualType T) {
8747   if (T->isReferenceType()) {
8748     S.Diag(Loc, diag::err_reference_without_init)
8749       << T.getNonReferenceType();
8750     return true;
8751   }
8752 
8753   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8754   if (!RD || !RD->hasUninitializedReferenceMember())
8755     return false;
8756 
8757   for (const auto *FI : RD->fields()) {
8758     if (FI->isUnnamedBitField())
8759       continue;
8760 
8761     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8762       S.Diag(Loc, diag::note_value_initialization_here) << RD;
8763       return true;
8764     }
8765   }
8766 
8767   for (const auto &BI : RD->bases()) {
8768     if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8769       S.Diag(Loc, diag::note_value_initialization_here) << RD;
8770       return true;
8771     }
8772   }
8773 
8774   return false;
8775 }
8776 
8777 
8778 //===----------------------------------------------------------------------===//
8779 // Diagnose initialization failures
8780 //===----------------------------------------------------------------------===//
8781 
8782 /// Emit notes associated with an initialization that failed due to a
8783 /// "simple" conversion failure.
emitBadConversionNotes(Sema & S,const InitializedEntity & entity,Expr * op)8784 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8785                                    Expr *op) {
8786   QualType destType = entity.getType();
8787   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8788       op->getType()->isObjCObjectPointerType()) {
8789 
8790     // Emit a possible note about the conversion failing because the
8791     // operand is a message send with a related result type.
8792     S.ObjC().EmitRelatedResultTypeNote(op);
8793 
8794     // Emit a possible note about a return failing because we're
8795     // expecting a related result type.
8796     if (entity.getKind() == InitializedEntity::EK_Result)
8797       S.ObjC().EmitRelatedResultTypeNoteForReturn(destType);
8798   }
8799   QualType fromType = op->getType();
8800   QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8801   QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8802   auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8803   auto *destDecl = destType->getPointeeCXXRecordDecl();
8804   if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8805       destDecl->getDeclKind() == Decl::CXXRecord &&
8806       !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8807       !fromDecl->hasDefinition() &&
8808       destPointeeType.getQualifiers().compatiblyIncludes(
8809           fromPointeeType.getQualifiers(), S.getASTContext()))
8810     S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8811         << S.getASTContext().getTagDeclType(fromDecl)
8812         << S.getASTContext().getTagDeclType(destDecl);
8813 }
8814 
diagnoseListInit(Sema & S,const InitializedEntity & Entity,InitListExpr * InitList)8815 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8816                              InitListExpr *InitList) {
8817   QualType DestType = Entity.getType();
8818 
8819   QualType E;
8820   if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8821     QualType ArrayType = S.Context.getConstantArrayType(
8822         E.withConst(),
8823         llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8824                     InitList->getNumInits()),
8825         nullptr, clang::ArraySizeModifier::Normal, 0);
8826     InitializedEntity HiddenArray =
8827         InitializedEntity::InitializeTemporary(ArrayType);
8828     return diagnoseListInit(S, HiddenArray, InitList);
8829   }
8830 
8831   if (DestType->isReferenceType()) {
8832     // A list-initialization failure for a reference means that we tried to
8833     // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8834     // inner initialization failed.
8835     QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8836     diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
8837     SourceLocation Loc = InitList->getBeginLoc();
8838     if (auto *D = Entity.getDecl())
8839       Loc = D->getLocation();
8840     S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8841     return;
8842   }
8843 
8844   InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8845                                    /*VerifyOnly=*/false,
8846                                    /*TreatUnavailableAsInvalid=*/false);
8847   assert(DiagnoseInitList.HadError() &&
8848          "Inconsistent init list check result.");
8849 }
8850 
Diagnose(Sema & S,const InitializedEntity & Entity,const InitializationKind & Kind,ArrayRef<Expr * > Args)8851 bool InitializationSequence::Diagnose(Sema &S,
8852                                       const InitializedEntity &Entity,
8853                                       const InitializationKind &Kind,
8854                                       ArrayRef<Expr *> Args) {
8855   if (!Failed())
8856     return false;
8857 
8858   QualType DestType = Entity.getType();
8859 
8860   // When we want to diagnose only one element of a braced-init-list,
8861   // we need to factor it out.
8862   Expr *OnlyArg;
8863   if (Args.size() == 1) {
8864     auto *List = dyn_cast<InitListExpr>(Args[0]);
8865     if (List && List->getNumInits() == 1)
8866       OnlyArg = List->getInit(0);
8867     else
8868       OnlyArg = Args[0];
8869 
8870     if (OnlyArg->getType() == S.Context.OverloadTy) {
8871       DeclAccessPair Found;
8872       if (FunctionDecl *FD = S.ResolveAddressOfOverloadedFunction(
8873               OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
8874               Found)) {
8875         if (Expr *Resolved =
8876                 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
8877           OnlyArg = Resolved;
8878       }
8879     }
8880   }
8881   else
8882     OnlyArg = nullptr;
8883 
8884   switch (Failure) {
8885   case FK_TooManyInitsForReference:
8886     // FIXME: Customize for the initialized entity?
8887     if (Args.empty()) {
8888       // Dig out the reference subobject which is uninitialized and diagnose it.
8889       // If this is value-initialization, this could be nested some way within
8890       // the target type.
8891       assert(Kind.getKind() == InitializationKind::IK_Value ||
8892              DestType->isReferenceType());
8893       bool Diagnosed =
8894         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8895       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8896       (void)Diagnosed;
8897     } else  // FIXME: diagnostic below could be better!
8898       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
8899           << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8900     break;
8901   case FK_ParenthesizedListInitForReference:
8902     S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8903       << 1 << Entity.getType() << Args[0]->getSourceRange();
8904     break;
8905 
8906   case FK_ArrayNeedsInitList:
8907     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
8908     break;
8909   case FK_ArrayNeedsInitListOrStringLiteral:
8910     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8911     break;
8912   case FK_ArrayNeedsInitListOrWideStringLiteral:
8913     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8914     break;
8915   case FK_NarrowStringIntoWideCharArray:
8916     S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8917     break;
8918   case FK_WideStringIntoCharArray:
8919     S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8920     break;
8921   case FK_IncompatWideStringIntoWideChar:
8922     S.Diag(Kind.getLocation(),
8923            diag::err_array_init_incompat_wide_string_into_wchar);
8924     break;
8925   case FK_PlainStringIntoUTF8Char:
8926     S.Diag(Kind.getLocation(),
8927            diag::err_array_init_plain_string_into_char8_t);
8928     S.Diag(Args.front()->getBeginLoc(),
8929            diag::note_array_init_plain_string_into_char8_t)
8930         << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
8931     break;
8932   case FK_UTF8StringIntoPlainChar:
8933     S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
8934         << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
8935     break;
8936   case FK_ArrayTypeMismatch:
8937   case FK_NonConstantArrayInit:
8938     S.Diag(Kind.getLocation(),
8939            (Failure == FK_ArrayTypeMismatch
8940               ? diag::err_array_init_different_type
8941               : diag::err_array_init_non_constant_array))
8942       << DestType.getNonReferenceType()
8943       << OnlyArg->getType()
8944       << Args[0]->getSourceRange();
8945     break;
8946 
8947   case FK_VariableLengthArrayHasInitializer:
8948     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8949       << Args[0]->getSourceRange();
8950     break;
8951 
8952   case FK_AddressOfOverloadFailed: {
8953     DeclAccessPair Found;
8954     S.ResolveAddressOfOverloadedFunction(OnlyArg,
8955                                          DestType.getNonReferenceType(),
8956                                          true,
8957                                          Found);
8958     break;
8959   }
8960 
8961   case FK_AddressOfUnaddressableFunction: {
8962     auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8963     S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8964                                         OnlyArg->getBeginLoc());
8965     break;
8966   }
8967 
8968   case FK_ReferenceInitOverloadFailed:
8969   case FK_UserConversionOverloadFailed:
8970     switch (FailedOverloadResult) {
8971     case OR_Ambiguous:
8972 
8973       FailedCandidateSet.NoteCandidates(
8974           PartialDiagnosticAt(
8975               Kind.getLocation(),
8976               Failure == FK_UserConversionOverloadFailed
8977                   ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8978                      << OnlyArg->getType() << DestType
8979                      << Args[0]->getSourceRange())
8980                   : (S.PDiag(diag::err_ref_init_ambiguous)
8981                      << DestType << OnlyArg->getType()
8982                      << Args[0]->getSourceRange())),
8983           S, OCD_AmbiguousCandidates, Args);
8984       break;
8985 
8986     case OR_No_Viable_Function: {
8987       auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
8988       if (!S.RequireCompleteType(Kind.getLocation(),
8989                                  DestType.getNonReferenceType(),
8990                           diag::err_typecheck_nonviable_condition_incomplete,
8991                                OnlyArg->getType(), Args[0]->getSourceRange()))
8992         S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
8993           << (Entity.getKind() == InitializedEntity::EK_Result)
8994           << OnlyArg->getType() << Args[0]->getSourceRange()
8995           << DestType.getNonReferenceType();
8996 
8997       FailedCandidateSet.NoteCandidates(S, Args, Cands);
8998       break;
8999     }
9000     case OR_Deleted: {
9001       OverloadCandidateSet::iterator Best;
9002       OverloadingResult Ovl
9003         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9004 
9005       StringLiteral *Msg = Best->Function->getDeletedMessage();
9006       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9007           << OnlyArg->getType() << DestType.getNonReferenceType()
9008           << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9009           << Args[0]->getSourceRange();
9010       if (Ovl == OR_Deleted) {
9011         S.NoteDeletedFunction(Best->Function);
9012       } else {
9013         llvm_unreachable("Inconsistent overload resolution?");
9014       }
9015       break;
9016     }
9017 
9018     case OR_Success:
9019       llvm_unreachable("Conversion did not fail!");
9020     }
9021     break;
9022 
9023   case FK_NonConstLValueReferenceBindingToTemporary:
9024     if (isa<InitListExpr>(Args[0])) {
9025       S.Diag(Kind.getLocation(),
9026              diag::err_lvalue_reference_bind_to_initlist)
9027       << DestType.getNonReferenceType().isVolatileQualified()
9028       << DestType.getNonReferenceType()
9029       << Args[0]->getSourceRange();
9030       break;
9031     }
9032     [[fallthrough]];
9033 
9034   case FK_NonConstLValueReferenceBindingToUnrelated:
9035     S.Diag(Kind.getLocation(),
9036            Failure == FK_NonConstLValueReferenceBindingToTemporary
9037              ? diag::err_lvalue_reference_bind_to_temporary
9038              : diag::err_lvalue_reference_bind_to_unrelated)
9039       << DestType.getNonReferenceType().isVolatileQualified()
9040       << DestType.getNonReferenceType()
9041       << OnlyArg->getType()
9042       << Args[0]->getSourceRange();
9043     break;
9044 
9045   case FK_NonConstLValueReferenceBindingToBitfield: {
9046     // We don't necessarily have an unambiguous source bit-field.
9047     FieldDecl *BitField = Args[0]->getSourceBitField();
9048     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9049       << DestType.isVolatileQualified()
9050       << (BitField ? BitField->getDeclName() : DeclarationName())
9051       << (BitField != nullptr)
9052       << Args[0]->getSourceRange();
9053     if (BitField)
9054       S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9055     break;
9056   }
9057 
9058   case FK_NonConstLValueReferenceBindingToVectorElement:
9059     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9060       << DestType.isVolatileQualified()
9061       << Args[0]->getSourceRange();
9062     break;
9063 
9064   case FK_NonConstLValueReferenceBindingToMatrixElement:
9065     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9066         << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9067     break;
9068 
9069   case FK_RValueReferenceBindingToLValue:
9070     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9071       << DestType.getNonReferenceType() << OnlyArg->getType()
9072       << Args[0]->getSourceRange();
9073     break;
9074 
9075   case FK_ReferenceAddrspaceMismatchTemporary:
9076     S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9077         << DestType << Args[0]->getSourceRange();
9078     break;
9079 
9080   case FK_ReferenceInitDropsQualifiers: {
9081     QualType SourceType = OnlyArg->getType();
9082     QualType NonRefType = DestType.getNonReferenceType();
9083     Qualifiers DroppedQualifiers =
9084         SourceType.getQualifiers() - NonRefType.getQualifiers();
9085 
9086     if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9087             SourceType.getQualifiers(), S.getASTContext()))
9088       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9089           << NonRefType << SourceType << 1 /*addr space*/
9090           << Args[0]->getSourceRange();
9091     else if (DroppedQualifiers.hasQualifiers())
9092       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9093           << NonRefType << SourceType << 0 /*cv quals*/
9094           << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9095           << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9096     else
9097       // FIXME: Consider decomposing the type and explaining which qualifiers
9098       // were dropped where, or on which level a 'const' is missing, etc.
9099       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9100           << NonRefType << SourceType << 2 /*incompatible quals*/
9101           << Args[0]->getSourceRange();
9102     break;
9103   }
9104 
9105   case FK_ReferenceInitFailed:
9106     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9107       << DestType.getNonReferenceType()
9108       << DestType.getNonReferenceType()->isIncompleteType()
9109       << OnlyArg->isLValue()
9110       << OnlyArg->getType()
9111       << Args[0]->getSourceRange();
9112     emitBadConversionNotes(S, Entity, Args[0]);
9113     break;
9114 
9115   case FK_ConversionFailed: {
9116     QualType FromType = OnlyArg->getType();
9117     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9118       << (int)Entity.getKind()
9119       << DestType
9120       << OnlyArg->isLValue()
9121       << FromType
9122       << Args[0]->getSourceRange();
9123     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9124     S.Diag(Kind.getLocation(), PDiag);
9125     emitBadConversionNotes(S, Entity, Args[0]);
9126     break;
9127   }
9128 
9129   case FK_ConversionFromPropertyFailed:
9130     // No-op. This error has already been reported.
9131     break;
9132 
9133   case FK_TooManyInitsForScalar: {
9134     SourceRange R;
9135 
9136     auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9137     if (InitList && InitList->getNumInits() >= 1) {
9138       R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9139     } else {
9140       assert(Args.size() > 1 && "Expected multiple initializers!");
9141       R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9142     }
9143 
9144     R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9145     if (Kind.isCStyleOrFunctionalCast())
9146       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9147         << R;
9148     else
9149       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9150         << /*scalar=*/2 << R;
9151     break;
9152   }
9153 
9154   case FK_ParenthesizedListInitForScalar:
9155     S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9156       << 0 << Entity.getType() << Args[0]->getSourceRange();
9157     break;
9158 
9159   case FK_ReferenceBindingToInitList:
9160     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9161       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9162     break;
9163 
9164   case FK_InitListBadDestinationType:
9165     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9166       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9167     break;
9168 
9169   case FK_ListConstructorOverloadFailed:
9170   case FK_ConstructorOverloadFailed: {
9171     SourceRange ArgsRange;
9172     if (Args.size())
9173       ArgsRange =
9174           SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9175 
9176     if (Failure == FK_ListConstructorOverloadFailed) {
9177       assert(Args.size() == 1 &&
9178              "List construction from other than 1 argument.");
9179       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9180       Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9181     }
9182 
9183     // FIXME: Using "DestType" for the entity we're printing is probably
9184     // bad.
9185     switch (FailedOverloadResult) {
9186       case OR_Ambiguous:
9187         FailedCandidateSet.NoteCandidates(
9188             PartialDiagnosticAt(Kind.getLocation(),
9189                                 S.PDiag(diag::err_ovl_ambiguous_init)
9190                                     << DestType << ArgsRange),
9191             S, OCD_AmbiguousCandidates, Args);
9192         break;
9193 
9194       case OR_No_Viable_Function:
9195         if (Kind.getKind() == InitializationKind::IK_Default &&
9196             (Entity.getKind() == InitializedEntity::EK_Base ||
9197              Entity.getKind() == InitializedEntity::EK_Member ||
9198              Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9199             isa<CXXConstructorDecl>(S.CurContext)) {
9200           // This is implicit default initialization of a member or
9201           // base within a constructor. If no viable function was
9202           // found, notify the user that they need to explicitly
9203           // initialize this base/member.
9204           CXXConstructorDecl *Constructor
9205             = cast<CXXConstructorDecl>(S.CurContext);
9206           const CXXRecordDecl *InheritedFrom = nullptr;
9207           if (auto Inherited = Constructor->getInheritedConstructor())
9208             InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9209           if (Entity.getKind() == InitializedEntity::EK_Base) {
9210             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9211               << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9212               << S.Context.getTypeDeclType(Constructor->getParent())
9213               << /*base=*/0
9214               << Entity.getType()
9215               << InheritedFrom;
9216 
9217             RecordDecl *BaseDecl
9218               = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9219                                                                   ->getDecl();
9220             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9221               << S.Context.getTagDeclType(BaseDecl);
9222           } else {
9223             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9224               << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9225               << S.Context.getTypeDeclType(Constructor->getParent())
9226               << /*member=*/1
9227               << Entity.getName()
9228               << InheritedFrom;
9229             S.Diag(Entity.getDecl()->getLocation(),
9230                    diag::note_member_declared_at);
9231 
9232             if (const RecordType *Record
9233                                  = Entity.getType()->getAs<RecordType>())
9234               S.Diag(Record->getDecl()->getLocation(),
9235                      diag::note_previous_decl)
9236                 << S.Context.getTagDeclType(Record->getDecl());
9237           }
9238           break;
9239         }
9240 
9241         FailedCandidateSet.NoteCandidates(
9242             PartialDiagnosticAt(
9243                 Kind.getLocation(),
9244                 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9245                     << DestType << ArgsRange),
9246             S, OCD_AllCandidates, Args);
9247         break;
9248 
9249       case OR_Deleted: {
9250         OverloadCandidateSet::iterator Best;
9251         OverloadingResult Ovl
9252           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9253         if (Ovl != OR_Deleted) {
9254           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9255               << DestType << ArgsRange;
9256           llvm_unreachable("Inconsistent overload resolution?");
9257           break;
9258         }
9259 
9260         // If this is a defaulted or implicitly-declared function, then
9261         // it was implicitly deleted. Make it clear that the deletion was
9262         // implicit.
9263         if (S.isImplicitlyDeleted(Best->Function))
9264           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9265               << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9266               << DestType << ArgsRange;
9267         else {
9268           StringLiteral *Msg = Best->Function->getDeletedMessage();
9269           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9270               << DestType << (Msg != nullptr)
9271               << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9272         }
9273 
9274         // If it's a default constructed member, but it's not in the
9275         // constructor's initializer list, explicitly note where the member is
9276         // declared so the user can see which member is erroneously initialized
9277         // with a deleted default constructor.
9278         if (Kind.getKind() == InitializationKind::IK_Default &&
9279             (Entity.getKind() == InitializedEntity::EK_Member ||
9280              Entity.getKind() == InitializedEntity::EK_ParenAggInitMember)) {
9281           S.Diag(Entity.getDecl()->getLocation(),
9282                  diag::note_default_constructed_field)
9283               << Entity.getDecl();
9284         }
9285         S.NoteDeletedFunction(Best->Function);
9286         break;
9287       }
9288 
9289       case OR_Success:
9290         llvm_unreachable("Conversion did not fail!");
9291     }
9292   }
9293   break;
9294 
9295   case FK_DefaultInitOfConst:
9296     if (Entity.getKind() == InitializedEntity::EK_Member &&
9297         isa<CXXConstructorDecl>(S.CurContext)) {
9298       // This is implicit default-initialization of a const member in
9299       // a constructor. Complain that it needs to be explicitly
9300       // initialized.
9301       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9302       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9303         << (Constructor->getInheritedConstructor() ? 2 :
9304             Constructor->isImplicit() ? 1 : 0)
9305         << S.Context.getTypeDeclType(Constructor->getParent())
9306         << /*const=*/1
9307         << Entity.getName();
9308       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9309         << Entity.getName();
9310     } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9311                VD && VD->isConstexpr()) {
9312       S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9313           << VD;
9314     } else {
9315       S.Diag(Kind.getLocation(), diag::err_default_init_const)
9316           << DestType << (bool)DestType->getAs<RecordType>();
9317     }
9318     break;
9319 
9320   case FK_Incomplete:
9321     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9322                           diag::err_init_incomplete_type);
9323     break;
9324 
9325   case FK_ListInitializationFailed: {
9326     // Run the init list checker again to emit diagnostics.
9327     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9328     diagnoseListInit(S, Entity, InitList);
9329     break;
9330   }
9331 
9332   case FK_PlaceholderType: {
9333     // FIXME: Already diagnosed!
9334     break;
9335   }
9336 
9337   case FK_ExplicitConstructor: {
9338     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9339       << Args[0]->getSourceRange();
9340     OverloadCandidateSet::iterator Best;
9341     OverloadingResult Ovl
9342       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9343     (void)Ovl;
9344     assert(Ovl == OR_Success && "Inconsistent overload resolution");
9345     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9346     S.Diag(CtorDecl->getLocation(),
9347            diag::note_explicit_ctor_deduction_guide_here) << false;
9348     break;
9349   }
9350 
9351   case FK_ParenthesizedListInitFailed:
9352     TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9353                                       /*VerifyOnly=*/false);
9354     break;
9355 
9356   case FK_DesignatedInitForNonAggregate:
9357     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9358     S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9359         << Entity.getType() << InitList->getSourceRange();
9360     break;
9361   }
9362 
9363   PrintInitLocationNote(S, Entity);
9364   return true;
9365 }
9366 
dump(raw_ostream & OS) const9367 void InitializationSequence::dump(raw_ostream &OS) const {
9368   switch (SequenceKind) {
9369   case FailedSequence: {
9370     OS << "Failed sequence: ";
9371     switch (Failure) {
9372     case FK_TooManyInitsForReference:
9373       OS << "too many initializers for reference";
9374       break;
9375 
9376     case FK_ParenthesizedListInitForReference:
9377       OS << "parenthesized list init for reference";
9378       break;
9379 
9380     case FK_ArrayNeedsInitList:
9381       OS << "array requires initializer list";
9382       break;
9383 
9384     case FK_AddressOfUnaddressableFunction:
9385       OS << "address of unaddressable function was taken";
9386       break;
9387 
9388     case FK_ArrayNeedsInitListOrStringLiteral:
9389       OS << "array requires initializer list or string literal";
9390       break;
9391 
9392     case FK_ArrayNeedsInitListOrWideStringLiteral:
9393       OS << "array requires initializer list or wide string literal";
9394       break;
9395 
9396     case FK_NarrowStringIntoWideCharArray:
9397       OS << "narrow string into wide char array";
9398       break;
9399 
9400     case FK_WideStringIntoCharArray:
9401       OS << "wide string into char array";
9402       break;
9403 
9404     case FK_IncompatWideStringIntoWideChar:
9405       OS << "incompatible wide string into wide char array";
9406       break;
9407 
9408     case FK_PlainStringIntoUTF8Char:
9409       OS << "plain string literal into char8_t array";
9410       break;
9411 
9412     case FK_UTF8StringIntoPlainChar:
9413       OS << "u8 string literal into char array";
9414       break;
9415 
9416     case FK_ArrayTypeMismatch:
9417       OS << "array type mismatch";
9418       break;
9419 
9420     case FK_NonConstantArrayInit:
9421       OS << "non-constant array initializer";
9422       break;
9423 
9424     case FK_AddressOfOverloadFailed:
9425       OS << "address of overloaded function failed";
9426       break;
9427 
9428     case FK_ReferenceInitOverloadFailed:
9429       OS << "overload resolution for reference initialization failed";
9430       break;
9431 
9432     case FK_NonConstLValueReferenceBindingToTemporary:
9433       OS << "non-const lvalue reference bound to temporary";
9434       break;
9435 
9436     case FK_NonConstLValueReferenceBindingToBitfield:
9437       OS << "non-const lvalue reference bound to bit-field";
9438       break;
9439 
9440     case FK_NonConstLValueReferenceBindingToVectorElement:
9441       OS << "non-const lvalue reference bound to vector element";
9442       break;
9443 
9444     case FK_NonConstLValueReferenceBindingToMatrixElement:
9445       OS << "non-const lvalue reference bound to matrix element";
9446       break;
9447 
9448     case FK_NonConstLValueReferenceBindingToUnrelated:
9449       OS << "non-const lvalue reference bound to unrelated type";
9450       break;
9451 
9452     case FK_RValueReferenceBindingToLValue:
9453       OS << "rvalue reference bound to an lvalue";
9454       break;
9455 
9456     case FK_ReferenceInitDropsQualifiers:
9457       OS << "reference initialization drops qualifiers";
9458       break;
9459 
9460     case FK_ReferenceAddrspaceMismatchTemporary:
9461       OS << "reference with mismatching address space bound to temporary";
9462       break;
9463 
9464     case FK_ReferenceInitFailed:
9465       OS << "reference initialization failed";
9466       break;
9467 
9468     case FK_ConversionFailed:
9469       OS << "conversion failed";
9470       break;
9471 
9472     case FK_ConversionFromPropertyFailed:
9473       OS << "conversion from property failed";
9474       break;
9475 
9476     case FK_TooManyInitsForScalar:
9477       OS << "too many initializers for scalar";
9478       break;
9479 
9480     case FK_ParenthesizedListInitForScalar:
9481       OS << "parenthesized list init for reference";
9482       break;
9483 
9484     case FK_ReferenceBindingToInitList:
9485       OS << "referencing binding to initializer list";
9486       break;
9487 
9488     case FK_InitListBadDestinationType:
9489       OS << "initializer list for non-aggregate, non-scalar type";
9490       break;
9491 
9492     case FK_UserConversionOverloadFailed:
9493       OS << "overloading failed for user-defined conversion";
9494       break;
9495 
9496     case FK_ConstructorOverloadFailed:
9497       OS << "constructor overloading failed";
9498       break;
9499 
9500     case FK_DefaultInitOfConst:
9501       OS << "default initialization of a const variable";
9502       break;
9503 
9504     case FK_Incomplete:
9505       OS << "initialization of incomplete type";
9506       break;
9507 
9508     case FK_ListInitializationFailed:
9509       OS << "list initialization checker failure";
9510       break;
9511 
9512     case FK_VariableLengthArrayHasInitializer:
9513       OS << "variable length array has an initializer";
9514       break;
9515 
9516     case FK_PlaceholderType:
9517       OS << "initializer expression isn't contextually valid";
9518       break;
9519 
9520     case FK_ListConstructorOverloadFailed:
9521       OS << "list constructor overloading failed";
9522       break;
9523 
9524     case FK_ExplicitConstructor:
9525       OS << "list copy initialization chose explicit constructor";
9526       break;
9527 
9528     case FK_ParenthesizedListInitFailed:
9529       OS << "parenthesized list initialization failed";
9530       break;
9531 
9532     case FK_DesignatedInitForNonAggregate:
9533       OS << "designated initializer for non-aggregate type";
9534       break;
9535     }
9536     OS << '\n';
9537     return;
9538   }
9539 
9540   case DependentSequence:
9541     OS << "Dependent sequence\n";
9542     return;
9543 
9544   case NormalSequence:
9545     OS << "Normal sequence: ";
9546     break;
9547   }
9548 
9549   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9550     if (S != step_begin()) {
9551       OS << " -> ";
9552     }
9553 
9554     switch (S->Kind) {
9555     case SK_ResolveAddressOfOverloadedFunction:
9556       OS << "resolve address of overloaded function";
9557       break;
9558 
9559     case SK_CastDerivedToBasePRValue:
9560       OS << "derived-to-base (prvalue)";
9561       break;
9562 
9563     case SK_CastDerivedToBaseXValue:
9564       OS << "derived-to-base (xvalue)";
9565       break;
9566 
9567     case SK_CastDerivedToBaseLValue:
9568       OS << "derived-to-base (lvalue)";
9569       break;
9570 
9571     case SK_BindReference:
9572       OS << "bind reference to lvalue";
9573       break;
9574 
9575     case SK_BindReferenceToTemporary:
9576       OS << "bind reference to a temporary";
9577       break;
9578 
9579     case SK_FinalCopy:
9580       OS << "final copy in class direct-initialization";
9581       break;
9582 
9583     case SK_ExtraneousCopyToTemporary:
9584       OS << "extraneous C++03 copy to temporary";
9585       break;
9586 
9587     case SK_UserConversion:
9588       OS << "user-defined conversion via " << *S->Function.Function;
9589       break;
9590 
9591     case SK_QualificationConversionPRValue:
9592       OS << "qualification conversion (prvalue)";
9593       break;
9594 
9595     case SK_QualificationConversionXValue:
9596       OS << "qualification conversion (xvalue)";
9597       break;
9598 
9599     case SK_QualificationConversionLValue:
9600       OS << "qualification conversion (lvalue)";
9601       break;
9602 
9603     case SK_FunctionReferenceConversion:
9604       OS << "function reference conversion";
9605       break;
9606 
9607     case SK_AtomicConversion:
9608       OS << "non-atomic-to-atomic conversion";
9609       break;
9610 
9611     case SK_ConversionSequence:
9612       OS << "implicit conversion sequence (";
9613       S->ICS->dump(); // FIXME: use OS
9614       OS << ")";
9615       break;
9616 
9617     case SK_ConversionSequenceNoNarrowing:
9618       OS << "implicit conversion sequence with narrowing prohibited (";
9619       S->ICS->dump(); // FIXME: use OS
9620       OS << ")";
9621       break;
9622 
9623     case SK_ListInitialization:
9624       OS << "list aggregate initialization";
9625       break;
9626 
9627     case SK_UnwrapInitList:
9628       OS << "unwrap reference initializer list";
9629       break;
9630 
9631     case SK_RewrapInitList:
9632       OS << "rewrap reference initializer list";
9633       break;
9634 
9635     case SK_ConstructorInitialization:
9636       OS << "constructor initialization";
9637       break;
9638 
9639     case SK_ConstructorInitializationFromList:
9640       OS << "list initialization via constructor";
9641       break;
9642 
9643     case SK_ZeroInitialization:
9644       OS << "zero initialization";
9645       break;
9646 
9647     case SK_CAssignment:
9648       OS << "C assignment";
9649       break;
9650 
9651     case SK_StringInit:
9652       OS << "string initialization";
9653       break;
9654 
9655     case SK_ObjCObjectConversion:
9656       OS << "Objective-C object conversion";
9657       break;
9658 
9659     case SK_ArrayLoopIndex:
9660       OS << "indexing for array initialization loop";
9661       break;
9662 
9663     case SK_ArrayLoopInit:
9664       OS << "array initialization loop";
9665       break;
9666 
9667     case SK_ArrayInit:
9668       OS << "array initialization";
9669       break;
9670 
9671     case SK_GNUArrayInit:
9672       OS << "array initialization (GNU extension)";
9673       break;
9674 
9675     case SK_ParenthesizedArrayInit:
9676       OS << "parenthesized array initialization";
9677       break;
9678 
9679     case SK_PassByIndirectCopyRestore:
9680       OS << "pass by indirect copy and restore";
9681       break;
9682 
9683     case SK_PassByIndirectRestore:
9684       OS << "pass by indirect restore";
9685       break;
9686 
9687     case SK_ProduceObjCObject:
9688       OS << "Objective-C object retension";
9689       break;
9690 
9691     case SK_StdInitializerList:
9692       OS << "std::initializer_list from initializer list";
9693       break;
9694 
9695     case SK_StdInitializerListConstructorCall:
9696       OS << "list initialization from std::initializer_list";
9697       break;
9698 
9699     case SK_OCLSamplerInit:
9700       OS << "OpenCL sampler_t from integer constant";
9701       break;
9702 
9703     case SK_OCLZeroOpaqueType:
9704       OS << "OpenCL opaque type from zero";
9705       break;
9706     case SK_ParenthesizedListInit:
9707       OS << "initialization from a parenthesized list of values";
9708       break;
9709     }
9710 
9711     OS << " [" << S->Type << ']';
9712   }
9713 
9714   OS << '\n';
9715 }
9716 
dump() const9717 void InitializationSequence::dump() const {
9718   dump(llvm::errs());
9719 }
9720 
DiagnoseNarrowingInInitList(Sema & S,const ImplicitConversionSequence & ICS,QualType PreNarrowingType,QualType EntityType,const Expr * PostInit)9721 static void DiagnoseNarrowingInInitList(Sema &S,
9722                                         const ImplicitConversionSequence &ICS,
9723                                         QualType PreNarrowingType,
9724                                         QualType EntityType,
9725                                         const Expr *PostInit) {
9726   const StandardConversionSequence *SCS = nullptr;
9727   switch (ICS.getKind()) {
9728   case ImplicitConversionSequence::StandardConversion:
9729     SCS = &ICS.Standard;
9730     break;
9731   case ImplicitConversionSequence::UserDefinedConversion:
9732     SCS = &ICS.UserDefined.After;
9733     break;
9734   case ImplicitConversionSequence::AmbiguousConversion:
9735   case ImplicitConversionSequence::StaticObjectArgumentConversion:
9736   case ImplicitConversionSequence::EllipsisConversion:
9737   case ImplicitConversionSequence::BadConversion:
9738     return;
9739   }
9740 
9741   auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9742                       unsigned ConstRefDiagID, unsigned WarnDiagID) {
9743     unsigned DiagID;
9744     auto &L = S.getLangOpts();
9745     if (L.CPlusPlus11 && !L.HLSL &&
9746         (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9747       DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9748     else
9749       DiagID = WarnDiagID;
9750     return S.Diag(PostInit->getBeginLoc(), DiagID)
9751            << PostInit->getSourceRange();
9752   };
9753 
9754   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9755   APValue ConstantValue;
9756   QualType ConstantType;
9757   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9758                                 ConstantType)) {
9759   case NK_Not_Narrowing:
9760   case NK_Dependent_Narrowing:
9761     // No narrowing occurred.
9762     return;
9763 
9764   case NK_Type_Narrowing: {
9765     // This was a floating-to-integer conversion, which is always considered a
9766     // narrowing conversion even if the value is a constant and can be
9767     // represented exactly as an integer.
9768     QualType T = EntityType.getNonReferenceType();
9769     MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9770              diag::ext_init_list_type_narrowing_const_reference,
9771              diag::warn_init_list_type_narrowing)
9772         << PreNarrowingType.getLocalUnqualifiedType()
9773         << T.getLocalUnqualifiedType();
9774     break;
9775   }
9776 
9777   case NK_Constant_Narrowing: {
9778     // A constant value was narrowed.
9779     MakeDiag(EntityType.getNonReferenceType() != EntityType,
9780              diag::ext_init_list_constant_narrowing,
9781              diag::ext_init_list_constant_narrowing_const_reference,
9782              diag::warn_init_list_constant_narrowing)
9783         << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9784         << EntityType.getNonReferenceType().getLocalUnqualifiedType();
9785     break;
9786   }
9787 
9788   case NK_Variable_Narrowing: {
9789     // A variable's value may have been narrowed.
9790     MakeDiag(EntityType.getNonReferenceType() != EntityType,
9791              diag::ext_init_list_variable_narrowing,
9792              diag::ext_init_list_variable_narrowing_const_reference,
9793              diag::warn_init_list_variable_narrowing)
9794         << PreNarrowingType.getLocalUnqualifiedType()
9795         << EntityType.getNonReferenceType().getLocalUnqualifiedType();
9796     break;
9797   }
9798   }
9799 
9800   SmallString<128> StaticCast;
9801   llvm::raw_svector_ostream OS(StaticCast);
9802   OS << "static_cast<";
9803   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9804     // It's important to use the typedef's name if there is one so that the
9805     // fixit doesn't break code using types like int64_t.
9806     //
9807     // FIXME: This will break if the typedef requires qualification.  But
9808     // getQualifiedNameAsString() includes non-machine-parsable components.
9809     OS << *TT->getDecl();
9810   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9811     OS << BT->getName(S.getLangOpts());
9812   else {
9813     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
9814     // with a broken cast.
9815     return;
9816   }
9817   OS << ">(";
9818   S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9819       << PostInit->getSourceRange()
9820       << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9821       << FixItHint::CreateInsertion(
9822              S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9823 }
9824 
CheckC23ConstexprInitConversion(Sema & S,QualType FromType,QualType ToType,Expr * Init)9825 static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
9826                                             QualType ToType, Expr *Init) {
9827   assert(S.getLangOpts().C23);
9828   ImplicitConversionSequence ICS = S.TryImplicitConversion(
9829       Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
9830       Sema::AllowedExplicit::None,
9831       /*InOverloadResolution*/ false,
9832       /*CStyle*/ false,
9833       /*AllowObjCWritebackConversion=*/false);
9834 
9835   if (!ICS.isStandard())
9836     return;
9837 
9838   APValue Value;
9839   QualType PreNarrowingType;
9840   // Reuse C++ narrowing check.
9841   switch (ICS.Standard.getNarrowingKind(
9842       S.Context, Init, Value, PreNarrowingType,
9843       /*IgnoreFloatToIntegralConversion*/ false)) {
9844   // The value doesn't fit.
9845   case NK_Constant_Narrowing:
9846     S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
9847         << Value.getAsString(S.Context, PreNarrowingType) << ToType;
9848     return;
9849 
9850   // Conversion to a narrower type.
9851   case NK_Type_Narrowing:
9852     S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
9853         << ToType << FromType;
9854     return;
9855 
9856   // Since we only reuse narrowing check for C23 constexpr variables here, we're
9857   // not really interested in these cases.
9858   case NK_Dependent_Narrowing:
9859   case NK_Variable_Narrowing:
9860   case NK_Not_Narrowing:
9861     return;
9862   }
9863   llvm_unreachable("unhandled case in switch");
9864 }
9865 
CheckC23ConstexprInitStringLiteral(const StringLiteral * SE,Sema & SemaRef,QualType & TT)9866 static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
9867                                                Sema &SemaRef, QualType &TT) {
9868   assert(SemaRef.getLangOpts().C23);
9869   // character that string literal contains fits into TT - target type.
9870   const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
9871   QualType CharType = AT->getElementType();
9872   uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
9873   bool isUnsigned = CharType->isUnsignedIntegerType();
9874   llvm::APSInt Value(BitWidth, isUnsigned);
9875   for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
9876     int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
9877     Value = C;
9878     if (Value != C) {
9879       SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
9880                    diag::err_c23_constexpr_init_not_representable)
9881           << C << CharType;
9882       return;
9883     }
9884   }
9885 }
9886 
9887 //===----------------------------------------------------------------------===//
9888 // Initialization helper functions
9889 //===----------------------------------------------------------------------===//
9890 bool
CanPerformCopyInitialization(const InitializedEntity & Entity,ExprResult Init)9891 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9892                                    ExprResult Init) {
9893   if (Init.isInvalid())
9894     return false;
9895 
9896   Expr *InitE = Init.get();
9897   assert(InitE && "No initialization expression");
9898 
9899   InitializationKind Kind =
9900       InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
9901   InitializationSequence Seq(*this, Entity, Kind, InitE);
9902   return !Seq.Failed();
9903 }
9904 
9905 ExprResult
PerformCopyInitialization(const InitializedEntity & Entity,SourceLocation EqualLoc,ExprResult Init,bool TopLevelOfInitList,bool AllowExplicit)9906 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9907                                 SourceLocation EqualLoc,
9908                                 ExprResult Init,
9909                                 bool TopLevelOfInitList,
9910                                 bool AllowExplicit) {
9911   if (Init.isInvalid())
9912     return ExprError();
9913 
9914   Expr *InitE = Init.get();
9915   assert(InitE && "No initialization expression?");
9916 
9917   if (EqualLoc.isInvalid())
9918     EqualLoc = InitE->getBeginLoc();
9919 
9920   InitializationKind Kind = InitializationKind::CreateCopy(
9921       InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9922   InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
9923 
9924   // Prevent infinite recursion when performing parameter copy-initialization.
9925   const bool ShouldTrackCopy =
9926       Entity.isParameterKind() && Seq.isConstructorInitialization();
9927   if (ShouldTrackCopy) {
9928     if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
9929       Seq.SetOverloadFailure(
9930           InitializationSequence::FK_ConstructorOverloadFailed,
9931           OR_No_Viable_Function);
9932 
9933       // Try to give a meaningful diagnostic note for the problematic
9934       // constructor.
9935       const auto LastStep = Seq.step_end() - 1;
9936       assert(LastStep->Kind ==
9937              InitializationSequence::SK_ConstructorInitialization);
9938       const FunctionDecl *Function = LastStep->Function.Function;
9939       auto Candidate =
9940           llvm::find_if(Seq.getFailedCandidateSet(),
9941                         [Function](const OverloadCandidate &Candidate) -> bool {
9942                           return Candidate.Viable &&
9943                                  Candidate.Function == Function &&
9944                                  Candidate.Conversions.size() > 0;
9945                         });
9946       if (Candidate != Seq.getFailedCandidateSet().end() &&
9947           Function->getNumParams() > 0) {
9948         Candidate->Viable = false;
9949         Candidate->FailureKind = ovl_fail_bad_conversion;
9950         Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9951                                          InitE,
9952                                          Function->getParamDecl(0)->getType());
9953       }
9954     }
9955     CurrentParameterCopyTypes.push_back(Entity.getType());
9956   }
9957 
9958   ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
9959 
9960   if (ShouldTrackCopy)
9961     CurrentParameterCopyTypes.pop_back();
9962 
9963   return Result;
9964 }
9965 
9966 /// Determine whether RD is, or is derived from, a specialization of CTD.
isOrIsDerivedFromSpecializationOf(CXXRecordDecl * RD,ClassTemplateDecl * CTD)9967 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9968                                               ClassTemplateDecl *CTD) {
9969   auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9970     auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9971     return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9972   };
9973   return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9974 }
9975 
DeduceTemplateSpecializationFromInitializer(TypeSourceInfo * TSInfo,const InitializedEntity & Entity,const InitializationKind & Kind,MultiExprArg Inits)9976 QualType Sema::DeduceTemplateSpecializationFromInitializer(
9977     TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9978     const InitializationKind &Kind, MultiExprArg Inits) {
9979   auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9980       TSInfo->getType()->getContainedDeducedType());
9981   assert(DeducedTST && "not a deduced template specialization type");
9982 
9983   auto TemplateName = DeducedTST->getTemplateName();
9984   if (TemplateName.isDependent())
9985     return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
9986 
9987   // We can only perform deduction for class templates or alias templates.
9988   auto *Template =
9989       dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9990   TemplateDecl *LookupTemplateDecl = Template;
9991   if (!Template) {
9992     if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
9993             TemplateName.getAsTemplateDecl())) {
9994       DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
9995       LookupTemplateDecl = AliasTemplate;
9996       auto UnderlyingType = AliasTemplate->getTemplatedDecl()
9997                                 ->getUnderlyingType()
9998                                 .getCanonicalType();
9999       // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10000       // of the form
10001       //   [typename] [nested-name-specifier] [template] simple-template-id
10002       if (const auto *TST =
10003               UnderlyingType->getAs<TemplateSpecializationType>()) {
10004         Template = dyn_cast_or_null<ClassTemplateDecl>(
10005             TST->getTemplateName().getAsTemplateDecl());
10006       } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10007         // Cases where template arguments in the RHS of the alias are not
10008         // dependent. e.g.
10009         //   using AliasFoo = Foo<bool>;
10010         if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
10011                 RT->getAsCXXRecordDecl()))
10012           Template = CTSD->getSpecializedTemplate();
10013       }
10014     }
10015   }
10016   if (!Template) {
10017     Diag(Kind.getLocation(),
10018          diag::err_deduced_non_class_or_alias_template_specialization_type)
10019         << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10020     if (auto *TD = TemplateName.getAsTemplateDecl())
10021       NoteTemplateLocation(*TD);
10022     return QualType();
10023   }
10024 
10025   // Can't deduce from dependent arguments.
10026   if (Expr::hasAnyTypeDependentArguments(Inits)) {
10027     Diag(TSInfo->getTypeLoc().getBeginLoc(),
10028          diag::warn_cxx14_compat_class_template_argument_deduction)
10029         << TSInfo->getTypeLoc().getSourceRange() << 0;
10030     return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10031   }
10032 
10033   // FIXME: Perform "exact type" matching first, per CWG discussion?
10034   //        Or implement this via an implied 'T(T) -> T' deduction guide?
10035 
10036   // Look up deduction guides, including those synthesized from constructors.
10037   //
10038   // C++1z [over.match.class.deduct]p1:
10039   //   A set of functions and function templates is formed comprising:
10040   //   - For each constructor of the class template designated by the
10041   //     template-name, a function template [...]
10042   //  - For each deduction-guide, a function or function template [...]
10043   DeclarationNameInfo NameInfo(
10044       Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10045       TSInfo->getTypeLoc().getEndLoc());
10046   LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10047   LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10048 
10049   // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10050   // clear on this, but they're not found by name so access does not apply.
10051   Guides.suppressDiagnostics();
10052 
10053   // Figure out if this is list-initialization.
10054   InitListExpr *ListInit =
10055       (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10056           ? dyn_cast<InitListExpr>(Inits[0])
10057           : nullptr;
10058 
10059   // C++1z [over.match.class.deduct]p1:
10060   //   Initialization and overload resolution are performed as described in
10061   //   [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10062   //   (as appropriate for the type of initialization performed) for an object
10063   //   of a hypothetical class type, where the selected functions and function
10064   //   templates are considered to be the constructors of that class type
10065   //
10066   // Since we know we're initializing a class type of a type unrelated to that
10067   // of the initializer, this reduces to something fairly reasonable.
10068   OverloadCandidateSet Candidates(Kind.getLocation(),
10069                                   OverloadCandidateSet::CSK_Normal);
10070   OverloadCandidateSet::iterator Best;
10071 
10072   bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10073 
10074   // Return true if the candidate is added successfully, false otherwise.
10075   auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10076                                    CXXDeductionGuideDecl *GD,
10077                                    DeclAccessPair FoundDecl,
10078                                    bool OnlyListConstructors,
10079                                    bool AllowAggregateDeductionCandidate) {
10080     // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10081     //   For copy-initialization, the candidate functions are all the
10082     //   converting constructors (12.3.1) of that class.
10083     // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10084     //   The converting constructors of T are candidate functions.
10085     if (!AllowExplicit) {
10086       // Overload resolution checks whether the deduction guide is declared
10087       // explicit for us.
10088 
10089       // When looking for a converting constructor, deduction guides that
10090       // could never be called with one argument are not interesting to
10091       // check or note.
10092       if (GD->getMinRequiredArguments() > 1 ||
10093           (GD->getNumParams() == 0 && !GD->isVariadic()))
10094         return;
10095     }
10096 
10097     // C++ [over.match.list]p1.1: (first phase list initialization)
10098     //   Initially, the candidate functions are the initializer-list
10099     //   constructors of the class T
10100     if (OnlyListConstructors && !isInitListConstructor(GD))
10101       return;
10102 
10103     if (!AllowAggregateDeductionCandidate &&
10104         GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10105       return;
10106 
10107     // C++ [over.match.list]p1.2: (second phase list initialization)
10108     //   the candidate functions are all the constructors of the class T
10109     // C++ [over.match.ctor]p1: (all other cases)
10110     //   the candidate functions are all the constructors of the class of
10111     //   the object being initialized
10112 
10113     // C++ [over.best.ics]p4:
10114     //   When [...] the constructor [...] is a candidate by
10115     //    - [over.match.copy] (in all cases)
10116     if (TD) {
10117 
10118       // As template candidates are not deduced immediately,
10119       // persist the array in the overload set.
10120       MutableArrayRef<Expr *> TmpInits =
10121           Candidates.getPersistentArgsArray(Inits.size());
10122 
10123       for (auto [I, E] : llvm::enumerate(Inits)) {
10124         if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10125           TmpInits[I] = DI->getInit();
10126         else
10127           TmpInits[I] = E;
10128       }
10129 
10130       AddTemplateOverloadCandidate(
10131           TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10132           /*SuppressUserConversions=*/false,
10133           /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10134           /*PO=*/{}, AllowAggregateDeductionCandidate);
10135     } else {
10136       AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10137                            /*SuppressUserConversions=*/false,
10138                            /*PartialOverloading=*/false, AllowExplicit);
10139     }
10140   };
10141 
10142   bool FoundDeductionGuide = false;
10143 
10144   auto TryToResolveOverload =
10145       [&](bool OnlyListConstructors) -> OverloadingResult {
10146     Candidates.clear(OverloadCandidateSet::CSK_Normal);
10147     bool HasAnyDeductionGuide = false;
10148 
10149     auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10150       auto *Pattern = Template;
10151       while (Pattern->getInstantiatedFromMemberTemplate()) {
10152         if (Pattern->isMemberSpecialization())
10153           break;
10154         Pattern = Pattern->getInstantiatedFromMemberTemplate();
10155       }
10156 
10157       auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10158       if (!(RD->getDefinition() && RD->isAggregate()))
10159         return;
10160       QualType Ty = Context.getRecordType(RD);
10161       SmallVector<QualType, 8> ElementTypes;
10162 
10163       InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10164       if (!CheckInitList.HadError()) {
10165         // C++ [over.match.class.deduct]p1.8:
10166         //   if e_i is of array type and x_i is a braced-init-list, T_i is an
10167         //   rvalue reference to the declared type of e_i and
10168         // C++ [over.match.class.deduct]p1.9:
10169         //   if e_i is of array type and x_i is a string-literal, T_i is an
10170         //   lvalue reference to the const-qualified declared type of e_i and
10171         // C++ [over.match.class.deduct]p1.10:
10172         //   otherwise, T_i is the declared type of e_i
10173         for (int I = 0, E = ListInit->getNumInits();
10174              I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10175           if (ElementTypes[I]->isArrayType()) {
10176             if (isa<InitListExpr, DesignatedInitExpr>(ListInit->getInit(I)))
10177               ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10178             else if (isa<StringLiteral>(
10179                          ListInit->getInit(I)->IgnoreParenImpCasts()))
10180               ElementTypes[I] =
10181                   Context.getLValueReferenceType(ElementTypes[I].withConst());
10182           }
10183 
10184         if (FunctionTemplateDecl *TD =
10185                 DeclareAggregateDeductionGuideFromInitList(
10186                     LookupTemplateDecl, ElementTypes,
10187                     TSInfo->getTypeLoc().getEndLoc())) {
10188           auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10189           addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10190                                 OnlyListConstructors,
10191                                 /*AllowAggregateDeductionCandidate=*/true);
10192           HasAnyDeductionGuide = true;
10193         }
10194       }
10195     };
10196 
10197     for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10198       NamedDecl *D = (*I)->getUnderlyingDecl();
10199       if (D->isInvalidDecl())
10200         continue;
10201 
10202       auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10203       auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10204           TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10205       if (!GD)
10206         continue;
10207 
10208       if (!GD->isImplicit())
10209         HasAnyDeductionGuide = true;
10210 
10211       addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10212                             /*AllowAggregateDeductionCandidate=*/false);
10213     }
10214 
10215     // C++ [over.match.class.deduct]p1.4:
10216     //   if C is defined and its definition satisfies the conditions for an
10217     //   aggregate class ([dcl.init.aggr]) with the assumption that any
10218     //   dependent base class has no virtual functions and no virtual base
10219     //   classes, and the initializer is a non-empty braced-init-list or
10220     //   parenthesized expression-list, and there are no deduction-guides for
10221     //   C, the set contains an additional function template, called the
10222     //   aggregate deduction candidate, defined as follows.
10223     if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10224       if (ListInit && ListInit->getNumInits()) {
10225         SynthesizeAggrGuide(ListInit);
10226       } else if (Inits.size()) { // parenthesized expression-list
10227         // Inits are expressions inside the parentheses. We don't have
10228         // the parentheses source locations, use the begin/end of Inits as the
10229         // best heuristic.
10230         InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10231                                   Inits, Inits.back()->getEndLoc());
10232         SynthesizeAggrGuide(&TempListInit);
10233       }
10234     }
10235 
10236     FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10237 
10238     return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10239   };
10240 
10241   OverloadingResult Result = OR_No_Viable_Function;
10242 
10243   // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10244   // try initializer-list constructors.
10245   if (ListInit) {
10246     bool TryListConstructors = true;
10247 
10248     // Try list constructors unless the list is empty and the class has one or
10249     // more default constructors, in which case those constructors win.
10250     if (!ListInit->getNumInits()) {
10251       for (NamedDecl *D : Guides) {
10252         auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10253         if (FD && FD->getMinRequiredArguments() == 0) {
10254           TryListConstructors = false;
10255           break;
10256         }
10257       }
10258     } else if (ListInit->getNumInits() == 1) {
10259       // C++ [over.match.class.deduct]:
10260       //   As an exception, the first phase in [over.match.list] (considering
10261       //   initializer-list constructors) is omitted if the initializer list
10262       //   consists of a single expression of type cv U, where U is a
10263       //   specialization of C or a class derived from a specialization of C.
10264       Expr *E = ListInit->getInit(0);
10265       auto *RD = E->getType()->getAsCXXRecordDecl();
10266       if (!isa<InitListExpr>(E) && RD &&
10267           isCompleteType(Kind.getLocation(), E->getType()) &&
10268           isOrIsDerivedFromSpecializationOf(RD, Template))
10269         TryListConstructors = false;
10270     }
10271 
10272     if (TryListConstructors)
10273       Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10274     // Then unwrap the initializer list and try again considering all
10275     // constructors.
10276     Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10277   }
10278 
10279   // If list-initialization fails, or if we're doing any other kind of
10280   // initialization, we (eventually) consider constructors.
10281   if (Result == OR_No_Viable_Function)
10282     Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10283 
10284   switch (Result) {
10285   case OR_Ambiguous:
10286     // FIXME: For list-initialization candidates, it'd usually be better to
10287     // list why they were not viable when given the initializer list itself as
10288     // an argument.
10289     Candidates.NoteCandidates(
10290         PartialDiagnosticAt(
10291             Kind.getLocation(),
10292             PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10293                 << TemplateName),
10294         *this, OCD_AmbiguousCandidates, Inits);
10295     return QualType();
10296 
10297   case OR_No_Viable_Function: {
10298     CXXRecordDecl *Primary =
10299         cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10300     bool Complete =
10301         isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10302     Candidates.NoteCandidates(
10303         PartialDiagnosticAt(
10304             Kind.getLocation(),
10305             PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10306                            : diag::err_deduced_class_template_incomplete)
10307                 << TemplateName << !Guides.empty()),
10308         *this, OCD_AllCandidates, Inits);
10309     return QualType();
10310   }
10311 
10312   case OR_Deleted: {
10313     // FIXME: There are no tests for this diagnostic, and it doesn't seem
10314     // like we ever get here; attempts to trigger this seem to yield a
10315     // generic c'all to deleted function' diagnostic instead.
10316     Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10317       << TemplateName;
10318     NoteDeletedFunction(Best->Function);
10319     return QualType();
10320   }
10321 
10322   case OR_Success:
10323     // C++ [over.match.list]p1:
10324     //   In copy-list-initialization, if an explicit constructor is chosen, the
10325     //   initialization is ill-formed.
10326     if (Kind.isCopyInit() && ListInit &&
10327         cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10328       bool IsDeductionGuide = !Best->Function->isImplicit();
10329       Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10330           << TemplateName << IsDeductionGuide;
10331       Diag(Best->Function->getLocation(),
10332            diag::note_explicit_ctor_deduction_guide_here)
10333           << IsDeductionGuide;
10334       return QualType();
10335     }
10336 
10337     // Make sure we didn't select an unusable deduction guide, and mark it
10338     // as referenced.
10339     DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10340     MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10341     break;
10342   }
10343 
10344   // C++ [dcl.type.class.deduct]p1:
10345   //  The placeholder is replaced by the return type of the function selected
10346   //  by overload resolution for class template deduction.
10347   QualType DeducedType =
10348       SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10349           ->getType();
10350   Diag(TSInfo->getTypeLoc().getBeginLoc(),
10351        diag::warn_cxx14_compat_class_template_argument_deduction)
10352       << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10353 
10354   // Warn if CTAD was used on a type that does not have any user-defined
10355   // deduction guides.
10356   if (!FoundDeductionGuide) {
10357     Diag(TSInfo->getTypeLoc().getBeginLoc(),
10358          diag::warn_ctad_maybe_unsupported)
10359         << TemplateName;
10360     Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10361   }
10362 
10363   return DeducedType;
10364 }
10365