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