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