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