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