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