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