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