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