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