xref: /freebsd-src/contrib/llvm-project/clang/lib/Sema/SemaInit.cpp (revision 647cbc5de815c5651677bf8582797f716ec7b48d)
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   }
7594   for (unsigned I = 0,
7595                 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7596        I != N; ++I) {
7597     if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7598       VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7599   }
7600 }
7601 
7602 /// Visit the locals that would be reachable through a reference bound to the
7603 /// glvalue expression \c Init.
7604 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7605                                                   Expr *Init, ReferenceKind RK,
7606                                                   LocalVisitor Visit,
7607                                                   bool EnableLifetimeWarnings) {
7608   RevertToOldSizeRAII RAII(Path);
7609 
7610   // Walk past any constructs which we can lifetime-extend across.
7611   Expr *Old;
7612   do {
7613     Old = Init;
7614 
7615     if (auto *FE = dyn_cast<FullExpr>(Init))
7616       Init = FE->getSubExpr();
7617 
7618     if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7619       // If this is just redundant braces around an initializer, step over it.
7620       if (ILE->isTransparent())
7621         Init = ILE->getInit(0);
7622     }
7623 
7624     // Step over any subobject adjustments; we may have a materialized
7625     // temporary inside them.
7626     Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7627 
7628     // Per current approach for DR1376, look through casts to reference type
7629     // when performing lifetime extension.
7630     if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7631       if (CE->getSubExpr()->isGLValue())
7632         Init = CE->getSubExpr();
7633 
7634     // Per the current approach for DR1299, look through array element access
7635     // on array glvalues when performing lifetime extension.
7636     if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7637       Init = ASE->getBase();
7638       auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7639       if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7640         Init = ICE->getSubExpr();
7641       else
7642         // We can't lifetime extend through this but we might still find some
7643         // retained temporaries.
7644         return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7645                                                 EnableLifetimeWarnings);
7646     }
7647 
7648     // Step into CXXDefaultInitExprs so we can diagnose cases where a
7649     // constructor inherits one as an implicit mem-initializer.
7650     if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7651       Path.push_back(
7652           {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7653       Init = DIE->getExpr();
7654     }
7655   } while (Init != Old);
7656 
7657   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7658     if (Visit(Path, Local(MTE), RK))
7659       visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7660                                        EnableLifetimeWarnings);
7661   }
7662 
7663   if (isa<CallExpr>(Init)) {
7664     if (EnableLifetimeWarnings)
7665       handleGslAnnotatedTypes(Path, Init, Visit);
7666     return visitLifetimeBoundArguments(Path, Init, Visit);
7667   }
7668 
7669   switch (Init->getStmtClass()) {
7670   case Stmt::DeclRefExprClass: {
7671     // If we find the name of a local non-reference parameter, we could have a
7672     // lifetime problem.
7673     auto *DRE = cast<DeclRefExpr>(Init);
7674     auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7675     if (VD && VD->hasLocalStorage() &&
7676         !DRE->refersToEnclosingVariableOrCapture()) {
7677       if (!VD->getType()->isReferenceType()) {
7678         Visit(Path, Local(DRE), RK);
7679       } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7680         // The lifetime of a reference parameter is unknown; assume it's OK
7681         // for now.
7682         break;
7683       } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7684         Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7685         visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7686                                               RK_ReferenceBinding, Visit,
7687                                               EnableLifetimeWarnings);
7688       }
7689     }
7690     break;
7691   }
7692 
7693   case Stmt::UnaryOperatorClass: {
7694     // The only unary operator that make sense to handle here
7695     // is Deref.  All others don't resolve to a "name."  This includes
7696     // handling all sorts of rvalues passed to a unary operator.
7697     const UnaryOperator *U = cast<UnaryOperator>(Init);
7698     if (U->getOpcode() == UO_Deref)
7699       visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7700                                        EnableLifetimeWarnings);
7701     break;
7702   }
7703 
7704   case Stmt::OMPArraySectionExprClass: {
7705     visitLocalsRetainedByInitializer(Path,
7706                                      cast<OMPArraySectionExpr>(Init)->getBase(),
7707                                      Visit, true, EnableLifetimeWarnings);
7708     break;
7709   }
7710 
7711   case Stmt::ConditionalOperatorClass:
7712   case Stmt::BinaryConditionalOperatorClass: {
7713     auto *C = cast<AbstractConditionalOperator>(Init);
7714     if (!C->getTrueExpr()->getType()->isVoidType())
7715       visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7716                                             EnableLifetimeWarnings);
7717     if (!C->getFalseExpr()->getType()->isVoidType())
7718       visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7719                                             EnableLifetimeWarnings);
7720     break;
7721   }
7722 
7723   // FIXME: Visit the left-hand side of an -> or ->*.
7724 
7725   default:
7726     break;
7727   }
7728 }
7729 
7730 /// Visit the locals that would be reachable through an object initialized by
7731 /// the prvalue expression \c Init.
7732 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7733                                              Expr *Init, LocalVisitor Visit,
7734                                              bool RevisitSubinits,
7735                                              bool EnableLifetimeWarnings) {
7736   RevertToOldSizeRAII RAII(Path);
7737 
7738   Expr *Old;
7739   do {
7740     Old = Init;
7741 
7742     // Step into CXXDefaultInitExprs so we can diagnose cases where a
7743     // constructor inherits one as an implicit mem-initializer.
7744     if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7745       Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7746       Init = DIE->getExpr();
7747     }
7748 
7749     if (auto *FE = dyn_cast<FullExpr>(Init))
7750       Init = FE->getSubExpr();
7751 
7752     // Dig out the expression which constructs the extended temporary.
7753     Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7754 
7755     if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7756       Init = BTE->getSubExpr();
7757 
7758     Init = Init->IgnoreParens();
7759 
7760     // Step over value-preserving rvalue casts.
7761     if (auto *CE = dyn_cast<CastExpr>(Init)) {
7762       switch (CE->getCastKind()) {
7763       case CK_LValueToRValue:
7764         // If we can match the lvalue to a const object, we can look at its
7765         // initializer.
7766         Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7767         return visitLocalsRetainedByReferenceBinding(
7768             Path, Init, RK_ReferenceBinding,
7769             [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7770           if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7771             auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7772             if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7773                 !isVarOnPath(Path, VD)) {
7774               Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7775               visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7776                                                EnableLifetimeWarnings);
7777             }
7778           } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7779             if (MTE->getType().isConstQualified())
7780               visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7781                                                true, EnableLifetimeWarnings);
7782           }
7783           return false;
7784         }, EnableLifetimeWarnings);
7785 
7786         // We assume that objects can be retained by pointers cast to integers,
7787         // but not if the integer is cast to floating-point type or to _Complex.
7788         // We assume that casts to 'bool' do not preserve enough information to
7789         // retain a local object.
7790       case CK_NoOp:
7791       case CK_BitCast:
7792       case CK_BaseToDerived:
7793       case CK_DerivedToBase:
7794       case CK_UncheckedDerivedToBase:
7795       case CK_Dynamic:
7796       case CK_ToUnion:
7797       case CK_UserDefinedConversion:
7798       case CK_ConstructorConversion:
7799       case CK_IntegralToPointer:
7800       case CK_PointerToIntegral:
7801       case CK_VectorSplat:
7802       case CK_IntegralCast:
7803       case CK_CPointerToObjCPointerCast:
7804       case CK_BlockPointerToObjCPointerCast:
7805       case CK_AnyPointerToBlockPointerCast:
7806       case CK_AddressSpaceConversion:
7807         break;
7808 
7809       case CK_ArrayToPointerDecay:
7810         // Model array-to-pointer decay as taking the address of the array
7811         // lvalue.
7812         Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7813         return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7814                                                      RK_ReferenceBinding, Visit,
7815                                                      EnableLifetimeWarnings);
7816 
7817       default:
7818         return;
7819       }
7820 
7821       Init = CE->getSubExpr();
7822     }
7823   } while (Old != Init);
7824 
7825   // C++17 [dcl.init.list]p6:
7826   //   initializing an initializer_list object from the array extends the
7827   //   lifetime of the array exactly like binding a reference to a temporary.
7828   if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7829     return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7830                                                  RK_StdInitializerList, Visit,
7831                                                  EnableLifetimeWarnings);
7832 
7833   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7834     // We already visited the elements of this initializer list while
7835     // performing the initialization. Don't visit them again unless we've
7836     // changed the lifetime of the initialized entity.
7837     if (!RevisitSubinits)
7838       return;
7839 
7840     if (ILE->isTransparent())
7841       return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7842                                               RevisitSubinits,
7843                                               EnableLifetimeWarnings);
7844 
7845     if (ILE->getType()->isArrayType()) {
7846       for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7847         visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7848                                          RevisitSubinits,
7849                                          EnableLifetimeWarnings);
7850       return;
7851     }
7852 
7853     if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7854       assert(RD->isAggregate() && "aggregate init on non-aggregate");
7855 
7856       // If we lifetime-extend a braced initializer which is initializing an
7857       // aggregate, and that aggregate contains reference members which are
7858       // bound to temporaries, those temporaries are also lifetime-extended.
7859       if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7860           ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
7861         visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
7862                                               RK_ReferenceBinding, Visit,
7863                                               EnableLifetimeWarnings);
7864       else {
7865         unsigned Index = 0;
7866         for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7867           visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7868                                            RevisitSubinits,
7869                                            EnableLifetimeWarnings);
7870         for (const auto *I : RD->fields()) {
7871           if (Index >= ILE->getNumInits())
7872             break;
7873           if (I->isUnnamedBitfield())
7874             continue;
7875           Expr *SubInit = ILE->getInit(Index);
7876           if (I->getType()->isReferenceType())
7877             visitLocalsRetainedByReferenceBinding(Path, SubInit,
7878                                                   RK_ReferenceBinding, Visit,
7879                                                   EnableLifetimeWarnings);
7880           else
7881             // This might be either aggregate-initialization of a member or
7882             // initialization of a std::initializer_list object. Regardless,
7883             // we should recursively lifetime-extend that initializer.
7884             visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7885                                              RevisitSubinits,
7886                                              EnableLifetimeWarnings);
7887           ++Index;
7888         }
7889       }
7890     }
7891     return;
7892   }
7893 
7894   // The lifetime of an init-capture is that of the closure object constructed
7895   // by a lambda-expression.
7896   if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7897     LambdaExpr::capture_iterator CapI = LE->capture_begin();
7898     for (Expr *E : LE->capture_inits()) {
7899       assert(CapI != LE->capture_end());
7900       const LambdaCapture &Cap = *CapI++;
7901       if (!E)
7902         continue;
7903       if (Cap.capturesVariable())
7904         Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7905       if (E->isGLValue())
7906         visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7907                                               Visit, EnableLifetimeWarnings);
7908       else
7909         visitLocalsRetainedByInitializer(Path, E, Visit, true,
7910                                          EnableLifetimeWarnings);
7911       if (Cap.capturesVariable())
7912         Path.pop_back();
7913     }
7914   }
7915 
7916   // Assume that a copy or move from a temporary references the same objects
7917   // that the temporary does.
7918   if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7919     if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7920       if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7921         Expr *Arg = MTE->getSubExpr();
7922         Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7923                         CCE->getConstructor()});
7924         visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7925                                          /*EnableLifetimeWarnings*/false);
7926         Path.pop_back();
7927       }
7928     }
7929   }
7930 
7931   if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7932     if (EnableLifetimeWarnings)
7933       handleGslAnnotatedTypes(Path, Init, Visit);
7934     return visitLifetimeBoundArguments(Path, Init, Visit);
7935   }
7936 
7937   switch (Init->getStmtClass()) {
7938   case Stmt::UnaryOperatorClass: {
7939     auto *UO = cast<UnaryOperator>(Init);
7940     // If the initializer is the address of a local, we could have a lifetime
7941     // problem.
7942     if (UO->getOpcode() == UO_AddrOf) {
7943       // If this is &rvalue, then it's ill-formed and we have already diagnosed
7944       // it. Don't produce a redundant warning about the lifetime of the
7945       // temporary.
7946       if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7947         return;
7948 
7949       Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7950       visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7951                                             RK_ReferenceBinding, Visit,
7952                                             EnableLifetimeWarnings);
7953     }
7954     break;
7955   }
7956 
7957   case Stmt::BinaryOperatorClass: {
7958     // Handle pointer arithmetic.
7959     auto *BO = cast<BinaryOperator>(Init);
7960     BinaryOperatorKind BOK = BO->getOpcode();
7961     if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7962       break;
7963 
7964     if (BO->getLHS()->getType()->isPointerType())
7965       visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
7966                                        EnableLifetimeWarnings);
7967     else if (BO->getRHS()->getType()->isPointerType())
7968       visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
7969                                        EnableLifetimeWarnings);
7970     break;
7971   }
7972 
7973   case Stmt::ConditionalOperatorClass:
7974   case Stmt::BinaryConditionalOperatorClass: {
7975     auto *C = cast<AbstractConditionalOperator>(Init);
7976     // In C++, we can have a throw-expression operand, which has 'void' type
7977     // and isn't interesting from a lifetime perspective.
7978     if (!C->getTrueExpr()->getType()->isVoidType())
7979       visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
7980                                        EnableLifetimeWarnings);
7981     if (!C->getFalseExpr()->getType()->isVoidType())
7982       visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
7983                                        EnableLifetimeWarnings);
7984     break;
7985   }
7986 
7987   case Stmt::BlockExprClass:
7988     if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7989       // This is a local block, whose lifetime is that of the function.
7990       Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7991     }
7992     break;
7993 
7994   case Stmt::AddrLabelExprClass:
7995     // We want to warn if the address of a label would escape the function.
7996     Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7997     break;
7998 
7999   default:
8000     break;
8001   }
8002 }
8003 
8004 /// Whether a path to an object supports lifetime extension.
8005 enum PathLifetimeKind {
8006   /// Lifetime-extend along this path.
8007   Extend,
8008   /// We should lifetime-extend, but we don't because (due to technical
8009   /// limitations) we can't. This happens for default member initializers,
8010   /// which we don't clone for every use, so we don't have a unique
8011   /// MaterializeTemporaryExpr to update.
8012   ShouldExtend,
8013   /// Do not lifetime extend along this path.
8014   NoExtend
8015 };
8016 
8017 /// Determine whether this is an indirect path to a temporary that we are
8018 /// supposed to lifetime-extend along.
8019 static PathLifetimeKind
8020 shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8021   PathLifetimeKind Kind = PathLifetimeKind::Extend;
8022   for (auto Elem : Path) {
8023     if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8024       Kind = PathLifetimeKind::ShouldExtend;
8025     else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8026       return PathLifetimeKind::NoExtend;
8027   }
8028   return Kind;
8029 }
8030 
8031 /// Find the range for the first interesting entry in the path at or after I.
8032 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8033                                       Expr *E) {
8034   for (unsigned N = Path.size(); I != N; ++I) {
8035     switch (Path[I].Kind) {
8036     case IndirectLocalPathEntry::AddressOf:
8037     case IndirectLocalPathEntry::LValToRVal:
8038     case IndirectLocalPathEntry::LifetimeBoundCall:
8039     case IndirectLocalPathEntry::TemporaryCopy:
8040     case IndirectLocalPathEntry::GslReferenceInit:
8041     case IndirectLocalPathEntry::GslPointerInit:
8042       // These exist primarily to mark the path as not permitting or
8043       // supporting lifetime extension.
8044       break;
8045 
8046     case IndirectLocalPathEntry::VarInit:
8047       if (cast<VarDecl>(Path[I].D)->isImplicit())
8048         return SourceRange();
8049       [[fallthrough]];
8050     case IndirectLocalPathEntry::DefaultInit:
8051       return Path[I].E->getSourceRange();
8052 
8053     case IndirectLocalPathEntry::LambdaCaptureInit:
8054       if (!Path[I].Capture->capturesVariable())
8055         continue;
8056       return Path[I].E->getSourceRange();
8057     }
8058   }
8059   return E->getSourceRange();
8060 }
8061 
8062 static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8063   for (const auto &It : llvm::reverse(Path)) {
8064     if (It.Kind == IndirectLocalPathEntry::VarInit)
8065       continue;
8066     if (It.Kind == IndirectLocalPathEntry::AddressOf)
8067       continue;
8068     if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8069       continue;
8070     return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8071            It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8072   }
8073   return false;
8074 }
8075 
8076 void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
8077                                     Expr *Init) {
8078   LifetimeResult LR = getEntityLifetime(&Entity);
8079   LifetimeKind LK = LR.getInt();
8080   const InitializedEntity *ExtendingEntity = LR.getPointer();
8081 
8082   // If this entity doesn't have an interesting lifetime, don't bother looking
8083   // for temporaries within its initializer.
8084   if (LK == LK_FullExpression)
8085     return;
8086 
8087   auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8088                               ReferenceKind RK) -> bool {
8089     SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8090     SourceLocation DiagLoc = DiagRange.getBegin();
8091 
8092     auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8093 
8094     bool IsGslPtrInitWithGslTempOwner = false;
8095     bool IsLocalGslOwner = false;
8096     if (pathOnlyInitializesGslPointer(Path)) {
8097       if (isa<DeclRefExpr>(L)) {
8098         // We do not want to follow the references when returning a pointer originating
8099         // from a local owner to avoid the following false positive:
8100         //   int &p = *localUniquePtr;
8101         //   someContainer.add(std::move(localUniquePtr));
8102         //   return p;
8103         IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8104         if (pathContainsInit(Path) || !IsLocalGslOwner)
8105           return false;
8106       } else {
8107         IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8108                             isRecordWithAttr<OwnerAttr>(MTE->getType());
8109         // Skipping a chain of initializing gsl::Pointer annotated objects.
8110         // We are looking only for the final source to find out if it was
8111         // a local or temporary owner or the address of a local variable/param.
8112         if (!IsGslPtrInitWithGslTempOwner)
8113           return true;
8114       }
8115     }
8116 
8117     switch (LK) {
8118     case LK_FullExpression:
8119       llvm_unreachable("already handled this");
8120 
8121     case LK_Extended: {
8122       if (!MTE) {
8123         // The initialized entity has lifetime beyond the full-expression,
8124         // and the local entity does too, so don't warn.
8125         //
8126         // FIXME: We should consider warning if a static / thread storage
8127         // duration variable retains an automatic storage duration local.
8128         return false;
8129       }
8130 
8131       if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8132         Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8133         return false;
8134       }
8135 
8136       switch (shouldLifetimeExtendThroughPath(Path)) {
8137       case PathLifetimeKind::Extend:
8138         // Update the storage duration of the materialized temporary.
8139         // FIXME: Rebuild the expression instead of mutating it.
8140         MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8141                               ExtendingEntity->allocateManglingNumber());
8142         // Also visit the temporaries lifetime-extended by this initializer.
8143         return true;
8144 
8145       case PathLifetimeKind::ShouldExtend:
8146         // We're supposed to lifetime-extend the temporary along this path (per
8147         // the resolution of DR1815), but we don't support that yet.
8148         //
8149         // FIXME: Properly handle this situation. Perhaps the easiest approach
8150         // would be to clone the initializer expression on each use that would
8151         // lifetime extend its temporaries.
8152         Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8153             << RK << DiagRange;
8154         break;
8155 
8156       case PathLifetimeKind::NoExtend:
8157         // If the path goes through the initialization of a variable or field,
8158         // it can't possibly reach a temporary created in this full-expression.
8159         // We will have already diagnosed any problems with the initializer.
8160         if (pathContainsInit(Path))
8161           return false;
8162 
8163         Diag(DiagLoc, diag::warn_dangling_variable)
8164             << RK << !Entity.getParent()
8165             << ExtendingEntity->getDecl()->isImplicit()
8166             << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8167         break;
8168       }
8169       break;
8170     }
8171 
8172     case LK_MemInitializer: {
8173       if (isa<MaterializeTemporaryExpr>(L)) {
8174         // Under C++ DR1696, if a mem-initializer (or a default member
8175         // initializer used by the absence of one) would lifetime-extend a
8176         // temporary, the program is ill-formed.
8177         if (auto *ExtendingDecl =
8178                 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8179           if (IsGslPtrInitWithGslTempOwner) {
8180             Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8181                 << ExtendingDecl << DiagRange;
8182             Diag(ExtendingDecl->getLocation(),
8183                  diag::note_ref_or_ptr_member_declared_here)
8184                 << true;
8185             return false;
8186           }
8187           bool IsSubobjectMember = ExtendingEntity != &Entity;
8188           Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8189                                 PathLifetimeKind::NoExtend
8190                             ? diag::err_dangling_member
8191                             : diag::warn_dangling_member)
8192               << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8193           // Don't bother adding a note pointing to the field if we're inside
8194           // its default member initializer; our primary diagnostic points to
8195           // the same place in that case.
8196           if (Path.empty() ||
8197               Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8198             Diag(ExtendingDecl->getLocation(),
8199                  diag::note_lifetime_extending_member_declared_here)
8200                 << RK << IsSubobjectMember;
8201           }
8202         } else {
8203           // We have a mem-initializer but no particular field within it; this
8204           // is either a base class or a delegating initializer directly
8205           // initializing the base-class from something that doesn't live long
8206           // enough.
8207           //
8208           // FIXME: Warn on this.
8209           return false;
8210         }
8211       } else {
8212         // Paths via a default initializer can only occur during error recovery
8213         // (there's no other way that a default initializer can refer to a
8214         // local). Don't produce a bogus warning on those cases.
8215         if (pathContainsInit(Path))
8216           return false;
8217 
8218         // Suppress false positives for code like the one below:
8219         //   Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8220         if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8221           return false;
8222 
8223         auto *DRE = dyn_cast<DeclRefExpr>(L);
8224         auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8225         if (!VD) {
8226           // A member was initialized to a local block.
8227           // FIXME: Warn on this.
8228           return false;
8229         }
8230 
8231         if (auto *Member =
8232                 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8233           bool IsPointer = !Member->getType()->isReferenceType();
8234           Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8235                                   : diag::warn_bind_ref_member_to_parameter)
8236               << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8237           Diag(Member->getLocation(),
8238                diag::note_ref_or_ptr_member_declared_here)
8239               << (unsigned)IsPointer;
8240         }
8241       }
8242       break;
8243     }
8244 
8245     case LK_New:
8246       if (isa<MaterializeTemporaryExpr>(L)) {
8247         if (IsGslPtrInitWithGslTempOwner)
8248           Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8249         else
8250           Diag(DiagLoc, RK == RK_ReferenceBinding
8251                             ? diag::warn_new_dangling_reference
8252                             : diag::warn_new_dangling_initializer_list)
8253               << !Entity.getParent() << DiagRange;
8254       } else {
8255         // We can't determine if the allocation outlives the local declaration.
8256         return false;
8257       }
8258       break;
8259 
8260     case LK_Return:
8261     case LK_StmtExprResult:
8262       if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8263         // We can't determine if the local variable outlives the statement
8264         // expression.
8265         if (LK == LK_StmtExprResult)
8266           return false;
8267         Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8268             << Entity.getType()->isReferenceType() << DRE->getDecl()
8269             << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8270       } else if (isa<BlockExpr>(L)) {
8271         Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8272       } else if (isa<AddrLabelExpr>(L)) {
8273         // Don't warn when returning a label from a statement expression.
8274         // Leaving the scope doesn't end its lifetime.
8275         if (LK == LK_StmtExprResult)
8276           return false;
8277         Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8278       } else {
8279         Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8280          << Entity.getType()->isReferenceType() << DiagRange;
8281       }
8282       break;
8283     }
8284 
8285     for (unsigned I = 0; I != Path.size(); ++I) {
8286       auto Elem = Path[I];
8287 
8288       switch (Elem.Kind) {
8289       case IndirectLocalPathEntry::AddressOf:
8290       case IndirectLocalPathEntry::LValToRVal:
8291         // These exist primarily to mark the path as not permitting or
8292         // supporting lifetime extension.
8293         break;
8294 
8295       case IndirectLocalPathEntry::LifetimeBoundCall:
8296       case IndirectLocalPathEntry::TemporaryCopy:
8297       case IndirectLocalPathEntry::GslPointerInit:
8298       case IndirectLocalPathEntry::GslReferenceInit:
8299         // FIXME: Consider adding a note for these.
8300         break;
8301 
8302       case IndirectLocalPathEntry::DefaultInit: {
8303         auto *FD = cast<FieldDecl>(Elem.D);
8304         Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8305             << FD << nextPathEntryRange(Path, I + 1, L);
8306         break;
8307       }
8308 
8309       case IndirectLocalPathEntry::VarInit: {
8310         const VarDecl *VD = cast<VarDecl>(Elem.D);
8311         Diag(VD->getLocation(), diag::note_local_var_initializer)
8312             << VD->getType()->isReferenceType()
8313             << VD->isImplicit() << VD->getDeclName()
8314             << nextPathEntryRange(Path, I + 1, L);
8315         break;
8316       }
8317 
8318       case IndirectLocalPathEntry::LambdaCaptureInit:
8319         if (!Elem.Capture->capturesVariable())
8320           break;
8321         // FIXME: We can't easily tell apart an init-capture from a nested
8322         // capture of an init-capture.
8323         const ValueDecl *VD = Elem.Capture->getCapturedVar();
8324         Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8325             << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8326             << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8327             << nextPathEntryRange(Path, I + 1, L);
8328         break;
8329       }
8330     }
8331 
8332     // We didn't lifetime-extend, so don't go any further; we don't need more
8333     // warnings or errors on inner temporaries within this one's initializer.
8334     return false;
8335   };
8336 
8337   bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8338       diag::warn_dangling_lifetime_pointer, SourceLocation());
8339   llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
8340   if (Init->isGLValue())
8341     visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8342                                           TemporaryVisitor,
8343                                           EnableLifetimeWarnings);
8344   else
8345     visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8346                                      EnableLifetimeWarnings);
8347 }
8348 
8349 static void DiagnoseNarrowingInInitList(Sema &S,
8350                                         const ImplicitConversionSequence &ICS,
8351                                         QualType PreNarrowingType,
8352                                         QualType EntityType,
8353                                         const Expr *PostInit);
8354 
8355 /// Provide warnings when std::move is used on construction.
8356 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8357                                     bool IsReturnStmt) {
8358   if (!InitExpr)
8359     return;
8360 
8361   if (S.inTemplateInstantiation())
8362     return;
8363 
8364   QualType DestType = InitExpr->getType();
8365   if (!DestType->isRecordType())
8366     return;
8367 
8368   unsigned DiagID = 0;
8369   if (IsReturnStmt) {
8370     const CXXConstructExpr *CCE =
8371         dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8372     if (!CCE || CCE->getNumArgs() != 1)
8373       return;
8374 
8375     if (!CCE->getConstructor()->isCopyOrMoveConstructor())
8376       return;
8377 
8378     InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8379   }
8380 
8381   // Find the std::move call and get the argument.
8382   const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8383   if (!CE || !CE->isCallToStdMove())
8384     return;
8385 
8386   const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8387 
8388   if (IsReturnStmt) {
8389     const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8390     if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8391       return;
8392 
8393     const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8394     if (!VD || !VD->hasLocalStorage())
8395       return;
8396 
8397     // __block variables are not moved implicitly.
8398     if (VD->hasAttr<BlocksAttr>())
8399       return;
8400 
8401     QualType SourceType = VD->getType();
8402     if (!SourceType->isRecordType())
8403       return;
8404 
8405     if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8406       return;
8407     }
8408 
8409     // If we're returning a function parameter, copy elision
8410     // is not possible.
8411     if (isa<ParmVarDecl>(VD))
8412       DiagID = diag::warn_redundant_move_on_return;
8413     else
8414       DiagID = diag::warn_pessimizing_move_on_return;
8415   } else {
8416     DiagID = diag::warn_pessimizing_move_on_initialization;
8417     const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8418     if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8419       return;
8420   }
8421 
8422   S.Diag(CE->getBeginLoc(), DiagID);
8423 
8424   // Get all the locations for a fix-it.  Don't emit the fix-it if any location
8425   // is within a macro.
8426   SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8427   if (CallBegin.isMacroID())
8428     return;
8429   SourceLocation RParen = CE->getRParenLoc();
8430   if (RParen.isMacroID())
8431     return;
8432   SourceLocation LParen;
8433   SourceLocation ArgLoc = Arg->getBeginLoc();
8434 
8435   // Special testing for the argument location.  Since the fix-it needs the
8436   // location right before the argument, the argument location can be in a
8437   // macro only if it is at the beginning of the macro.
8438   while (ArgLoc.isMacroID() &&
8439          S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
8440     ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
8441   }
8442 
8443   if (LParen.isMacroID())
8444     return;
8445 
8446   LParen = ArgLoc.getLocWithOffset(-1);
8447 
8448   S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8449       << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8450       << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8451 }
8452 
8453 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8454   // Check to see if we are dereferencing a null pointer.  If so, this is
8455   // undefined behavior, so warn about it.  This only handles the pattern
8456   // "*null", which is a very syntactic check.
8457   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8458     if (UO->getOpcode() == UO_Deref &&
8459         UO->getSubExpr()->IgnoreParenCasts()->
8460         isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8461     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8462                           S.PDiag(diag::warn_binding_null_to_reference)
8463                             << UO->getSubExpr()->getSourceRange());
8464   }
8465 }
8466 
8467 MaterializeTemporaryExpr *
8468 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
8469                                      bool BoundToLvalueReference) {
8470   auto MTE = new (Context)
8471       MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8472 
8473   // Order an ExprWithCleanups for lifetime marks.
8474   //
8475   // TODO: It'll be good to have a single place to check the access of the
8476   // destructor and generate ExprWithCleanups for various uses. Currently these
8477   // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8478   // but there may be a chance to merge them.
8479   Cleanup.setExprNeedsCleanups(false);
8480   return MTE;
8481 }
8482 
8483 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
8484   // In C++98, we don't want to implicitly create an xvalue.
8485   // FIXME: This means that AST consumers need to deal with "prvalues" that
8486   // denote materialized temporaries. Maybe we should add another ValueKind
8487   // for "xvalue pretending to be a prvalue" for C++98 support.
8488   if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8489     return E;
8490 
8491   // C++1z [conv.rval]/1: T shall be a complete type.
8492   // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8493   // If so, we should check for a non-abstract class type here too.
8494   QualType T = E->getType();
8495   if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8496     return ExprError();
8497 
8498   return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8499 }
8500 
8501 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
8502                                                 ExprValueKind VK,
8503                                                 CheckedConversionKind CCK) {
8504 
8505   CastKind CK = CK_NoOp;
8506 
8507   if (VK == VK_PRValue) {
8508     auto PointeeTy = Ty->getPointeeType();
8509     auto ExprPointeeTy = E->getType()->getPointeeType();
8510     if (!PointeeTy.isNull() &&
8511         PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8512       CK = CK_AddressSpaceConversion;
8513   } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8514     CK = CK_AddressSpaceConversion;
8515   }
8516 
8517   return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8518 }
8519 
8520 ExprResult InitializationSequence::Perform(Sema &S,
8521                                            const InitializedEntity &Entity,
8522                                            const InitializationKind &Kind,
8523                                            MultiExprArg Args,
8524                                            QualType *ResultType) {
8525   if (Failed()) {
8526     Diagnose(S, Entity, Kind, Args);
8527     return ExprError();
8528   }
8529   if (!ZeroInitializationFixit.empty()) {
8530     const Decl *D = Entity.getDecl();
8531     const auto *VD = dyn_cast_or_null<VarDecl>(D);
8532     QualType DestType = Entity.getType();
8533 
8534     // The initialization would have succeeded with this fixit. Since the fixit
8535     // is on the error, we need to build a valid AST in this case, so this isn't
8536     // handled in the Failed() branch above.
8537     if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8538       // Use a more useful diagnostic for constexpr variables.
8539       S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8540           << VD
8541           << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8542                                         ZeroInitializationFixit);
8543     } else {
8544       unsigned DiagID = diag::err_default_init_const;
8545       if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8546         DiagID = diag::ext_default_init_const;
8547 
8548       S.Diag(Kind.getLocation(), DiagID)
8549           << DestType << (bool)DestType->getAs<RecordType>()
8550           << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8551                                         ZeroInitializationFixit);
8552     }
8553   }
8554 
8555   if (getKind() == DependentSequence) {
8556     // If the declaration is a non-dependent, incomplete array type
8557     // that has an initializer, then its type will be completed once
8558     // the initializer is instantiated.
8559     if (ResultType && !Entity.getType()->isDependentType() &&
8560         Args.size() == 1) {
8561       QualType DeclType = Entity.getType();
8562       if (const IncompleteArrayType *ArrayT
8563                            = S.Context.getAsIncompleteArrayType(DeclType)) {
8564         // FIXME: We don't currently have the ability to accurately
8565         // compute the length of an initializer list without
8566         // performing full type-checking of the initializer list
8567         // (since we have to determine where braces are implicitly
8568         // introduced and such).  So, we fall back to making the array
8569         // type a dependently-sized array type with no specified
8570         // bound.
8571         if (isa<InitListExpr>((Expr *)Args[0])) {
8572           SourceRange Brackets;
8573 
8574           // Scavange the location of the brackets from the entity, if we can.
8575           if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8576             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8577               TypeLoc TL = TInfo->getTypeLoc();
8578               if (IncompleteArrayTypeLoc ArrayLoc =
8579                       TL.getAs<IncompleteArrayTypeLoc>())
8580                 Brackets = ArrayLoc.getBracketsRange();
8581             }
8582           }
8583 
8584           *ResultType
8585             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8586                                                    /*NumElts=*/nullptr,
8587                                                    ArrayT->getSizeModifier(),
8588                                        ArrayT->getIndexTypeCVRQualifiers(),
8589                                                    Brackets);
8590         }
8591 
8592       }
8593     }
8594     if (Kind.getKind() == InitializationKind::IK_Direct &&
8595         !Kind.isExplicitCast()) {
8596       // Rebuild the ParenListExpr.
8597       SourceRange ParenRange = Kind.getParenOrBraceRange();
8598       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8599                                   Args);
8600     }
8601     assert(Kind.getKind() == InitializationKind::IK_Copy ||
8602            Kind.isExplicitCast() ||
8603            Kind.getKind() == InitializationKind::IK_DirectList);
8604     return ExprResult(Args[0]);
8605   }
8606 
8607   // No steps means no initialization.
8608   if (Steps.empty())
8609     return ExprResult((Expr *)nullptr);
8610 
8611   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8612       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8613       !Entity.isParamOrTemplateParamKind()) {
8614     // Produce a C++98 compatibility warning if we are initializing a reference
8615     // from an initializer list. For parameters, we produce a better warning
8616     // elsewhere.
8617     Expr *Init = Args[0];
8618     S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8619         << Init->getSourceRange();
8620   }
8621 
8622   if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8623       isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8624     // Produce a Microsoft compatibility warning when initializing from a
8625     // predefined expression since MSVC treats predefined expressions as string
8626     // literals.
8627     Expr *Init = Args[0];
8628     S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8629   }
8630 
8631   // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8632   QualType ETy = Entity.getType();
8633   bool HasGlobalAS = ETy.hasAddressSpace() &&
8634                      ETy.getAddressSpace() == LangAS::opencl_global;
8635 
8636   if (S.getLangOpts().OpenCLVersion >= 200 &&
8637       ETy->isAtomicType() && !HasGlobalAS &&
8638       Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8639     S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8640         << 1
8641         << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8642     return ExprError();
8643   }
8644 
8645   QualType DestType = Entity.getType().getNonReferenceType();
8646   // FIXME: Ugly hack around the fact that Entity.getType() is not
8647   // the same as Entity.getDecl()->getType() in cases involving type merging,
8648   //  and we want latter when it makes sense.
8649   if (ResultType)
8650     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8651                                      Entity.getType();
8652 
8653   ExprResult CurInit((Expr *)nullptr);
8654   SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8655 
8656   // HLSL allows vector initialization to function like list initialization, but
8657   // use the syntax of a C++-like constructor.
8658   bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8659                           isa<InitListExpr>(Args[0]);
8660   (void)IsHLSLVectorInit;
8661 
8662   // For initialization steps that start with a single initializer,
8663   // grab the only argument out the Args and place it into the "current"
8664   // initializer.
8665   switch (Steps.front().Kind) {
8666   case SK_ResolveAddressOfOverloadedFunction:
8667   case SK_CastDerivedToBasePRValue:
8668   case SK_CastDerivedToBaseXValue:
8669   case SK_CastDerivedToBaseLValue:
8670   case SK_BindReference:
8671   case SK_BindReferenceToTemporary:
8672   case SK_FinalCopy:
8673   case SK_ExtraneousCopyToTemporary:
8674   case SK_UserConversion:
8675   case SK_QualificationConversionLValue:
8676   case SK_QualificationConversionXValue:
8677   case SK_QualificationConversionPRValue:
8678   case SK_FunctionReferenceConversion:
8679   case SK_AtomicConversion:
8680   case SK_ConversionSequence:
8681   case SK_ConversionSequenceNoNarrowing:
8682   case SK_ListInitialization:
8683   case SK_UnwrapInitList:
8684   case SK_RewrapInitList:
8685   case SK_CAssignment:
8686   case SK_StringInit:
8687   case SK_ObjCObjectConversion:
8688   case SK_ArrayLoopIndex:
8689   case SK_ArrayLoopInit:
8690   case SK_ArrayInit:
8691   case SK_GNUArrayInit:
8692   case SK_ParenthesizedArrayInit:
8693   case SK_PassByIndirectCopyRestore:
8694   case SK_PassByIndirectRestore:
8695   case SK_ProduceObjCObject:
8696   case SK_StdInitializerList:
8697   case SK_OCLSamplerInit:
8698   case SK_OCLZeroOpaqueType: {
8699     assert(Args.size() == 1 || IsHLSLVectorInit);
8700     CurInit = Args[0];
8701     if (!CurInit.get()) return ExprError();
8702     break;
8703   }
8704 
8705   case SK_ConstructorInitialization:
8706   case SK_ConstructorInitializationFromList:
8707   case SK_StdInitializerListConstructorCall:
8708   case SK_ZeroInitialization:
8709   case SK_ParenthesizedListInit:
8710     break;
8711   }
8712 
8713   // Promote from an unevaluated context to an unevaluated list context in
8714   // C++11 list-initialization; we need to instantiate entities usable in
8715   // constant expressions here in order to perform narrowing checks =(
8716   EnterExpressionEvaluationContext Evaluated(
8717       S, EnterExpressionEvaluationContext::InitList,
8718       CurInit.get() && isa<InitListExpr>(CurInit.get()));
8719 
8720   // C++ [class.abstract]p2:
8721   //   no objects of an abstract class can be created except as subobjects
8722   //   of a class derived from it
8723   auto checkAbstractType = [&](QualType T) -> bool {
8724     if (Entity.getKind() == InitializedEntity::EK_Base ||
8725         Entity.getKind() == InitializedEntity::EK_Delegating)
8726       return false;
8727     return S.RequireNonAbstractType(Kind.getLocation(), T,
8728                                     diag::err_allocation_of_abstract_type);
8729   };
8730 
8731   // Walk through the computed steps for the initialization sequence,
8732   // performing the specified conversions along the way.
8733   bool ConstructorInitRequiresZeroInit = false;
8734   for (step_iterator Step = step_begin(), StepEnd = step_end();
8735        Step != StepEnd; ++Step) {
8736     if (CurInit.isInvalid())
8737       return ExprError();
8738 
8739     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8740 
8741     switch (Step->Kind) {
8742     case SK_ResolveAddressOfOverloadedFunction:
8743       // Overload resolution determined which function invoke; update the
8744       // initializer to reflect that choice.
8745       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
8746       if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8747         return ExprError();
8748       CurInit = S.FixOverloadedFunctionReference(CurInit,
8749                                                  Step->Function.FoundDecl,
8750                                                  Step->Function.Function);
8751       // We might get back another placeholder expression if we resolved to a
8752       // builtin.
8753       if (!CurInit.isInvalid())
8754         CurInit = S.CheckPlaceholderExpr(CurInit.get());
8755       break;
8756 
8757     case SK_CastDerivedToBasePRValue:
8758     case SK_CastDerivedToBaseXValue:
8759     case SK_CastDerivedToBaseLValue: {
8760       // We have a derived-to-base cast that produces either an rvalue or an
8761       // lvalue. Perform that cast.
8762 
8763       CXXCastPath BasePath;
8764 
8765       // Casts to inaccessible base classes are allowed with C-style casts.
8766       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8767       if (S.CheckDerivedToBaseConversion(
8768               SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8769               CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8770         return ExprError();
8771 
8772       ExprValueKind VK =
8773           Step->Kind == SK_CastDerivedToBaseLValue
8774               ? VK_LValue
8775               : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8776                                                           : VK_PRValue);
8777       CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8778                                          CK_DerivedToBase, CurInit.get(),
8779                                          &BasePath, VK, FPOptionsOverride());
8780       break;
8781     }
8782 
8783     case SK_BindReference:
8784       // Reference binding does not have any corresponding ASTs.
8785 
8786       // Check exception specifications
8787       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8788         return ExprError();
8789 
8790       // We don't check for e.g. function pointers here, since address
8791       // availability checks should only occur when the function first decays
8792       // into a pointer or reference.
8793       if (CurInit.get()->getType()->isFunctionProtoType()) {
8794         if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8795           if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8796             if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8797                                                      DRE->getBeginLoc()))
8798               return ExprError();
8799           }
8800         }
8801       }
8802 
8803       CheckForNullPointerDereference(S, CurInit.get());
8804       break;
8805 
8806     case SK_BindReferenceToTemporary: {
8807       // Make sure the "temporary" is actually an rvalue.
8808       assert(CurInit.get()->isPRValue() && "not a temporary");
8809 
8810       // Check exception specifications
8811       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8812         return ExprError();
8813 
8814       QualType MTETy = Step->Type;
8815 
8816       // When this is an incomplete array type (such as when this is
8817       // initializing an array of unknown bounds from an init list), use THAT
8818       // type instead so that we propagate the array bounds.
8819       if (MTETy->isIncompleteArrayType() &&
8820           !CurInit.get()->getType()->isIncompleteArrayType() &&
8821           S.Context.hasSameType(
8822               MTETy->getPointeeOrArrayElementType(),
8823               CurInit.get()->getType()->getPointeeOrArrayElementType()))
8824         MTETy = CurInit.get()->getType();
8825 
8826       // Materialize the temporary into memory.
8827       MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8828           MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8829       CurInit = MTE;
8830 
8831       // If we're extending this temporary to automatic storage duration -- we
8832       // need to register its cleanup during the full-expression's cleanups.
8833       if (MTE->getStorageDuration() == SD_Automatic &&
8834           MTE->getType().isDestructedType())
8835         S.Cleanup.setExprNeedsCleanups(true);
8836       break;
8837     }
8838 
8839     case SK_FinalCopy:
8840       if (checkAbstractType(Step->Type))
8841         return ExprError();
8842 
8843       // If the overall initialization is initializing a temporary, we already
8844       // bound our argument if it was necessary to do so. If not (if we're
8845       // ultimately initializing a non-temporary), our argument needs to be
8846       // bound since it's initializing a function parameter.
8847       // FIXME: This is a mess. Rationalize temporary destruction.
8848       if (!shouldBindAsTemporary(Entity))
8849         CurInit = S.MaybeBindToTemporary(CurInit.get());
8850       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8851                            /*IsExtraneousCopy=*/false);
8852       break;
8853 
8854     case SK_ExtraneousCopyToTemporary:
8855       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8856                            /*IsExtraneousCopy=*/true);
8857       break;
8858 
8859     case SK_UserConversion: {
8860       // We have a user-defined conversion that invokes either a constructor
8861       // or a conversion function.
8862       CastKind CastKind;
8863       FunctionDecl *Fn = Step->Function.Function;
8864       DeclAccessPair FoundFn = Step->Function.FoundDecl;
8865       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8866       bool CreatedObject = false;
8867       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8868         // Build a call to the selected constructor.
8869         SmallVector<Expr*, 8> ConstructorArgs;
8870         SourceLocation Loc = CurInit.get()->getBeginLoc();
8871 
8872         // Determine the arguments required to actually perform the constructor
8873         // call.
8874         Expr *Arg = CurInit.get();
8875         if (S.CompleteConstructorCall(Constructor, Step->Type,
8876                                       MultiExprArg(&Arg, 1), Loc,
8877                                       ConstructorArgs))
8878           return ExprError();
8879 
8880         // Build an expression that constructs a temporary.
8881         CurInit = S.BuildCXXConstructExpr(
8882             Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8883             HadMultipleCandidates,
8884             /*ListInit*/ false,
8885             /*StdInitListInit*/ false,
8886             /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8887         if (CurInit.isInvalid())
8888           return ExprError();
8889 
8890         S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8891                                  Entity);
8892         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8893           return ExprError();
8894 
8895         CastKind = CK_ConstructorConversion;
8896         CreatedObject = true;
8897       } else {
8898         // Build a call to the conversion function.
8899         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8900         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8901                                     FoundFn);
8902         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8903           return ExprError();
8904 
8905         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8906                                            HadMultipleCandidates);
8907         if (CurInit.isInvalid())
8908           return ExprError();
8909 
8910         CastKind = CK_UserDefinedConversion;
8911         CreatedObject = Conversion->getReturnType()->isRecordType();
8912       }
8913 
8914       if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8915         return ExprError();
8916 
8917       CurInit = ImplicitCastExpr::Create(
8918           S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8919           CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8920 
8921       if (shouldBindAsTemporary(Entity))
8922         // The overall entity is temporary, so this expression should be
8923         // destroyed at the end of its full-expression.
8924         CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8925       else if (CreatedObject && shouldDestroyEntity(Entity)) {
8926         // The object outlasts the full-expression, but we need to prepare for
8927         // a destructor being run on it.
8928         // FIXME: It makes no sense to do this here. This should happen
8929         // regardless of how we initialized the entity.
8930         QualType T = CurInit.get()->getType();
8931         if (const RecordType *Record = T->getAs<RecordType>()) {
8932           CXXDestructorDecl *Destructor
8933             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8934           S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8935                                   S.PDiag(diag::err_access_dtor_temp) << T);
8936           S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8937           if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8938             return ExprError();
8939         }
8940       }
8941       break;
8942     }
8943 
8944     case SK_QualificationConversionLValue:
8945     case SK_QualificationConversionXValue:
8946     case SK_QualificationConversionPRValue: {
8947       // Perform a qualification conversion; these can never go wrong.
8948       ExprValueKind VK =
8949           Step->Kind == SK_QualificationConversionLValue
8950               ? VK_LValue
8951               : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8952                                                                 : VK_PRValue);
8953       CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8954       break;
8955     }
8956 
8957     case SK_FunctionReferenceConversion:
8958       assert(CurInit.get()->isLValue() &&
8959              "function reference should be lvalue");
8960       CurInit =
8961           S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8962       break;
8963 
8964     case SK_AtomicConversion: {
8965       assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8966       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8967                                     CK_NonAtomicToAtomic, VK_PRValue);
8968       break;
8969     }
8970 
8971     case SK_ConversionSequence:
8972     case SK_ConversionSequenceNoNarrowing: {
8973       if (const auto *FromPtrType =
8974               CurInit.get()->getType()->getAs<PointerType>()) {
8975         if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8976           if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8977               !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8978             // Do not check static casts here because they are checked earlier
8979             // in Sema::ActOnCXXNamedCast()
8980             if (!Kind.isStaticCast()) {
8981               S.Diag(CurInit.get()->getExprLoc(),
8982                      diag::warn_noderef_to_dereferenceable_pointer)
8983                   << CurInit.get()->getSourceRange();
8984             }
8985           }
8986         }
8987       }
8988 
8989       Sema::CheckedConversionKind CCK
8990         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
8991         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
8992         : Kind.isExplicitCast()? Sema::CCK_OtherCast
8993         : Sema::CCK_ImplicitConversion;
8994       ExprResult CurInitExprRes =
8995         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
8996                                     getAssignmentAction(Entity), CCK);
8997       if (CurInitExprRes.isInvalid())
8998         return ExprError();
8999 
9000       S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
9001 
9002       CurInit = CurInitExprRes;
9003 
9004       if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
9005           S.getLangOpts().CPlusPlus)
9006         DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9007                                     CurInit.get());
9008 
9009       break;
9010     }
9011 
9012     case SK_ListInitialization: {
9013       if (checkAbstractType(Step->Type))
9014         return ExprError();
9015 
9016       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9017       // If we're not initializing the top-level entity, we need to create an
9018       // InitializeTemporary entity for our target type.
9019       QualType Ty = Step->Type;
9020       bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9021       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
9022       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9023       InitListChecker PerformInitList(S, InitEntity,
9024           InitList, Ty, /*VerifyOnly=*/false,
9025           /*TreatUnavailableAsInvalid=*/false);
9026       if (PerformInitList.HadError())
9027         return ExprError();
9028 
9029       // Hack: We must update *ResultType if available in order to set the
9030       // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9031       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9032       if (ResultType &&
9033           ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9034         if ((*ResultType)->isRValueReferenceType())
9035           Ty = S.Context.getRValueReferenceType(Ty);
9036         else if ((*ResultType)->isLValueReferenceType())
9037           Ty = S.Context.getLValueReferenceType(Ty,
9038             (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9039         *ResultType = Ty;
9040       }
9041 
9042       InitListExpr *StructuredInitList =
9043           PerformInitList.getFullyStructuredList();
9044       CurInit.get();
9045       CurInit = shouldBindAsTemporary(InitEntity)
9046           ? S.MaybeBindToTemporary(StructuredInitList)
9047           : StructuredInitList;
9048       break;
9049     }
9050 
9051     case SK_ConstructorInitializationFromList: {
9052       if (checkAbstractType(Step->Type))
9053         return ExprError();
9054 
9055       // When an initializer list is passed for a parameter of type "reference
9056       // to object", we don't get an EK_Temporary entity, but instead an
9057       // EK_Parameter entity with reference type.
9058       // FIXME: This is a hack. What we really should do is create a user
9059       // conversion step for this case, but this makes it considerably more
9060       // complicated. For now, this will do.
9061       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9062                                         Entity.getType().getNonReferenceType());
9063       bool UseTemporary = Entity.getType()->isReferenceType();
9064       assert(Args.size() == 1 && "expected a single argument for list init");
9065       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9066       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9067         << InitList->getSourceRange();
9068       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9069       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9070                                                                    Entity,
9071                                                  Kind, Arg, *Step,
9072                                                ConstructorInitRequiresZeroInit,
9073                                                /*IsListInitialization*/true,
9074                                                /*IsStdInitListInit*/false,
9075                                                InitList->getLBraceLoc(),
9076                                                InitList->getRBraceLoc());
9077       break;
9078     }
9079 
9080     case SK_UnwrapInitList:
9081       CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9082       break;
9083 
9084     case SK_RewrapInitList: {
9085       Expr *E = CurInit.get();
9086       InitListExpr *Syntactic = Step->WrappingSyntacticList;
9087       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9088           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9089       ILE->setSyntacticForm(Syntactic);
9090       ILE->setType(E->getType());
9091       ILE->setValueKind(E->getValueKind());
9092       CurInit = ILE;
9093       break;
9094     }
9095 
9096     case SK_ConstructorInitialization:
9097     case SK_StdInitializerListConstructorCall: {
9098       if (checkAbstractType(Step->Type))
9099         return ExprError();
9100 
9101       // When an initializer list is passed for a parameter of type "reference
9102       // to object", we don't get an EK_Temporary entity, but instead an
9103       // EK_Parameter entity with reference type.
9104       // FIXME: This is a hack. What we really should do is create a user
9105       // conversion step for this case, but this makes it considerably more
9106       // complicated. For now, this will do.
9107       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9108                                         Entity.getType().getNonReferenceType());
9109       bool UseTemporary = Entity.getType()->isReferenceType();
9110       bool IsStdInitListInit =
9111           Step->Kind == SK_StdInitializerListConstructorCall;
9112       Expr *Source = CurInit.get();
9113       SourceRange Range = Kind.hasParenOrBraceRange()
9114                               ? Kind.getParenOrBraceRange()
9115                               : SourceRange();
9116       CurInit = PerformConstructorInitialization(
9117           S, UseTemporary ? TempEntity : Entity, Kind,
9118           Source ? MultiExprArg(Source) : Args, *Step,
9119           ConstructorInitRequiresZeroInit,
9120           /*IsListInitialization*/ IsStdInitListInit,
9121           /*IsStdInitListInitialization*/ IsStdInitListInit,
9122           /*LBraceLoc*/ Range.getBegin(),
9123           /*RBraceLoc*/ Range.getEnd());
9124       break;
9125     }
9126 
9127     case SK_ZeroInitialization: {
9128       step_iterator NextStep = Step;
9129       ++NextStep;
9130       if (NextStep != StepEnd &&
9131           (NextStep->Kind == SK_ConstructorInitialization ||
9132            NextStep->Kind == SK_ConstructorInitializationFromList)) {
9133         // The need for zero-initialization is recorded directly into
9134         // the call to the object's constructor within the next step.
9135         ConstructorInitRequiresZeroInit = true;
9136       } else if (Kind.getKind() == InitializationKind::IK_Value &&
9137                  S.getLangOpts().CPlusPlus &&
9138                  !Kind.isImplicitValueInit()) {
9139         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9140         if (!TSInfo)
9141           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
9142                                                     Kind.getRange().getBegin());
9143 
9144         CurInit = new (S.Context) CXXScalarValueInitExpr(
9145             Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9146             Kind.getRange().getEnd());
9147       } else {
9148         CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9149       }
9150       break;
9151     }
9152 
9153     case SK_CAssignment: {
9154       QualType SourceType = CurInit.get()->getType();
9155 
9156       // Save off the initial CurInit in case we need to emit a diagnostic
9157       ExprResult InitialCurInit = CurInit;
9158       ExprResult Result = CurInit;
9159       Sema::AssignConvertType ConvTy =
9160         S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
9161             Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
9162       if (Result.isInvalid())
9163         return ExprError();
9164       CurInit = Result;
9165 
9166       // If this is a call, allow conversion to a transparent union.
9167       ExprResult CurInitExprRes = CurInit;
9168       if (ConvTy != Sema::Compatible &&
9169           Entity.isParameterKind() &&
9170           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
9171             == Sema::Compatible)
9172         ConvTy = Sema::Compatible;
9173       if (CurInitExprRes.isInvalid())
9174         return ExprError();
9175       CurInit = CurInitExprRes;
9176 
9177       bool Complained;
9178       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9179                                      Step->Type, SourceType,
9180                                      InitialCurInit.get(),
9181                                      getAssignmentAction(Entity, true),
9182                                      &Complained)) {
9183         PrintInitLocationNote(S, Entity);
9184         return ExprError();
9185       } else if (Complained)
9186         PrintInitLocationNote(S, Entity);
9187       break;
9188     }
9189 
9190     case SK_StringInit: {
9191       QualType Ty = Step->Type;
9192       bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9193       CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9194                       S.Context.getAsArrayType(Ty), S);
9195       break;
9196     }
9197 
9198     case SK_ObjCObjectConversion:
9199       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9200                           CK_ObjCObjectLValueCast,
9201                           CurInit.get()->getValueKind());
9202       break;
9203 
9204     case SK_ArrayLoopIndex: {
9205       Expr *Cur = CurInit.get();
9206       Expr *BaseExpr = new (S.Context)
9207           OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9208                           Cur->getValueKind(), Cur->getObjectKind(), Cur);
9209       Expr *IndexExpr =
9210           new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
9211       CurInit = S.CreateBuiltinArraySubscriptExpr(
9212           BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9213       ArrayLoopCommonExprs.push_back(BaseExpr);
9214       break;
9215     }
9216 
9217     case SK_ArrayLoopInit: {
9218       assert(!ArrayLoopCommonExprs.empty() &&
9219              "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9220       Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9221       CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9222                                                   CurInit.get());
9223       break;
9224     }
9225 
9226     case SK_GNUArrayInit:
9227       // Okay: we checked everything before creating this step. Note that
9228       // this is a GNU extension.
9229       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9230         << Step->Type << CurInit.get()->getType()
9231         << CurInit.get()->getSourceRange();
9232       updateGNUCompoundLiteralRValue(CurInit.get());
9233       [[fallthrough]];
9234     case SK_ArrayInit:
9235       // If the destination type is an incomplete array type, update the
9236       // type accordingly.
9237       if (ResultType) {
9238         if (const IncompleteArrayType *IncompleteDest
9239                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
9240           if (const ConstantArrayType *ConstantSource
9241                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9242             *ResultType = S.Context.getConstantArrayType(
9243                 IncompleteDest->getElementType(), ConstantSource->getSize(),
9244                 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9245           }
9246         }
9247       }
9248       break;
9249 
9250     case SK_ParenthesizedArrayInit:
9251       // Okay: we checked everything before creating this step. Note that
9252       // this is a GNU extension.
9253       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9254         << CurInit.get()->getSourceRange();
9255       break;
9256 
9257     case SK_PassByIndirectCopyRestore:
9258     case SK_PassByIndirectRestore:
9259       checkIndirectCopyRestoreSource(S, CurInit.get());
9260       CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9261           CurInit.get(), Step->Type,
9262           Step->Kind == SK_PassByIndirectCopyRestore);
9263       break;
9264 
9265     case SK_ProduceObjCObject:
9266       CurInit = ImplicitCastExpr::Create(
9267           S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9268           VK_PRValue, FPOptionsOverride());
9269       break;
9270 
9271     case SK_StdInitializerList: {
9272       S.Diag(CurInit.get()->getExprLoc(),
9273              diag::warn_cxx98_compat_initializer_list_init)
9274         << CurInit.get()->getSourceRange();
9275 
9276       // Materialize the temporary into memory.
9277       MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
9278           CurInit.get()->getType(), CurInit.get(),
9279           /*BoundToLvalueReference=*/false);
9280 
9281       // Wrap it in a construction of a std::initializer_list<T>.
9282       CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9283 
9284       // Bind the result, in case the library has given initializer_list a
9285       // non-trivial destructor.
9286       if (shouldBindAsTemporary(Entity))
9287         CurInit = S.MaybeBindToTemporary(CurInit.get());
9288       break;
9289     }
9290 
9291     case SK_OCLSamplerInit: {
9292       // Sampler initialization have 5 cases:
9293       //   1. function argument passing
9294       //      1a. argument is a file-scope variable
9295       //      1b. argument is a function-scope variable
9296       //      1c. argument is one of caller function's parameters
9297       //   2. variable initialization
9298       //      2a. initializing a file-scope variable
9299       //      2b. initializing a function-scope variable
9300       //
9301       // For file-scope variables, since they cannot be initialized by function
9302       // call of __translate_sampler_initializer in LLVM IR, their references
9303       // need to be replaced by a cast from their literal initializers to
9304       // sampler type. Since sampler variables can only be used in function
9305       // calls as arguments, we only need to replace them when handling the
9306       // argument passing.
9307       assert(Step->Type->isSamplerT() &&
9308              "Sampler initialization on non-sampler type.");
9309       Expr *Init = CurInit.get()->IgnoreParens();
9310       QualType SourceType = Init->getType();
9311       // Case 1
9312       if (Entity.isParameterKind()) {
9313         if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9314           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9315             << SourceType;
9316           break;
9317         } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9318           auto Var = cast<VarDecl>(DRE->getDecl());
9319           // Case 1b and 1c
9320           // No cast from integer to sampler is needed.
9321           if (!Var->hasGlobalStorage()) {
9322             CurInit = ImplicitCastExpr::Create(
9323                 S.Context, Step->Type, CK_LValueToRValue, Init,
9324                 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9325             break;
9326           }
9327           // Case 1a
9328           // For function call with a file-scope sampler variable as argument,
9329           // get the integer literal.
9330           // Do not diagnose if the file-scope variable does not have initializer
9331           // since this has already been diagnosed when parsing the variable
9332           // declaration.
9333           if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9334             break;
9335           Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9336             Var->getInit()))->getSubExpr();
9337           SourceType = Init->getType();
9338         }
9339       } else {
9340         // Case 2
9341         // Check initializer is 32 bit integer constant.
9342         // If the initializer is taken from global variable, do not diagnose since
9343         // this has already been done when parsing the variable declaration.
9344         if (!Init->isConstantInitializer(S.Context, false))
9345           break;
9346 
9347         if (!SourceType->isIntegerType() ||
9348             32 != S.Context.getIntWidth(SourceType)) {
9349           S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9350             << SourceType;
9351           break;
9352         }
9353 
9354         Expr::EvalResult EVResult;
9355         Init->EvaluateAsInt(EVResult, S.Context);
9356         llvm::APSInt Result = EVResult.Val.getInt();
9357         const uint64_t SamplerValue = Result.getLimitedValue();
9358         // 32-bit value of sampler's initializer is interpreted as
9359         // bit-field with the following structure:
9360         // |unspecified|Filter|Addressing Mode| Normalized Coords|
9361         // |31        6|5    4|3             1|                 0|
9362         // This structure corresponds to enum values of sampler properties
9363         // defined in SPIR spec v1.2 and also opencl-c.h
9364         unsigned AddressingMode  = (0x0E & SamplerValue) >> 1;
9365         unsigned FilterMode      = (0x30 & SamplerValue) >> 4;
9366         if (FilterMode != 1 && FilterMode != 2 &&
9367             !S.getOpenCLOptions().isAvailableOption(
9368                 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9369           S.Diag(Kind.getLocation(),
9370                  diag::warn_sampler_initializer_invalid_bits)
9371                  << "Filter Mode";
9372         if (AddressingMode > 4)
9373           S.Diag(Kind.getLocation(),
9374                  diag::warn_sampler_initializer_invalid_bits)
9375                  << "Addressing Mode";
9376       }
9377 
9378       // Cases 1a, 2a and 2b
9379       // Insert cast from integer to sampler.
9380       CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
9381                                       CK_IntToOCLSampler);
9382       break;
9383     }
9384     case SK_OCLZeroOpaqueType: {
9385       assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9386               Step->Type->isOCLIntelSubgroupAVCType()) &&
9387              "Wrong type for initialization of OpenCL opaque type.");
9388 
9389       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9390                                     CK_ZeroToOCLOpaqueType,
9391                                     CurInit.get()->getValueKind());
9392       break;
9393     }
9394     case SK_ParenthesizedListInit: {
9395       CurInit = nullptr;
9396       TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9397                                         /*VerifyOnly=*/false, &CurInit);
9398       if (CurInit.get() && ResultType)
9399         *ResultType = CurInit.get()->getType();
9400       if (shouldBindAsTemporary(Entity))
9401         CurInit = S.MaybeBindToTemporary(CurInit.get());
9402       break;
9403     }
9404     }
9405   }
9406 
9407   Expr *Init = CurInit.get();
9408   if (!Init)
9409     return ExprError();
9410 
9411   // Check whether the initializer has a shorter lifetime than the initialized
9412   // entity, and if not, either lifetime-extend or warn as appropriate.
9413   S.checkInitializerLifetime(Entity, Init);
9414 
9415   // Diagnose non-fatal problems with the completed initialization.
9416   if (InitializedEntity::EntityKind EK = Entity.getKind();
9417       (EK == InitializedEntity::EK_Member ||
9418        EK == InitializedEntity::EK_ParenAggInitMember) &&
9419       cast<FieldDecl>(Entity.getDecl())->isBitField())
9420     S.CheckBitFieldInitialization(Kind.getLocation(),
9421                                   cast<FieldDecl>(Entity.getDecl()), Init);
9422 
9423   // Check for std::move on construction.
9424   CheckMoveOnConstruction(S, Init,
9425                           Entity.getKind() == InitializedEntity::EK_Result);
9426 
9427   return Init;
9428 }
9429 
9430 /// Somewhere within T there is an uninitialized reference subobject.
9431 /// Dig it out and diagnose it.
9432 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
9433                                            QualType T) {
9434   if (T->isReferenceType()) {
9435     S.Diag(Loc, diag::err_reference_without_init)
9436       << T.getNonReferenceType();
9437     return true;
9438   }
9439 
9440   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
9441   if (!RD || !RD->hasUninitializedReferenceMember())
9442     return false;
9443 
9444   for (const auto *FI : RD->fields()) {
9445     if (FI->isUnnamedBitfield())
9446       continue;
9447 
9448     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9449       S.Diag(Loc, diag::note_value_initialization_here) << RD;
9450       return true;
9451     }
9452   }
9453 
9454   for (const auto &BI : RD->bases()) {
9455     if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9456       S.Diag(Loc, diag::note_value_initialization_here) << RD;
9457       return true;
9458     }
9459   }
9460 
9461   return false;
9462 }
9463 
9464 
9465 //===----------------------------------------------------------------------===//
9466 // Diagnose initialization failures
9467 //===----------------------------------------------------------------------===//
9468 
9469 /// Emit notes associated with an initialization that failed due to a
9470 /// "simple" conversion failure.
9471 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9472                                    Expr *op) {
9473   QualType destType = entity.getType();
9474   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9475       op->getType()->isObjCObjectPointerType()) {
9476 
9477     // Emit a possible note about the conversion failing because the
9478     // operand is a message send with a related result type.
9479     S.EmitRelatedResultTypeNote(op);
9480 
9481     // Emit a possible note about a return failing because we're
9482     // expecting a related result type.
9483     if (entity.getKind() == InitializedEntity::EK_Result)
9484       S.EmitRelatedResultTypeNoteForReturn(destType);
9485   }
9486   QualType fromType = op->getType();
9487   QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9488   QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9489   auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9490   auto *destDecl = destType->getPointeeCXXRecordDecl();
9491   if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9492       destDecl->getDeclKind() == Decl::CXXRecord &&
9493       !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9494       !fromDecl->hasDefinition() &&
9495       destPointeeType.getQualifiers().compatiblyIncludes(
9496           fromPointeeType.getQualifiers()))
9497     S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9498         << S.getASTContext().getTagDeclType(fromDecl)
9499         << S.getASTContext().getTagDeclType(destDecl);
9500 }
9501 
9502 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9503                              InitListExpr *InitList) {
9504   QualType DestType = Entity.getType();
9505 
9506   QualType E;
9507   if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9508     QualType ArrayType = S.Context.getConstantArrayType(
9509         E.withConst(),
9510         llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9511                     InitList->getNumInits()),
9512         nullptr, clang::ArraySizeModifier::Normal, 0);
9513     InitializedEntity HiddenArray =
9514         InitializedEntity::InitializeTemporary(ArrayType);
9515     return diagnoseListInit(S, HiddenArray, InitList);
9516   }
9517 
9518   if (DestType->isReferenceType()) {
9519     // A list-initialization failure for a reference means that we tried to
9520     // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9521     // inner initialization failed.
9522     QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9523     diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
9524     SourceLocation Loc = InitList->getBeginLoc();
9525     if (auto *D = Entity.getDecl())
9526       Loc = D->getLocation();
9527     S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9528     return;
9529   }
9530 
9531   InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9532                                    /*VerifyOnly=*/false,
9533                                    /*TreatUnavailableAsInvalid=*/false);
9534   assert(DiagnoseInitList.HadError() &&
9535          "Inconsistent init list check result.");
9536 }
9537 
9538 bool InitializationSequence::Diagnose(Sema &S,
9539                                       const InitializedEntity &Entity,
9540                                       const InitializationKind &Kind,
9541                                       ArrayRef<Expr *> Args) {
9542   if (!Failed())
9543     return false;
9544 
9545   // When we want to diagnose only one element of a braced-init-list,
9546   // we need to factor it out.
9547   Expr *OnlyArg;
9548   if (Args.size() == 1) {
9549     auto *List = dyn_cast<InitListExpr>(Args[0]);
9550     if (List && List->getNumInits() == 1)
9551       OnlyArg = List->getInit(0);
9552     else
9553       OnlyArg = Args[0];
9554   }
9555   else
9556     OnlyArg = nullptr;
9557 
9558   QualType DestType = Entity.getType();
9559   switch (Failure) {
9560   case FK_TooManyInitsForReference:
9561     // FIXME: Customize for the initialized entity?
9562     if (Args.empty()) {
9563       // Dig out the reference subobject which is uninitialized and diagnose it.
9564       // If this is value-initialization, this could be nested some way within
9565       // the target type.
9566       assert(Kind.getKind() == InitializationKind::IK_Value ||
9567              DestType->isReferenceType());
9568       bool Diagnosed =
9569         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9570       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9571       (void)Diagnosed;
9572     } else  // FIXME: diagnostic below could be better!
9573       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9574           << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9575     break;
9576   case FK_ParenthesizedListInitForReference:
9577     S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9578       << 1 << Entity.getType() << Args[0]->getSourceRange();
9579     break;
9580 
9581   case FK_ArrayNeedsInitList:
9582     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9583     break;
9584   case FK_ArrayNeedsInitListOrStringLiteral:
9585     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9586     break;
9587   case FK_ArrayNeedsInitListOrWideStringLiteral:
9588     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9589     break;
9590   case FK_NarrowStringIntoWideCharArray:
9591     S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9592     break;
9593   case FK_WideStringIntoCharArray:
9594     S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9595     break;
9596   case FK_IncompatWideStringIntoWideChar:
9597     S.Diag(Kind.getLocation(),
9598            diag::err_array_init_incompat_wide_string_into_wchar);
9599     break;
9600   case FK_PlainStringIntoUTF8Char:
9601     S.Diag(Kind.getLocation(),
9602            diag::err_array_init_plain_string_into_char8_t);
9603     S.Diag(Args.front()->getBeginLoc(),
9604            diag::note_array_init_plain_string_into_char8_t)
9605         << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9606     break;
9607   case FK_UTF8StringIntoPlainChar:
9608     S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9609         << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9610     break;
9611   case FK_ArrayTypeMismatch:
9612   case FK_NonConstantArrayInit:
9613     S.Diag(Kind.getLocation(),
9614            (Failure == FK_ArrayTypeMismatch
9615               ? diag::err_array_init_different_type
9616               : diag::err_array_init_non_constant_array))
9617       << DestType.getNonReferenceType()
9618       << OnlyArg->getType()
9619       << Args[0]->getSourceRange();
9620     break;
9621 
9622   case FK_VariableLengthArrayHasInitializer:
9623     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9624       << Args[0]->getSourceRange();
9625     break;
9626 
9627   case FK_AddressOfOverloadFailed: {
9628     DeclAccessPair Found;
9629     S.ResolveAddressOfOverloadedFunction(OnlyArg,
9630                                          DestType.getNonReferenceType(),
9631                                          true,
9632                                          Found);
9633     break;
9634   }
9635 
9636   case FK_AddressOfUnaddressableFunction: {
9637     auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9638     S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9639                                         OnlyArg->getBeginLoc());
9640     break;
9641   }
9642 
9643   case FK_ReferenceInitOverloadFailed:
9644   case FK_UserConversionOverloadFailed:
9645     switch (FailedOverloadResult) {
9646     case OR_Ambiguous:
9647 
9648       FailedCandidateSet.NoteCandidates(
9649           PartialDiagnosticAt(
9650               Kind.getLocation(),
9651               Failure == FK_UserConversionOverloadFailed
9652                   ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9653                      << OnlyArg->getType() << DestType
9654                      << Args[0]->getSourceRange())
9655                   : (S.PDiag(diag::err_ref_init_ambiguous)
9656                      << DestType << OnlyArg->getType()
9657                      << Args[0]->getSourceRange())),
9658           S, OCD_AmbiguousCandidates, Args);
9659       break;
9660 
9661     case OR_No_Viable_Function: {
9662       auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9663       if (!S.RequireCompleteType(Kind.getLocation(),
9664                                  DestType.getNonReferenceType(),
9665                           diag::err_typecheck_nonviable_condition_incomplete,
9666                                OnlyArg->getType(), Args[0]->getSourceRange()))
9667         S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9668           << (Entity.getKind() == InitializedEntity::EK_Result)
9669           << OnlyArg->getType() << Args[0]->getSourceRange()
9670           << DestType.getNonReferenceType();
9671 
9672       FailedCandidateSet.NoteCandidates(S, Args, Cands);
9673       break;
9674     }
9675     case OR_Deleted: {
9676       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9677         << OnlyArg->getType() << DestType.getNonReferenceType()
9678         << Args[0]->getSourceRange();
9679       OverloadCandidateSet::iterator Best;
9680       OverloadingResult Ovl
9681         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9682       if (Ovl == OR_Deleted) {
9683         S.NoteDeletedFunction(Best->Function);
9684       } else {
9685         llvm_unreachable("Inconsistent overload resolution?");
9686       }
9687       break;
9688     }
9689 
9690     case OR_Success:
9691       llvm_unreachable("Conversion did not fail!");
9692     }
9693     break;
9694 
9695   case FK_NonConstLValueReferenceBindingToTemporary:
9696     if (isa<InitListExpr>(Args[0])) {
9697       S.Diag(Kind.getLocation(),
9698              diag::err_lvalue_reference_bind_to_initlist)
9699       << DestType.getNonReferenceType().isVolatileQualified()
9700       << DestType.getNonReferenceType()
9701       << Args[0]->getSourceRange();
9702       break;
9703     }
9704     [[fallthrough]];
9705 
9706   case FK_NonConstLValueReferenceBindingToUnrelated:
9707     S.Diag(Kind.getLocation(),
9708            Failure == FK_NonConstLValueReferenceBindingToTemporary
9709              ? diag::err_lvalue_reference_bind_to_temporary
9710              : diag::err_lvalue_reference_bind_to_unrelated)
9711       << DestType.getNonReferenceType().isVolatileQualified()
9712       << DestType.getNonReferenceType()
9713       << OnlyArg->getType()
9714       << Args[0]->getSourceRange();
9715     break;
9716 
9717   case FK_NonConstLValueReferenceBindingToBitfield: {
9718     // We don't necessarily have an unambiguous source bit-field.
9719     FieldDecl *BitField = Args[0]->getSourceBitField();
9720     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9721       << DestType.isVolatileQualified()
9722       << (BitField ? BitField->getDeclName() : DeclarationName())
9723       << (BitField != nullptr)
9724       << Args[0]->getSourceRange();
9725     if (BitField)
9726       S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9727     break;
9728   }
9729 
9730   case FK_NonConstLValueReferenceBindingToVectorElement:
9731     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9732       << DestType.isVolatileQualified()
9733       << Args[0]->getSourceRange();
9734     break;
9735 
9736   case FK_NonConstLValueReferenceBindingToMatrixElement:
9737     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9738         << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9739     break;
9740 
9741   case FK_RValueReferenceBindingToLValue:
9742     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9743       << DestType.getNonReferenceType() << OnlyArg->getType()
9744       << Args[0]->getSourceRange();
9745     break;
9746 
9747   case FK_ReferenceAddrspaceMismatchTemporary:
9748     S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9749         << DestType << Args[0]->getSourceRange();
9750     break;
9751 
9752   case FK_ReferenceInitDropsQualifiers: {
9753     QualType SourceType = OnlyArg->getType();
9754     QualType NonRefType = DestType.getNonReferenceType();
9755     Qualifiers DroppedQualifiers =
9756         SourceType.getQualifiers() - NonRefType.getQualifiers();
9757 
9758     if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9759             SourceType.getQualifiers()))
9760       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9761           << NonRefType << SourceType << 1 /*addr space*/
9762           << Args[0]->getSourceRange();
9763     else if (DroppedQualifiers.hasQualifiers())
9764       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9765           << NonRefType << SourceType << 0 /*cv quals*/
9766           << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9767           << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9768     else
9769       // FIXME: Consider decomposing the type and explaining which qualifiers
9770       // were dropped where, or on which level a 'const' is missing, etc.
9771       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9772           << NonRefType << SourceType << 2 /*incompatible quals*/
9773           << Args[0]->getSourceRange();
9774     break;
9775   }
9776 
9777   case FK_ReferenceInitFailed:
9778     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9779       << DestType.getNonReferenceType()
9780       << DestType.getNonReferenceType()->isIncompleteType()
9781       << OnlyArg->isLValue()
9782       << OnlyArg->getType()
9783       << Args[0]->getSourceRange();
9784     emitBadConversionNotes(S, Entity, Args[0]);
9785     break;
9786 
9787   case FK_ConversionFailed: {
9788     QualType FromType = OnlyArg->getType();
9789     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9790       << (int)Entity.getKind()
9791       << DestType
9792       << OnlyArg->isLValue()
9793       << FromType
9794       << Args[0]->getSourceRange();
9795     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9796     S.Diag(Kind.getLocation(), PDiag);
9797     emitBadConversionNotes(S, Entity, Args[0]);
9798     break;
9799   }
9800 
9801   case FK_ConversionFromPropertyFailed:
9802     // No-op. This error has already been reported.
9803     break;
9804 
9805   case FK_TooManyInitsForScalar: {
9806     SourceRange R;
9807 
9808     auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9809     if (InitList && InitList->getNumInits() >= 1) {
9810       R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9811     } else {
9812       assert(Args.size() > 1 && "Expected multiple initializers!");
9813       R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9814     }
9815 
9816     R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9817     if (Kind.isCStyleOrFunctionalCast())
9818       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9819         << R;
9820     else
9821       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9822         << /*scalar=*/2 << R;
9823     break;
9824   }
9825 
9826   case FK_ParenthesizedListInitForScalar:
9827     S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9828       << 0 << Entity.getType() << Args[0]->getSourceRange();
9829     break;
9830 
9831   case FK_ReferenceBindingToInitList:
9832     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9833       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9834     break;
9835 
9836   case FK_InitListBadDestinationType:
9837     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9838       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9839     break;
9840 
9841   case FK_ListConstructorOverloadFailed:
9842   case FK_ConstructorOverloadFailed: {
9843     SourceRange ArgsRange;
9844     if (Args.size())
9845       ArgsRange =
9846           SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9847 
9848     if (Failure == FK_ListConstructorOverloadFailed) {
9849       assert(Args.size() == 1 &&
9850              "List construction from other than 1 argument.");
9851       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9852       Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9853     }
9854 
9855     // FIXME: Using "DestType" for the entity we're printing is probably
9856     // bad.
9857     switch (FailedOverloadResult) {
9858       case OR_Ambiguous:
9859         FailedCandidateSet.NoteCandidates(
9860             PartialDiagnosticAt(Kind.getLocation(),
9861                                 S.PDiag(diag::err_ovl_ambiguous_init)
9862                                     << DestType << ArgsRange),
9863             S, OCD_AmbiguousCandidates, Args);
9864         break;
9865 
9866       case OR_No_Viable_Function:
9867         if (Kind.getKind() == InitializationKind::IK_Default &&
9868             (Entity.getKind() == InitializedEntity::EK_Base ||
9869              Entity.getKind() == InitializedEntity::EK_Member ||
9870              Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9871             isa<CXXConstructorDecl>(S.CurContext)) {
9872           // This is implicit default initialization of a member or
9873           // base within a constructor. If no viable function was
9874           // found, notify the user that they need to explicitly
9875           // initialize this base/member.
9876           CXXConstructorDecl *Constructor
9877             = cast<CXXConstructorDecl>(S.CurContext);
9878           const CXXRecordDecl *InheritedFrom = nullptr;
9879           if (auto Inherited = Constructor->getInheritedConstructor())
9880             InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9881           if (Entity.getKind() == InitializedEntity::EK_Base) {
9882             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9883               << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9884               << S.Context.getTypeDeclType(Constructor->getParent())
9885               << /*base=*/0
9886               << Entity.getType()
9887               << InheritedFrom;
9888 
9889             RecordDecl *BaseDecl
9890               = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9891                                                                   ->getDecl();
9892             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9893               << S.Context.getTagDeclType(BaseDecl);
9894           } else {
9895             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9896               << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9897               << S.Context.getTypeDeclType(Constructor->getParent())
9898               << /*member=*/1
9899               << Entity.getName()
9900               << InheritedFrom;
9901             S.Diag(Entity.getDecl()->getLocation(),
9902                    diag::note_member_declared_at);
9903 
9904             if (const RecordType *Record
9905                                  = Entity.getType()->getAs<RecordType>())
9906               S.Diag(Record->getDecl()->getLocation(),
9907                      diag::note_previous_decl)
9908                 << S.Context.getTagDeclType(Record->getDecl());
9909           }
9910           break;
9911         }
9912 
9913         FailedCandidateSet.NoteCandidates(
9914             PartialDiagnosticAt(
9915                 Kind.getLocation(),
9916                 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9917                     << DestType << ArgsRange),
9918             S, OCD_AllCandidates, Args);
9919         break;
9920 
9921       case OR_Deleted: {
9922         OverloadCandidateSet::iterator Best;
9923         OverloadingResult Ovl
9924           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9925         if (Ovl != OR_Deleted) {
9926           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9927               << DestType << ArgsRange;
9928           llvm_unreachable("Inconsistent overload resolution?");
9929           break;
9930         }
9931 
9932         // If this is a defaulted or implicitly-declared function, then
9933         // it was implicitly deleted. Make it clear that the deletion was
9934         // implicit.
9935         if (S.isImplicitlyDeleted(Best->Function))
9936           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9937             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9938             << DestType << ArgsRange;
9939         else
9940           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9941               << DestType << ArgsRange;
9942 
9943         S.NoteDeletedFunction(Best->Function);
9944         break;
9945       }
9946 
9947       case OR_Success:
9948         llvm_unreachable("Conversion did not fail!");
9949     }
9950   }
9951   break;
9952 
9953   case FK_DefaultInitOfConst:
9954     if (Entity.getKind() == InitializedEntity::EK_Member &&
9955         isa<CXXConstructorDecl>(S.CurContext)) {
9956       // This is implicit default-initialization of a const member in
9957       // a constructor. Complain that it needs to be explicitly
9958       // initialized.
9959       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9960       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9961         << (Constructor->getInheritedConstructor() ? 2 :
9962             Constructor->isImplicit() ? 1 : 0)
9963         << S.Context.getTypeDeclType(Constructor->getParent())
9964         << /*const=*/1
9965         << Entity.getName();
9966       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9967         << Entity.getName();
9968     } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9969                VD && VD->isConstexpr()) {
9970       S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9971           << VD;
9972     } else {
9973       S.Diag(Kind.getLocation(), diag::err_default_init_const)
9974           << DestType << (bool)DestType->getAs<RecordType>();
9975     }
9976     break;
9977 
9978   case FK_Incomplete:
9979     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9980                           diag::err_init_incomplete_type);
9981     break;
9982 
9983   case FK_ListInitializationFailed: {
9984     // Run the init list checker again to emit diagnostics.
9985     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9986     diagnoseListInit(S, Entity, InitList);
9987     break;
9988   }
9989 
9990   case FK_PlaceholderType: {
9991     // FIXME: Already diagnosed!
9992     break;
9993   }
9994 
9995   case FK_ExplicitConstructor: {
9996     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9997       << Args[0]->getSourceRange();
9998     OverloadCandidateSet::iterator Best;
9999     OverloadingResult Ovl
10000       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10001     (void)Ovl;
10002     assert(Ovl == OR_Success && "Inconsistent overload resolution");
10003     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10004     S.Diag(CtorDecl->getLocation(),
10005            diag::note_explicit_ctor_deduction_guide_here) << false;
10006     break;
10007   }
10008 
10009   case FK_ParenthesizedListInitFailed:
10010     TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10011                                       /*VerifyOnly=*/false);
10012     break;
10013 
10014   case FK_DesignatedInitForNonAggregate:
10015     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10016     S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10017         << Entity.getType() << InitList->getSourceRange();
10018     break;
10019   }
10020 
10021   PrintInitLocationNote(S, Entity);
10022   return true;
10023 }
10024 
10025 void InitializationSequence::dump(raw_ostream &OS) const {
10026   switch (SequenceKind) {
10027   case FailedSequence: {
10028     OS << "Failed sequence: ";
10029     switch (Failure) {
10030     case FK_TooManyInitsForReference:
10031       OS << "too many initializers for reference";
10032       break;
10033 
10034     case FK_ParenthesizedListInitForReference:
10035       OS << "parenthesized list init for reference";
10036       break;
10037 
10038     case FK_ArrayNeedsInitList:
10039       OS << "array requires initializer list";
10040       break;
10041 
10042     case FK_AddressOfUnaddressableFunction:
10043       OS << "address of unaddressable function was taken";
10044       break;
10045 
10046     case FK_ArrayNeedsInitListOrStringLiteral:
10047       OS << "array requires initializer list or string literal";
10048       break;
10049 
10050     case FK_ArrayNeedsInitListOrWideStringLiteral:
10051       OS << "array requires initializer list or wide string literal";
10052       break;
10053 
10054     case FK_NarrowStringIntoWideCharArray:
10055       OS << "narrow string into wide char array";
10056       break;
10057 
10058     case FK_WideStringIntoCharArray:
10059       OS << "wide string into char array";
10060       break;
10061 
10062     case FK_IncompatWideStringIntoWideChar:
10063       OS << "incompatible wide string into wide char array";
10064       break;
10065 
10066     case FK_PlainStringIntoUTF8Char:
10067       OS << "plain string literal into char8_t array";
10068       break;
10069 
10070     case FK_UTF8StringIntoPlainChar:
10071       OS << "u8 string literal into char array";
10072       break;
10073 
10074     case FK_ArrayTypeMismatch:
10075       OS << "array type mismatch";
10076       break;
10077 
10078     case FK_NonConstantArrayInit:
10079       OS << "non-constant array initializer";
10080       break;
10081 
10082     case FK_AddressOfOverloadFailed:
10083       OS << "address of overloaded function failed";
10084       break;
10085 
10086     case FK_ReferenceInitOverloadFailed:
10087       OS << "overload resolution for reference initialization failed";
10088       break;
10089 
10090     case FK_NonConstLValueReferenceBindingToTemporary:
10091       OS << "non-const lvalue reference bound to temporary";
10092       break;
10093 
10094     case FK_NonConstLValueReferenceBindingToBitfield:
10095       OS << "non-const lvalue reference bound to bit-field";
10096       break;
10097 
10098     case FK_NonConstLValueReferenceBindingToVectorElement:
10099       OS << "non-const lvalue reference bound to vector element";
10100       break;
10101 
10102     case FK_NonConstLValueReferenceBindingToMatrixElement:
10103       OS << "non-const lvalue reference bound to matrix element";
10104       break;
10105 
10106     case FK_NonConstLValueReferenceBindingToUnrelated:
10107       OS << "non-const lvalue reference bound to unrelated type";
10108       break;
10109 
10110     case FK_RValueReferenceBindingToLValue:
10111       OS << "rvalue reference bound to an lvalue";
10112       break;
10113 
10114     case FK_ReferenceInitDropsQualifiers:
10115       OS << "reference initialization drops qualifiers";
10116       break;
10117 
10118     case FK_ReferenceAddrspaceMismatchTemporary:
10119       OS << "reference with mismatching address space bound to temporary";
10120       break;
10121 
10122     case FK_ReferenceInitFailed:
10123       OS << "reference initialization failed";
10124       break;
10125 
10126     case FK_ConversionFailed:
10127       OS << "conversion failed";
10128       break;
10129 
10130     case FK_ConversionFromPropertyFailed:
10131       OS << "conversion from property failed";
10132       break;
10133 
10134     case FK_TooManyInitsForScalar:
10135       OS << "too many initializers for scalar";
10136       break;
10137 
10138     case FK_ParenthesizedListInitForScalar:
10139       OS << "parenthesized list init for reference";
10140       break;
10141 
10142     case FK_ReferenceBindingToInitList:
10143       OS << "referencing binding to initializer list";
10144       break;
10145 
10146     case FK_InitListBadDestinationType:
10147       OS << "initializer list for non-aggregate, non-scalar type";
10148       break;
10149 
10150     case FK_UserConversionOverloadFailed:
10151       OS << "overloading failed for user-defined conversion";
10152       break;
10153 
10154     case FK_ConstructorOverloadFailed:
10155       OS << "constructor overloading failed";
10156       break;
10157 
10158     case FK_DefaultInitOfConst:
10159       OS << "default initialization of a const variable";
10160       break;
10161 
10162     case FK_Incomplete:
10163       OS << "initialization of incomplete type";
10164       break;
10165 
10166     case FK_ListInitializationFailed:
10167       OS << "list initialization checker failure";
10168       break;
10169 
10170     case FK_VariableLengthArrayHasInitializer:
10171       OS << "variable length array has an initializer";
10172       break;
10173 
10174     case FK_PlaceholderType:
10175       OS << "initializer expression isn't contextually valid";
10176       break;
10177 
10178     case FK_ListConstructorOverloadFailed:
10179       OS << "list constructor overloading failed";
10180       break;
10181 
10182     case FK_ExplicitConstructor:
10183       OS << "list copy initialization chose explicit constructor";
10184       break;
10185 
10186     case FK_ParenthesizedListInitFailed:
10187       OS << "parenthesized list initialization failed";
10188       break;
10189 
10190     case FK_DesignatedInitForNonAggregate:
10191       OS << "designated initializer for non-aggregate type";
10192       break;
10193     }
10194     OS << '\n';
10195     return;
10196   }
10197 
10198   case DependentSequence:
10199     OS << "Dependent sequence\n";
10200     return;
10201 
10202   case NormalSequence:
10203     OS << "Normal sequence: ";
10204     break;
10205   }
10206 
10207   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10208     if (S != step_begin()) {
10209       OS << " -> ";
10210     }
10211 
10212     switch (S->Kind) {
10213     case SK_ResolveAddressOfOverloadedFunction:
10214       OS << "resolve address of overloaded function";
10215       break;
10216 
10217     case SK_CastDerivedToBasePRValue:
10218       OS << "derived-to-base (prvalue)";
10219       break;
10220 
10221     case SK_CastDerivedToBaseXValue:
10222       OS << "derived-to-base (xvalue)";
10223       break;
10224 
10225     case SK_CastDerivedToBaseLValue:
10226       OS << "derived-to-base (lvalue)";
10227       break;
10228 
10229     case SK_BindReference:
10230       OS << "bind reference to lvalue";
10231       break;
10232 
10233     case SK_BindReferenceToTemporary:
10234       OS << "bind reference to a temporary";
10235       break;
10236 
10237     case SK_FinalCopy:
10238       OS << "final copy in class direct-initialization";
10239       break;
10240 
10241     case SK_ExtraneousCopyToTemporary:
10242       OS << "extraneous C++03 copy to temporary";
10243       break;
10244 
10245     case SK_UserConversion:
10246       OS << "user-defined conversion via " << *S->Function.Function;
10247       break;
10248 
10249     case SK_QualificationConversionPRValue:
10250       OS << "qualification conversion (prvalue)";
10251       break;
10252 
10253     case SK_QualificationConversionXValue:
10254       OS << "qualification conversion (xvalue)";
10255       break;
10256 
10257     case SK_QualificationConversionLValue:
10258       OS << "qualification conversion (lvalue)";
10259       break;
10260 
10261     case SK_FunctionReferenceConversion:
10262       OS << "function reference conversion";
10263       break;
10264 
10265     case SK_AtomicConversion:
10266       OS << "non-atomic-to-atomic conversion";
10267       break;
10268 
10269     case SK_ConversionSequence:
10270       OS << "implicit conversion sequence (";
10271       S->ICS->dump(); // FIXME: use OS
10272       OS << ")";
10273       break;
10274 
10275     case SK_ConversionSequenceNoNarrowing:
10276       OS << "implicit conversion sequence with narrowing prohibited (";
10277       S->ICS->dump(); // FIXME: use OS
10278       OS << ")";
10279       break;
10280 
10281     case SK_ListInitialization:
10282       OS << "list aggregate initialization";
10283       break;
10284 
10285     case SK_UnwrapInitList:
10286       OS << "unwrap reference initializer list";
10287       break;
10288 
10289     case SK_RewrapInitList:
10290       OS << "rewrap reference initializer list";
10291       break;
10292 
10293     case SK_ConstructorInitialization:
10294       OS << "constructor initialization";
10295       break;
10296 
10297     case SK_ConstructorInitializationFromList:
10298       OS << "list initialization via constructor";
10299       break;
10300 
10301     case SK_ZeroInitialization:
10302       OS << "zero initialization";
10303       break;
10304 
10305     case SK_CAssignment:
10306       OS << "C assignment";
10307       break;
10308 
10309     case SK_StringInit:
10310       OS << "string initialization";
10311       break;
10312 
10313     case SK_ObjCObjectConversion:
10314       OS << "Objective-C object conversion";
10315       break;
10316 
10317     case SK_ArrayLoopIndex:
10318       OS << "indexing for array initialization loop";
10319       break;
10320 
10321     case SK_ArrayLoopInit:
10322       OS << "array initialization loop";
10323       break;
10324 
10325     case SK_ArrayInit:
10326       OS << "array initialization";
10327       break;
10328 
10329     case SK_GNUArrayInit:
10330       OS << "array initialization (GNU extension)";
10331       break;
10332 
10333     case SK_ParenthesizedArrayInit:
10334       OS << "parenthesized array initialization";
10335       break;
10336 
10337     case SK_PassByIndirectCopyRestore:
10338       OS << "pass by indirect copy and restore";
10339       break;
10340 
10341     case SK_PassByIndirectRestore:
10342       OS << "pass by indirect restore";
10343       break;
10344 
10345     case SK_ProduceObjCObject:
10346       OS << "Objective-C object retension";
10347       break;
10348 
10349     case SK_StdInitializerList:
10350       OS << "std::initializer_list from initializer list";
10351       break;
10352 
10353     case SK_StdInitializerListConstructorCall:
10354       OS << "list initialization from std::initializer_list";
10355       break;
10356 
10357     case SK_OCLSamplerInit:
10358       OS << "OpenCL sampler_t from integer constant";
10359       break;
10360 
10361     case SK_OCLZeroOpaqueType:
10362       OS << "OpenCL opaque type from zero";
10363       break;
10364     case SK_ParenthesizedListInit:
10365       OS << "initialization from a parenthesized list of values";
10366       break;
10367     }
10368 
10369     OS << " [" << S->Type << ']';
10370   }
10371 
10372   OS << '\n';
10373 }
10374 
10375 void InitializationSequence::dump() const {
10376   dump(llvm::errs());
10377 }
10378 
10379 static bool NarrowingErrs(const LangOptions &L) {
10380   return L.CPlusPlus11 &&
10381          (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
10382 }
10383 
10384 static void DiagnoseNarrowingInInitList(Sema &S,
10385                                         const ImplicitConversionSequence &ICS,
10386                                         QualType PreNarrowingType,
10387                                         QualType EntityType,
10388                                         const Expr *PostInit) {
10389   const StandardConversionSequence *SCS = nullptr;
10390   switch (ICS.getKind()) {
10391   case ImplicitConversionSequence::StandardConversion:
10392     SCS = &ICS.Standard;
10393     break;
10394   case ImplicitConversionSequence::UserDefinedConversion:
10395     SCS = &ICS.UserDefined.After;
10396     break;
10397   case ImplicitConversionSequence::AmbiguousConversion:
10398   case ImplicitConversionSequence::StaticObjectArgumentConversion:
10399   case ImplicitConversionSequence::EllipsisConversion:
10400   case ImplicitConversionSequence::BadConversion:
10401     return;
10402   }
10403 
10404   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10405   APValue ConstantValue;
10406   QualType ConstantType;
10407   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10408                                 ConstantType)) {
10409   case NK_Not_Narrowing:
10410   case NK_Dependent_Narrowing:
10411     // No narrowing occurred.
10412     return;
10413 
10414   case NK_Type_Narrowing: {
10415     // This was a floating-to-integer conversion, which is always considered a
10416     // narrowing conversion even if the value is a constant and can be
10417     // represented exactly as an integer.
10418     QualType T = EntityType.getNonReferenceType();
10419     S.Diag(PostInit->getBeginLoc(),
10420            NarrowingErrs(S.getLangOpts())
10421                ? (T == EntityType
10422                       ? diag::ext_init_list_type_narrowing
10423                       : diag::ext_init_list_type_narrowing_const_reference)
10424                : diag::warn_init_list_type_narrowing)
10425         << PostInit->getSourceRange()
10426         << PreNarrowingType.getLocalUnqualifiedType()
10427         << T.getLocalUnqualifiedType();
10428     break;
10429   }
10430 
10431   case NK_Constant_Narrowing: {
10432     // A constant value was narrowed.
10433     QualType T = EntityType.getNonReferenceType();
10434     S.Diag(PostInit->getBeginLoc(),
10435            NarrowingErrs(S.getLangOpts())
10436                ? (T == EntityType
10437                       ? diag::ext_init_list_constant_narrowing
10438                       : diag::ext_init_list_constant_narrowing_const_reference)
10439                : diag::warn_init_list_constant_narrowing)
10440         << PostInit->getSourceRange()
10441         << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10442         << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10443     break;
10444   }
10445 
10446   case NK_Variable_Narrowing: {
10447     // A variable's value may have been narrowed.
10448     QualType T = EntityType.getNonReferenceType();
10449     S.Diag(PostInit->getBeginLoc(),
10450            NarrowingErrs(S.getLangOpts())
10451                ? (T == EntityType
10452                       ? diag::ext_init_list_variable_narrowing
10453                       : diag::ext_init_list_variable_narrowing_const_reference)
10454                : diag::warn_init_list_variable_narrowing)
10455         << PostInit->getSourceRange()
10456         << PreNarrowingType.getLocalUnqualifiedType()
10457         << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10458     break;
10459   }
10460   }
10461 
10462   SmallString<128> StaticCast;
10463   llvm::raw_svector_ostream OS(StaticCast);
10464   OS << "static_cast<";
10465   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10466     // It's important to use the typedef's name if there is one so that the
10467     // fixit doesn't break code using types like int64_t.
10468     //
10469     // FIXME: This will break if the typedef requires qualification.  But
10470     // getQualifiedNameAsString() includes non-machine-parsable components.
10471     OS << *TT->getDecl();
10472   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10473     OS << BT->getName(S.getLangOpts());
10474   else {
10475     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
10476     // with a broken cast.
10477     return;
10478   }
10479   OS << ">(";
10480   S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10481       << PostInit->getSourceRange()
10482       << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10483       << FixItHint::CreateInsertion(
10484              S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10485 }
10486 
10487 //===----------------------------------------------------------------------===//
10488 // Initialization helper functions
10489 //===----------------------------------------------------------------------===//
10490 bool
10491 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10492                                    ExprResult Init) {
10493   if (Init.isInvalid())
10494     return false;
10495 
10496   Expr *InitE = Init.get();
10497   assert(InitE && "No initialization expression");
10498 
10499   InitializationKind Kind =
10500       InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
10501   InitializationSequence Seq(*this, Entity, Kind, InitE);
10502   return !Seq.Failed();
10503 }
10504 
10505 ExprResult
10506 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10507                                 SourceLocation EqualLoc,
10508                                 ExprResult Init,
10509                                 bool TopLevelOfInitList,
10510                                 bool AllowExplicit) {
10511   if (Init.isInvalid())
10512     return ExprError();
10513 
10514   Expr *InitE = Init.get();
10515   assert(InitE && "No initialization expression?");
10516 
10517   if (EqualLoc.isInvalid())
10518     EqualLoc = InitE->getBeginLoc();
10519 
10520   InitializationKind Kind = InitializationKind::CreateCopy(
10521       InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10522   InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10523 
10524   // Prevent infinite recursion when performing parameter copy-initialization.
10525   const bool ShouldTrackCopy =
10526       Entity.isParameterKind() && Seq.isConstructorInitialization();
10527   if (ShouldTrackCopy) {
10528     if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10529       Seq.SetOverloadFailure(
10530           InitializationSequence::FK_ConstructorOverloadFailed,
10531           OR_No_Viable_Function);
10532 
10533       // Try to give a meaningful diagnostic note for the problematic
10534       // constructor.
10535       const auto LastStep = Seq.step_end() - 1;
10536       assert(LastStep->Kind ==
10537              InitializationSequence::SK_ConstructorInitialization);
10538       const FunctionDecl *Function = LastStep->Function.Function;
10539       auto Candidate =
10540           llvm::find_if(Seq.getFailedCandidateSet(),
10541                         [Function](const OverloadCandidate &Candidate) -> bool {
10542                           return Candidate.Viable &&
10543                                  Candidate.Function == Function &&
10544                                  Candidate.Conversions.size() > 0;
10545                         });
10546       if (Candidate != Seq.getFailedCandidateSet().end() &&
10547           Function->getNumParams() > 0) {
10548         Candidate->Viable = false;
10549         Candidate->FailureKind = ovl_fail_bad_conversion;
10550         Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
10551                                          InitE,
10552                                          Function->getParamDecl(0)->getType());
10553       }
10554     }
10555     CurrentParameterCopyTypes.push_back(Entity.getType());
10556   }
10557 
10558   ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10559 
10560   if (ShouldTrackCopy)
10561     CurrentParameterCopyTypes.pop_back();
10562 
10563   return Result;
10564 }
10565 
10566 /// Determine whether RD is, or is derived from, a specialization of CTD.
10567 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10568                                               ClassTemplateDecl *CTD) {
10569   auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10570     auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10571     return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10572   };
10573   return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10574 }
10575 
10576 QualType Sema::DeduceTemplateSpecializationFromInitializer(
10577     TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10578     const InitializationKind &Kind, MultiExprArg Inits) {
10579   auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10580       TSInfo->getType()->getContainedDeducedType());
10581   assert(DeducedTST && "not a deduced template specialization type");
10582 
10583   auto TemplateName = DeducedTST->getTemplateName();
10584   if (TemplateName.isDependent())
10585     return SubstAutoTypeDependent(TSInfo->getType());
10586 
10587   // We can only perform deduction for class templates.
10588   auto *Template =
10589       dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10590   if (!Template) {
10591     Diag(Kind.getLocation(),
10592          diag::err_deduced_non_class_template_specialization_type)
10593       << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10594     if (auto *TD = TemplateName.getAsTemplateDecl())
10595       NoteTemplateLocation(*TD);
10596     return QualType();
10597   }
10598 
10599   // Can't deduce from dependent arguments.
10600   if (Expr::hasAnyTypeDependentArguments(Inits)) {
10601     Diag(TSInfo->getTypeLoc().getBeginLoc(),
10602          diag::warn_cxx14_compat_class_template_argument_deduction)
10603         << TSInfo->getTypeLoc().getSourceRange() << 0;
10604     return SubstAutoTypeDependent(TSInfo->getType());
10605   }
10606 
10607   // FIXME: Perform "exact type" matching first, per CWG discussion?
10608   //        Or implement this via an implied 'T(T) -> T' deduction guide?
10609 
10610   // FIXME: Do we need/want a std::initializer_list<T> special case?
10611 
10612   // Look up deduction guides, including those synthesized from constructors.
10613   //
10614   // C++1z [over.match.class.deduct]p1:
10615   //   A set of functions and function templates is formed comprising:
10616   //   - For each constructor of the class template designated by the
10617   //     template-name, a function template [...]
10618   //  - For each deduction-guide, a function or function template [...]
10619   DeclarationNameInfo NameInfo(
10620       Context.DeclarationNames.getCXXDeductionGuideName(Template),
10621       TSInfo->getTypeLoc().getEndLoc());
10622   LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10623   LookupQualifiedName(Guides, Template->getDeclContext());
10624 
10625   // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10626   // clear on this, but they're not found by name so access does not apply.
10627   Guides.suppressDiagnostics();
10628 
10629   // Figure out if this is list-initialization.
10630   InitListExpr *ListInit =
10631       (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10632           ? dyn_cast<InitListExpr>(Inits[0])
10633           : nullptr;
10634 
10635   // C++1z [over.match.class.deduct]p1:
10636   //   Initialization and overload resolution are performed as described in
10637   //   [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10638   //   (as appropriate for the type of initialization performed) for an object
10639   //   of a hypothetical class type, where the selected functions and function
10640   //   templates are considered to be the constructors of that class type
10641   //
10642   // Since we know we're initializing a class type of a type unrelated to that
10643   // of the initializer, this reduces to something fairly reasonable.
10644   OverloadCandidateSet Candidates(Kind.getLocation(),
10645                                   OverloadCandidateSet::CSK_Normal);
10646   OverloadCandidateSet::iterator Best;
10647 
10648   bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10649 
10650   // Return true if the candidate is added successfully, false otherwise.
10651   auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10652                                    CXXDeductionGuideDecl *GD,
10653                                    DeclAccessPair FoundDecl,
10654                                    bool OnlyListConstructors,
10655                                    bool AllowAggregateDeductionCandidate) {
10656     // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10657     //   For copy-initialization, the candidate functions are all the
10658     //   converting constructors (12.3.1) of that class.
10659     // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10660     //   The converting constructors of T are candidate functions.
10661     if (!AllowExplicit) {
10662       // Overload resolution checks whether the deduction guide is declared
10663       // explicit for us.
10664 
10665       // When looking for a converting constructor, deduction guides that
10666       // could never be called with one argument are not interesting to
10667       // check or note.
10668       if (GD->getMinRequiredArguments() > 1 ||
10669           (GD->getNumParams() == 0 && !GD->isVariadic()))
10670         return;
10671     }
10672 
10673     // C++ [over.match.list]p1.1: (first phase list initialization)
10674     //   Initially, the candidate functions are the initializer-list
10675     //   constructors of the class T
10676     if (OnlyListConstructors && !isInitListConstructor(GD))
10677       return;
10678 
10679     if (!AllowAggregateDeductionCandidate &&
10680         GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10681       return;
10682 
10683     // C++ [over.match.list]p1.2: (second phase list initialization)
10684     //   the candidate functions are all the constructors of the class T
10685     // C++ [over.match.ctor]p1: (all other cases)
10686     //   the candidate functions are all the constructors of the class of
10687     //   the object being initialized
10688 
10689     // C++ [over.best.ics]p4:
10690     //   When [...] the constructor [...] is a candidate by
10691     //    - [over.match.copy] (in all cases)
10692     // FIXME: The "second phase of [over.match.list] case can also
10693     // theoretically happen here, but it's not clear whether we can
10694     // ever have a parameter of the right type.
10695     bool SuppressUserConversions = Kind.isCopyInit();
10696 
10697     if (TD) {
10698       SmallVector<Expr *, 8> TmpInits;
10699       for (Expr *E : Inits)
10700         if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10701           TmpInits.push_back(DI->getInit());
10702         else
10703           TmpInits.push_back(E);
10704       AddTemplateOverloadCandidate(
10705           TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10706           SuppressUserConversions,
10707           /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10708           /*PO=*/{}, AllowAggregateDeductionCandidate);
10709     } else {
10710       AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10711                            SuppressUserConversions,
10712                            /*PartialOverloading=*/false, AllowExplicit);
10713     }
10714   };
10715 
10716   bool FoundDeductionGuide = false;
10717 
10718   auto TryToResolveOverload =
10719       [&](bool OnlyListConstructors) -> OverloadingResult {
10720     Candidates.clear(OverloadCandidateSet::CSK_Normal);
10721     bool HasAnyDeductionGuide = false;
10722 
10723     auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10724       auto *RD = cast<CXXRecordDecl>(Template->getTemplatedDecl());
10725       if (!(RD->getDefinition() && RD->isAggregate()))
10726         return;
10727       QualType Ty = Context.getRecordType(RD);
10728       SmallVector<QualType, 8> ElementTypes;
10729 
10730       InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10731       if (!CheckInitList.HadError()) {
10732         // C++ [over.match.class.deduct]p1.8:
10733         //   if e_i is of array type and x_i is a braced-init-list, T_i is an
10734         //   rvalue reference to the declared type of e_i and
10735         // C++ [over.match.class.deduct]p1.9:
10736         //   if e_i is of array type and x_i is a bstring-literal, T_i is an
10737         //   lvalue reference to the const-qualified declared type of e_i and
10738         // C++ [over.match.class.deduct]p1.10:
10739         //   otherwise, T_i is the declared type of e_i
10740         for (int I = 0, E = ListInit->getNumInits();
10741              I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10742           if (ElementTypes[I]->isArrayType()) {
10743             if (isa<InitListExpr>(ListInit->getInit(I)))
10744               ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10745             else if (isa<StringLiteral>(
10746                          ListInit->getInit(I)->IgnoreParenImpCasts()))
10747               ElementTypes[I] =
10748                   Context.getLValueReferenceType(ElementTypes[I].withConst());
10749           }
10750 
10751         llvm::FoldingSetNodeID ID;
10752         ID.AddPointer(Template);
10753         for (auto &T : ElementTypes)
10754           T.getCanonicalType().Profile(ID);
10755         unsigned Hash = ID.ComputeHash();
10756         if (AggregateDeductionCandidates.count(Hash) == 0) {
10757           if (FunctionTemplateDecl *TD =
10758                   DeclareImplicitDeductionGuideFromInitList(
10759                       Template, ElementTypes,
10760                       TSInfo->getTypeLoc().getEndLoc())) {
10761             auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10762             GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
10763             AggregateDeductionCandidates[Hash] = GD;
10764             addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10765                                   OnlyListConstructors,
10766                                   /*AllowAggregateDeductionCandidate=*/true);
10767           }
10768         } else {
10769           CXXDeductionGuideDecl *GD = AggregateDeductionCandidates[Hash];
10770           FunctionTemplateDecl *TD = GD->getDescribedFunctionTemplate();
10771           assert(TD && "aggregate deduction candidate is function template");
10772           addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10773                                 OnlyListConstructors,
10774                                 /*AllowAggregateDeductionCandidate=*/true);
10775         }
10776         HasAnyDeductionGuide = true;
10777       }
10778     };
10779 
10780     for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10781       NamedDecl *D = (*I)->getUnderlyingDecl();
10782       if (D->isInvalidDecl())
10783         continue;
10784 
10785       auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10786       auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10787           TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10788       if (!GD)
10789         continue;
10790 
10791       if (!GD->isImplicit())
10792         HasAnyDeductionGuide = true;
10793 
10794       addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10795                             /*AllowAggregateDeductionCandidate=*/false);
10796     }
10797 
10798     // C++ [over.match.class.deduct]p1.4:
10799     //   if C is defined and its definition satisfies the conditions for an
10800     //   aggregate class ([dcl.init.aggr]) with the assumption that any
10801     //   dependent base class has no virtual functions and no virtual base
10802     //   classes, and the initializer is a non-empty braced-init-list or
10803     //   parenthesized expression-list, and there are no deduction-guides for
10804     //   C, the set contains an additional function template, called the
10805     //   aggregate deduction candidate, defined as follows.
10806     if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10807       if (ListInit && ListInit->getNumInits()) {
10808         SynthesizeAggrGuide(ListInit);
10809       } else if (Inits.size()) { // parenthesized expression-list
10810         // Inits are expressions inside the parentheses. We don't have
10811         // the parentheses source locations, use the begin/end of Inits as the
10812         // best heuristic.
10813         InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10814                                   Inits, Inits.back()->getEndLoc());
10815         SynthesizeAggrGuide(&TempListInit);
10816       }
10817     }
10818 
10819     FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10820 
10821     return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10822   };
10823 
10824   OverloadingResult Result = OR_No_Viable_Function;
10825 
10826   // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10827   // try initializer-list constructors.
10828   if (ListInit) {
10829     bool TryListConstructors = true;
10830 
10831     // Try list constructors unless the list is empty and the class has one or
10832     // more default constructors, in which case those constructors win.
10833     if (!ListInit->getNumInits()) {
10834       for (NamedDecl *D : Guides) {
10835         auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10836         if (FD && FD->getMinRequiredArguments() == 0) {
10837           TryListConstructors = false;
10838           break;
10839         }
10840       }
10841     } else if (ListInit->getNumInits() == 1) {
10842       // C++ [over.match.class.deduct]:
10843       //   As an exception, the first phase in [over.match.list] (considering
10844       //   initializer-list constructors) is omitted if the initializer list
10845       //   consists of a single expression of type cv U, where U is a
10846       //   specialization of C or a class derived from a specialization of C.
10847       Expr *E = ListInit->getInit(0);
10848       auto *RD = E->getType()->getAsCXXRecordDecl();
10849       if (!isa<InitListExpr>(E) && RD &&
10850           isCompleteType(Kind.getLocation(), E->getType()) &&
10851           isOrIsDerivedFromSpecializationOf(RD, Template))
10852         TryListConstructors = false;
10853     }
10854 
10855     if (TryListConstructors)
10856       Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10857     // Then unwrap the initializer list and try again considering all
10858     // constructors.
10859     Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10860   }
10861 
10862   // If list-initialization fails, or if we're doing any other kind of
10863   // initialization, we (eventually) consider constructors.
10864   if (Result == OR_No_Viable_Function)
10865     Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10866 
10867   switch (Result) {
10868   case OR_Ambiguous:
10869     // FIXME: For list-initialization candidates, it'd usually be better to
10870     // list why they were not viable when given the initializer list itself as
10871     // an argument.
10872     Candidates.NoteCandidates(
10873         PartialDiagnosticAt(
10874             Kind.getLocation(),
10875             PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10876                 << TemplateName),
10877         *this, OCD_AmbiguousCandidates, Inits);
10878     return QualType();
10879 
10880   case OR_No_Viable_Function: {
10881     CXXRecordDecl *Primary =
10882         cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10883     bool Complete =
10884         isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10885     Candidates.NoteCandidates(
10886         PartialDiagnosticAt(
10887             Kind.getLocation(),
10888             PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10889                            : diag::err_deduced_class_template_incomplete)
10890                 << TemplateName << !Guides.empty()),
10891         *this, OCD_AllCandidates, Inits);
10892     return QualType();
10893   }
10894 
10895   case OR_Deleted: {
10896     Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10897       << TemplateName;
10898     NoteDeletedFunction(Best->Function);
10899     return QualType();
10900   }
10901 
10902   case OR_Success:
10903     // C++ [over.match.list]p1:
10904     //   In copy-list-initialization, if an explicit constructor is chosen, the
10905     //   initialization is ill-formed.
10906     if (Kind.isCopyInit() && ListInit &&
10907         cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10908       bool IsDeductionGuide = !Best->Function->isImplicit();
10909       Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10910           << TemplateName << IsDeductionGuide;
10911       Diag(Best->Function->getLocation(),
10912            diag::note_explicit_ctor_deduction_guide_here)
10913           << IsDeductionGuide;
10914       return QualType();
10915     }
10916 
10917     // Make sure we didn't select an unusable deduction guide, and mark it
10918     // as referenced.
10919     DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10920     MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10921     break;
10922   }
10923 
10924   // C++ [dcl.type.class.deduct]p1:
10925   //  The placeholder is replaced by the return type of the function selected
10926   //  by overload resolution for class template deduction.
10927   QualType DeducedType =
10928       SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10929   Diag(TSInfo->getTypeLoc().getBeginLoc(),
10930        diag::warn_cxx14_compat_class_template_argument_deduction)
10931       << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10932 
10933   // Warn if CTAD was used on a type that does not have any user-defined
10934   // deduction guides.
10935   if (!FoundDeductionGuide) {
10936     Diag(TSInfo->getTypeLoc().getBeginLoc(),
10937          diag::warn_ctad_maybe_unsupported)
10938         << TemplateName;
10939     Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10940   }
10941 
10942   return DeducedType;
10943 }
10944