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