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