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