1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Initialization.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include <map>
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
35/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38  if (Context.typesAreCompatible(Context.getWideCharType(), T))
39    return true;
40  if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41    return Context.typesAreCompatible(Context.Char16Ty, T) ||
42           Context.typesAreCompatible(Context.Char32Ty, T);
43  }
44  return false;
45}
46
47enum StringInitFailureKind {
48  SIF_None,
49  SIF_NarrowStringIntoWideChar,
50  SIF_WideStringIntoChar,
51  SIF_IncompatWideStringIntoWideChar,
52  SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60                                          ASTContext &Context) {
61  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
62    return SIF_Other;
63
64  // See if this is a string literal or @encode.
65  Init = Init->IgnoreParens();
66
67  // Handle @encode, which is a narrow string.
68  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
69    return SIF_None;
70
71  // Otherwise we can only handle string literals.
72  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
73  if (!SL)
74    return SIF_Other;
75
76  const QualType ElemTy =
77      Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
78
79  switch (SL->getKind()) {
80  case StringLiteral::Ascii:
81  case StringLiteral::UTF8:
82    // char array can be initialized with a narrow string.
83    // Only allow char x[] = "foo";  not char x[] = L"foo";
84    if (ElemTy->isCharType())
85      return SIF_None;
86    if (IsWideCharCompatible(ElemTy, Context))
87      return SIF_NarrowStringIntoWideChar;
88    return SIF_Other;
89  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90  // "An array with element type compatible with a qualified or unqualified
91  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92  // string literal with the corresponding encoding prefix (L, u, or U,
93  // respectively), optionally enclosed in braces.
94  case StringLiteral::UTF16:
95    if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96      return SIF_None;
97    if (ElemTy->isCharType())
98      return SIF_WideStringIntoChar;
99    if (IsWideCharCompatible(ElemTy, Context))
100      return SIF_IncompatWideStringIntoWideChar;
101    return SIF_Other;
102  case StringLiteral::UTF32:
103    if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104      return SIF_None;
105    if (ElemTy->isCharType())
106      return SIF_WideStringIntoChar;
107    if (IsWideCharCompatible(ElemTy, Context))
108      return SIF_IncompatWideStringIntoWideChar;
109    return SIF_Other;
110  case StringLiteral::Wide:
111    if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112      return SIF_None;
113    if (ElemTy->isCharType())
114      return SIF_WideStringIntoChar;
115    if (IsWideCharCompatible(ElemTy, Context))
116      return SIF_IncompatWideStringIntoWideChar;
117    return SIF_Other;
118  }
119
120  llvm_unreachable("missed a StringLiteral kind?");
121}
122
123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124                                          ASTContext &Context) {
125  const ArrayType *arrayType = Context.getAsArrayType(declType);
126  if (!arrayType)
127    return SIF_Other;
128  return IsStringInit(init, arrayType, Context);
129}
130
131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
134  while (true) {
135    E->setType(Ty);
136    if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137      break;
138    else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139      E = PE->getSubExpr();
140    else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141      E = UO->getSubExpr();
142    else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143      E = GSE->getResultExpr();
144    else
145      llvm_unreachable("unexpected expr in string literal init");
146  }
147}
148
149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150                            Sema &S) {
151  // Get the length of the string as parsed.
152  auto *ConstantArrayTy =
153      cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
154  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
155
156  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
157    // C99 6.7.8p14. We have an array of character type with unknown size
158    // being initialized to a string literal.
159    llvm::APInt ConstVal(32, StrLength);
160    // Return a new array type (C99 6.7.8p22).
161    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162                                           ConstVal,
163                                           ArrayType::Normal, 0);
164    updateStringLiteralType(Str, DeclT);
165    return;
166  }
167
168  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
169
170  // We have an array of character type with known size.  However,
171  // the size may be smaller or larger than the string we are initializing.
172  // FIXME: Avoid truncation for 64-bit length strings.
173  if (S.getLangOpts().CPlusPlus) {
174    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
175      // For Pascal strings it's OK to strip off the terminating null character,
176      // so the example below is valid:
177      //
178      // unsigned char a[2] = "\pa";
179      if (SL->isPascal())
180        StrLength--;
181    }
182
183    // [dcl.init.string]p2
184    if (StrLength > CAT->getSize().getZExtValue())
185      S.Diag(Str->getLocStart(),
186             diag::err_initializer_string_for_char_array_too_long)
187        << Str->getSourceRange();
188  } else {
189    // C99 6.7.8p14.
190    if (StrLength-1 > CAT->getSize().getZExtValue())
191      S.Diag(Str->getLocStart(),
192             diag::ext_initializer_string_for_char_array_too_long)
193        << Str->getSourceRange();
194  }
195
196  // Set the type to the actual size that we are initializing.  If we have
197  // something like:
198  //   char x[1] = "foo";
199  // then this will set the string literal's type to char[1].
200  updateStringLiteralType(Str, DeclT);
201}
202
203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
221/// arguments, which contains the current "structured" (semantic)
222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
234namespace {
235class InitListChecker {
236  Sema &SemaRef;
237  bool hadError;
238  bool VerifyOnly; // no diagnostics, no structure building
239  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
240  InitListExpr *FullyStructuredList;
241
242  void CheckImplicitInitList(const InitializedEntity &Entity,
243                             InitListExpr *ParentIList, QualType T,
244                             unsigned &Index, InitListExpr *StructuredList,
245                             unsigned &StructuredIndex);
246  void CheckExplicitInitList(const InitializedEntity &Entity,
247                             InitListExpr *IList, QualType &T,
248                             InitListExpr *StructuredList,
249                             bool TopLevelObject = false);
250  void CheckListElementTypes(const InitializedEntity &Entity,
251                             InitListExpr *IList, QualType &DeclType,
252                             bool SubobjectIsDesignatorContext,
253                             unsigned &Index,
254                             InitListExpr *StructuredList,
255                             unsigned &StructuredIndex,
256                             bool TopLevelObject = false);
257  void CheckSubElementType(const InitializedEntity &Entity,
258                           InitListExpr *IList, QualType ElemType,
259                           unsigned &Index,
260                           InitListExpr *StructuredList,
261                           unsigned &StructuredIndex);
262  void CheckComplexType(const InitializedEntity &Entity,
263                        InitListExpr *IList, QualType DeclType,
264                        unsigned &Index,
265                        InitListExpr *StructuredList,
266                        unsigned &StructuredIndex);
267  void CheckScalarType(const InitializedEntity &Entity,
268                       InitListExpr *IList, QualType DeclType,
269                       unsigned &Index,
270                       InitListExpr *StructuredList,
271                       unsigned &StructuredIndex);
272  void CheckReferenceType(const InitializedEntity &Entity,
273                          InitListExpr *IList, QualType DeclType,
274                          unsigned &Index,
275                          InitListExpr *StructuredList,
276                          unsigned &StructuredIndex);
277  void CheckVectorType(const InitializedEntity &Entity,
278                       InitListExpr *IList, QualType DeclType, unsigned &Index,
279                       InitListExpr *StructuredList,
280                       unsigned &StructuredIndex);
281  void CheckStructUnionTypes(const InitializedEntity &Entity,
282                             InitListExpr *IList, QualType DeclType,
283                             RecordDecl::field_iterator Field,
284                             bool SubobjectIsDesignatorContext, unsigned &Index,
285                             InitListExpr *StructuredList,
286                             unsigned &StructuredIndex,
287                             bool TopLevelObject = false);
288  void CheckArrayType(const InitializedEntity &Entity,
289                      InitListExpr *IList, QualType &DeclType,
290                      llvm::APSInt elementIndex,
291                      bool SubobjectIsDesignatorContext, unsigned &Index,
292                      InitListExpr *StructuredList,
293                      unsigned &StructuredIndex);
294  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
295                                  InitListExpr *IList, DesignatedInitExpr *DIE,
296                                  unsigned DesigIdx,
297                                  QualType &CurrentObjectType,
298                                  RecordDecl::field_iterator *NextField,
299                                  llvm::APSInt *NextElementIndex,
300                                  unsigned &Index,
301                                  InitListExpr *StructuredList,
302                                  unsigned &StructuredIndex,
303                                  bool FinishSubobjectInit,
304                                  bool TopLevelObject);
305  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306                                           QualType CurrentObjectType,
307                                           InitListExpr *StructuredList,
308                                           unsigned StructuredIndex,
309                                           SourceRange InitRange);
310  void UpdateStructuredListElement(InitListExpr *StructuredList,
311                                   unsigned &StructuredIndex,
312                                   Expr *expr);
313  int numArrayElements(QualType DeclType);
314  int numStructUnionElements(QualType DeclType);
315
316  static ExprResult PerformEmptyInit(Sema &SemaRef,
317                                     SourceLocation Loc,
318                                     const InitializedEntity &Entity,
319                                     bool VerifyOnly);
320  void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
321                               const InitializedEntity &ParentEntity,
322                               InitListExpr *ILE, bool &RequiresSecondPass);
323  void FillInEmptyInitializations(const InitializedEntity &Entity,
324                                  InitListExpr *ILE, bool &RequiresSecondPass);
325  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326                              Expr *InitExpr, FieldDecl *Field,
327                              bool TopLevelObject);
328  void CheckEmptyInitializable(const InitializedEntity &Entity,
329                               SourceLocation Loc);
330
331public:
332  InitListChecker(Sema &S, const InitializedEntity &Entity,
333                  InitListExpr *IL, QualType &T, bool VerifyOnly);
334  bool HadError() { return hadError; }
335
336  // @brief Retrieves the fully-structured initializer list used for
337  // semantic analysis and code generation.
338  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
340} // end anonymous namespace
341
342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343                                             SourceLocation Loc,
344                                             const InitializedEntity &Entity,
345                                             bool VerifyOnly) {
346  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347                                                            true);
348  MultiExprArg SubInit;
349  Expr *InitExpr;
350  InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
351
352  // C++ [dcl.init.aggr]p7:
353  //   If there are fewer initializer-clauses in the list than there are
354  //   members in the aggregate, then each member not explicitly initialized
355  //   ...
356  bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357      Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358  if (EmptyInitList) {
359    // C++1y / DR1070:
360    //   shall be initialized [...] from an empty initializer list.
361    //
362    // We apply the resolution of this DR to C++11 but not C++98, since C++98
363    // does not have useful semantics for initialization from an init list.
364    // We treat this as copy-initialization, because aggregate initialization
365    // always performs copy-initialization on its elements.
366    //
367    // Only do this if we're initializing a class type, to avoid filling in
368    // the initializer list where possible.
369    InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
370                   InitListExpr(SemaRef.Context, Loc, None, Loc);
371    InitExpr->setType(SemaRef.Context.VoidTy);
372    SubInit = InitExpr;
373    Kind = InitializationKind::CreateCopy(Loc, Loc);
374  } else {
375    // C++03:
376    //   shall be value-initialized.
377  }
378
379  InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
380  // libstdc++4.6 marks the vector default constructor as explicit in
381  // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
382  // stlport does so too. Look for std::__debug for libstdc++, and for
383  // std:: for stlport.  This is effectively a compiler-side implementation of
384  // LWG2193.
385  if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
386          InitializationSequence::FK_ExplicitConstructor) {
387    OverloadCandidateSet::iterator Best;
388    OverloadingResult O =
389        InitSeq.getFailedCandidateSet()
390            .BestViableFunction(SemaRef, Kind.getLocation(), Best);
391    (void)O;
392    assert(O == OR_Success && "Inconsistent overload resolution");
393    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394    CXXRecordDecl *R = CtorDecl->getParent();
395
396    if (CtorDecl->getMinRequiredArguments() == 0 &&
397        CtorDecl->isExplicit() && R->getDeclName() &&
398        SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
399
400
401      bool IsInStd = false;
402      for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
403           ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
404        if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
405          IsInStd = true;
406      }
407
408      if (IsInStd && llvm::StringSwitch<bool>(R->getName())
409              .Cases("basic_string", "deque", "forward_list", true)
410              .Cases("list", "map", "multimap", "multiset", true)
411              .Cases("priority_queue", "queue", "set", "stack", true)
412              .Cases("unordered_map", "unordered_set", "vector", true)
413              .Default(false)) {
414        InitSeq.InitializeFrom(
415            SemaRef, Entity,
416            InitializationKind::CreateValue(Loc, Loc, Loc, true),
417            MultiExprArg(), /*TopLevelOfInitList=*/false);
418        // Emit a warning for this.  System header warnings aren't shown
419        // by default, but people working on system headers should see it.
420        if (!VerifyOnly) {
421          SemaRef.Diag(CtorDecl->getLocation(),
422                       diag::warn_invalid_initializer_from_system_header);
423          SemaRef.Diag(Entity.getDecl()->getLocation(),
424                       diag::note_used_in_initialization_here);
425        }
426      }
427    }
428  }
429  if (!InitSeq) {
430    if (!VerifyOnly) {
431      InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
432      if (Entity.getKind() == InitializedEntity::EK_Member)
433        SemaRef.Diag(Entity.getDecl()->getLocation(),
434                     diag::note_in_omitted_aggregate_initializer)
435          << /*field*/1 << Entity.getDecl();
436      else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
437        SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
438          << /*array element*/0 << Entity.getElementIndex();
439    }
440    return ExprError();
441  }
442
443  return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
444                    : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
445}
446
447void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
448                                              SourceLocation Loc) {
449  assert(VerifyOnly &&
450         "CheckEmptyInitializable is only inteded for verification mode.");
451  if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
452    hadError = true;
453}
454
455void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
456                                        const InitializedEntity &ParentEntity,
457                                              InitListExpr *ILE,
458                                              bool &RequiresSecondPass) {
459  SourceLocation Loc = ILE->getLocEnd();
460  unsigned NumInits = ILE->getNumInits();
461  InitializedEntity MemberEntity
462    = InitializedEntity::InitializeMember(Field, &ParentEntity);
463  if (Init >= NumInits || !ILE->getInit(Init)) {
464    // C++1y [dcl.init.aggr]p7:
465    //   If there are fewer initializer-clauses in the list than there are
466    //   members in the aggregate, then each member not explicitly initialized
467    //   shall be initialized from its brace-or-equal-initializer [...]
468    if (Field->hasInClassInitializer()) {
469      ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
470      if (DIE.isInvalid()) {
471        hadError = true;
472        return;
473      }
474      if (Init < NumInits)
475        ILE->setInit(Init, DIE.get());
476      else {
477        ILE->updateInit(SemaRef.Context, Init, DIE.get());
478        RequiresSecondPass = true;
479      }
480      return;
481    }
482
483    if (Field->getType()->isReferenceType()) {
484      // C++ [dcl.init.aggr]p9:
485      //   If an incomplete or empty initializer-list leaves a
486      //   member of reference type uninitialized, the program is
487      //   ill-formed.
488      SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
489        << Field->getType()
490        << ILE->getSyntacticForm()->getSourceRange();
491      SemaRef.Diag(Field->getLocation(),
492                   diag::note_uninit_reference_member);
493      hadError = true;
494      return;
495    }
496
497    ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
498                                             /*VerifyOnly*/false);
499    if (MemberInit.isInvalid()) {
500      hadError = true;
501      return;
502    }
503
504    if (hadError) {
505      // Do nothing
506    } else if (Init < NumInits) {
507      ILE->setInit(Init, MemberInit.getAs<Expr>());
508    } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
509      // Empty initialization requires a constructor call, so
510      // extend the initializer list to include the constructor
511      // call and make a note that we'll need to take another pass
512      // through the initializer list.
513      ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
514      RequiresSecondPass = true;
515    }
516  } else if (InitListExpr *InnerILE
517               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
518    FillInEmptyInitializations(MemberEntity, InnerILE,
519                               RequiresSecondPass);
520}
521
522/// Recursively replaces NULL values within the given initializer list
523/// with expressions that perform value-initialization of the
524/// appropriate type.
525void
526InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
527                                            InitListExpr *ILE,
528                                            bool &RequiresSecondPass) {
529  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
530         "Should not have void type");
531
532  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
533    const RecordDecl *RDecl = RType->getDecl();
534    if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
535      FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
536                              Entity, ILE, RequiresSecondPass);
537    else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
538             cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
539      for (auto *Field : RDecl->fields()) {
540        if (Field->hasInClassInitializer()) {
541          FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
542          break;
543        }
544      }
545    } else {
546      unsigned Init = 0;
547      for (auto *Field : RDecl->fields()) {
548        if (Field->isUnnamedBitfield())
549          continue;
550
551        if (hadError)
552          return;
553
554        FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
555        if (hadError)
556          return;
557
558        ++Init;
559
560        // Only look at the first initialization of a union.
561        if (RDecl->isUnion())
562          break;
563      }
564    }
565
566    return;
567  }
568
569  QualType ElementType;
570
571  InitializedEntity ElementEntity = Entity;
572  unsigned NumInits = ILE->getNumInits();
573  unsigned NumElements = NumInits;
574  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
575    ElementType = AType->getElementType();
576    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
577      NumElements = CAType->getSize().getZExtValue();
578    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
579                                                         0, Entity);
580  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
581    ElementType = VType->getElementType();
582    NumElements = VType->getNumElements();
583    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
584                                                         0, Entity);
585  } else
586    ElementType = ILE->getType();
587
588  for (unsigned Init = 0; Init != NumElements; ++Init) {
589    if (hadError)
590      return;
591
592    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
593        ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
594      ElementEntity.setElementIndex(Init);
595
596    Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
597    if (!InitExpr && !ILE->hasArrayFiller()) {
598      ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
599                                                ElementEntity,
600                                                /*VerifyOnly*/false);
601      if (ElementInit.isInvalid()) {
602        hadError = true;
603        return;
604      }
605
606      if (hadError) {
607        // Do nothing
608      } else if (Init < NumInits) {
609        // For arrays, just set the expression used for value-initialization
610        // of the "holes" in the array.
611        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
612          ILE->setArrayFiller(ElementInit.getAs<Expr>());
613        else
614          ILE->setInit(Init, ElementInit.getAs<Expr>());
615      } else {
616        // For arrays, just set the expression used for value-initialization
617        // of the rest of elements and exit.
618        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
619          ILE->setArrayFiller(ElementInit.getAs<Expr>());
620          return;
621        }
622
623        if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
624          // Empty initialization requires a constructor call, so
625          // extend the initializer list to include the constructor
626          // call and make a note that we'll need to take another pass
627          // through the initializer list.
628          ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
629          RequiresSecondPass = true;
630        }
631      }
632    } else if (InitListExpr *InnerILE
633                 = dyn_cast_or_null<InitListExpr>(InitExpr))
634      FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
635  }
636}
637
638
639InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
640                                 InitListExpr *IL, QualType &T,
641                                 bool VerifyOnly)
642  : SemaRef(S), VerifyOnly(VerifyOnly) {
643  // FIXME: Check that IL isn't already the semantic form of some other
644  // InitListExpr. If it is, we'd create a broken AST.
645
646  hadError = false;
647
648  FullyStructuredList =
649      getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
650  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
651                        /*TopLevelObject=*/true);
652
653  if (!hadError && !VerifyOnly) {
654    bool RequiresSecondPass = false;
655    FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
656    if (RequiresSecondPass && !hadError)
657      FillInEmptyInitializations(Entity, FullyStructuredList,
658                                 RequiresSecondPass);
659  }
660}
661
662int InitListChecker::numArrayElements(QualType DeclType) {
663  // FIXME: use a proper constant
664  int maxElements = 0x7FFFFFFF;
665  if (const ConstantArrayType *CAT =
666        SemaRef.Context.getAsConstantArrayType(DeclType)) {
667    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
668  }
669  return maxElements;
670}
671
672int InitListChecker::numStructUnionElements(QualType DeclType) {
673  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
674  int InitializableMembers = 0;
675  for (const auto *Field : structDecl->fields())
676    if (!Field->isUnnamedBitfield())
677      ++InitializableMembers;
678
679  if (structDecl->isUnion())
680    return std::min(InitializableMembers, 1);
681  return InitializableMembers - structDecl->hasFlexibleArrayMember();
682}
683
684/// Check whether the range of the initializer \p ParentIList from element
685/// \p Index onwards can be used to initialize an object of type \p T. Update
686/// \p Index to indicate how many elements of the list were consumed.
687///
688/// This also fills in \p StructuredList, from element \p StructuredIndex
689/// onwards, with the fully-braced, desugared form of the initialization.
690void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
691                                            InitListExpr *ParentIList,
692                                            QualType T, unsigned &Index,
693                                            InitListExpr *StructuredList,
694                                            unsigned &StructuredIndex) {
695  int maxElements = 0;
696
697  if (T->isArrayType())
698    maxElements = numArrayElements(T);
699  else if (T->isRecordType())
700    maxElements = numStructUnionElements(T);
701  else if (T->isVectorType())
702    maxElements = T->getAs<VectorType>()->getNumElements();
703  else
704    llvm_unreachable("CheckImplicitInitList(): Illegal type");
705
706  if (maxElements == 0) {
707    if (!VerifyOnly)
708      SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
709                   diag::err_implicit_empty_initializer);
710    ++Index;
711    hadError = true;
712    return;
713  }
714
715  // Build a structured initializer list corresponding to this subobject.
716  InitListExpr *StructuredSubobjectInitList
717    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
718                                 StructuredIndex,
719          SourceRange(ParentIList->getInit(Index)->getLocStart(),
720                      ParentIList->getSourceRange().getEnd()));
721  unsigned StructuredSubobjectInitIndex = 0;
722
723  // Check the element types and build the structural subobject.
724  unsigned StartIndex = Index;
725  CheckListElementTypes(Entity, ParentIList, T,
726                        /*SubobjectIsDesignatorContext=*/false, Index,
727                        StructuredSubobjectInitList,
728                        StructuredSubobjectInitIndex);
729
730  if (!VerifyOnly) {
731    StructuredSubobjectInitList->setType(T);
732
733    unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
734    // Update the structured sub-object initializer so that it's ending
735    // range corresponds with the end of the last initializer it used.
736    if (EndIndex < ParentIList->getNumInits()) {
737      SourceLocation EndLoc
738        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
739      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
740    }
741
742    // Complain about missing braces.
743    if (T->isArrayType() || T->isRecordType()) {
744      SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
745                   diag::warn_missing_braces)
746          << StructuredSubobjectInitList->getSourceRange()
747          << FixItHint::CreateInsertion(
748                 StructuredSubobjectInitList->getLocStart(), "{")
749          << FixItHint::CreateInsertion(
750                 SemaRef.getLocForEndOfToken(
751                     StructuredSubobjectInitList->getLocEnd()),
752                 "}");
753    }
754  }
755}
756
757/// Warn that \p Entity was of scalar type and was initialized by a
758/// single-element braced initializer list.
759static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
760                                 SourceRange Braces) {
761  // Don't warn during template instantiation. If the initialization was
762  // non-dependent, we warned during the initial parse; otherwise, the
763  // type might not be scalar in some uses of the template.
764  if (!S.ActiveTemplateInstantiations.empty())
765    return;
766
767  unsigned DiagID = 0;
768
769  switch (Entity.getKind()) {
770  case InitializedEntity::EK_VectorElement:
771  case InitializedEntity::EK_ComplexElement:
772  case InitializedEntity::EK_ArrayElement:
773  case InitializedEntity::EK_Parameter:
774  case InitializedEntity::EK_Parameter_CF_Audited:
775  case InitializedEntity::EK_Result:
776    // Extra braces here are suspicious.
777    DiagID = diag::warn_braces_around_scalar_init;
778    break;
779
780  case InitializedEntity::EK_Member:
781    // Warn on aggregate initialization but not on ctor init list or
782    // default member initializer.
783    if (Entity.getParent())
784      DiagID = diag::warn_braces_around_scalar_init;
785    break;
786
787  case InitializedEntity::EK_Variable:
788  case InitializedEntity::EK_LambdaCapture:
789    // No warning, might be direct-list-initialization.
790    // FIXME: Should we warn for copy-list-initialization in these cases?
791    break;
792
793  case InitializedEntity::EK_New:
794  case InitializedEntity::EK_Temporary:
795  case InitializedEntity::EK_CompoundLiteralInit:
796    // No warning, braces are part of the syntax of the underlying construct.
797    break;
798
799  case InitializedEntity::EK_RelatedResult:
800    // No warning, we already warned when initializing the result.
801    break;
802
803  case InitializedEntity::EK_Exception:
804  case InitializedEntity::EK_Base:
805  case InitializedEntity::EK_Delegating:
806  case InitializedEntity::EK_BlockElement:
807    llvm_unreachable("unexpected braced scalar init");
808  }
809
810  if (DiagID) {
811    S.Diag(Braces.getBegin(), DiagID)
812      << Braces
813      << FixItHint::CreateRemoval(Braces.getBegin())
814      << FixItHint::CreateRemoval(Braces.getEnd());
815  }
816}
817
818
819/// Check whether the initializer \p IList (that was written with explicit
820/// braces) can be used to initialize an object of type \p T.
821///
822/// This also fills in \p StructuredList with the fully-braced, desugared
823/// form of the initialization.
824void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
825                                            InitListExpr *IList, QualType &T,
826                                            InitListExpr *StructuredList,
827                                            bool TopLevelObject) {
828  if (!VerifyOnly) {
829    SyntacticToSemantic[IList] = StructuredList;
830    StructuredList->setSyntacticForm(IList);
831  }
832
833  unsigned Index = 0, StructuredIndex = 0;
834  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
835                        Index, StructuredList, StructuredIndex, TopLevelObject);
836  if (!VerifyOnly) {
837    QualType ExprTy = T;
838    if (!ExprTy->isArrayType())
839      ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
840    IList->setType(ExprTy);
841    StructuredList->setType(ExprTy);
842  }
843  if (hadError)
844    return;
845
846  if (Index < IList->getNumInits()) {
847    // We have leftover initializers
848    if (VerifyOnly) {
849      if (SemaRef.getLangOpts().CPlusPlus ||
850          (SemaRef.getLangOpts().OpenCL &&
851           IList->getType()->isVectorType())) {
852        hadError = true;
853      }
854      return;
855    }
856
857    if (StructuredIndex == 1 &&
858        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
859            SIF_None) {
860      unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
861      if (SemaRef.getLangOpts().CPlusPlus) {
862        DK = diag::err_excess_initializers_in_char_array_initializer;
863        hadError = true;
864      }
865      // Special-case
866      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
867        << IList->getInit(Index)->getSourceRange();
868    } else if (!T->isIncompleteType()) {
869      // Don't complain for incomplete types, since we'll get an error
870      // elsewhere
871      QualType CurrentObjectType = StructuredList->getType();
872      int initKind =
873        CurrentObjectType->isArrayType()? 0 :
874        CurrentObjectType->isVectorType()? 1 :
875        CurrentObjectType->isScalarType()? 2 :
876        CurrentObjectType->isUnionType()? 3 :
877        4;
878
879      unsigned DK = diag::ext_excess_initializers;
880      if (SemaRef.getLangOpts().CPlusPlus) {
881        DK = diag::err_excess_initializers;
882        hadError = true;
883      }
884      if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
885        DK = diag::err_excess_initializers;
886        hadError = true;
887      }
888
889      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
890        << initKind << IList->getInit(Index)->getSourceRange();
891    }
892  }
893
894  if (!VerifyOnly && T->isScalarType() &&
895      IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
896    warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
897}
898
899void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
900                                            InitListExpr *IList,
901                                            QualType &DeclType,
902                                            bool SubobjectIsDesignatorContext,
903                                            unsigned &Index,
904                                            InitListExpr *StructuredList,
905                                            unsigned &StructuredIndex,
906                                            bool TopLevelObject) {
907  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
908    // Explicitly braced initializer for complex type can be real+imaginary
909    // parts.
910    CheckComplexType(Entity, IList, DeclType, Index,
911                     StructuredList, StructuredIndex);
912  } else if (DeclType->isScalarType()) {
913    CheckScalarType(Entity, IList, DeclType, Index,
914                    StructuredList, StructuredIndex);
915  } else if (DeclType->isVectorType()) {
916    CheckVectorType(Entity, IList, DeclType, Index,
917                    StructuredList, StructuredIndex);
918  } else if (DeclType->isRecordType()) {
919    assert(DeclType->isAggregateType() &&
920           "non-aggregate records should be handed in CheckSubElementType");
921    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
922    CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
923                          SubobjectIsDesignatorContext, Index,
924                          StructuredList, StructuredIndex,
925                          TopLevelObject);
926  } else if (DeclType->isArrayType()) {
927    llvm::APSInt Zero(
928                    SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
929                    false);
930    CheckArrayType(Entity, IList, DeclType, Zero,
931                   SubobjectIsDesignatorContext, Index,
932                   StructuredList, StructuredIndex);
933  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
934    // This type is invalid, issue a diagnostic.
935    ++Index;
936    if (!VerifyOnly)
937      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
938        << DeclType;
939    hadError = true;
940  } else if (DeclType->isReferenceType()) {
941    CheckReferenceType(Entity, IList, DeclType, Index,
942                       StructuredList, StructuredIndex);
943  } else if (DeclType->isObjCObjectType()) {
944    if (!VerifyOnly)
945      SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
946        << DeclType;
947    hadError = true;
948  } else {
949    if (!VerifyOnly)
950      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
951        << DeclType;
952    hadError = true;
953  }
954}
955
956void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
957                                          InitListExpr *IList,
958                                          QualType ElemType,
959                                          unsigned &Index,
960                                          InitListExpr *StructuredList,
961                                          unsigned &StructuredIndex) {
962  Expr *expr = IList->getInit(Index);
963
964  if (ElemType->isReferenceType())
965    return CheckReferenceType(Entity, IList, ElemType, Index,
966                              StructuredList, StructuredIndex);
967
968  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
969    if (!SemaRef.getLangOpts().CPlusPlus) {
970      InitListExpr *InnerStructuredList
971        = getStructuredSubobjectInit(IList, Index, ElemType,
972                                     StructuredList, StructuredIndex,
973                                     SubInitList->getSourceRange());
974      CheckExplicitInitList(Entity, SubInitList, ElemType,
975                            InnerStructuredList);
976      ++StructuredIndex;
977      ++Index;
978      return;
979    }
980    // C++ initialization is handled later.
981  } else if (isa<ImplicitValueInitExpr>(expr)) {
982    // This happens during template instantiation when we see an InitListExpr
983    // that we've already checked once.
984    assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
985           "found implicit initialization for the wrong type");
986    if (!VerifyOnly)
987      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
988    ++Index;
989    return;
990  }
991
992  if (SemaRef.getLangOpts().CPlusPlus) {
993    // C++ [dcl.init.aggr]p2:
994    //   Each member is copy-initialized from the corresponding
995    //   initializer-clause.
996
997    // FIXME: Better EqualLoc?
998    InitializationKind Kind =
999      InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1000    InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1001                               /*TopLevelOfInitList*/ true);
1002
1003    // C++14 [dcl.init.aggr]p13:
1004    //   If the assignment-expression can initialize a member, the member is
1005    //   initialized. Otherwise [...] brace elision is assumed
1006    //
1007    // Brace elision is never performed if the element is not an
1008    // assignment-expression.
1009    if (Seq || isa<InitListExpr>(expr)) {
1010      if (!VerifyOnly) {
1011        ExprResult Result =
1012          Seq.Perform(SemaRef, Entity, Kind, expr);
1013        if (Result.isInvalid())
1014          hadError = true;
1015
1016        UpdateStructuredListElement(StructuredList, StructuredIndex,
1017                                    Result.getAs<Expr>());
1018      } else if (!Seq)
1019        hadError = true;
1020      ++Index;
1021      return;
1022    }
1023
1024    // Fall through for subaggregate initialization
1025  } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1026    // FIXME: Need to handle atomic aggregate types with implicit init lists.
1027    return CheckScalarType(Entity, IList, ElemType, Index,
1028                           StructuredList, StructuredIndex);
1029  } else if (const ArrayType *arrayType =
1030                 SemaRef.Context.getAsArrayType(ElemType)) {
1031    // arrayType can be incomplete if we're initializing a flexible
1032    // array member.  There's nothing we can do with the completed
1033    // type here, though.
1034
1035    if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1036      if (!VerifyOnly) {
1037        CheckStringInit(expr, ElemType, arrayType, SemaRef);
1038        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1039      }
1040      ++Index;
1041      return;
1042    }
1043
1044    // Fall through for subaggregate initialization.
1045
1046  } else {
1047    assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
1048           "Unexpected type");
1049
1050    // C99 6.7.8p13:
1051    //
1052    //   The initializer for a structure or union object that has
1053    //   automatic storage duration shall be either an initializer
1054    //   list as described below, or a single expression that has
1055    //   compatible structure or union type. In the latter case, the
1056    //   initial value of the object, including unnamed members, is
1057    //   that of the expression.
1058    ExprResult ExprRes = expr;
1059    if (SemaRef.CheckSingleAssignmentConstraints(
1060            ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1061      if (ExprRes.isInvalid())
1062        hadError = true;
1063      else {
1064        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1065          if (ExprRes.isInvalid())
1066            hadError = true;
1067      }
1068      UpdateStructuredListElement(StructuredList, StructuredIndex,
1069                                  ExprRes.getAs<Expr>());
1070      ++Index;
1071      return;
1072    }
1073    ExprRes.get();
1074    // Fall through for subaggregate initialization
1075  }
1076
1077  // C++ [dcl.init.aggr]p12:
1078  //
1079  //   [...] Otherwise, if the member is itself a non-empty
1080  //   subaggregate, brace elision is assumed and the initializer is
1081  //   considered for the initialization of the first member of
1082  //   the subaggregate.
1083  if (!SemaRef.getLangOpts().OpenCL &&
1084      (ElemType->isAggregateType() || ElemType->isVectorType())) {
1085    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1086                          StructuredIndex);
1087    ++StructuredIndex;
1088  } else {
1089    if (!VerifyOnly) {
1090      // We cannot initialize this element, so let
1091      // PerformCopyInitialization produce the appropriate diagnostic.
1092      SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1093                                        /*TopLevelOfInitList=*/true);
1094    }
1095    hadError = true;
1096    ++Index;
1097    ++StructuredIndex;
1098  }
1099}
1100
1101void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1102                                       InitListExpr *IList, QualType DeclType,
1103                                       unsigned &Index,
1104                                       InitListExpr *StructuredList,
1105                                       unsigned &StructuredIndex) {
1106  assert(Index == 0 && "Index in explicit init list must be zero");
1107
1108  // As an extension, clang supports complex initializers, which initialize
1109  // a complex number component-wise.  When an explicit initializer list for
1110  // a complex number contains two two initializers, this extension kicks in:
1111  // it exepcts the initializer list to contain two elements convertible to
1112  // the element type of the complex type. The first element initializes
1113  // the real part, and the second element intitializes the imaginary part.
1114
1115  if (IList->getNumInits() != 2)
1116    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1117                           StructuredIndex);
1118
1119  // This is an extension in C.  (The builtin _Complex type does not exist
1120  // in the C++ standard.)
1121  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1122    SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1123      << IList->getSourceRange();
1124
1125  // Initialize the complex number.
1126  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1127  InitializedEntity ElementEntity =
1128    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1129
1130  for (unsigned i = 0; i < 2; ++i) {
1131    ElementEntity.setElementIndex(Index);
1132    CheckSubElementType(ElementEntity, IList, elementType, Index,
1133                        StructuredList, StructuredIndex);
1134  }
1135}
1136
1137
1138void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1139                                      InitListExpr *IList, QualType DeclType,
1140                                      unsigned &Index,
1141                                      InitListExpr *StructuredList,
1142                                      unsigned &StructuredIndex) {
1143  if (Index >= IList->getNumInits()) {
1144    if (!VerifyOnly)
1145      SemaRef.Diag(IList->getLocStart(),
1146                   SemaRef.getLangOpts().CPlusPlus11 ?
1147                     diag::warn_cxx98_compat_empty_scalar_initializer :
1148                     diag::err_empty_scalar_initializer)
1149        << IList->getSourceRange();
1150    hadError = !SemaRef.getLangOpts().CPlusPlus11;
1151    ++Index;
1152    ++StructuredIndex;
1153    return;
1154  }
1155
1156  Expr *expr = IList->getInit(Index);
1157  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1158    // FIXME: This is invalid, and accepting it causes overload resolution
1159    // to pick the wrong overload in some corner cases.
1160    if (!VerifyOnly)
1161      SemaRef.Diag(SubIList->getLocStart(),
1162                   diag::ext_many_braces_around_scalar_init)
1163        << SubIList->getSourceRange();
1164
1165    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1166                    StructuredIndex);
1167    return;
1168  } else if (isa<DesignatedInitExpr>(expr)) {
1169    if (!VerifyOnly)
1170      SemaRef.Diag(expr->getLocStart(),
1171                   diag::err_designator_for_scalar_init)
1172        << DeclType << expr->getSourceRange();
1173    hadError = true;
1174    ++Index;
1175    ++StructuredIndex;
1176    return;
1177  }
1178
1179  if (VerifyOnly) {
1180    if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1181      hadError = true;
1182    ++Index;
1183    return;
1184  }
1185
1186  ExprResult Result =
1187    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1188                                      /*TopLevelOfInitList=*/true);
1189
1190  Expr *ResultExpr = nullptr;
1191
1192  if (Result.isInvalid())
1193    hadError = true; // types weren't compatible.
1194  else {
1195    ResultExpr = Result.getAs<Expr>();
1196
1197    if (ResultExpr != expr) {
1198      // The type was promoted, update initializer list.
1199      IList->setInit(Index, ResultExpr);
1200    }
1201  }
1202  if (hadError)
1203    ++StructuredIndex;
1204  else
1205    UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1206  ++Index;
1207}
1208
1209void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1210                                         InitListExpr *IList, QualType DeclType,
1211                                         unsigned &Index,
1212                                         InitListExpr *StructuredList,
1213                                         unsigned &StructuredIndex) {
1214  if (Index >= IList->getNumInits()) {
1215    // FIXME: It would be wonderful if we could point at the actual member. In
1216    // general, it would be useful to pass location information down the stack,
1217    // so that we know the location (or decl) of the "current object" being
1218    // initialized.
1219    if (!VerifyOnly)
1220      SemaRef.Diag(IList->getLocStart(),
1221                    diag::err_init_reference_member_uninitialized)
1222        << DeclType
1223        << IList->getSourceRange();
1224    hadError = true;
1225    ++Index;
1226    ++StructuredIndex;
1227    return;
1228  }
1229
1230  Expr *expr = IList->getInit(Index);
1231  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1232    if (!VerifyOnly)
1233      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1234        << DeclType << IList->getSourceRange();
1235    hadError = true;
1236    ++Index;
1237    ++StructuredIndex;
1238    return;
1239  }
1240
1241  if (VerifyOnly) {
1242    if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1243      hadError = true;
1244    ++Index;
1245    return;
1246  }
1247
1248  ExprResult Result =
1249      SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1250                                        /*TopLevelOfInitList=*/true);
1251
1252  if (Result.isInvalid())
1253    hadError = true;
1254
1255  expr = Result.getAs<Expr>();
1256  IList->setInit(Index, expr);
1257
1258  if (hadError)
1259    ++StructuredIndex;
1260  else
1261    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1262  ++Index;
1263}
1264
1265void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1266                                      InitListExpr *IList, QualType DeclType,
1267                                      unsigned &Index,
1268                                      InitListExpr *StructuredList,
1269                                      unsigned &StructuredIndex) {
1270  const VectorType *VT = DeclType->getAs<VectorType>();
1271  unsigned maxElements = VT->getNumElements();
1272  unsigned numEltsInit = 0;
1273  QualType elementType = VT->getElementType();
1274
1275  if (Index >= IList->getNumInits()) {
1276    // Make sure the element type can be value-initialized.
1277    if (VerifyOnly)
1278      CheckEmptyInitializable(
1279          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1280          IList->getLocEnd());
1281    return;
1282  }
1283
1284  if (!SemaRef.getLangOpts().OpenCL) {
1285    // If the initializing element is a vector, try to copy-initialize
1286    // instead of breaking it apart (which is doomed to failure anyway).
1287    Expr *Init = IList->getInit(Index);
1288    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1289      if (VerifyOnly) {
1290        if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1291          hadError = true;
1292        ++Index;
1293        return;
1294      }
1295
1296  ExprResult Result =
1297      SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1298                                        /*TopLevelOfInitList=*/true);
1299
1300      Expr *ResultExpr = nullptr;
1301      if (Result.isInvalid())
1302        hadError = true; // types weren't compatible.
1303      else {
1304        ResultExpr = Result.getAs<Expr>();
1305
1306        if (ResultExpr != Init) {
1307          // The type was promoted, update initializer list.
1308          IList->setInit(Index, ResultExpr);
1309        }
1310      }
1311      if (hadError)
1312        ++StructuredIndex;
1313      else
1314        UpdateStructuredListElement(StructuredList, StructuredIndex,
1315                                    ResultExpr);
1316      ++Index;
1317      return;
1318    }
1319
1320    InitializedEntity ElementEntity =
1321      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1322
1323    for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1324      // Don't attempt to go past the end of the init list
1325      if (Index >= IList->getNumInits()) {
1326        if (VerifyOnly)
1327          CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1328        break;
1329      }
1330
1331      ElementEntity.setElementIndex(Index);
1332      CheckSubElementType(ElementEntity, IList, elementType, Index,
1333                          StructuredList, StructuredIndex);
1334    }
1335
1336    if (VerifyOnly)
1337      return;
1338
1339    bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1340    const VectorType *T = Entity.getType()->getAs<VectorType>();
1341    if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1342                        T->getVectorKind() == VectorType::NeonPolyVector)) {
1343      // The ability to use vector initializer lists is a GNU vector extension
1344      // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1345      // endian machines it works fine, however on big endian machines it
1346      // exhibits surprising behaviour:
1347      //
1348      //   uint32x2_t x = {42, 64};
1349      //   return vget_lane_u32(x, 0); // Will return 64.
1350      //
1351      // Because of this, explicitly call out that it is non-portable.
1352      //
1353      SemaRef.Diag(IList->getLocStart(),
1354                   diag::warn_neon_vector_initializer_non_portable);
1355
1356      const char *typeCode;
1357      unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1358
1359      if (elementType->isFloatingType())
1360        typeCode = "f";
1361      else if (elementType->isSignedIntegerType())
1362        typeCode = "s";
1363      else if (elementType->isUnsignedIntegerType())
1364        typeCode = "u";
1365      else
1366        llvm_unreachable("Invalid element type!");
1367
1368      SemaRef.Diag(IList->getLocStart(),
1369                   SemaRef.Context.getTypeSize(VT) > 64 ?
1370                   diag::note_neon_vector_initializer_non_portable_q :
1371                   diag::note_neon_vector_initializer_non_portable)
1372        << typeCode << typeSize;
1373    }
1374
1375    return;
1376  }
1377
1378  InitializedEntity ElementEntity =
1379    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1380
1381  // OpenCL initializers allows vectors to be constructed from vectors.
1382  for (unsigned i = 0; i < maxElements; ++i) {
1383    // Don't attempt to go past the end of the init list
1384    if (Index >= IList->getNumInits())
1385      break;
1386
1387    ElementEntity.setElementIndex(Index);
1388
1389    QualType IType = IList->getInit(Index)->getType();
1390    if (!IType->isVectorType()) {
1391      CheckSubElementType(ElementEntity, IList, elementType, Index,
1392                          StructuredList, StructuredIndex);
1393      ++numEltsInit;
1394    } else {
1395      QualType VecType;
1396      const VectorType *IVT = IType->getAs<VectorType>();
1397      unsigned numIElts = IVT->getNumElements();
1398
1399      if (IType->isExtVectorType())
1400        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1401      else
1402        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1403                                                IVT->getVectorKind());
1404      CheckSubElementType(ElementEntity, IList, VecType, Index,
1405                          StructuredList, StructuredIndex);
1406      numEltsInit += numIElts;
1407    }
1408  }
1409
1410  // OpenCL requires all elements to be initialized.
1411  if (numEltsInit != maxElements) {
1412    if (!VerifyOnly)
1413      SemaRef.Diag(IList->getLocStart(),
1414                   diag::err_vector_incorrect_num_initializers)
1415        << (numEltsInit < maxElements) << maxElements << numEltsInit;
1416    hadError = true;
1417  }
1418}
1419
1420void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1421                                     InitListExpr *IList, QualType &DeclType,
1422                                     llvm::APSInt elementIndex,
1423                                     bool SubobjectIsDesignatorContext,
1424                                     unsigned &Index,
1425                                     InitListExpr *StructuredList,
1426                                     unsigned &StructuredIndex) {
1427  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1428
1429  // Check for the special-case of initializing an array with a string.
1430  if (Index < IList->getNumInits()) {
1431    if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1432        SIF_None) {
1433      // We place the string literal directly into the resulting
1434      // initializer list. This is the only place where the structure
1435      // of the structured initializer list doesn't match exactly,
1436      // because doing so would involve allocating one character
1437      // constant for each string.
1438      if (!VerifyOnly) {
1439        CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1440        UpdateStructuredListElement(StructuredList, StructuredIndex,
1441                                    IList->getInit(Index));
1442        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1443      }
1444      ++Index;
1445      return;
1446    }
1447  }
1448  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1449    // Check for VLAs; in standard C it would be possible to check this
1450    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1451    // them in all sorts of strange places).
1452    if (!VerifyOnly)
1453      SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1454                    diag::err_variable_object_no_init)
1455        << VAT->getSizeExpr()->getSourceRange();
1456    hadError = true;
1457    ++Index;
1458    ++StructuredIndex;
1459    return;
1460  }
1461
1462  // We might know the maximum number of elements in advance.
1463  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1464                           elementIndex.isUnsigned());
1465  bool maxElementsKnown = false;
1466  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1467    maxElements = CAT->getSize();
1468    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1469    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1470    maxElementsKnown = true;
1471  }
1472
1473  QualType elementType = arrayType->getElementType();
1474  while (Index < IList->getNumInits()) {
1475    Expr *Init = IList->getInit(Index);
1476    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1477      // If we're not the subobject that matches up with the '{' for
1478      // the designator, we shouldn't be handling the
1479      // designator. Return immediately.
1480      if (!SubobjectIsDesignatorContext)
1481        return;
1482
1483      // Handle this designated initializer. elementIndex will be
1484      // updated to be the next array element we'll initialize.
1485      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1486                                     DeclType, nullptr, &elementIndex, Index,
1487                                     StructuredList, StructuredIndex, true,
1488                                     false)) {
1489        hadError = true;
1490        continue;
1491      }
1492
1493      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1494        maxElements = maxElements.extend(elementIndex.getBitWidth());
1495      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1496        elementIndex = elementIndex.extend(maxElements.getBitWidth());
1497      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1498
1499      // If the array is of incomplete type, keep track of the number of
1500      // elements in the initializer.
1501      if (!maxElementsKnown && elementIndex > maxElements)
1502        maxElements = elementIndex;
1503
1504      continue;
1505    }
1506
1507    // If we know the maximum number of elements, and we've already
1508    // hit it, stop consuming elements in the initializer list.
1509    if (maxElementsKnown && elementIndex == maxElements)
1510      break;
1511
1512    InitializedEntity ElementEntity =
1513      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1514                                           Entity);
1515    // Check this element.
1516    CheckSubElementType(ElementEntity, IList, elementType, Index,
1517                        StructuredList, StructuredIndex);
1518    ++elementIndex;
1519
1520    // If the array is of incomplete type, keep track of the number of
1521    // elements in the initializer.
1522    if (!maxElementsKnown && elementIndex > maxElements)
1523      maxElements = elementIndex;
1524  }
1525  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1526    // If this is an incomplete array type, the actual type needs to
1527    // be calculated here.
1528    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1529    if (maxElements == Zero) {
1530      // Sizing an array implicitly to zero is not allowed by ISO C,
1531      // but is supported by GNU.
1532      SemaRef.Diag(IList->getLocStart(),
1533                    diag::ext_typecheck_zero_array_size);
1534    }
1535
1536    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1537                                                     ArrayType::Normal, 0);
1538  }
1539  if (!hadError && VerifyOnly) {
1540    // Check if there are any members of the array that get value-initialized.
1541    // If so, check if doing that is possible.
1542    // FIXME: This needs to detect holes left by designated initializers too.
1543    if (maxElementsKnown && elementIndex < maxElements)
1544      CheckEmptyInitializable(InitializedEntity::InitializeElement(
1545                                                  SemaRef.Context, 0, Entity),
1546                              IList->getLocEnd());
1547  }
1548}
1549
1550bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1551                                             Expr *InitExpr,
1552                                             FieldDecl *Field,
1553                                             bool TopLevelObject) {
1554  // Handle GNU flexible array initializers.
1555  unsigned FlexArrayDiag;
1556  if (isa<InitListExpr>(InitExpr) &&
1557      cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1558    // Empty flexible array init always allowed as an extension
1559    FlexArrayDiag = diag::ext_flexible_array_init;
1560  } else if (SemaRef.getLangOpts().CPlusPlus) {
1561    // Disallow flexible array init in C++; it is not required for gcc
1562    // compatibility, and it needs work to IRGen correctly in general.
1563    FlexArrayDiag = diag::err_flexible_array_init;
1564  } else if (!TopLevelObject) {
1565    // Disallow flexible array init on non-top-level object
1566    FlexArrayDiag = diag::err_flexible_array_init;
1567  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1568    // Disallow flexible array init on anything which is not a variable.
1569    FlexArrayDiag = diag::err_flexible_array_init;
1570  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1571    // Disallow flexible array init on local variables.
1572    FlexArrayDiag = diag::err_flexible_array_init;
1573  } else {
1574    // Allow other cases.
1575    FlexArrayDiag = diag::ext_flexible_array_init;
1576  }
1577
1578  if (!VerifyOnly) {
1579    SemaRef.Diag(InitExpr->getLocStart(),
1580                 FlexArrayDiag)
1581      << InitExpr->getLocStart();
1582    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1583      << Field;
1584  }
1585
1586  return FlexArrayDiag != diag::ext_flexible_array_init;
1587}
1588
1589void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1590                                            InitListExpr *IList,
1591                                            QualType DeclType,
1592                                            RecordDecl::field_iterator Field,
1593                                            bool SubobjectIsDesignatorContext,
1594                                            unsigned &Index,
1595                                            InitListExpr *StructuredList,
1596                                            unsigned &StructuredIndex,
1597                                            bool TopLevelObject) {
1598  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1599
1600  // If the record is invalid, some of it's members are invalid. To avoid
1601  // confusion, we forgo checking the intializer for the entire record.
1602  if (structDecl->isInvalidDecl()) {
1603    // Assume it was supposed to consume a single initializer.
1604    ++Index;
1605    hadError = true;
1606    return;
1607  }
1608
1609  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1610    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1611
1612    // If there's a default initializer, use it.
1613    if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1614      if (VerifyOnly)
1615        return;
1616      for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1617           Field != FieldEnd; ++Field) {
1618        if (Field->hasInClassInitializer()) {
1619          StructuredList->setInitializedFieldInUnion(*Field);
1620          // FIXME: Actually build a CXXDefaultInitExpr?
1621          return;
1622        }
1623      }
1624    }
1625
1626    // Value-initialize the first member of the union that isn't an unnamed
1627    // bitfield.
1628    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1629         Field != FieldEnd; ++Field) {
1630      if (!Field->isUnnamedBitfield()) {
1631        if (VerifyOnly)
1632          CheckEmptyInitializable(
1633              InitializedEntity::InitializeMember(*Field, &Entity),
1634              IList->getLocEnd());
1635        else
1636          StructuredList->setInitializedFieldInUnion(*Field);
1637        break;
1638      }
1639    }
1640    return;
1641  }
1642
1643  // If structDecl is a forward declaration, this loop won't do
1644  // anything except look at designated initializers; That's okay,
1645  // because an error should get printed out elsewhere. It might be
1646  // worthwhile to skip over the rest of the initializer, though.
1647  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1648  RecordDecl::field_iterator FieldEnd = RD->field_end();
1649  bool InitializedSomething = false;
1650  bool CheckForMissingFields = true;
1651  while (Index < IList->getNumInits()) {
1652    Expr *Init = IList->getInit(Index);
1653
1654    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1655      // If we're not the subobject that matches up with the '{' for
1656      // the designator, we shouldn't be handling the
1657      // designator. Return immediately.
1658      if (!SubobjectIsDesignatorContext)
1659        return;
1660
1661      // Handle this designated initializer. Field will be updated to
1662      // the next field that we'll be initializing.
1663      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1664                                     DeclType, &Field, nullptr, Index,
1665                                     StructuredList, StructuredIndex,
1666                                     true, TopLevelObject))
1667        hadError = true;
1668
1669      InitializedSomething = true;
1670
1671      // Disable check for missing fields when designators are used.
1672      // This matches gcc behaviour.
1673      CheckForMissingFields = false;
1674      continue;
1675    }
1676
1677    if (Field == FieldEnd) {
1678      // We've run out of fields. We're done.
1679      break;
1680    }
1681
1682    // We've already initialized a member of a union. We're done.
1683    if (InitializedSomething && DeclType->isUnionType())
1684      break;
1685
1686    // If we've hit the flexible array member at the end, we're done.
1687    if (Field->getType()->isIncompleteArrayType())
1688      break;
1689
1690    if (Field->isUnnamedBitfield()) {
1691      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1692      ++Field;
1693      continue;
1694    }
1695
1696    // Make sure we can use this declaration.
1697    bool InvalidUse;
1698    if (VerifyOnly)
1699      InvalidUse = !SemaRef.CanUseDecl(*Field);
1700    else
1701      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1702                                          IList->getInit(Index)->getLocStart());
1703    if (InvalidUse) {
1704      ++Index;
1705      ++Field;
1706      hadError = true;
1707      continue;
1708    }
1709
1710    InitializedEntity MemberEntity =
1711      InitializedEntity::InitializeMember(*Field, &Entity);
1712    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1713                        StructuredList, StructuredIndex);
1714    InitializedSomething = true;
1715
1716    if (DeclType->isUnionType() && !VerifyOnly) {
1717      // Initialize the first field within the union.
1718      StructuredList->setInitializedFieldInUnion(*Field);
1719    }
1720
1721    ++Field;
1722  }
1723
1724  // Emit warnings for missing struct field initializers.
1725  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1726      Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1727      !DeclType->isUnionType()) {
1728    // It is possible we have one or more unnamed bitfields remaining.
1729    // Find first (if any) named field and emit warning.
1730    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1731         it != end; ++it) {
1732      if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1733        SemaRef.Diag(IList->getSourceRange().getEnd(),
1734                     diag::warn_missing_field_initializers) << *it;
1735        break;
1736      }
1737    }
1738  }
1739
1740  // Check that any remaining fields can be value-initialized.
1741  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1742      !Field->getType()->isIncompleteArrayType()) {
1743    // FIXME: Should check for holes left by designated initializers too.
1744    for (; Field != FieldEnd && !hadError; ++Field) {
1745      if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1746        CheckEmptyInitializable(
1747            InitializedEntity::InitializeMember(*Field, &Entity),
1748            IList->getLocEnd());
1749    }
1750  }
1751
1752  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1753      Index >= IList->getNumInits())
1754    return;
1755
1756  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1757                             TopLevelObject)) {
1758    hadError = true;
1759    ++Index;
1760    return;
1761  }
1762
1763  InitializedEntity MemberEntity =
1764    InitializedEntity::InitializeMember(*Field, &Entity);
1765
1766  if (isa<InitListExpr>(IList->getInit(Index)))
1767    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1768                        StructuredList, StructuredIndex);
1769  else
1770    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1771                          StructuredList, StructuredIndex);
1772}
1773
1774/// \brief Expand a field designator that refers to a member of an
1775/// anonymous struct or union into a series of field designators that
1776/// refers to the field within the appropriate subobject.
1777///
1778static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1779                                           DesignatedInitExpr *DIE,
1780                                           unsigned DesigIdx,
1781                                           IndirectFieldDecl *IndirectField) {
1782  typedef DesignatedInitExpr::Designator Designator;
1783
1784  // Build the replacement designators.
1785  SmallVector<Designator, 4> Replacements;
1786  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1787       PE = IndirectField->chain_end(); PI != PE; ++PI) {
1788    if (PI + 1 == PE)
1789      Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1790                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1791                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1792    else
1793      Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1794                                        SourceLocation(), SourceLocation()));
1795    assert(isa<FieldDecl>(*PI));
1796    Replacements.back().setField(cast<FieldDecl>(*PI));
1797  }
1798
1799  // Expand the current designator into the set of replacement
1800  // designators, so we have a full subobject path down to where the
1801  // member of the anonymous struct/union is actually stored.
1802  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1803                        &Replacements[0] + Replacements.size());
1804}
1805
1806static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1807                                                   DesignatedInitExpr *DIE) {
1808  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1809  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1810  for (unsigned I = 0; I < NumIndexExprs; ++I)
1811    IndexExprs[I] = DIE->getSubExpr(I + 1);
1812  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1813                                    DIE->size(), IndexExprs,
1814                                    DIE->getEqualOrColonLoc(),
1815                                    DIE->usesGNUSyntax(), DIE->getInit());
1816}
1817
1818namespace {
1819
1820// Callback to only accept typo corrections that are for field members of
1821// the given struct or union.
1822class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1823 public:
1824  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1825      : Record(RD) {}
1826
1827  bool ValidateCandidate(const TypoCorrection &candidate) override {
1828    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1829    return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1830  }
1831
1832 private:
1833  RecordDecl *Record;
1834};
1835
1836}
1837
1838/// @brief Check the well-formedness of a C99 designated initializer.
1839///
1840/// Determines whether the designated initializer @p DIE, which
1841/// resides at the given @p Index within the initializer list @p
1842/// IList, is well-formed for a current object of type @p DeclType
1843/// (C99 6.7.8). The actual subobject that this designator refers to
1844/// within the current subobject is returned in either
1845/// @p NextField or @p NextElementIndex (whichever is appropriate).
1846///
1847/// @param IList  The initializer list in which this designated
1848/// initializer occurs.
1849///
1850/// @param DIE The designated initializer expression.
1851///
1852/// @param DesigIdx  The index of the current designator.
1853///
1854/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1855/// into which the designation in @p DIE should refer.
1856///
1857/// @param NextField  If non-NULL and the first designator in @p DIE is
1858/// a field, this will be set to the field declaration corresponding
1859/// to the field named by the designator.
1860///
1861/// @param NextElementIndex  If non-NULL and the first designator in @p
1862/// DIE is an array designator or GNU array-range designator, this
1863/// will be set to the last index initialized by this designator.
1864///
1865/// @param Index  Index into @p IList where the designated initializer
1866/// @p DIE occurs.
1867///
1868/// @param StructuredList  The initializer list expression that
1869/// describes all of the subobject initializers in the order they'll
1870/// actually be initialized.
1871///
1872/// @returns true if there was an error, false otherwise.
1873bool
1874InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1875                                            InitListExpr *IList,
1876                                            DesignatedInitExpr *DIE,
1877                                            unsigned DesigIdx,
1878                                            QualType &CurrentObjectType,
1879                                          RecordDecl::field_iterator *NextField,
1880                                            llvm::APSInt *NextElementIndex,
1881                                            unsigned &Index,
1882                                            InitListExpr *StructuredList,
1883                                            unsigned &StructuredIndex,
1884                                            bool FinishSubobjectInit,
1885                                            bool TopLevelObject) {
1886  if (DesigIdx == DIE->size()) {
1887    // Check the actual initialization for the designated object type.
1888    bool prevHadError = hadError;
1889
1890    // Temporarily remove the designator expression from the
1891    // initializer list that the child calls see, so that we don't try
1892    // to re-process the designator.
1893    unsigned OldIndex = Index;
1894    IList->setInit(OldIndex, DIE->getInit());
1895
1896    CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1897                        StructuredList, StructuredIndex);
1898
1899    // Restore the designated initializer expression in the syntactic
1900    // form of the initializer list.
1901    if (IList->getInit(OldIndex) != DIE->getInit())
1902      DIE->setInit(IList->getInit(OldIndex));
1903    IList->setInit(OldIndex, DIE);
1904
1905    return hadError && !prevHadError;
1906  }
1907
1908  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1909  bool IsFirstDesignator = (DesigIdx == 0);
1910  if (!VerifyOnly) {
1911    assert((IsFirstDesignator || StructuredList) &&
1912           "Need a non-designated initializer list to start from");
1913
1914    // Determine the structural initializer list that corresponds to the
1915    // current subobject.
1916    StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1917      : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1918                                   StructuredList, StructuredIndex,
1919                                   SourceRange(D->getLocStart(),
1920                                               DIE->getLocEnd()));
1921    assert(StructuredList && "Expected a structured initializer list");
1922  }
1923
1924  if (D->isFieldDesignator()) {
1925    // C99 6.7.8p7:
1926    //
1927    //   If a designator has the form
1928    //
1929    //      . identifier
1930    //
1931    //   then the current object (defined below) shall have
1932    //   structure or union type and the identifier shall be the
1933    //   name of a member of that type.
1934    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1935    if (!RT) {
1936      SourceLocation Loc = D->getDotLoc();
1937      if (Loc.isInvalid())
1938        Loc = D->getFieldLoc();
1939      if (!VerifyOnly)
1940        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1941          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1942      ++Index;
1943      return true;
1944    }
1945
1946    FieldDecl *KnownField = D->getField();
1947    if (!KnownField) {
1948      IdentifierInfo *FieldName = D->getFieldName();
1949      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1950      for (NamedDecl *ND : Lookup) {
1951        if (auto *FD = dyn_cast<FieldDecl>(ND)) {
1952          KnownField = FD;
1953          break;
1954        }
1955        if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
1956          // In verify mode, don't modify the original.
1957          if (VerifyOnly)
1958            DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1959          ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
1960          D = DIE->getDesignator(DesigIdx);
1961          KnownField = cast<FieldDecl>(*IFD->chain_begin());
1962          break;
1963        }
1964      }
1965      if (!KnownField) {
1966        if (VerifyOnly) {
1967          ++Index;
1968          return true;  // No typo correction when just trying this out.
1969        }
1970
1971        // Name lookup found something, but it wasn't a field.
1972        if (!Lookup.empty()) {
1973          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1974            << FieldName;
1975          SemaRef.Diag(Lookup.front()->getLocation(),
1976                       diag::note_field_designator_found);
1977          ++Index;
1978          return true;
1979        }
1980
1981        // Name lookup didn't find anything.
1982        // Determine whether this was a typo for another field name.
1983        if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1984                DeclarationNameInfo(FieldName, D->getFieldLoc()),
1985                Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
1986                llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
1987                Sema::CTK_ErrorRecovery, RT->getDecl())) {
1988          SemaRef.diagnoseTypo(
1989              Corrected,
1990              SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1991                << FieldName << CurrentObjectType);
1992          KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
1993          hadError = true;
1994        } else {
1995          // Typo correction didn't find anything.
1996          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1997            << FieldName << CurrentObjectType;
1998          ++Index;
1999          return true;
2000        }
2001      }
2002    }
2003
2004    unsigned FieldIndex = 0;
2005    for (auto *FI : RT->getDecl()->fields()) {
2006      if (FI->isUnnamedBitfield())
2007        continue;
2008      if (KnownField == FI)
2009        break;
2010      ++FieldIndex;
2011    }
2012
2013    RecordDecl::field_iterator Field =
2014        RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2015
2016    // All of the fields of a union are located at the same place in
2017    // the initializer list.
2018    if (RT->getDecl()->isUnion()) {
2019      FieldIndex = 0;
2020      if (!VerifyOnly) {
2021        FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2022        if (CurrentField && CurrentField != *Field) {
2023          assert(StructuredList->getNumInits() == 1
2024                 && "A union should never have more than one initializer!");
2025
2026          // we're about to throw away an initializer, emit warning
2027          SemaRef.Diag(D->getFieldLoc(),
2028                       diag::warn_initializer_overrides)
2029            << D->getSourceRange();
2030          Expr *ExistingInit = StructuredList->getInit(0);
2031          SemaRef.Diag(ExistingInit->getLocStart(),
2032                       diag::note_previous_initializer)
2033            << /*FIXME:has side effects=*/0
2034            << ExistingInit->getSourceRange();
2035
2036          // remove existing initializer
2037          StructuredList->resizeInits(SemaRef.Context, 0);
2038          StructuredList->setInitializedFieldInUnion(nullptr);
2039        }
2040
2041        StructuredList->setInitializedFieldInUnion(*Field);
2042      }
2043    }
2044
2045    // Make sure we can use this declaration.
2046    bool InvalidUse;
2047    if (VerifyOnly)
2048      InvalidUse = !SemaRef.CanUseDecl(*Field);
2049    else
2050      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2051    if (InvalidUse) {
2052      ++Index;
2053      return true;
2054    }
2055
2056    if (!VerifyOnly) {
2057      // Update the designator with the field declaration.
2058      D->setField(*Field);
2059
2060      // Make sure that our non-designated initializer list has space
2061      // for a subobject corresponding to this field.
2062      if (FieldIndex >= StructuredList->getNumInits())
2063        StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2064    }
2065
2066    // This designator names a flexible array member.
2067    if (Field->getType()->isIncompleteArrayType()) {
2068      bool Invalid = false;
2069      if ((DesigIdx + 1) != DIE->size()) {
2070        // We can't designate an object within the flexible array
2071        // member (because GCC doesn't allow it).
2072        if (!VerifyOnly) {
2073          DesignatedInitExpr::Designator *NextD
2074            = DIE->getDesignator(DesigIdx + 1);
2075          SemaRef.Diag(NextD->getLocStart(),
2076                        diag::err_designator_into_flexible_array_member)
2077            << SourceRange(NextD->getLocStart(),
2078                           DIE->getLocEnd());
2079          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2080            << *Field;
2081        }
2082        Invalid = true;
2083      }
2084
2085      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2086          !isa<StringLiteral>(DIE->getInit())) {
2087        // The initializer is not an initializer list.
2088        if (!VerifyOnly) {
2089          SemaRef.Diag(DIE->getInit()->getLocStart(),
2090                        diag::err_flexible_array_init_needs_braces)
2091            << DIE->getInit()->getSourceRange();
2092          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2093            << *Field;
2094        }
2095        Invalid = true;
2096      }
2097
2098      // Check GNU flexible array initializer.
2099      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2100                                             TopLevelObject))
2101        Invalid = true;
2102
2103      if (Invalid) {
2104        ++Index;
2105        return true;
2106      }
2107
2108      // Initialize the array.
2109      bool prevHadError = hadError;
2110      unsigned newStructuredIndex = FieldIndex;
2111      unsigned OldIndex = Index;
2112      IList->setInit(Index, DIE->getInit());
2113
2114      InitializedEntity MemberEntity =
2115        InitializedEntity::InitializeMember(*Field, &Entity);
2116      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2117                          StructuredList, newStructuredIndex);
2118
2119      IList->setInit(OldIndex, DIE);
2120      if (hadError && !prevHadError) {
2121        ++Field;
2122        ++FieldIndex;
2123        if (NextField)
2124          *NextField = Field;
2125        StructuredIndex = FieldIndex;
2126        return true;
2127      }
2128    } else {
2129      // Recurse to check later designated subobjects.
2130      QualType FieldType = Field->getType();
2131      unsigned newStructuredIndex = FieldIndex;
2132
2133      InitializedEntity MemberEntity =
2134        InitializedEntity::InitializeMember(*Field, &Entity);
2135      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2136                                     FieldType, nullptr, nullptr, Index,
2137                                     StructuredList, newStructuredIndex,
2138                                     true, false))
2139        return true;
2140    }
2141
2142    // Find the position of the next field to be initialized in this
2143    // subobject.
2144    ++Field;
2145    ++FieldIndex;
2146
2147    // If this the first designator, our caller will continue checking
2148    // the rest of this struct/class/union subobject.
2149    if (IsFirstDesignator) {
2150      if (NextField)
2151        *NextField = Field;
2152      StructuredIndex = FieldIndex;
2153      return false;
2154    }
2155
2156    if (!FinishSubobjectInit)
2157      return false;
2158
2159    // We've already initialized something in the union; we're done.
2160    if (RT->getDecl()->isUnion())
2161      return hadError;
2162
2163    // Check the remaining fields within this class/struct/union subobject.
2164    bool prevHadError = hadError;
2165
2166    CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
2167                          StructuredList, FieldIndex);
2168    return hadError && !prevHadError;
2169  }
2170
2171  // C99 6.7.8p6:
2172  //
2173  //   If a designator has the form
2174  //
2175  //      [ constant-expression ]
2176  //
2177  //   then the current object (defined below) shall have array
2178  //   type and the expression shall be an integer constant
2179  //   expression. If the array is of unknown size, any
2180  //   nonnegative value is valid.
2181  //
2182  // Additionally, cope with the GNU extension that permits
2183  // designators of the form
2184  //
2185  //      [ constant-expression ... constant-expression ]
2186  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2187  if (!AT) {
2188    if (!VerifyOnly)
2189      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2190        << CurrentObjectType;
2191    ++Index;
2192    return true;
2193  }
2194
2195  Expr *IndexExpr = nullptr;
2196  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2197  if (D->isArrayDesignator()) {
2198    IndexExpr = DIE->getArrayIndex(*D);
2199    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2200    DesignatedEndIndex = DesignatedStartIndex;
2201  } else {
2202    assert(D->isArrayRangeDesignator() && "Need array-range designator");
2203
2204    DesignatedStartIndex =
2205      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2206    DesignatedEndIndex =
2207      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2208    IndexExpr = DIE->getArrayRangeEnd(*D);
2209
2210    // Codegen can't handle evaluating array range designators that have side
2211    // effects, because we replicate the AST value for each initialized element.
2212    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2213    // elements with something that has a side effect, so codegen can emit an
2214    // "error unsupported" error instead of miscompiling the app.
2215    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2216        DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2217      FullyStructuredList->sawArrayRangeDesignator();
2218  }
2219
2220  if (isa<ConstantArrayType>(AT)) {
2221    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2222    DesignatedStartIndex
2223      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2224    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2225    DesignatedEndIndex
2226      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2227    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2228    if (DesignatedEndIndex >= MaxElements) {
2229      if (!VerifyOnly)
2230        SemaRef.Diag(IndexExpr->getLocStart(),
2231                      diag::err_array_designator_too_large)
2232          << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2233          << IndexExpr->getSourceRange();
2234      ++Index;
2235      return true;
2236    }
2237  } else {
2238    // Make sure the bit-widths and signedness match.
2239    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2240      DesignatedEndIndex
2241        = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2242    else if (DesignatedStartIndex.getBitWidth() <
2243             DesignatedEndIndex.getBitWidth())
2244      DesignatedStartIndex
2245        = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2246    DesignatedStartIndex.setIsUnsigned(true);
2247    DesignatedEndIndex.setIsUnsigned(true);
2248  }
2249
2250  if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2251    // We're modifying a string literal init; we have to decompose the string
2252    // so we can modify the individual characters.
2253    ASTContext &Context = SemaRef.Context;
2254    Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2255
2256    // Compute the character type
2257    QualType CharTy = AT->getElementType();
2258
2259    // Compute the type of the integer literals.
2260    QualType PromotedCharTy = CharTy;
2261    if (CharTy->isPromotableIntegerType())
2262      PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2263    unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2264
2265    if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2266      // Get the length of the string.
2267      uint64_t StrLen = SL->getLength();
2268      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2269        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2270      StructuredList->resizeInits(Context, StrLen);
2271
2272      // Build a literal for each character in the string, and put them into
2273      // the init list.
2274      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2275        llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2276        Expr *Init = new (Context) IntegerLiteral(
2277            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2278        if (CharTy != PromotedCharTy)
2279          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2280                                          Init, nullptr, VK_RValue);
2281        StructuredList->updateInit(Context, i, Init);
2282      }
2283    } else {
2284      ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2285      std::string Str;
2286      Context.getObjCEncodingForType(E->getEncodedType(), Str);
2287
2288      // Get the length of the string.
2289      uint64_t StrLen = Str.size();
2290      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2291        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2292      StructuredList->resizeInits(Context, StrLen);
2293
2294      // Build a literal for each character in the string, and put them into
2295      // the init list.
2296      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2297        llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2298        Expr *Init = new (Context) IntegerLiteral(
2299            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2300        if (CharTy != PromotedCharTy)
2301          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2302                                          Init, nullptr, VK_RValue);
2303        StructuredList->updateInit(Context, i, Init);
2304      }
2305    }
2306  }
2307
2308  // Make sure that our non-designated initializer list has space
2309  // for a subobject corresponding to this array element.
2310  if (!VerifyOnly &&
2311      DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2312    StructuredList->resizeInits(SemaRef.Context,
2313                                DesignatedEndIndex.getZExtValue() + 1);
2314
2315  // Repeatedly perform subobject initializations in the range
2316  // [DesignatedStartIndex, DesignatedEndIndex].
2317
2318  // Move to the next designator
2319  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2320  unsigned OldIndex = Index;
2321
2322  InitializedEntity ElementEntity =
2323    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2324
2325  while (DesignatedStartIndex <= DesignatedEndIndex) {
2326    // Recurse to check later designated subobjects.
2327    QualType ElementType = AT->getElementType();
2328    Index = OldIndex;
2329
2330    ElementEntity.setElementIndex(ElementIndex);
2331    if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2332                                   ElementType, nullptr, nullptr, Index,
2333                                   StructuredList, ElementIndex,
2334                                   (DesignatedStartIndex == DesignatedEndIndex),
2335                                   false))
2336      return true;
2337
2338    // Move to the next index in the array that we'll be initializing.
2339    ++DesignatedStartIndex;
2340    ElementIndex = DesignatedStartIndex.getZExtValue();
2341  }
2342
2343  // If this the first designator, our caller will continue checking
2344  // the rest of this array subobject.
2345  if (IsFirstDesignator) {
2346    if (NextElementIndex)
2347      *NextElementIndex = DesignatedStartIndex;
2348    StructuredIndex = ElementIndex;
2349    return false;
2350  }
2351
2352  if (!FinishSubobjectInit)
2353    return false;
2354
2355  // Check the remaining elements within this array subobject.
2356  bool prevHadError = hadError;
2357  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2358                 /*SubobjectIsDesignatorContext=*/false, Index,
2359                 StructuredList, ElementIndex);
2360  return hadError && !prevHadError;
2361}
2362
2363// Get the structured initializer list for a subobject of type
2364// @p CurrentObjectType.
2365InitListExpr *
2366InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2367                                            QualType CurrentObjectType,
2368                                            InitListExpr *StructuredList,
2369                                            unsigned StructuredIndex,
2370                                            SourceRange InitRange) {
2371  if (VerifyOnly)
2372    return nullptr; // No structured list in verification-only mode.
2373  Expr *ExistingInit = nullptr;
2374  if (!StructuredList)
2375    ExistingInit = SyntacticToSemantic.lookup(IList);
2376  else if (StructuredIndex < StructuredList->getNumInits())
2377    ExistingInit = StructuredList->getInit(StructuredIndex);
2378
2379  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2380    return Result;
2381
2382  if (ExistingInit) {
2383    // We are creating an initializer list that initializes the
2384    // subobjects of the current object, but there was already an
2385    // initialization that completely initialized the current
2386    // subobject, e.g., by a compound literal:
2387    //
2388    // struct X { int a, b; };
2389    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2390    //
2391    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2392    // designated initializer re-initializes the whole
2393    // subobject [0], overwriting previous initializers.
2394    SemaRef.Diag(InitRange.getBegin(),
2395                 diag::warn_subobject_initializer_overrides)
2396      << InitRange;
2397    SemaRef.Diag(ExistingInit->getLocStart(),
2398                  diag::note_previous_initializer)
2399      << /*FIXME:has side effects=*/0
2400      << ExistingInit->getSourceRange();
2401  }
2402
2403  InitListExpr *Result
2404    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2405                                         InitRange.getBegin(), None,
2406                                         InitRange.getEnd());
2407
2408  QualType ResultType = CurrentObjectType;
2409  if (!ResultType->isArrayType())
2410    ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2411  Result->setType(ResultType);
2412
2413  // Pre-allocate storage for the structured initializer list.
2414  unsigned NumElements = 0;
2415  unsigned NumInits = 0;
2416  bool GotNumInits = false;
2417  if (!StructuredList) {
2418    NumInits = IList->getNumInits();
2419    GotNumInits = true;
2420  } else if (Index < IList->getNumInits()) {
2421    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2422      NumInits = SubList->getNumInits();
2423      GotNumInits = true;
2424    }
2425  }
2426
2427  if (const ArrayType *AType
2428      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2429    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2430      NumElements = CAType->getSize().getZExtValue();
2431      // Simple heuristic so that we don't allocate a very large
2432      // initializer with many empty entries at the end.
2433      if (GotNumInits && NumElements > NumInits)
2434        NumElements = 0;
2435    }
2436  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2437    NumElements = VType->getNumElements();
2438  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2439    RecordDecl *RDecl = RType->getDecl();
2440    if (RDecl->isUnion())
2441      NumElements = 1;
2442    else
2443      NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2444  }
2445
2446  Result->reserveInits(SemaRef.Context, NumElements);
2447
2448  // Link this new initializer list into the structured initializer
2449  // lists.
2450  if (StructuredList)
2451    StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2452  else {
2453    Result->setSyntacticForm(IList);
2454    SyntacticToSemantic[IList] = Result;
2455  }
2456
2457  return Result;
2458}
2459
2460/// Update the initializer at index @p StructuredIndex within the
2461/// structured initializer list to the value @p expr.
2462void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2463                                                  unsigned &StructuredIndex,
2464                                                  Expr *expr) {
2465  // No structured initializer list to update
2466  if (!StructuredList)
2467    return;
2468
2469  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2470                                                  StructuredIndex, expr)) {
2471    // This initializer overwrites a previous initializer. Warn.
2472    SemaRef.Diag(expr->getLocStart(),
2473                  diag::warn_initializer_overrides)
2474      << expr->getSourceRange();
2475    SemaRef.Diag(PrevInit->getLocStart(),
2476                  diag::note_previous_initializer)
2477      << /*FIXME:has side effects=*/0
2478      << PrevInit->getSourceRange();
2479  }
2480
2481  ++StructuredIndex;
2482}
2483
2484/// Check that the given Index expression is a valid array designator
2485/// value. This is essentially just a wrapper around
2486/// VerifyIntegerConstantExpression that also checks for negative values
2487/// and produces a reasonable diagnostic if there is a
2488/// failure. Returns the index expression, possibly with an implicit cast
2489/// added, on success.  If everything went okay, Value will receive the
2490/// value of the constant expression.
2491static ExprResult
2492CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2493  SourceLocation Loc = Index->getLocStart();
2494
2495  // Make sure this is an integer constant expression.
2496  ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2497  if (Result.isInvalid())
2498    return Result;
2499
2500  if (Value.isSigned() && Value.isNegative())
2501    return S.Diag(Loc, diag::err_array_designator_negative)
2502      << Value.toString(10) << Index->getSourceRange();
2503
2504  Value.setIsUnsigned(true);
2505  return Result;
2506}
2507
2508ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2509                                            SourceLocation Loc,
2510                                            bool GNUSyntax,
2511                                            ExprResult Init) {
2512  typedef DesignatedInitExpr::Designator ASTDesignator;
2513
2514  bool Invalid = false;
2515  SmallVector<ASTDesignator, 32> Designators;
2516  SmallVector<Expr *, 32> InitExpressions;
2517
2518  // Build designators and check array designator expressions.
2519  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2520    const Designator &D = Desig.getDesignator(Idx);
2521    switch (D.getKind()) {
2522    case Designator::FieldDesignator:
2523      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2524                                          D.getFieldLoc()));
2525      break;
2526
2527    case Designator::ArrayDesignator: {
2528      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2529      llvm::APSInt IndexValue;
2530      if (!Index->isTypeDependent() && !Index->isValueDependent())
2531        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2532      if (!Index)
2533        Invalid = true;
2534      else {
2535        Designators.push_back(ASTDesignator(InitExpressions.size(),
2536                                            D.getLBracketLoc(),
2537                                            D.getRBracketLoc()));
2538        InitExpressions.push_back(Index);
2539      }
2540      break;
2541    }
2542
2543    case Designator::ArrayRangeDesignator: {
2544      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2545      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2546      llvm::APSInt StartValue;
2547      llvm::APSInt EndValue;
2548      bool StartDependent = StartIndex->isTypeDependent() ||
2549                            StartIndex->isValueDependent();
2550      bool EndDependent = EndIndex->isTypeDependent() ||
2551                          EndIndex->isValueDependent();
2552      if (!StartDependent)
2553        StartIndex =
2554            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2555      if (!EndDependent)
2556        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2557
2558      if (!StartIndex || !EndIndex)
2559        Invalid = true;
2560      else {
2561        // Make sure we're comparing values with the same bit width.
2562        if (StartDependent || EndDependent) {
2563          // Nothing to compute.
2564        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2565          EndValue = EndValue.extend(StartValue.getBitWidth());
2566        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2567          StartValue = StartValue.extend(EndValue.getBitWidth());
2568
2569        if (!StartDependent && !EndDependent && EndValue < StartValue) {
2570          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2571            << StartValue.toString(10) << EndValue.toString(10)
2572            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2573          Invalid = true;
2574        } else {
2575          Designators.push_back(ASTDesignator(InitExpressions.size(),
2576                                              D.getLBracketLoc(),
2577                                              D.getEllipsisLoc(),
2578                                              D.getRBracketLoc()));
2579          InitExpressions.push_back(StartIndex);
2580          InitExpressions.push_back(EndIndex);
2581        }
2582      }
2583      break;
2584    }
2585    }
2586  }
2587
2588  if (Invalid || Init.isInvalid())
2589    return ExprError();
2590
2591  // Clear out the expressions within the designation.
2592  Desig.ClearExprs(*this);
2593
2594  DesignatedInitExpr *DIE
2595    = DesignatedInitExpr::Create(Context,
2596                                 Designators.data(), Designators.size(),
2597                                 InitExpressions, Loc, GNUSyntax,
2598                                 Init.getAs<Expr>());
2599
2600  if (!getLangOpts().C99)
2601    Diag(DIE->getLocStart(), diag::ext_designated_init)
2602      << DIE->getSourceRange();
2603
2604  return DIE;
2605}
2606
2607//===----------------------------------------------------------------------===//
2608// Initialization entity
2609//===----------------------------------------------------------------------===//
2610
2611InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2612                                     const InitializedEntity &Parent)
2613  : Parent(&Parent), Index(Index)
2614{
2615  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2616    Kind = EK_ArrayElement;
2617    Type = AT->getElementType();
2618  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2619    Kind = EK_VectorElement;
2620    Type = VT->getElementType();
2621  } else {
2622    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2623    assert(CT && "Unexpected type");
2624    Kind = EK_ComplexElement;
2625    Type = CT->getElementType();
2626  }
2627}
2628
2629InitializedEntity
2630InitializedEntity::InitializeBase(ASTContext &Context,
2631                                  const CXXBaseSpecifier *Base,
2632                                  bool IsInheritedVirtualBase) {
2633  InitializedEntity Result;
2634  Result.Kind = EK_Base;
2635  Result.Parent = nullptr;
2636  Result.Base = reinterpret_cast<uintptr_t>(Base);
2637  if (IsInheritedVirtualBase)
2638    Result.Base |= 0x01;
2639
2640  Result.Type = Base->getType();
2641  return Result;
2642}
2643
2644DeclarationName InitializedEntity::getName() const {
2645  switch (getKind()) {
2646  case EK_Parameter:
2647  case EK_Parameter_CF_Audited: {
2648    ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2649    return (D ? D->getDeclName() : DeclarationName());
2650  }
2651
2652  case EK_Variable:
2653  case EK_Member:
2654    return VariableOrMember->getDeclName();
2655
2656  case EK_LambdaCapture:
2657    return DeclarationName(Capture.VarID);
2658
2659  case EK_Result:
2660  case EK_Exception:
2661  case EK_New:
2662  case EK_Temporary:
2663  case EK_Base:
2664  case EK_Delegating:
2665  case EK_ArrayElement:
2666  case EK_VectorElement:
2667  case EK_ComplexElement:
2668  case EK_BlockElement:
2669  case EK_CompoundLiteralInit:
2670  case EK_RelatedResult:
2671    return DeclarationName();
2672  }
2673
2674  llvm_unreachable("Invalid EntityKind!");
2675}
2676
2677DeclaratorDecl *InitializedEntity::getDecl() const {
2678  switch (getKind()) {
2679  case EK_Variable:
2680  case EK_Member:
2681    return VariableOrMember;
2682
2683  case EK_Parameter:
2684  case EK_Parameter_CF_Audited:
2685    return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2686
2687  case EK_Result:
2688  case EK_Exception:
2689  case EK_New:
2690  case EK_Temporary:
2691  case EK_Base:
2692  case EK_Delegating:
2693  case EK_ArrayElement:
2694  case EK_VectorElement:
2695  case EK_ComplexElement:
2696  case EK_BlockElement:
2697  case EK_LambdaCapture:
2698  case EK_CompoundLiteralInit:
2699  case EK_RelatedResult:
2700    return nullptr;
2701  }
2702
2703  llvm_unreachable("Invalid EntityKind!");
2704}
2705
2706bool InitializedEntity::allowsNRVO() const {
2707  switch (getKind()) {
2708  case EK_Result:
2709  case EK_Exception:
2710    return LocAndNRVO.NRVO;
2711
2712  case EK_Variable:
2713  case EK_Parameter:
2714  case EK_Parameter_CF_Audited:
2715  case EK_Member:
2716  case EK_New:
2717  case EK_Temporary:
2718  case EK_CompoundLiteralInit:
2719  case EK_Base:
2720  case EK_Delegating:
2721  case EK_ArrayElement:
2722  case EK_VectorElement:
2723  case EK_ComplexElement:
2724  case EK_BlockElement:
2725  case EK_LambdaCapture:
2726  case EK_RelatedResult:
2727    break;
2728  }
2729
2730  return false;
2731}
2732
2733unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2734  assert(getParent() != this);
2735  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2736  for (unsigned I = 0; I != Depth; ++I)
2737    OS << "`-";
2738
2739  switch (getKind()) {
2740  case EK_Variable: OS << "Variable"; break;
2741  case EK_Parameter: OS << "Parameter"; break;
2742  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2743    break;
2744  case EK_Result: OS << "Result"; break;
2745  case EK_Exception: OS << "Exception"; break;
2746  case EK_Member: OS << "Member"; break;
2747  case EK_New: OS << "New"; break;
2748  case EK_Temporary: OS << "Temporary"; break;
2749  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2750  case EK_RelatedResult: OS << "RelatedResult"; break;
2751  case EK_Base: OS << "Base"; break;
2752  case EK_Delegating: OS << "Delegating"; break;
2753  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2754  case EK_VectorElement: OS << "VectorElement " << Index; break;
2755  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2756  case EK_BlockElement: OS << "Block"; break;
2757  case EK_LambdaCapture:
2758    OS << "LambdaCapture ";
2759    OS << DeclarationName(Capture.VarID);
2760    break;
2761  }
2762
2763  if (Decl *D = getDecl()) {
2764    OS << " ";
2765    cast<NamedDecl>(D)->printQualifiedName(OS);
2766  }
2767
2768  OS << " '" << getType().getAsString() << "'\n";
2769
2770  return Depth + 1;
2771}
2772
2773void InitializedEntity::dump() const {
2774  dumpImpl(llvm::errs());
2775}
2776
2777//===----------------------------------------------------------------------===//
2778// Initialization sequence
2779//===----------------------------------------------------------------------===//
2780
2781void InitializationSequence::Step::Destroy() {
2782  switch (Kind) {
2783  case SK_ResolveAddressOfOverloadedFunction:
2784  case SK_CastDerivedToBaseRValue:
2785  case SK_CastDerivedToBaseXValue:
2786  case SK_CastDerivedToBaseLValue:
2787  case SK_BindReference:
2788  case SK_BindReferenceToTemporary:
2789  case SK_ExtraneousCopyToTemporary:
2790  case SK_UserConversion:
2791  case SK_QualificationConversionRValue:
2792  case SK_QualificationConversionXValue:
2793  case SK_QualificationConversionLValue:
2794  case SK_AtomicConversion:
2795  case SK_LValueToRValue:
2796  case SK_ListInitialization:
2797  case SK_UnwrapInitList:
2798  case SK_RewrapInitList:
2799  case SK_ConstructorInitialization:
2800  case SK_ConstructorInitializationFromList:
2801  case SK_ZeroInitialization:
2802  case SK_CAssignment:
2803  case SK_StringInit:
2804  case SK_ObjCObjectConversion:
2805  case SK_ArrayInit:
2806  case SK_ParenthesizedArrayInit:
2807  case SK_PassByIndirectCopyRestore:
2808  case SK_PassByIndirectRestore:
2809  case SK_ProduceObjCObject:
2810  case SK_StdInitializerList:
2811  case SK_StdInitializerListConstructorCall:
2812  case SK_OCLSamplerInit:
2813  case SK_OCLZeroEvent:
2814    break;
2815
2816  case SK_ConversionSequence:
2817  case SK_ConversionSequenceNoNarrowing:
2818    delete ICS;
2819  }
2820}
2821
2822bool InitializationSequence::isDirectReferenceBinding() const {
2823  return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2824}
2825
2826bool InitializationSequence::isAmbiguous() const {
2827  if (!Failed())
2828    return false;
2829
2830  switch (getFailureKind()) {
2831  case FK_TooManyInitsForReference:
2832  case FK_ArrayNeedsInitList:
2833  case FK_ArrayNeedsInitListOrStringLiteral:
2834  case FK_ArrayNeedsInitListOrWideStringLiteral:
2835  case FK_NarrowStringIntoWideCharArray:
2836  case FK_WideStringIntoCharArray:
2837  case FK_IncompatWideStringIntoWideChar:
2838  case FK_AddressOfOverloadFailed: // FIXME: Could do better
2839  case FK_NonConstLValueReferenceBindingToTemporary:
2840  case FK_NonConstLValueReferenceBindingToUnrelated:
2841  case FK_RValueReferenceBindingToLValue:
2842  case FK_ReferenceInitDropsQualifiers:
2843  case FK_ReferenceInitFailed:
2844  case FK_ConversionFailed:
2845  case FK_ConversionFromPropertyFailed:
2846  case FK_TooManyInitsForScalar:
2847  case FK_ReferenceBindingToInitList:
2848  case FK_InitListBadDestinationType:
2849  case FK_DefaultInitOfConst:
2850  case FK_Incomplete:
2851  case FK_ArrayTypeMismatch:
2852  case FK_NonConstantArrayInit:
2853  case FK_ListInitializationFailed:
2854  case FK_VariableLengthArrayHasInitializer:
2855  case FK_PlaceholderType:
2856  case FK_ExplicitConstructor:
2857    return false;
2858
2859  case FK_ReferenceInitOverloadFailed:
2860  case FK_UserConversionOverloadFailed:
2861  case FK_ConstructorOverloadFailed:
2862  case FK_ListConstructorOverloadFailed:
2863    return FailedOverloadResult == OR_Ambiguous;
2864  }
2865
2866  llvm_unreachable("Invalid EntityKind!");
2867}
2868
2869bool InitializationSequence::isConstructorInitialization() const {
2870  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2871}
2872
2873void
2874InitializationSequence
2875::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2876                                   DeclAccessPair Found,
2877                                   bool HadMultipleCandidates) {
2878  Step S;
2879  S.Kind = SK_ResolveAddressOfOverloadedFunction;
2880  S.Type = Function->getType();
2881  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2882  S.Function.Function = Function;
2883  S.Function.FoundDecl = Found;
2884  Steps.push_back(S);
2885}
2886
2887void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2888                                                      ExprValueKind VK) {
2889  Step S;
2890  switch (VK) {
2891  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2892  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2893  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2894  }
2895  S.Type = BaseType;
2896  Steps.push_back(S);
2897}
2898
2899void InitializationSequence::AddReferenceBindingStep(QualType T,
2900                                                     bool BindingTemporary) {
2901  Step S;
2902  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2903  S.Type = T;
2904  Steps.push_back(S);
2905}
2906
2907void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2908  Step S;
2909  S.Kind = SK_ExtraneousCopyToTemporary;
2910  S.Type = T;
2911  Steps.push_back(S);
2912}
2913
2914void
2915InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2916                                              DeclAccessPair FoundDecl,
2917                                              QualType T,
2918                                              bool HadMultipleCandidates) {
2919  Step S;
2920  S.Kind = SK_UserConversion;
2921  S.Type = T;
2922  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2923  S.Function.Function = Function;
2924  S.Function.FoundDecl = FoundDecl;
2925  Steps.push_back(S);
2926}
2927
2928void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2929                                                            ExprValueKind VK) {
2930  Step S;
2931  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2932  switch (VK) {
2933  case VK_RValue:
2934    S.Kind = SK_QualificationConversionRValue;
2935    break;
2936  case VK_XValue:
2937    S.Kind = SK_QualificationConversionXValue;
2938    break;
2939  case VK_LValue:
2940    S.Kind = SK_QualificationConversionLValue;
2941    break;
2942  }
2943  S.Type = Ty;
2944  Steps.push_back(S);
2945}
2946
2947void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2948  Step S;
2949  S.Kind = SK_AtomicConversion;
2950  S.Type = Ty;
2951  Steps.push_back(S);
2952}
2953
2954void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2955  assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2956
2957  Step S;
2958  S.Kind = SK_LValueToRValue;
2959  S.Type = Ty;
2960  Steps.push_back(S);
2961}
2962
2963void InitializationSequence::AddConversionSequenceStep(
2964    const ImplicitConversionSequence &ICS, QualType T,
2965    bool TopLevelOfInitList) {
2966  Step S;
2967  S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2968                              : SK_ConversionSequence;
2969  S.Type = T;
2970  S.ICS = new ImplicitConversionSequence(ICS);
2971  Steps.push_back(S);
2972}
2973
2974void InitializationSequence::AddListInitializationStep(QualType T) {
2975  Step S;
2976  S.Kind = SK_ListInitialization;
2977  S.Type = T;
2978  Steps.push_back(S);
2979}
2980
2981void
2982InitializationSequence
2983::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2984                                   AccessSpecifier Access,
2985                                   QualType T,
2986                                   bool HadMultipleCandidates,
2987                                   bool FromInitList, bool AsInitList) {
2988  Step S;
2989  S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
2990                                     : SK_ConstructorInitializationFromList
2991                        : SK_ConstructorInitialization;
2992  S.Type = T;
2993  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2994  S.Function.Function = Constructor;
2995  S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2996  Steps.push_back(S);
2997}
2998
2999void InitializationSequence::AddZeroInitializationStep(QualType T) {
3000  Step S;
3001  S.Kind = SK_ZeroInitialization;
3002  S.Type = T;
3003  Steps.push_back(S);
3004}
3005
3006void InitializationSequence::AddCAssignmentStep(QualType T) {
3007  Step S;
3008  S.Kind = SK_CAssignment;
3009  S.Type = T;
3010  Steps.push_back(S);
3011}
3012
3013void InitializationSequence::AddStringInitStep(QualType T) {
3014  Step S;
3015  S.Kind = SK_StringInit;
3016  S.Type = T;
3017  Steps.push_back(S);
3018}
3019
3020void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3021  Step S;
3022  S.Kind = SK_ObjCObjectConversion;
3023  S.Type = T;
3024  Steps.push_back(S);
3025}
3026
3027void InitializationSequence::AddArrayInitStep(QualType T) {
3028  Step S;
3029  S.Kind = SK_ArrayInit;
3030  S.Type = T;
3031  Steps.push_back(S);
3032}
3033
3034void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3035  Step S;
3036  S.Kind = SK_ParenthesizedArrayInit;
3037  S.Type = T;
3038  Steps.push_back(S);
3039}
3040
3041void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3042                                                              bool shouldCopy) {
3043  Step s;
3044  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3045                       : SK_PassByIndirectRestore);
3046  s.Type = type;
3047  Steps.push_back(s);
3048}
3049
3050void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3051  Step S;
3052  S.Kind = SK_ProduceObjCObject;
3053  S.Type = T;
3054  Steps.push_back(S);
3055}
3056
3057void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3058  Step S;
3059  S.Kind = SK_StdInitializerList;
3060  S.Type = T;
3061  Steps.push_back(S);
3062}
3063
3064void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3065  Step S;
3066  S.Kind = SK_OCLSamplerInit;
3067  S.Type = T;
3068  Steps.push_back(S);
3069}
3070
3071void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3072  Step S;
3073  S.Kind = SK_OCLZeroEvent;
3074  S.Type = T;
3075  Steps.push_back(S);
3076}
3077
3078void InitializationSequence::RewrapReferenceInitList(QualType T,
3079                                                     InitListExpr *Syntactic) {
3080  assert(Syntactic->getNumInits() == 1 &&
3081         "Can only rewrap trivial init lists.");
3082  Step S;
3083  S.Kind = SK_UnwrapInitList;
3084  S.Type = Syntactic->getInit(0)->getType();
3085  Steps.insert(Steps.begin(), S);
3086
3087  S.Kind = SK_RewrapInitList;
3088  S.Type = T;
3089  S.WrappingSyntacticList = Syntactic;
3090  Steps.push_back(S);
3091}
3092
3093void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3094                                                OverloadingResult Result) {
3095  setSequenceKind(FailedSequence);
3096  this->Failure = Failure;
3097  this->FailedOverloadResult = Result;
3098}
3099
3100//===----------------------------------------------------------------------===//
3101// Attempt initialization
3102//===----------------------------------------------------------------------===//
3103
3104static void MaybeProduceObjCObject(Sema &S,
3105                                   InitializationSequence &Sequence,
3106                                   const InitializedEntity &Entity) {
3107  if (!S.getLangOpts().ObjCAutoRefCount) return;
3108
3109  /// When initializing a parameter, produce the value if it's marked
3110  /// __attribute__((ns_consumed)).
3111  if (Entity.isParameterKind()) {
3112    if (!Entity.isParameterConsumed())
3113      return;
3114
3115    assert(Entity.getType()->isObjCRetainableType() &&
3116           "consuming an object of unretainable type?");
3117    Sequence.AddProduceObjCObjectStep(Entity.getType());
3118
3119  /// When initializing a return value, if the return type is a
3120  /// retainable type, then returns need to immediately retain the
3121  /// object.  If an autorelease is required, it will be done at the
3122  /// last instant.
3123  } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3124    if (!Entity.getType()->isObjCRetainableType())
3125      return;
3126
3127    Sequence.AddProduceObjCObjectStep(Entity.getType());
3128  }
3129}
3130
3131static void TryListInitialization(Sema &S,
3132                                  const InitializedEntity &Entity,
3133                                  const InitializationKind &Kind,
3134                                  InitListExpr *InitList,
3135                                  InitializationSequence &Sequence);
3136
3137/// \brief When initializing from init list via constructor, handle
3138/// initialization of an object of type std::initializer_list<T>.
3139///
3140/// \return true if we have handled initialization of an object of type
3141/// std::initializer_list<T>, false otherwise.
3142static bool TryInitializerListConstruction(Sema &S,
3143                                           InitListExpr *List,
3144                                           QualType DestType,
3145                                           InitializationSequence &Sequence) {
3146  QualType E;
3147  if (!S.isStdInitializerList(DestType, &E))
3148    return false;
3149
3150  if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3151    Sequence.setIncompleteTypeFailure(E);
3152    return true;
3153  }
3154
3155  // Try initializing a temporary array from the init list.
3156  QualType ArrayType = S.Context.getConstantArrayType(
3157      E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3158                                 List->getNumInits()),
3159      clang::ArrayType::Normal, 0);
3160  InitializedEntity HiddenArray =
3161      InitializedEntity::InitializeTemporary(ArrayType);
3162  InitializationKind Kind =
3163      InitializationKind::CreateDirectList(List->getExprLoc());
3164  TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3165  if (Sequence)
3166    Sequence.AddStdInitializerListConstructionStep(DestType);
3167  return true;
3168}
3169
3170static OverloadingResult
3171ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3172                           MultiExprArg Args,
3173                           OverloadCandidateSet &CandidateSet,
3174                           DeclContext::lookup_result Ctors,
3175                           OverloadCandidateSet::iterator &Best,
3176                           bool CopyInitializing, bool AllowExplicit,
3177                           bool OnlyListConstructors, bool IsListInit) {
3178  CandidateSet.clear();
3179
3180  for (NamedDecl *D : Ctors) {
3181    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3182    bool SuppressUserConversions = false;
3183
3184    // Find the constructor (which may be a template).
3185    CXXConstructorDecl *Constructor = nullptr;
3186    FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3187    if (ConstructorTmpl)
3188      Constructor = cast<CXXConstructorDecl>(
3189                                           ConstructorTmpl->getTemplatedDecl());
3190    else {
3191      Constructor = cast<CXXConstructorDecl>(D);
3192
3193      // C++11 [over.best.ics]p4:
3194      //   ... and the constructor or user-defined conversion function is a
3195      //   candidate by
3196      //   - 13.3.1.3, when the argument is the temporary in the second step
3197      //     of a class copy-initialization, or
3198      //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
3199      //   user-defined conversion sequences are not considered.
3200      // FIXME: This breaks backward compatibility, e.g. PR12117. As a
3201      //        temporary fix, let's re-instate the third bullet above until
3202      //        there is a resolution in the standard, i.e.,
3203      //   - 13.3.1.7 when the initializer list has exactly one element that is
3204      //     itself an initializer list and a conversion to some class X or
3205      //     reference to (possibly cv-qualified) X is considered for the first
3206      //     parameter of a constructor of X.
3207      if ((CopyInitializing ||
3208           (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3209          Constructor->isCopyOrMoveConstructor())
3210        SuppressUserConversions = true;
3211    }
3212
3213    if (!Constructor->isInvalidDecl() &&
3214        (AllowExplicit || !Constructor->isExplicit()) &&
3215        (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
3216      if (ConstructorTmpl)
3217        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3218                                       /*ExplicitArgs*/ nullptr, Args,
3219                                       CandidateSet, SuppressUserConversions);
3220      else {
3221        // C++ [over.match.copy]p1:
3222        //   - When initializing a temporary to be bound to the first parameter
3223        //     of a constructor that takes a reference to possibly cv-qualified
3224        //     T as its first argument, called with a single argument in the
3225        //     context of direct-initialization, explicit conversion functions
3226        //     are also considered.
3227        bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3228                                 Args.size() == 1 &&
3229                                 Constructor->isCopyOrMoveConstructor();
3230        S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
3231                               SuppressUserConversions,
3232                               /*PartialOverloading=*/false,
3233                               /*AllowExplicit=*/AllowExplicitConv);
3234      }
3235    }
3236  }
3237
3238  // Perform overload resolution and return the result.
3239  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3240}
3241
3242/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3243/// enumerates the constructors of the initialized entity and performs overload
3244/// resolution to select the best.
3245/// \param IsListInit     Is this list-initialization?
3246/// \param IsInitListCopy Is this non-list-initialization resulting from a
3247///                       list-initialization from {x} where x is the same
3248///                       type as the entity?
3249static void TryConstructorInitialization(Sema &S,
3250                                         const InitializedEntity &Entity,
3251                                         const InitializationKind &Kind,
3252                                         MultiExprArg Args, QualType DestType,
3253                                         InitializationSequence &Sequence,
3254                                         bool IsListInit = false,
3255                                         bool IsInitListCopy = false) {
3256  assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3257         "IsListInit must come with a single initializer list argument.");
3258
3259  // The type we're constructing needs to be complete.
3260  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3261    Sequence.setIncompleteTypeFailure(DestType);
3262    return;
3263  }
3264
3265  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3266  assert(DestRecordType && "Constructor initialization requires record type");
3267  CXXRecordDecl *DestRecordDecl
3268    = cast<CXXRecordDecl>(DestRecordType->getDecl());
3269
3270  // Build the candidate set directly in the initialization sequence
3271  // structure, so that it will persist if we fail.
3272  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3273
3274  // Determine whether we are allowed to call explicit constructors or
3275  // explicit conversion operators.
3276  bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3277  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3278
3279  //   - Otherwise, if T is a class type, constructors are considered. The
3280  //     applicable constructors are enumerated, and the best one is chosen
3281  //     through overload resolution.
3282  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3283
3284  OverloadingResult Result = OR_No_Viable_Function;
3285  OverloadCandidateSet::iterator Best;
3286  bool AsInitializerList = false;
3287
3288  // C++11 [over.match.list]p1, per DR1467:
3289  //   When objects of non-aggregate type T are list-initialized, such that
3290  //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
3291  //   according to the rules in this section, overload resolution selects
3292  //   the constructor in two phases:
3293  //
3294  //   - Initially, the candidate functions are the initializer-list
3295  //     constructors of the class T and the argument list consists of the
3296  //     initializer list as a single argument.
3297  if (IsListInit) {
3298    InitListExpr *ILE = cast<InitListExpr>(Args[0]);
3299    AsInitializerList = true;
3300
3301    // If the initializer list has no elements and T has a default constructor,
3302    // the first phase is omitted.
3303    if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
3304      Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3305                                          CandidateSet, Ctors, Best,
3306                                          CopyInitialization, AllowExplicit,
3307                                          /*OnlyListConstructor=*/true,
3308                                          IsListInit);
3309
3310    // Time to unwrap the init list.
3311    Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
3312  }
3313
3314  // C++11 [over.match.list]p1:
3315  //   - If no viable initializer-list constructor is found, overload resolution
3316  //     is performed again, where the candidate functions are all the
3317  //     constructors of the class T and the argument list consists of the
3318  //     elements of the initializer list.
3319  if (Result == OR_No_Viable_Function) {
3320    AsInitializerList = false;
3321    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3322                                        CandidateSet, Ctors, Best,
3323                                        CopyInitialization, AllowExplicit,
3324                                        /*OnlyListConstructors=*/false,
3325                                        IsListInit);
3326  }
3327  if (Result) {
3328    Sequence.SetOverloadFailure(IsListInit ?
3329                      InitializationSequence::FK_ListConstructorOverloadFailed :
3330                      InitializationSequence::FK_ConstructorOverloadFailed,
3331                                Result);
3332    return;
3333  }
3334
3335  // C++11 [dcl.init]p6:
3336  //   If a program calls for the default initialization of an object
3337  //   of a const-qualified type T, T shall be a class type with a
3338  //   user-provided default constructor.
3339  if (Kind.getKind() == InitializationKind::IK_Default &&
3340      Entity.getType().isConstQualified() &&
3341      !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
3342    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3343    return;
3344  }
3345
3346  // C++11 [over.match.list]p1:
3347  //   In copy-list-initialization, if an explicit constructor is chosen, the
3348  //   initializer is ill-formed.
3349  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3350  if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3351    Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3352    return;
3353  }
3354
3355  // Add the constructor initialization step. Any cv-qualification conversion is
3356  // subsumed by the initialization.
3357  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3358  Sequence.AddConstructorInitializationStep(
3359      CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
3360      IsListInit | IsInitListCopy, AsInitializerList);
3361}
3362
3363static bool
3364ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3365                                             Expr *Initializer,
3366                                             QualType &SourceType,
3367                                             QualType &UnqualifiedSourceType,
3368                                             QualType UnqualifiedTargetType,
3369                                             InitializationSequence &Sequence) {
3370  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3371        S.Context.OverloadTy) {
3372    DeclAccessPair Found;
3373    bool HadMultipleCandidates = false;
3374    if (FunctionDecl *Fn
3375        = S.ResolveAddressOfOverloadedFunction(Initializer,
3376                                               UnqualifiedTargetType,
3377                                               false, Found,
3378                                               &HadMultipleCandidates)) {
3379      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3380                                                HadMultipleCandidates);
3381      SourceType = Fn->getType();
3382      UnqualifiedSourceType = SourceType.getUnqualifiedType();
3383    } else if (!UnqualifiedTargetType->isRecordType()) {
3384      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3385      return true;
3386    }
3387  }
3388  return false;
3389}
3390
3391static void TryReferenceInitializationCore(Sema &S,
3392                                           const InitializedEntity &Entity,
3393                                           const InitializationKind &Kind,
3394                                           Expr *Initializer,
3395                                           QualType cv1T1, QualType T1,
3396                                           Qualifiers T1Quals,
3397                                           QualType cv2T2, QualType T2,
3398                                           Qualifiers T2Quals,
3399                                           InitializationSequence &Sequence);
3400
3401static void TryValueInitialization(Sema &S,
3402                                   const InitializedEntity &Entity,
3403                                   const InitializationKind &Kind,
3404                                   InitializationSequence &Sequence,
3405                                   InitListExpr *InitList = nullptr);
3406
3407/// \brief Attempt list initialization of a reference.
3408static void TryReferenceListInitialization(Sema &S,
3409                                           const InitializedEntity &Entity,
3410                                           const InitializationKind &Kind,
3411                                           InitListExpr *InitList,
3412                                           InitializationSequence &Sequence) {
3413  // First, catch C++03 where this isn't possible.
3414  if (!S.getLangOpts().CPlusPlus11) {
3415    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3416    return;
3417  }
3418
3419  QualType DestType = Entity.getType();
3420  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3421  Qualifiers T1Quals;
3422  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3423
3424  // Reference initialization via an initializer list works thus:
3425  // If the initializer list consists of a single element that is
3426  // reference-related to the referenced type, bind directly to that element
3427  // (possibly creating temporaries).
3428  // Otherwise, initialize a temporary with the initializer list and
3429  // bind to that.
3430  if (InitList->getNumInits() == 1) {
3431    Expr *Initializer = InitList->getInit(0);
3432    QualType cv2T2 = Initializer->getType();
3433    Qualifiers T2Quals;
3434    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3435
3436    // If this fails, creating a temporary wouldn't work either.
3437    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3438                                                     T1, Sequence))
3439      return;
3440
3441    SourceLocation DeclLoc = Initializer->getLocStart();
3442    bool dummy1, dummy2, dummy3;
3443    Sema::ReferenceCompareResult RefRelationship
3444      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3445                                       dummy2, dummy3);
3446    if (RefRelationship >= Sema::Ref_Related) {
3447      // Try to bind the reference here.
3448      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3449                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
3450      if (Sequence)
3451        Sequence.RewrapReferenceInitList(cv1T1, InitList);
3452      return;
3453    }
3454
3455    // Update the initializer if we've resolved an overloaded function.
3456    if (Sequence.step_begin() != Sequence.step_end())
3457      Sequence.RewrapReferenceInitList(cv1T1, InitList);
3458  }
3459
3460  // Not reference-related. Create a temporary and bind to that.
3461  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3462
3463  TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3464  if (Sequence) {
3465    if (DestType->isRValueReferenceType() ||
3466        (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3467      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3468    else
3469      Sequence.SetFailed(
3470          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3471  }
3472}
3473
3474/// \brief Attempt list initialization (C++0x [dcl.init.list])
3475static void TryListInitialization(Sema &S,
3476                                  const InitializedEntity &Entity,
3477                                  const InitializationKind &Kind,
3478                                  InitListExpr *InitList,
3479                                  InitializationSequence &Sequence) {
3480  QualType DestType = Entity.getType();
3481
3482  // C++ doesn't allow scalar initialization with more than one argument.
3483  // But C99 complex numbers are scalars and it makes sense there.
3484  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3485      !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3486    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3487    return;
3488  }
3489  if (DestType->isReferenceType()) {
3490    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3491    return;
3492  }
3493
3494  if (DestType->isRecordType() &&
3495      S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3496    Sequence.setIncompleteTypeFailure(DestType);
3497    return;
3498  }
3499
3500  // C++11 [dcl.init.list]p3, per DR1467:
3501  // - If T is a class type and the initializer list has a single element of
3502  //   type cv U, where U is T or a class derived from T, the object is
3503  //   initialized from that element (by copy-initialization for
3504  //   copy-list-initialization, or by direct-initialization for
3505  //   direct-list-initialization).
3506  // - Otherwise, if T is a character array and the initializer list has a
3507  //   single element that is an appropriately-typed string literal
3508  //   (8.5.2 [dcl.init.string]), initialization is performed as described
3509  //   in that section.
3510  // - Otherwise, if T is an aggregate, [...] (continue below).
3511  if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
3512    if (DestType->isRecordType()) {
3513      QualType InitType = InitList->getInit(0)->getType();
3514      if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3515          S.IsDerivedFrom(InitType, DestType)) {
3516        Expr *InitAsExpr = InitList->getInit(0);
3517        TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3518                                     Sequence, /*InitListSyntax*/ false,
3519                                     /*IsInitListCopy*/ true);
3520        return;
3521      }
3522    }
3523    if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3524      Expr *SubInit[1] = {InitList->getInit(0)};
3525      if (!isa<VariableArrayType>(DestAT) &&
3526          IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3527        InitializationKind SubKind =
3528            Kind.getKind() == InitializationKind::IK_DirectList
3529                ? InitializationKind::CreateDirect(Kind.getLocation(),
3530                                                   InitList->getLBraceLoc(),
3531                                                   InitList->getRBraceLoc())
3532                : Kind;
3533        Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3534                                /*TopLevelOfInitList*/ true);
3535
3536        // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3537        // the element is not an appropriately-typed string literal, in which
3538        // case we should proceed as in C++11 (below).
3539        if (Sequence) {
3540          Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3541          return;
3542        }
3543      }
3544    }
3545  }
3546
3547  // C++11 [dcl.init.list]p3:
3548  //   - If T is an aggregate, aggregate initialization is performed.
3549  if (DestType->isRecordType() && !DestType->isAggregateType()) {
3550    if (S.getLangOpts().CPlusPlus11) {
3551      //   - Otherwise, if the initializer list has no elements and T is a
3552      //     class type with a default constructor, the object is
3553      //     value-initialized.
3554      if (InitList->getNumInits() == 0) {
3555        CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3556        if (RD->hasDefaultConstructor()) {
3557          TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3558          return;
3559        }
3560      }
3561
3562      //   - Otherwise, if T is a specialization of std::initializer_list<E>,
3563      //     an initializer_list object constructed [...]
3564      if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3565        return;
3566
3567      //   - Otherwise, if T is a class type, constructors are considered.
3568      Expr *InitListAsExpr = InitList;
3569      TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3570                                   Sequence, /*InitListSyntax*/ true);
3571    } else
3572      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3573    return;
3574  }
3575
3576  if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3577      InitList->getNumInits() == 1 &&
3578      InitList->getInit(0)->getType()->isRecordType()) {
3579    //   - Otherwise, if the initializer list has a single element of type E
3580    //     [...references are handled above...], the object or reference is
3581    //     initialized from that element (by copy-initialization for
3582    //     copy-list-initialization, or by direct-initialization for
3583    //     direct-list-initialization); if a narrowing conversion is required
3584    //     to convert the element to T, the program is ill-formed.
3585    //
3586    // Per core-24034, this is direct-initialization if we were performing
3587    // direct-list-initialization and copy-initialization otherwise.
3588    // We can't use InitListChecker for this, because it always performs
3589    // copy-initialization. This only matters if we might use an 'explicit'
3590    // conversion operator, so we only need to handle the cases where the source
3591    // is of record type.
3592    InitializationKind SubKind =
3593        Kind.getKind() == InitializationKind::IK_DirectList
3594            ? InitializationKind::CreateDirect(Kind.getLocation(),
3595                                               InitList->getLBraceLoc(),
3596                                               InitList->getRBraceLoc())
3597            : Kind;
3598    Expr *SubInit[1] = { InitList->getInit(0) };
3599    Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3600                            /*TopLevelOfInitList*/true);
3601    if (Sequence)
3602      Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3603    return;
3604  }
3605
3606  InitListChecker CheckInitList(S, Entity, InitList,
3607          DestType, /*VerifyOnly=*/true);
3608  if (CheckInitList.HadError()) {
3609    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3610    return;
3611  }
3612
3613  // Add the list initialization step with the built init list.
3614  Sequence.AddListInitializationStep(DestType);
3615}
3616
3617/// \brief Try a reference initialization that involves calling a conversion
3618/// function.
3619static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3620                                             const InitializedEntity &Entity,
3621                                             const InitializationKind &Kind,
3622                                             Expr *Initializer,
3623                                             bool AllowRValues,
3624                                             InitializationSequence &Sequence) {
3625  QualType DestType = Entity.getType();
3626  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3627  QualType T1 = cv1T1.getUnqualifiedType();
3628  QualType cv2T2 = Initializer->getType();
3629  QualType T2 = cv2T2.getUnqualifiedType();
3630
3631  bool DerivedToBase;
3632  bool ObjCConversion;
3633  bool ObjCLifetimeConversion;
3634  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3635                                         T1, T2, DerivedToBase,
3636                                         ObjCConversion,
3637                                         ObjCLifetimeConversion) &&
3638         "Must have incompatible references when binding via conversion");
3639  (void)DerivedToBase;
3640  (void)ObjCConversion;
3641  (void)ObjCLifetimeConversion;
3642
3643  // Build the candidate set directly in the initialization sequence
3644  // structure, so that it will persist if we fail.
3645  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3646  CandidateSet.clear();
3647
3648  // Determine whether we are allowed to call explicit constructors or
3649  // explicit conversion operators.
3650  bool AllowExplicit = Kind.AllowExplicit();
3651  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3652
3653  const RecordType *T1RecordType = nullptr;
3654  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3655      !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3656    // The type we're converting to is a class type. Enumerate its constructors
3657    // to see if there is a suitable conversion.
3658    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3659
3660    for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
3661      DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3662
3663      // Find the constructor (which may be a template).
3664      CXXConstructorDecl *Constructor = nullptr;
3665      FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3666      if (ConstructorTmpl)
3667        Constructor = cast<CXXConstructorDecl>(
3668                                         ConstructorTmpl->getTemplatedDecl());
3669      else
3670        Constructor = cast<CXXConstructorDecl>(D);
3671
3672      if (!Constructor->isInvalidDecl() &&
3673          Constructor->isConvertingConstructor(AllowExplicit)) {
3674        if (ConstructorTmpl)
3675          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3676                                         /*ExplicitArgs*/ nullptr,
3677                                         Initializer, CandidateSet,
3678                                         /*SuppressUserConversions=*/true);
3679        else
3680          S.AddOverloadCandidate(Constructor, FoundDecl,
3681                                 Initializer, CandidateSet,
3682                                 /*SuppressUserConversions=*/true);
3683      }
3684    }
3685  }
3686  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3687    return OR_No_Viable_Function;
3688
3689  const RecordType *T2RecordType = nullptr;
3690  if ((T2RecordType = T2->getAs<RecordType>()) &&
3691      !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3692    // The type we're converting from is a class type, enumerate its conversion
3693    // functions.
3694    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3695
3696    const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
3697    for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3698      NamedDecl *D = *I;
3699      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3700      if (isa<UsingShadowDecl>(D))
3701        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3702
3703      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3704      CXXConversionDecl *Conv;
3705      if (ConvTemplate)
3706        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3707      else
3708        Conv = cast<CXXConversionDecl>(D);
3709
3710      // If the conversion function doesn't return a reference type,
3711      // it can't be considered for this conversion unless we're allowed to
3712      // consider rvalues.
3713      // FIXME: Do we need to make sure that we only consider conversion
3714      // candidates with reference-compatible results? That might be needed to
3715      // break recursion.
3716      if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3717          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3718        if (ConvTemplate)
3719          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3720                                           ActingDC, Initializer,
3721                                           DestType, CandidateSet,
3722                                           /*AllowObjCConversionOnExplicit=*/
3723                                             false);
3724        else
3725          S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3726                                   Initializer, DestType, CandidateSet,
3727                                   /*AllowObjCConversionOnExplicit=*/false);
3728      }
3729    }
3730  }
3731  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3732    return OR_No_Viable_Function;
3733
3734  SourceLocation DeclLoc = Initializer->getLocStart();
3735
3736  // Perform overload resolution. If it fails, return the failed result.
3737  OverloadCandidateSet::iterator Best;
3738  if (OverloadingResult Result
3739        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3740    return Result;
3741
3742  FunctionDecl *Function = Best->Function;
3743  // This is the overload that will be used for this initialization step if we
3744  // use this initialization. Mark it as referenced.
3745  Function->setReferenced();
3746
3747  // Compute the returned type of the conversion.
3748  if (isa<CXXConversionDecl>(Function))
3749    T2 = Function->getReturnType();
3750  else
3751    T2 = cv1T1;
3752
3753  // Add the user-defined conversion step.
3754  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3755  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3756                                 T2.getNonLValueExprType(S.Context),
3757                                 HadMultipleCandidates);
3758
3759  // Determine whether we need to perform derived-to-base or
3760  // cv-qualification adjustments.
3761  ExprValueKind VK = VK_RValue;
3762  if (T2->isLValueReferenceType())
3763    VK = VK_LValue;
3764  else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3765    VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3766
3767  bool NewDerivedToBase = false;
3768  bool NewObjCConversion = false;
3769  bool NewObjCLifetimeConversion = false;
3770  Sema::ReferenceCompareResult NewRefRelationship
3771    = S.CompareReferenceRelationship(DeclLoc, T1,
3772                                     T2.getNonLValueExprType(S.Context),
3773                                     NewDerivedToBase, NewObjCConversion,
3774                                     NewObjCLifetimeConversion);
3775  if (NewRefRelationship == Sema::Ref_Incompatible) {
3776    // If the type we've converted to is not reference-related to the
3777    // type we're looking for, then there is another conversion step
3778    // we need to perform to produce a temporary of the right type
3779    // that we'll be binding to.
3780    ImplicitConversionSequence ICS;
3781    ICS.setStandard();
3782    ICS.Standard = Best->FinalConversion;
3783    T2 = ICS.Standard.getToType(2);
3784    Sequence.AddConversionSequenceStep(ICS, T2);
3785  } else if (NewDerivedToBase)
3786    Sequence.AddDerivedToBaseCastStep(
3787                                S.Context.getQualifiedType(T1,
3788                                  T2.getNonReferenceType().getQualifiers()),
3789                                      VK);
3790  else if (NewObjCConversion)
3791    Sequence.AddObjCObjectConversionStep(
3792                                S.Context.getQualifiedType(T1,
3793                                  T2.getNonReferenceType().getQualifiers()));
3794
3795  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3796    Sequence.AddQualificationConversionStep(cv1T1, VK);
3797
3798  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3799  return OR_Success;
3800}
3801
3802static void CheckCXX98CompatAccessibleCopy(Sema &S,
3803                                           const InitializedEntity &Entity,
3804                                           Expr *CurInitExpr);
3805
3806/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3807static void TryReferenceInitialization(Sema &S,
3808                                       const InitializedEntity &Entity,
3809                                       const InitializationKind &Kind,
3810                                       Expr *Initializer,
3811                                       InitializationSequence &Sequence) {
3812  QualType DestType = Entity.getType();
3813  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3814  Qualifiers T1Quals;
3815  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3816  QualType cv2T2 = Initializer->getType();
3817  Qualifiers T2Quals;
3818  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3819
3820  // If the initializer is the address of an overloaded function, try
3821  // to resolve the overloaded function. If all goes well, T2 is the
3822  // type of the resulting function.
3823  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3824                                                   T1, Sequence))
3825    return;
3826
3827  // Delegate everything else to a subfunction.
3828  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3829                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
3830}
3831
3832/// Converts the target of reference initialization so that it has the
3833/// appropriate qualifiers and value kind.
3834///
3835/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3836/// \code
3837///   int x;
3838///   const int &r = x;
3839/// \endcode
3840///
3841/// In this case the reference is binding to a bitfield lvalue, which isn't
3842/// valid. Perform a load to create a lifetime-extended temporary instead.
3843/// \code
3844///   const int &r = someStruct.bitfield;
3845/// \endcode
3846static ExprValueKind
3847convertQualifiersAndValueKindIfNecessary(Sema &S,
3848                                         InitializationSequence &Sequence,
3849                                         Expr *Initializer,
3850                                         QualType cv1T1,
3851                                         Qualifiers T1Quals,
3852                                         Qualifiers T2Quals,
3853                                         bool IsLValueRef) {
3854  bool IsNonAddressableType = Initializer->refersToBitField() ||
3855                              Initializer->refersToVectorElement();
3856
3857  if (IsNonAddressableType) {
3858    // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3859    // lvalue reference to a non-volatile const type, or the reference shall be
3860    // an rvalue reference.
3861    //
3862    // If not, we can't make a temporary and bind to that. Give up and allow the
3863    // error to be diagnosed later.
3864    if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3865      assert(Initializer->isGLValue());
3866      return Initializer->getValueKind();
3867    }
3868
3869    // Force a load so we can materialize a temporary.
3870    Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3871    return VK_RValue;
3872  }
3873
3874  if (T1Quals != T2Quals) {
3875    Sequence.AddQualificationConversionStep(cv1T1,
3876                                            Initializer->getValueKind());
3877  }
3878
3879  return Initializer->getValueKind();
3880}
3881
3882
3883/// \brief Reference initialization without resolving overloaded functions.
3884static void TryReferenceInitializationCore(Sema &S,
3885                                           const InitializedEntity &Entity,
3886                                           const InitializationKind &Kind,
3887                                           Expr *Initializer,
3888                                           QualType cv1T1, QualType T1,
3889                                           Qualifiers T1Quals,
3890                                           QualType cv2T2, QualType T2,
3891                                           Qualifiers T2Quals,
3892                                           InitializationSequence &Sequence) {
3893  QualType DestType = Entity.getType();
3894  SourceLocation DeclLoc = Initializer->getLocStart();
3895  // Compute some basic properties of the types and the initializer.
3896  bool isLValueRef = DestType->isLValueReferenceType();
3897  bool isRValueRef = !isLValueRef;
3898  bool DerivedToBase = false;
3899  bool ObjCConversion = false;
3900  bool ObjCLifetimeConversion = false;
3901  Expr::Classification InitCategory = Initializer->Classify(S.Context);
3902  Sema::ReferenceCompareResult RefRelationship
3903    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3904                                     ObjCConversion, ObjCLifetimeConversion);
3905
3906  // C++0x [dcl.init.ref]p5:
3907  //   A reference to type "cv1 T1" is initialized by an expression of type
3908  //   "cv2 T2" as follows:
3909  //
3910  //     - If the reference is an lvalue reference and the initializer
3911  //       expression
3912  // Note the analogous bullet points for rvalue refs to functions. Because
3913  // there are no function rvalues in C++, rvalue refs to functions are treated
3914  // like lvalue refs.
3915  OverloadingResult ConvOvlResult = OR_Success;
3916  bool T1Function = T1->isFunctionType();
3917  if (isLValueRef || T1Function) {
3918    if (InitCategory.isLValue() &&
3919        (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3920         (Kind.isCStyleOrFunctionalCast() &&
3921          RefRelationship == Sema::Ref_Related))) {
3922      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3923      //     reference-compatible with "cv2 T2," or
3924      //
3925      // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3926      // bit-field when we're determining whether the reference initialization
3927      // can occur. However, we do pay attention to whether it is a bit-field
3928      // to decide whether we're actually binding to a temporary created from
3929      // the bit-field.
3930      if (DerivedToBase)
3931        Sequence.AddDerivedToBaseCastStep(
3932                         S.Context.getQualifiedType(T1, T2Quals),
3933                         VK_LValue);
3934      else if (ObjCConversion)
3935        Sequence.AddObjCObjectConversionStep(
3936                                     S.Context.getQualifiedType(T1, T2Quals));
3937
3938      ExprValueKind ValueKind =
3939        convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3940                                                 cv1T1, T1Quals, T2Quals,
3941                                                 isLValueRef);
3942      Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3943      return;
3944    }
3945
3946    //     - has a class type (i.e., T2 is a class type), where T1 is not
3947    //       reference-related to T2, and can be implicitly converted to an
3948    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3949    //       with "cv3 T3" (this conversion is selected by enumerating the
3950    //       applicable conversion functions (13.3.1.6) and choosing the best
3951    //       one through overload resolution (13.3)),
3952    // If we have an rvalue ref to function type here, the rhs must be
3953    // an rvalue. DR1287 removed the "implicitly" here.
3954    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3955        (isLValueRef || InitCategory.isRValue())) {
3956      ConvOvlResult = TryRefInitWithConversionFunction(
3957          S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
3958      if (ConvOvlResult == OR_Success)
3959        return;
3960      if (ConvOvlResult != OR_No_Viable_Function)
3961        Sequence.SetOverloadFailure(
3962            InitializationSequence::FK_ReferenceInitOverloadFailed,
3963            ConvOvlResult);
3964    }
3965  }
3966
3967  //     - Otherwise, the reference shall be an lvalue reference to a
3968  //       non-volatile const type (i.e., cv1 shall be const), or the reference
3969  //       shall be an rvalue reference.
3970  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3971    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3972      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3973    else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3974      Sequence.SetOverloadFailure(
3975                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3976                                  ConvOvlResult);
3977    else
3978      Sequence.SetFailed(InitCategory.isLValue()
3979        ? (RefRelationship == Sema::Ref_Related
3980             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3981             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3982        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3983
3984    return;
3985  }
3986
3987  //    - If the initializer expression
3988  //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3989  //        "cv1 T1" is reference-compatible with "cv2 T2"
3990  // Note: functions are handled below.
3991  if (!T1Function &&
3992      (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3993       (Kind.isCStyleOrFunctionalCast() &&
3994        RefRelationship == Sema::Ref_Related)) &&
3995      (InitCategory.isXValue() ||
3996       (InitCategory.isPRValue() && T2->isRecordType()) ||
3997       (InitCategory.isPRValue() && T2->isArrayType()))) {
3998    ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3999    if (InitCategory.isPRValue() && T2->isRecordType()) {
4000      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4001      // compiler the freedom to perform a copy here or bind to the
4002      // object, while C++0x requires that we bind directly to the
4003      // object. Hence, we always bind to the object without making an
4004      // extra copy. However, in C++03 requires that we check for the
4005      // presence of a suitable copy constructor:
4006      //
4007      //   The constructor that would be used to make the copy shall
4008      //   be callable whether or not the copy is actually done.
4009      if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4010        Sequence.AddExtraneousCopyToTemporary(cv2T2);
4011      else if (S.getLangOpts().CPlusPlus11)
4012        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4013    }
4014
4015    if (DerivedToBase)
4016      Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
4017                                        ValueKind);
4018    else if (ObjCConversion)
4019      Sequence.AddObjCObjectConversionStep(
4020                                       S.Context.getQualifiedType(T1, T2Quals));
4021
4022    ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
4023                                                         Initializer, cv1T1,
4024                                                         T1Quals, T2Quals,
4025                                                         isLValueRef);
4026
4027    Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
4028    return;
4029  }
4030
4031  //       - has a class type (i.e., T2 is a class type), where T1 is not
4032  //         reference-related to T2, and can be implicitly converted to an
4033  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
4034  //         where "cv1 T1" is reference-compatible with "cv3 T3",
4035  //
4036  // DR1287 removes the "implicitly" here.
4037  if (T2->isRecordType()) {
4038    if (RefRelationship == Sema::Ref_Incompatible) {
4039      ConvOvlResult = TryRefInitWithConversionFunction(
4040          S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
4041      if (ConvOvlResult)
4042        Sequence.SetOverloadFailure(
4043            InitializationSequence::FK_ReferenceInitOverloadFailed,
4044            ConvOvlResult);
4045
4046      return;
4047    }
4048
4049    if ((RefRelationship == Sema::Ref_Compatible ||
4050         RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
4051        isRValueRef && InitCategory.isLValue()) {
4052      Sequence.SetFailed(
4053        InitializationSequence::FK_RValueReferenceBindingToLValue);
4054      return;
4055    }
4056
4057    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4058    return;
4059  }
4060
4061  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
4062  //        from the initializer expression using the rules for a non-reference
4063  //        copy-initialization (8.5). The reference is then bound to the
4064  //        temporary. [...]
4065
4066  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4067
4068  // FIXME: Why do we use an implicit conversion here rather than trying
4069  // copy-initialization?
4070  ImplicitConversionSequence ICS
4071    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4072                              /*SuppressUserConversions=*/false,
4073                              /*AllowExplicit=*/false,
4074                              /*FIXME:InOverloadResolution=*/false,
4075                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4076                              /*AllowObjCWritebackConversion=*/false);
4077
4078  if (ICS.isBad()) {
4079    // FIXME: Use the conversion function set stored in ICS to turn
4080    // this into an overloading ambiguity diagnostic. However, we need
4081    // to keep that set as an OverloadCandidateSet rather than as some
4082    // other kind of set.
4083    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4084      Sequence.SetOverloadFailure(
4085                        InitializationSequence::FK_ReferenceInitOverloadFailed,
4086                                  ConvOvlResult);
4087    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4088      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4089    else
4090      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4091    return;
4092  } else {
4093    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4094  }
4095
4096  //        [...] If T1 is reference-related to T2, cv1 must be the
4097  //        same cv-qualification as, or greater cv-qualification
4098  //        than, cv2; otherwise, the program is ill-formed.
4099  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4100  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4101  if (RefRelationship == Sema::Ref_Related &&
4102      (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4103    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4104    return;
4105  }
4106
4107  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
4108  //   reference, the initializer expression shall not be an lvalue.
4109  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4110      InitCategory.isLValue()) {
4111    Sequence.SetFailed(
4112                    InitializationSequence::FK_RValueReferenceBindingToLValue);
4113    return;
4114  }
4115
4116  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4117  return;
4118}
4119
4120/// \brief Attempt character array initialization from a string literal
4121/// (C++ [dcl.init.string], C99 6.7.8).
4122static void TryStringLiteralInitialization(Sema &S,
4123                                           const InitializedEntity &Entity,
4124                                           const InitializationKind &Kind,
4125                                           Expr *Initializer,
4126                                       InitializationSequence &Sequence) {
4127  Sequence.AddStringInitStep(Entity.getType());
4128}
4129
4130/// \brief Attempt value initialization (C++ [dcl.init]p7).
4131static void TryValueInitialization(Sema &S,
4132                                   const InitializedEntity &Entity,
4133                                   const InitializationKind &Kind,
4134                                   InitializationSequence &Sequence,
4135                                   InitListExpr *InitList) {
4136  assert((!InitList || InitList->getNumInits() == 0) &&
4137         "Shouldn't use value-init for non-empty init lists");
4138
4139  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4140  //
4141  //   To value-initialize an object of type T means:
4142  QualType T = Entity.getType();
4143
4144  //     -- if T is an array type, then each element is value-initialized;
4145  T = S.Context.getBaseElementType(T);
4146
4147  if (const RecordType *RT = T->getAs<RecordType>()) {
4148    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4149      bool NeedZeroInitialization = true;
4150      if (!S.getLangOpts().CPlusPlus11) {
4151        // C++98:
4152        // -- if T is a class type (clause 9) with a user-declared constructor
4153        //    (12.1), then the default constructor for T is called (and the
4154        //    initialization is ill-formed if T has no accessible default
4155        //    constructor);
4156        if (ClassDecl->hasUserDeclaredConstructor())
4157          NeedZeroInitialization = false;
4158      } else {
4159        // C++11:
4160        // -- if T is a class type (clause 9) with either no default constructor
4161        //    (12.1 [class.ctor]) or a default constructor that is user-provided
4162        //    or deleted, then the object is default-initialized;
4163        CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4164        if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4165          NeedZeroInitialization = false;
4166      }
4167
4168      // -- if T is a (possibly cv-qualified) non-union class type without a
4169      //    user-provided or deleted default constructor, then the object is
4170      //    zero-initialized and, if T has a non-trivial default constructor,
4171      //    default-initialized;
4172      // The 'non-union' here was removed by DR1502. The 'non-trivial default
4173      // constructor' part was removed by DR1507.
4174      if (NeedZeroInitialization)
4175        Sequence.AddZeroInitializationStep(Entity.getType());
4176
4177      // C++03:
4178      // -- if T is a non-union class type without a user-declared constructor,
4179      //    then every non-static data member and base class component of T is
4180      //    value-initialized;
4181      // [...] A program that calls for [...] value-initialization of an
4182      // entity of reference type is ill-formed.
4183      //
4184      // C++11 doesn't need this handling, because value-initialization does not
4185      // occur recursively there, and the implicit default constructor is
4186      // defined as deleted in the problematic cases.
4187      if (!S.getLangOpts().CPlusPlus11 &&
4188          ClassDecl->hasUninitializedReferenceMember()) {
4189        Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4190        return;
4191      }
4192
4193      // If this is list-value-initialization, pass the empty init list on when
4194      // building the constructor call. This affects the semantics of a few
4195      // things (such as whether an explicit default constructor can be called).
4196      Expr *InitListAsExpr = InitList;
4197      MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4198      bool InitListSyntax = InitList;
4199
4200      return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4201                                          InitListSyntax);
4202    }
4203  }
4204
4205  Sequence.AddZeroInitializationStep(Entity.getType());
4206}
4207
4208/// \brief Attempt default initialization (C++ [dcl.init]p6).
4209static void TryDefaultInitialization(Sema &S,
4210                                     const InitializedEntity &Entity,
4211                                     const InitializationKind &Kind,
4212                                     InitializationSequence &Sequence) {
4213  assert(Kind.getKind() == InitializationKind::IK_Default);
4214
4215  // C++ [dcl.init]p6:
4216  //   To default-initialize an object of type T means:
4217  //     - if T is an array type, each element is default-initialized;
4218  QualType DestType = S.Context.getBaseElementType(Entity.getType());
4219
4220  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
4221  //       constructor for T is called (and the initialization is ill-formed if
4222  //       T has no accessible default constructor);
4223  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4224    TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
4225    return;
4226  }
4227
4228  //     - otherwise, no initialization is performed.
4229
4230  //   If a program calls for the default initialization of an object of
4231  //   a const-qualified type T, T shall be a class type with a user-provided
4232  //   default constructor.
4233  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4234    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4235    return;
4236  }
4237
4238  // If the destination type has a lifetime property, zero-initialize it.
4239  if (DestType.getQualifiers().hasObjCLifetime()) {
4240    Sequence.AddZeroInitializationStep(Entity.getType());
4241    return;
4242  }
4243}
4244
4245/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4246/// which enumerates all conversion functions and performs overload resolution
4247/// to select the best.
4248static void TryUserDefinedConversion(Sema &S,
4249                                     QualType DestType,
4250                                     const InitializationKind &Kind,
4251                                     Expr *Initializer,
4252                                     InitializationSequence &Sequence,
4253                                     bool TopLevelOfInitList) {
4254  assert(!DestType->isReferenceType() && "References are handled elsewhere");
4255  QualType SourceType = Initializer->getType();
4256  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4257         "Must have a class type to perform a user-defined conversion");
4258
4259  // Build the candidate set directly in the initialization sequence
4260  // structure, so that it will persist if we fail.
4261  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4262  CandidateSet.clear();
4263
4264  // Determine whether we are allowed to call explicit constructors or
4265  // explicit conversion operators.
4266  bool AllowExplicit = Kind.AllowExplicit();
4267
4268  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4269    // The type we're converting to is a class type. Enumerate its constructors
4270    // to see if there is a suitable conversion.
4271    CXXRecordDecl *DestRecordDecl
4272      = cast<CXXRecordDecl>(DestRecordType->getDecl());
4273
4274    // Try to complete the type we're converting to.
4275    if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
4276      DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4277      // The container holding the constructors can under certain conditions
4278      // be changed while iterating. To be safe we copy the lookup results
4279      // to a new container.
4280      SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4281      for (SmallVectorImpl<NamedDecl *>::iterator
4282             Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4283           Con != ConEnd; ++Con) {
4284        NamedDecl *D = *Con;
4285        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
4286
4287        // Find the constructor (which may be a template).
4288        CXXConstructorDecl *Constructor = nullptr;
4289        FunctionTemplateDecl *ConstructorTmpl
4290          = dyn_cast<FunctionTemplateDecl>(D);
4291        if (ConstructorTmpl)
4292          Constructor = cast<CXXConstructorDecl>(
4293                                           ConstructorTmpl->getTemplatedDecl());
4294        else
4295          Constructor = cast<CXXConstructorDecl>(D);
4296
4297        if (!Constructor->isInvalidDecl() &&
4298            Constructor->isConvertingConstructor(AllowExplicit)) {
4299          if (ConstructorTmpl)
4300            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4301                                           /*ExplicitArgs*/ nullptr,
4302                                           Initializer, CandidateSet,
4303                                           /*SuppressUserConversions=*/true);
4304          else
4305            S.AddOverloadCandidate(Constructor, FoundDecl,
4306                                   Initializer, CandidateSet,
4307                                   /*SuppressUserConversions=*/true);
4308        }
4309      }
4310    }
4311  }
4312
4313  SourceLocation DeclLoc = Initializer->getLocStart();
4314
4315  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4316    // The type we're converting from is a class type, enumerate its conversion
4317    // functions.
4318
4319    // We can only enumerate the conversion functions for a complete type; if
4320    // the type isn't complete, simply skip this step.
4321    if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4322      CXXRecordDecl *SourceRecordDecl
4323        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4324
4325      const auto &Conversions =
4326          SourceRecordDecl->getVisibleConversionFunctions();
4327      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4328        NamedDecl *D = *I;
4329        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4330        if (isa<UsingShadowDecl>(D))
4331          D = cast<UsingShadowDecl>(D)->getTargetDecl();
4332
4333        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4334        CXXConversionDecl *Conv;
4335        if (ConvTemplate)
4336          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4337        else
4338          Conv = cast<CXXConversionDecl>(D);
4339
4340        if (AllowExplicit || !Conv->isExplicit()) {
4341          if (ConvTemplate)
4342            S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4343                                             ActingDC, Initializer, DestType,
4344                                             CandidateSet, AllowExplicit);
4345          else
4346            S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4347                                     Initializer, DestType, CandidateSet,
4348                                     AllowExplicit);
4349        }
4350      }
4351    }
4352  }
4353
4354  // Perform overload resolution. If it fails, return the failed result.
4355  OverloadCandidateSet::iterator Best;
4356  if (OverloadingResult Result
4357        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4358    Sequence.SetOverloadFailure(
4359                        InitializationSequence::FK_UserConversionOverloadFailed,
4360                                Result);
4361    return;
4362  }
4363
4364  FunctionDecl *Function = Best->Function;
4365  Function->setReferenced();
4366  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4367
4368  if (isa<CXXConstructorDecl>(Function)) {
4369    // Add the user-defined conversion step. Any cv-qualification conversion is
4370    // subsumed by the initialization. Per DR5, the created temporary is of the
4371    // cv-unqualified type of the destination.
4372    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4373                                   DestType.getUnqualifiedType(),
4374                                   HadMultipleCandidates);
4375    return;
4376  }
4377
4378  // Add the user-defined conversion step that calls the conversion function.
4379  QualType ConvType = Function->getCallResultType();
4380  if (ConvType->getAs<RecordType>()) {
4381    // If we're converting to a class type, there may be an copy of
4382    // the resulting temporary object (possible to create an object of
4383    // a base class type). That copy is not a separate conversion, so
4384    // we just make a note of the actual destination type (possibly a
4385    // base class of the type returned by the conversion function) and
4386    // let the user-defined conversion step handle the conversion.
4387    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4388                                   HadMultipleCandidates);
4389    return;
4390  }
4391
4392  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4393                                 HadMultipleCandidates);
4394
4395  // If the conversion following the call to the conversion function
4396  // is interesting, add it as a separate step.
4397  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4398      Best->FinalConversion.Third) {
4399    ImplicitConversionSequence ICS;
4400    ICS.setStandard();
4401    ICS.Standard = Best->FinalConversion;
4402    Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4403  }
4404}
4405
4406/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4407/// a function with a pointer return type contains a 'return false;' statement.
4408/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4409/// code using that header.
4410///
4411/// Work around this by treating 'return false;' as zero-initializing the result
4412/// if it's used in a pointer-returning function in a system header.
4413static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4414                                              const InitializedEntity &Entity,
4415                                              const Expr *Init) {
4416  return S.getLangOpts().CPlusPlus11 &&
4417         Entity.getKind() == InitializedEntity::EK_Result &&
4418         Entity.getType()->isPointerType() &&
4419         isa<CXXBoolLiteralExpr>(Init) &&
4420         !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4421         S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4422}
4423
4424/// The non-zero enum values here are indexes into diagnostic alternatives.
4425enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4426
4427/// Determines whether this expression is an acceptable ICR source.
4428static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4429                                         bool isAddressOf, bool &isWeakAccess) {
4430  // Skip parens.
4431  e = e->IgnoreParens();
4432
4433  // Skip address-of nodes.
4434  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4435    if (op->getOpcode() == UO_AddrOf)
4436      return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4437                                isWeakAccess);
4438
4439  // Skip certain casts.
4440  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4441    switch (ce->getCastKind()) {
4442    case CK_Dependent:
4443    case CK_BitCast:
4444    case CK_LValueBitCast:
4445    case CK_NoOp:
4446      return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4447
4448    case CK_ArrayToPointerDecay:
4449      return IIK_nonscalar;
4450
4451    case CK_NullToPointer:
4452      return IIK_okay;
4453
4454    default:
4455      break;
4456    }
4457
4458  // If we have a declaration reference, it had better be a local variable.
4459  } else if (isa<DeclRefExpr>(e)) {
4460    // set isWeakAccess to true, to mean that there will be an implicit
4461    // load which requires a cleanup.
4462    if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4463      isWeakAccess = true;
4464
4465    if (!isAddressOf) return IIK_nonlocal;
4466
4467    VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4468    if (!var) return IIK_nonlocal;
4469
4470    return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4471
4472  // If we have a conditional operator, check both sides.
4473  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4474    if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4475                                                isWeakAccess))
4476      return iik;
4477
4478    return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4479
4480  // These are never scalar.
4481  } else if (isa<ArraySubscriptExpr>(e)) {
4482    return IIK_nonscalar;
4483
4484  // Otherwise, it needs to be a null pointer constant.
4485  } else {
4486    return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4487            ? IIK_okay : IIK_nonlocal);
4488  }
4489
4490  return IIK_nonlocal;
4491}
4492
4493/// Check whether the given expression is a valid operand for an
4494/// indirect copy/restore.
4495static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4496  assert(src->isRValue());
4497  bool isWeakAccess = false;
4498  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4499  // If isWeakAccess to true, there will be an implicit
4500  // load which requires a cleanup.
4501  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4502    S.ExprNeedsCleanups = true;
4503
4504  if (iik == IIK_okay) return;
4505
4506  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4507    << ((unsigned) iik - 1)  // shift index into diagnostic explanations
4508    << src->getSourceRange();
4509}
4510
4511/// \brief Determine whether we have compatible array types for the
4512/// purposes of GNU by-copy array initialization.
4513static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
4514                                    const ArrayType *Source) {
4515  // If the source and destination array types are equivalent, we're
4516  // done.
4517  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4518    return true;
4519
4520  // Make sure that the element types are the same.
4521  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4522    return false;
4523
4524  // The only mismatch we allow is when the destination is an
4525  // incomplete array type and the source is a constant array type.
4526  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4527}
4528
4529static bool tryObjCWritebackConversion(Sema &S,
4530                                       InitializationSequence &Sequence,
4531                                       const InitializedEntity &Entity,
4532                                       Expr *Initializer) {
4533  bool ArrayDecay = false;
4534  QualType ArgType = Initializer->getType();
4535  QualType ArgPointee;
4536  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4537    ArrayDecay = true;
4538    ArgPointee = ArgArrayType->getElementType();
4539    ArgType = S.Context.getPointerType(ArgPointee);
4540  }
4541
4542  // Handle write-back conversion.
4543  QualType ConvertedArgType;
4544  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4545                                   ConvertedArgType))
4546    return false;
4547
4548  // We should copy unless we're passing to an argument explicitly
4549  // marked 'out'.
4550  bool ShouldCopy = true;
4551  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4552    ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4553
4554  // Do we need an lvalue conversion?
4555  if (ArrayDecay || Initializer->isGLValue()) {
4556    ImplicitConversionSequence ICS;
4557    ICS.setStandard();
4558    ICS.Standard.setAsIdentityConversion();
4559
4560    QualType ResultType;
4561    if (ArrayDecay) {
4562      ICS.Standard.First = ICK_Array_To_Pointer;
4563      ResultType = S.Context.getPointerType(ArgPointee);
4564    } else {
4565      ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4566      ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4567    }
4568
4569    Sequence.AddConversionSequenceStep(ICS, ResultType);
4570  }
4571
4572  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4573  return true;
4574}
4575
4576static bool TryOCLSamplerInitialization(Sema &S,
4577                                        InitializationSequence &Sequence,
4578                                        QualType DestType,
4579                                        Expr *Initializer) {
4580  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4581    !Initializer->isIntegerConstantExpr(S.getASTContext()))
4582    return false;
4583
4584  Sequence.AddOCLSamplerInitStep(DestType);
4585  return true;
4586}
4587
4588//
4589// OpenCL 1.2 spec, s6.12.10
4590//
4591// The event argument can also be used to associate the
4592// async_work_group_copy with a previous async copy allowing
4593// an event to be shared by multiple async copies; otherwise
4594// event should be zero.
4595//
4596static bool TryOCLZeroEventInitialization(Sema &S,
4597                                          InitializationSequence &Sequence,
4598                                          QualType DestType,
4599                                          Expr *Initializer) {
4600  if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4601      !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4602      (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4603    return false;
4604
4605  Sequence.AddOCLZeroEventStep(DestType);
4606  return true;
4607}
4608
4609InitializationSequence::InitializationSequence(Sema &S,
4610                                               const InitializedEntity &Entity,
4611                                               const InitializationKind &Kind,
4612                                               MultiExprArg Args,
4613                                               bool TopLevelOfInitList)
4614    : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
4615  InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4616}
4617
4618void InitializationSequence::InitializeFrom(Sema &S,
4619                                            const InitializedEntity &Entity,
4620                                            const InitializationKind &Kind,
4621                                            MultiExprArg Args,
4622                                            bool TopLevelOfInitList) {
4623  ASTContext &Context = S.Context;
4624
4625  // Eliminate non-overload placeholder types in the arguments.  We
4626  // need to do this before checking whether types are dependent
4627  // because lowering a pseudo-object expression might well give us
4628  // something of dependent type.
4629  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4630    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4631      // FIXME: should we be doing this here?
4632      ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4633      if (result.isInvalid()) {
4634        SetFailed(FK_PlaceholderType);
4635        return;
4636      }
4637      Args[I] = result.get();
4638    }
4639
4640  // C++0x [dcl.init]p16:
4641  //   The semantics of initializers are as follows. The destination type is
4642  //   the type of the object or reference being initialized and the source
4643  //   type is the type of the initializer expression. The source type is not
4644  //   defined when the initializer is a braced-init-list or when it is a
4645  //   parenthesized list of expressions.
4646  QualType DestType = Entity.getType();
4647
4648  if (DestType->isDependentType() ||
4649      Expr::hasAnyTypeDependentArguments(Args)) {
4650    SequenceKind = DependentSequence;
4651    return;
4652  }
4653
4654  // Almost everything is a normal sequence.
4655  setSequenceKind(NormalSequence);
4656
4657  QualType SourceType;
4658  Expr *Initializer = nullptr;
4659  if (Args.size() == 1) {
4660    Initializer = Args[0];
4661    if (S.getLangOpts().ObjC1) {
4662      if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4663                                              DestType, Initializer->getType(),
4664                                              Initializer) ||
4665          S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4666        Args[0] = Initializer;
4667    }
4668    if (!isa<InitListExpr>(Initializer))
4669      SourceType = Initializer->getType();
4670  }
4671
4672  //     - If the initializer is a (non-parenthesized) braced-init-list, the
4673  //       object is list-initialized (8.5.4).
4674  if (Kind.getKind() != InitializationKind::IK_Direct) {
4675    if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4676      TryListInitialization(S, Entity, Kind, InitList, *this);
4677      return;
4678    }
4679  }
4680
4681  //     - If the destination type is a reference type, see 8.5.3.
4682  if (DestType->isReferenceType()) {
4683    // C++0x [dcl.init.ref]p1:
4684    //   A variable declared to be a T& or T&&, that is, "reference to type T"
4685    //   (8.3.2), shall be initialized by an object, or function, of type T or
4686    //   by an object that can be converted into a T.
4687    // (Therefore, multiple arguments are not permitted.)
4688    if (Args.size() != 1)
4689      SetFailed(FK_TooManyInitsForReference);
4690    else
4691      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4692    return;
4693  }
4694
4695  //     - If the initializer is (), the object is value-initialized.
4696  if (Kind.getKind() == InitializationKind::IK_Value ||
4697      (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4698    TryValueInitialization(S, Entity, Kind, *this);
4699    return;
4700  }
4701
4702  // Handle default initialization.
4703  if (Kind.getKind() == InitializationKind::IK_Default) {
4704    TryDefaultInitialization(S, Entity, Kind, *this);
4705    return;
4706  }
4707
4708  //     - If the destination type is an array of characters, an array of
4709  //       char16_t, an array of char32_t, or an array of wchar_t, and the
4710  //       initializer is a string literal, see 8.5.2.
4711  //     - Otherwise, if the destination type is an array, the program is
4712  //       ill-formed.
4713  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4714    if (Initializer && isa<VariableArrayType>(DestAT)) {
4715      SetFailed(FK_VariableLengthArrayHasInitializer);
4716      return;
4717    }
4718
4719    if (Initializer) {
4720      switch (IsStringInit(Initializer, DestAT, Context)) {
4721      case SIF_None:
4722        TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4723        return;
4724      case SIF_NarrowStringIntoWideChar:
4725        SetFailed(FK_NarrowStringIntoWideCharArray);
4726        return;
4727      case SIF_WideStringIntoChar:
4728        SetFailed(FK_WideStringIntoCharArray);
4729        return;
4730      case SIF_IncompatWideStringIntoWideChar:
4731        SetFailed(FK_IncompatWideStringIntoWideChar);
4732        return;
4733      case SIF_Other:
4734        break;
4735      }
4736    }
4737
4738    // Note: as an GNU C extension, we allow initialization of an
4739    // array from a compound literal that creates an array of the same
4740    // type, so long as the initializer has no side effects.
4741    if (!S.getLangOpts().CPlusPlus && Initializer &&
4742        isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4743        Initializer->getType()->isArrayType()) {
4744      const ArrayType *SourceAT
4745        = Context.getAsArrayType(Initializer->getType());
4746      if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4747        SetFailed(FK_ArrayTypeMismatch);
4748      else if (Initializer->HasSideEffects(S.Context))
4749        SetFailed(FK_NonConstantArrayInit);
4750      else {
4751        AddArrayInitStep(DestType);
4752      }
4753    }
4754    // Note: as a GNU C++ extension, we allow list-initialization of a
4755    // class member of array type from a parenthesized initializer list.
4756    else if (S.getLangOpts().CPlusPlus &&
4757             Entity.getKind() == InitializedEntity::EK_Member &&
4758             Initializer && isa<InitListExpr>(Initializer)) {
4759      TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4760                            *this);
4761      AddParenthesizedArrayInitStep(DestType);
4762    } else if (DestAT->getElementType()->isCharType())
4763      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4764    else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4765      SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
4766    else
4767      SetFailed(FK_ArrayNeedsInitList);
4768
4769    return;
4770  }
4771
4772  // Determine whether we should consider writeback conversions for
4773  // Objective-C ARC.
4774  bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4775         Entity.isParameterKind();
4776
4777  // We're at the end of the line for C: it's either a write-back conversion
4778  // or it's a C assignment. There's no need to check anything else.
4779  if (!S.getLangOpts().CPlusPlus) {
4780    // If allowed, check whether this is an Objective-C writeback conversion.
4781    if (allowObjCWritebackConversion &&
4782        tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4783      return;
4784    }
4785
4786    if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4787      return;
4788
4789    if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4790      return;
4791
4792    // Handle initialization in C
4793    AddCAssignmentStep(DestType);
4794    MaybeProduceObjCObject(S, *this, Entity);
4795    return;
4796  }
4797
4798  assert(S.getLangOpts().CPlusPlus);
4799
4800  //     - If the destination type is a (possibly cv-qualified) class type:
4801  if (DestType->isRecordType()) {
4802    //     - If the initialization is direct-initialization, or if it is
4803    //       copy-initialization where the cv-unqualified version of the
4804    //       source type is the same class as, or a derived class of, the
4805    //       class of the destination, constructors are considered. [...]
4806    if (Kind.getKind() == InitializationKind::IK_Direct ||
4807        (Kind.getKind() == InitializationKind::IK_Copy &&
4808         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4809          S.IsDerivedFrom(SourceType, DestType))))
4810      TryConstructorInitialization(S, Entity, Kind, Args,
4811                                   DestType, *this);
4812    //     - Otherwise (i.e., for the remaining copy-initialization cases),
4813    //       user-defined conversion sequences that can convert from the source
4814    //       type to the destination type or (when a conversion function is
4815    //       used) to a derived class thereof are enumerated as described in
4816    //       13.3.1.4, and the best one is chosen through overload resolution
4817    //       (13.3).
4818    else
4819      TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
4820                               TopLevelOfInitList);
4821    return;
4822  }
4823
4824  if (Args.size() > 1) {
4825    SetFailed(FK_TooManyInitsForScalar);
4826    return;
4827  }
4828  assert(Args.size() == 1 && "Zero-argument case handled above");
4829
4830  //    - Otherwise, if the source type is a (possibly cv-qualified) class
4831  //      type, conversion functions are considered.
4832  if (!SourceType.isNull() && SourceType->isRecordType()) {
4833    // For a conversion to _Atomic(T) from either T or a class type derived
4834    // from T, initialize the T object then convert to _Atomic type.
4835    bool NeedAtomicConversion = false;
4836    if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4837      if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4838          S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4839        DestType = Atomic->getValueType();
4840        NeedAtomicConversion = true;
4841      }
4842    }
4843
4844    TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
4845                             TopLevelOfInitList);
4846    MaybeProduceObjCObject(S, *this, Entity);
4847    if (!Failed() && NeedAtomicConversion)
4848      AddAtomicConversionStep(Entity.getType());
4849    return;
4850  }
4851
4852  //    - Otherwise, the initial value of the object being initialized is the
4853  //      (possibly converted) value of the initializer expression. Standard
4854  //      conversions (Clause 4) will be used, if necessary, to convert the
4855  //      initializer expression to the cv-unqualified version of the
4856  //      destination type; no user-defined conversions are considered.
4857
4858  ImplicitConversionSequence ICS
4859    = S.TryImplicitConversion(Initializer, DestType,
4860                              /*SuppressUserConversions*/true,
4861                              /*AllowExplicitConversions*/ false,
4862                              /*InOverloadResolution*/ false,
4863                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4864                              allowObjCWritebackConversion);
4865
4866  if (ICS.isStandard() &&
4867      ICS.Standard.Second == ICK_Writeback_Conversion) {
4868    // Objective-C ARC writeback conversion.
4869
4870    // We should copy unless we're passing to an argument explicitly
4871    // marked 'out'.
4872    bool ShouldCopy = true;
4873    if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4874      ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4875
4876    // If there was an lvalue adjustment, add it as a separate conversion.
4877    if (ICS.Standard.First == ICK_Array_To_Pointer ||
4878        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4879      ImplicitConversionSequence LvalueICS;
4880      LvalueICS.setStandard();
4881      LvalueICS.Standard.setAsIdentityConversion();
4882      LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4883      LvalueICS.Standard.First = ICS.Standard.First;
4884      AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4885    }
4886
4887    AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
4888  } else if (ICS.isBad()) {
4889    DeclAccessPair dap;
4890    if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4891      AddZeroInitializationStep(Entity.getType());
4892    } else if (Initializer->getType() == Context.OverloadTy &&
4893               !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4894                                                     false, dap))
4895      SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4896    else
4897      SetFailed(InitializationSequence::FK_ConversionFailed);
4898  } else {
4899    AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4900
4901    MaybeProduceObjCObject(S, *this, Entity);
4902  }
4903}
4904
4905InitializationSequence::~InitializationSequence() {
4906  for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4907                                          StepEnd = Steps.end();
4908       Step != StepEnd; ++Step)
4909    Step->Destroy();
4910}
4911
4912//===----------------------------------------------------------------------===//
4913// Perform initialization
4914//===----------------------------------------------------------------------===//
4915static Sema::AssignmentAction
4916getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
4917  switch(Entity.getKind()) {
4918  case InitializedEntity::EK_Variable:
4919  case InitializedEntity::EK_New:
4920  case InitializedEntity::EK_Exception:
4921  case InitializedEntity::EK_Base:
4922  case InitializedEntity::EK_Delegating:
4923    return Sema::AA_Initializing;
4924
4925  case InitializedEntity::EK_Parameter:
4926    if (Entity.getDecl() &&
4927        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4928      return Sema::AA_Sending;
4929
4930    return Sema::AA_Passing;
4931
4932  case InitializedEntity::EK_Parameter_CF_Audited:
4933    if (Entity.getDecl() &&
4934      isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4935      return Sema::AA_Sending;
4936
4937    return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4938
4939  case InitializedEntity::EK_Result:
4940    return Sema::AA_Returning;
4941
4942  case InitializedEntity::EK_Temporary:
4943  case InitializedEntity::EK_RelatedResult:
4944    // FIXME: Can we tell apart casting vs. converting?
4945    return Sema::AA_Casting;
4946
4947  case InitializedEntity::EK_Member:
4948  case InitializedEntity::EK_ArrayElement:
4949  case InitializedEntity::EK_VectorElement:
4950  case InitializedEntity::EK_ComplexElement:
4951  case InitializedEntity::EK_BlockElement:
4952  case InitializedEntity::EK_LambdaCapture:
4953  case InitializedEntity::EK_CompoundLiteralInit:
4954    return Sema::AA_Initializing;
4955  }
4956
4957  llvm_unreachable("Invalid EntityKind!");
4958}
4959
4960/// \brief Whether we should bind a created object as a temporary when
4961/// initializing the given entity.
4962static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4963  switch (Entity.getKind()) {
4964  case InitializedEntity::EK_ArrayElement:
4965  case InitializedEntity::EK_Member:
4966  case InitializedEntity::EK_Result:
4967  case InitializedEntity::EK_New:
4968  case InitializedEntity::EK_Variable:
4969  case InitializedEntity::EK_Base:
4970  case InitializedEntity::EK_Delegating:
4971  case InitializedEntity::EK_VectorElement:
4972  case InitializedEntity::EK_ComplexElement:
4973  case InitializedEntity::EK_Exception:
4974  case InitializedEntity::EK_BlockElement:
4975  case InitializedEntity::EK_LambdaCapture:
4976  case InitializedEntity::EK_CompoundLiteralInit:
4977    return false;
4978
4979  case InitializedEntity::EK_Parameter:
4980  case InitializedEntity::EK_Parameter_CF_Audited:
4981  case InitializedEntity::EK_Temporary:
4982  case InitializedEntity::EK_RelatedResult:
4983    return true;
4984  }
4985
4986  llvm_unreachable("missed an InitializedEntity kind?");
4987}
4988
4989/// \brief Whether the given entity, when initialized with an object
4990/// created for that initialization, requires destruction.
4991static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4992  switch (Entity.getKind()) {
4993    case InitializedEntity::EK_Result:
4994    case InitializedEntity::EK_New:
4995    case InitializedEntity::EK_Base:
4996    case InitializedEntity::EK_Delegating:
4997    case InitializedEntity::EK_VectorElement:
4998    case InitializedEntity::EK_ComplexElement:
4999    case InitializedEntity::EK_BlockElement:
5000    case InitializedEntity::EK_LambdaCapture:
5001      return false;
5002
5003    case InitializedEntity::EK_Member:
5004    case InitializedEntity::EK_Variable:
5005    case InitializedEntity::EK_Parameter:
5006    case InitializedEntity::EK_Parameter_CF_Audited:
5007    case InitializedEntity::EK_Temporary:
5008    case InitializedEntity::EK_ArrayElement:
5009    case InitializedEntity::EK_Exception:
5010    case InitializedEntity::EK_CompoundLiteralInit:
5011    case InitializedEntity::EK_RelatedResult:
5012      return true;
5013  }
5014
5015  llvm_unreachable("missed an InitializedEntity kind?");
5016}
5017
5018/// \brief Look for copy and move constructors and constructor templates, for
5019/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
5020static void LookupCopyAndMoveConstructors(Sema &S,
5021                                          OverloadCandidateSet &CandidateSet,
5022                                          CXXRecordDecl *Class,
5023                                          Expr *CurInitExpr) {
5024  DeclContext::lookup_result R = S.LookupConstructors(Class);
5025  // The container holding the constructors can under certain conditions
5026  // be changed while iterating (e.g. because of deserialization).
5027  // To be safe we copy the lookup results to a new container.
5028  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
5029  for (SmallVectorImpl<NamedDecl *>::iterator
5030         CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
5031    NamedDecl *D = *CI;
5032    CXXConstructorDecl *Constructor = nullptr;
5033
5034    if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
5035      // Handle copy/moveconstructors, only.
5036      if (!Constructor || Constructor->isInvalidDecl() ||
5037          !Constructor->isCopyOrMoveConstructor() ||
5038          !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5039        continue;
5040
5041      DeclAccessPair FoundDecl
5042        = DeclAccessPair::make(Constructor, Constructor->getAccess());
5043      S.AddOverloadCandidate(Constructor, FoundDecl,
5044                             CurInitExpr, CandidateSet);
5045      continue;
5046    }
5047
5048    // Handle constructor templates.
5049    FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
5050    if (ConstructorTmpl->isInvalidDecl())
5051      continue;
5052
5053    Constructor = cast<CXXConstructorDecl>(
5054                                         ConstructorTmpl->getTemplatedDecl());
5055    if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5056      continue;
5057
5058    // FIXME: Do we need to limit this to copy-constructor-like
5059    // candidates?
5060    DeclAccessPair FoundDecl
5061      = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
5062    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
5063                                   CurInitExpr, CandidateSet, true);
5064  }
5065}
5066
5067/// \brief Get the location at which initialization diagnostics should appear.
5068static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5069                                           Expr *Initializer) {
5070  switch (Entity.getKind()) {
5071  case InitializedEntity::EK_Result:
5072    return Entity.getReturnLoc();
5073
5074  case InitializedEntity::EK_Exception:
5075    return Entity.getThrowLoc();
5076
5077  case InitializedEntity::EK_Variable:
5078    return Entity.getDecl()->getLocation();
5079
5080  case InitializedEntity::EK_LambdaCapture:
5081    return Entity.getCaptureLoc();
5082
5083  case InitializedEntity::EK_ArrayElement:
5084  case InitializedEntity::EK_Member:
5085  case InitializedEntity::EK_Parameter:
5086  case InitializedEntity::EK_Parameter_CF_Audited:
5087  case InitializedEntity::EK_Temporary:
5088  case InitializedEntity::EK_New:
5089  case InitializedEntity::EK_Base:
5090  case InitializedEntity::EK_Delegating:
5091  case InitializedEntity::EK_VectorElement:
5092  case InitializedEntity::EK_ComplexElement:
5093  case InitializedEntity::EK_BlockElement:
5094  case InitializedEntity::EK_CompoundLiteralInit:
5095  case InitializedEntity::EK_RelatedResult:
5096    return Initializer->getLocStart();
5097  }
5098  llvm_unreachable("missed an InitializedEntity kind?");
5099}
5100
5101/// \brief Make a (potentially elidable) temporary copy of the object
5102/// provided by the given initializer by calling the appropriate copy
5103/// constructor.
5104///
5105/// \param S The Sema object used for type-checking.
5106///
5107/// \param T The type of the temporary object, which must either be
5108/// the type of the initializer expression or a superclass thereof.
5109///
5110/// \param Entity The entity being initialized.
5111///
5112/// \param CurInit The initializer expression.
5113///
5114/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5115/// is permitted in C++03 (but not C++0x) when binding a reference to
5116/// an rvalue.
5117///
5118/// \returns An expression that copies the initializer expression into
5119/// a temporary object, or an error expression if a copy could not be
5120/// created.
5121static ExprResult CopyObject(Sema &S,
5122                             QualType T,
5123                             const InitializedEntity &Entity,
5124                             ExprResult CurInit,
5125                             bool IsExtraneousCopy) {
5126  if (CurInit.isInvalid())
5127    return CurInit;
5128  // Determine which class type we're copying to.
5129  Expr *CurInitExpr = (Expr *)CurInit.get();
5130  CXXRecordDecl *Class = nullptr;
5131  if (const RecordType *Record = T->getAs<RecordType>())
5132    Class = cast<CXXRecordDecl>(Record->getDecl());
5133  if (!Class)
5134    return CurInit;
5135
5136  // C++0x [class.copy]p32:
5137  //   When certain criteria are met, an implementation is allowed to
5138  //   omit the copy/move construction of a class object, even if the
5139  //   copy/move constructor and/or destructor for the object have
5140  //   side effects. [...]
5141  //     - when a temporary class object that has not been bound to a
5142  //       reference (12.2) would be copied/moved to a class object
5143  //       with the same cv-unqualified type, the copy/move operation
5144  //       can be omitted by constructing the temporary object
5145  //       directly into the target of the omitted copy/move
5146  //
5147  // Note that the other three bullets are handled elsewhere. Copy
5148  // elision for return statements and throw expressions are handled as part
5149  // of constructor initialization, while copy elision for exception handlers
5150  // is handled by the run-time.
5151  bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
5152  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5153
5154  // Make sure that the type we are copying is complete.
5155  if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5156    return CurInit;
5157
5158  // Perform overload resolution using the class's copy/move constructors.
5159  // Only consider constructors and constructor templates. Per
5160  // C++0x [dcl.init]p16, second bullet to class types, this initialization
5161  // is direct-initialization.
5162  OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5163  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
5164
5165  bool HadMultipleCandidates = (CandidateSet.size() > 1);
5166
5167  OverloadCandidateSet::iterator Best;
5168  switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
5169  case OR_Success:
5170    break;
5171
5172  case OR_No_Viable_Function:
5173    S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5174           ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5175           : diag::err_temp_copy_no_viable)
5176      << (int)Entity.getKind() << CurInitExpr->getType()
5177      << CurInitExpr->getSourceRange();
5178    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5179    if (!IsExtraneousCopy || S.isSFINAEContext())
5180      return ExprError();
5181    return CurInit;
5182
5183  case OR_Ambiguous:
5184    S.Diag(Loc, diag::err_temp_copy_ambiguous)
5185      << (int)Entity.getKind() << CurInitExpr->getType()
5186      << CurInitExpr->getSourceRange();
5187    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5188    return ExprError();
5189
5190  case OR_Deleted:
5191    S.Diag(Loc, diag::err_temp_copy_deleted)
5192      << (int)Entity.getKind() << CurInitExpr->getType()
5193      << CurInitExpr->getSourceRange();
5194    S.NoteDeletedFunction(Best->Function);
5195    return ExprError();
5196  }
5197
5198  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5199  SmallVector<Expr*, 8> ConstructorArgs;
5200  CurInit.get(); // Ownership transferred into MultiExprArg, below.
5201
5202  S.CheckConstructorAccess(Loc, Constructor, Entity,
5203                           Best->FoundDecl.getAccess(), IsExtraneousCopy);
5204
5205  if (IsExtraneousCopy) {
5206    // If this is a totally extraneous copy for C++03 reference
5207    // binding purposes, just return the original initialization
5208    // expression. We don't generate an (elided) copy operation here
5209    // because doing so would require us to pass down a flag to avoid
5210    // infinite recursion, where each step adds another extraneous,
5211    // elidable copy.
5212
5213    // Instantiate the default arguments of any extra parameters in
5214    // the selected copy constructor, as if we were going to create a
5215    // proper call to the copy constructor.
5216    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5217      ParmVarDecl *Parm = Constructor->getParamDecl(I);
5218      if (S.RequireCompleteType(Loc, Parm->getType(),
5219                                diag::err_call_incomplete_argument))
5220        break;
5221
5222      // Build the default argument expression; we don't actually care
5223      // if this succeeds or not, because this routine will complain
5224      // if there was a problem.
5225      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5226    }
5227
5228    return CurInitExpr;
5229  }
5230
5231  // Determine the arguments required to actually perform the
5232  // constructor call (we might have derived-to-base conversions, or
5233  // the copy constructor may have default arguments).
5234  if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5235    return ExprError();
5236
5237  // Actually perform the constructor call.
5238  CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
5239                                    ConstructorArgs,
5240                                    HadMultipleCandidates,
5241                                    /*ListInit*/ false,
5242                                    /*StdInitListInit*/ false,
5243                                    /*ZeroInit*/ false,
5244                                    CXXConstructExpr::CK_Complete,
5245                                    SourceRange());
5246
5247  // If we're supposed to bind temporaries, do so.
5248  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5249    CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5250  return CurInit;
5251}
5252
5253/// \brief Check whether elidable copy construction for binding a reference to
5254/// a temporary would have succeeded if we were building in C++98 mode, for
5255/// -Wc++98-compat.
5256static void CheckCXX98CompatAccessibleCopy(Sema &S,
5257                                           const InitializedEntity &Entity,
5258                                           Expr *CurInitExpr) {
5259  assert(S.getLangOpts().CPlusPlus11);
5260
5261  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5262  if (!Record)
5263    return;
5264
5265  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5266  if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5267    return;
5268
5269  // Find constructors which would have been considered.
5270  OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5271  LookupCopyAndMoveConstructors(
5272      S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5273
5274  // Perform overload resolution.
5275  OverloadCandidateSet::iterator Best;
5276  OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5277
5278  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5279    << OR << (int)Entity.getKind() << CurInitExpr->getType()
5280    << CurInitExpr->getSourceRange();
5281
5282  switch (OR) {
5283  case OR_Success:
5284    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5285                             Entity, Best->FoundDecl.getAccess(), Diag);
5286    // FIXME: Check default arguments as far as that's possible.
5287    break;
5288
5289  case OR_No_Viable_Function:
5290    S.Diag(Loc, Diag);
5291    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5292    break;
5293
5294  case OR_Ambiguous:
5295    S.Diag(Loc, Diag);
5296    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5297    break;
5298
5299  case OR_Deleted:
5300    S.Diag(Loc, Diag);
5301    S.NoteDeletedFunction(Best->Function);
5302    break;
5303  }
5304}
5305
5306void InitializationSequence::PrintInitLocationNote(Sema &S,
5307                                              const InitializedEntity &Entity) {
5308  if (Entity.isParameterKind() && Entity.getDecl()) {
5309    if (Entity.getDecl()->getLocation().isInvalid())
5310      return;
5311
5312    if (Entity.getDecl()->getDeclName())
5313      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5314        << Entity.getDecl()->getDeclName();
5315    else
5316      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5317  }
5318  else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5319           Entity.getMethodDecl())
5320    S.Diag(Entity.getMethodDecl()->getLocation(),
5321           diag::note_method_return_type_change)
5322      << Entity.getMethodDecl()->getDeclName();
5323}
5324
5325static bool isReferenceBinding(const InitializationSequence::Step &s) {
5326  return s.Kind == InitializationSequence::SK_BindReference ||
5327         s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5328}
5329
5330/// Returns true if the parameters describe a constructor initialization of
5331/// an explicit temporary object, e.g. "Point(x, y)".
5332static bool isExplicitTemporary(const InitializedEntity &Entity,
5333                                const InitializationKind &Kind,
5334                                unsigned NumArgs) {
5335  switch (Entity.getKind()) {
5336  case InitializedEntity::EK_Temporary:
5337  case InitializedEntity::EK_CompoundLiteralInit:
5338  case InitializedEntity::EK_RelatedResult:
5339    break;
5340  default:
5341    return false;
5342  }
5343
5344  switch (Kind.getKind()) {
5345  case InitializationKind::IK_DirectList:
5346    return true;
5347  // FIXME: Hack to work around cast weirdness.
5348  case InitializationKind::IK_Direct:
5349  case InitializationKind::IK_Value:
5350    return NumArgs != 1;
5351  default:
5352    return false;
5353  }
5354}
5355
5356static ExprResult
5357PerformConstructorInitialization(Sema &S,
5358                                 const InitializedEntity &Entity,
5359                                 const InitializationKind &Kind,
5360                                 MultiExprArg Args,
5361                                 const InitializationSequence::Step& Step,
5362                                 bool &ConstructorInitRequiresZeroInit,
5363                                 bool IsListInitialization,
5364                                 bool IsStdInitListInitialization,
5365                                 SourceLocation LBraceLoc,
5366                                 SourceLocation RBraceLoc) {
5367  unsigned NumArgs = Args.size();
5368  CXXConstructorDecl *Constructor
5369    = cast<CXXConstructorDecl>(Step.Function.Function);
5370  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5371
5372  // Build a call to the selected constructor.
5373  SmallVector<Expr*, 8> ConstructorArgs;
5374  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5375                         ? Kind.getEqualLoc()
5376                         : Kind.getLocation();
5377
5378  if (Kind.getKind() == InitializationKind::IK_Default) {
5379    // Force even a trivial, implicit default constructor to be
5380    // semantically checked. We do this explicitly because we don't build
5381    // the definition for completely trivial constructors.
5382    assert(Constructor->getParent() && "No parent class for constructor.");
5383    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5384        Constructor->isTrivial() && !Constructor->isUsed(false))
5385      S.DefineImplicitDefaultConstructor(Loc, Constructor);
5386  }
5387
5388  ExprResult CurInit((Expr *)nullptr);
5389
5390  // C++ [over.match.copy]p1:
5391  //   - When initializing a temporary to be bound to the first parameter
5392  //     of a constructor that takes a reference to possibly cv-qualified
5393  //     T as its first argument, called with a single argument in the
5394  //     context of direct-initialization, explicit conversion functions
5395  //     are also considered.
5396  bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5397                           Args.size() == 1 &&
5398                           Constructor->isCopyOrMoveConstructor();
5399
5400  // Determine the arguments required to actually perform the constructor
5401  // call.
5402  if (S.CompleteConstructorCall(Constructor, Args,
5403                                Loc, ConstructorArgs,
5404                                AllowExplicitConv,
5405                                IsListInitialization))
5406    return ExprError();
5407
5408
5409  if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5410    // An explicitly-constructed temporary, e.g., X(1, 2).
5411    S.MarkFunctionReferenced(Loc, Constructor);
5412    if (S.DiagnoseUseOfDecl(Constructor, Loc))
5413      return ExprError();
5414
5415    TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5416    if (!TSInfo)
5417      TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5418    SourceRange ParenOrBraceRange =
5419      (Kind.getKind() == InitializationKind::IK_DirectList)
5420      ? SourceRange(LBraceLoc, RBraceLoc)
5421      : Kind.getParenRange();
5422
5423    CurInit = new (S.Context) CXXTemporaryObjectExpr(
5424        S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5425        HadMultipleCandidates, IsListInitialization,
5426        IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
5427  } else {
5428    CXXConstructExpr::ConstructionKind ConstructKind =
5429      CXXConstructExpr::CK_Complete;
5430
5431    if (Entity.getKind() == InitializedEntity::EK_Base) {
5432      ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5433        CXXConstructExpr::CK_VirtualBase :
5434        CXXConstructExpr::CK_NonVirtualBase;
5435    } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5436      ConstructKind = CXXConstructExpr::CK_Delegating;
5437    }
5438
5439    // Only get the parenthesis or brace range if it is a list initialization or
5440    // direct construction.
5441    SourceRange ParenOrBraceRange;
5442    if (IsListInitialization)
5443      ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5444    else if (Kind.getKind() == InitializationKind::IK_Direct)
5445      ParenOrBraceRange = Kind.getParenRange();
5446
5447    // If the entity allows NRVO, mark the construction as elidable
5448    // unconditionally.
5449    if (Entity.allowsNRVO())
5450      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5451                                        Constructor, /*Elidable=*/true,
5452                                        ConstructorArgs,
5453                                        HadMultipleCandidates,
5454                                        IsListInitialization,
5455                                        IsStdInitListInitialization,
5456                                        ConstructorInitRequiresZeroInit,
5457                                        ConstructKind,
5458                                        ParenOrBraceRange);
5459    else
5460      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5461                                        Constructor,
5462                                        ConstructorArgs,
5463                                        HadMultipleCandidates,
5464                                        IsListInitialization,
5465                                        IsStdInitListInitialization,
5466                                        ConstructorInitRequiresZeroInit,
5467                                        ConstructKind,
5468                                        ParenOrBraceRange);
5469  }
5470  if (CurInit.isInvalid())
5471    return ExprError();
5472
5473  // Only check access if all of that succeeded.
5474  S.CheckConstructorAccess(Loc, Constructor, Entity,
5475                           Step.Function.FoundDecl.getAccess());
5476  if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5477    return ExprError();
5478
5479  if (shouldBindAsTemporary(Entity))
5480    CurInit = S.MaybeBindToTemporary(CurInit.get());
5481
5482  return CurInit;
5483}
5484
5485/// Determine whether the specified InitializedEntity definitely has a lifetime
5486/// longer than the current full-expression. Conservatively returns false if
5487/// it's unclear.
5488static bool
5489InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5490  const InitializedEntity *Top = &Entity;
5491  while (Top->getParent())
5492    Top = Top->getParent();
5493
5494  switch (Top->getKind()) {
5495  case InitializedEntity::EK_Variable:
5496  case InitializedEntity::EK_Result:
5497  case InitializedEntity::EK_Exception:
5498  case InitializedEntity::EK_Member:
5499  case InitializedEntity::EK_New:
5500  case InitializedEntity::EK_Base:
5501  case InitializedEntity::EK_Delegating:
5502    return true;
5503
5504  case InitializedEntity::EK_ArrayElement:
5505  case InitializedEntity::EK_VectorElement:
5506  case InitializedEntity::EK_BlockElement:
5507  case InitializedEntity::EK_ComplexElement:
5508    // Could not determine what the full initialization is. Assume it might not
5509    // outlive the full-expression.
5510    return false;
5511
5512  case InitializedEntity::EK_Parameter:
5513  case InitializedEntity::EK_Parameter_CF_Audited:
5514  case InitializedEntity::EK_Temporary:
5515  case InitializedEntity::EK_LambdaCapture:
5516  case InitializedEntity::EK_CompoundLiteralInit:
5517  case InitializedEntity::EK_RelatedResult:
5518    // The entity being initialized might not outlive the full-expression.
5519    return false;
5520  }
5521
5522  llvm_unreachable("unknown entity kind");
5523}
5524
5525/// Determine the declaration which an initialized entity ultimately refers to,
5526/// for the purpose of lifetime-extending a temporary bound to a reference in
5527/// the initialization of \p Entity.
5528static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5529    const InitializedEntity *Entity,
5530    const InitializedEntity *FallbackDecl = nullptr) {
5531  // C++11 [class.temporary]p5:
5532  switch (Entity->getKind()) {
5533  case InitializedEntity::EK_Variable:
5534    //   The temporary [...] persists for the lifetime of the reference
5535    return Entity;
5536
5537  case InitializedEntity::EK_Member:
5538    // For subobjects, we look at the complete object.
5539    if (Entity->getParent())
5540      return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5541                                                    Entity);
5542
5543    //   except:
5544    //   -- A temporary bound to a reference member in a constructor's
5545    //      ctor-initializer persists until the constructor exits.
5546    return Entity;
5547
5548  case InitializedEntity::EK_Parameter:
5549  case InitializedEntity::EK_Parameter_CF_Audited:
5550    //   -- A temporary bound to a reference parameter in a function call
5551    //      persists until the completion of the full-expression containing
5552    //      the call.
5553  case InitializedEntity::EK_Result:
5554    //   -- The lifetime of a temporary bound to the returned value in a
5555    //      function return statement is not extended; the temporary is
5556    //      destroyed at the end of the full-expression in the return statement.
5557  case InitializedEntity::EK_New:
5558    //   -- A temporary bound to a reference in a new-initializer persists
5559    //      until the completion of the full-expression containing the
5560    //      new-initializer.
5561    return nullptr;
5562
5563  case InitializedEntity::EK_Temporary:
5564  case InitializedEntity::EK_CompoundLiteralInit:
5565  case InitializedEntity::EK_RelatedResult:
5566    // We don't yet know the storage duration of the surrounding temporary.
5567    // Assume it's got full-expression duration for now, it will patch up our
5568    // storage duration if that's not correct.
5569    return nullptr;
5570
5571  case InitializedEntity::EK_ArrayElement:
5572    // For subobjects, we look at the complete object.
5573    return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5574                                                  FallbackDecl);
5575
5576  case InitializedEntity::EK_Base:
5577  case InitializedEntity::EK_Delegating:
5578    // We can reach this case for aggregate initialization in a constructor:
5579    //   struct A { int &&r; };
5580    //   struct B : A { B() : A{0} {} };
5581    // In this case, use the innermost field decl as the context.
5582    return FallbackDecl;
5583
5584  case InitializedEntity::EK_BlockElement:
5585  case InitializedEntity::EK_LambdaCapture:
5586  case InitializedEntity::EK_Exception:
5587  case InitializedEntity::EK_VectorElement:
5588  case InitializedEntity::EK_ComplexElement:
5589    return nullptr;
5590  }
5591  llvm_unreachable("unknown entity kind");
5592}
5593
5594static void performLifetimeExtension(Expr *Init,
5595                                     const InitializedEntity *ExtendingEntity);
5596
5597/// Update a glvalue expression that is used as the initializer of a reference
5598/// to note that its lifetime is extended.
5599/// \return \c true if any temporary had its lifetime extended.
5600static bool
5601performReferenceExtension(Expr *Init,
5602                          const InitializedEntity *ExtendingEntity) {
5603  // Walk past any constructs which we can lifetime-extend across.
5604  Expr *Old;
5605  do {
5606    Old = Init;
5607
5608    if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5609      if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5610        // This is just redundant braces around an initializer. Step over it.
5611        Init = ILE->getInit(0);
5612      }
5613    }
5614
5615    // Step over any subobject adjustments; we may have a materialized
5616    // temporary inside them.
5617    SmallVector<const Expr *, 2> CommaLHSs;
5618    SmallVector<SubobjectAdjustment, 2> Adjustments;
5619    Init = const_cast<Expr *>(
5620        Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5621
5622    // Per current approach for DR1376, look through casts to reference type
5623    // when performing lifetime extension.
5624    if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5625      if (CE->getSubExpr()->isGLValue())
5626        Init = CE->getSubExpr();
5627
5628    // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5629    // It's unclear if binding a reference to that xvalue extends the array
5630    // temporary.
5631  } while (Init != Old);
5632
5633  if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5634    // Update the storage duration of the materialized temporary.
5635    // FIXME: Rebuild the expression instead of mutating it.
5636    ME->setExtendingDecl(ExtendingEntity->getDecl(),
5637                         ExtendingEntity->allocateManglingNumber());
5638    performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
5639    return true;
5640  }
5641
5642  return false;
5643}
5644
5645/// Update a prvalue expression that is going to be materialized as a
5646/// lifetime-extended temporary.
5647static void performLifetimeExtension(Expr *Init,
5648                                     const InitializedEntity *ExtendingEntity) {
5649  // Dig out the expression which constructs the extended temporary.
5650  SmallVector<const Expr *, 2> CommaLHSs;
5651  SmallVector<SubobjectAdjustment, 2> Adjustments;
5652  Init = const_cast<Expr *>(
5653      Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5654
5655  if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5656    Init = BTE->getSubExpr();
5657
5658  if (CXXStdInitializerListExpr *ILE =
5659          dyn_cast<CXXStdInitializerListExpr>(Init)) {
5660    performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
5661    return;
5662  }
5663
5664  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5665    if (ILE->getType()->isArrayType()) {
5666      for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5667        performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
5668      return;
5669    }
5670
5671    if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
5672      assert(RD->isAggregate() && "aggregate init on non-aggregate");
5673
5674      // If we lifetime-extend a braced initializer which is initializing an
5675      // aggregate, and that aggregate contains reference members which are
5676      // bound to temporaries, those temporaries are also lifetime-extended.
5677      if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5678          ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5679        performReferenceExtension(ILE->getInit(0), ExtendingEntity);
5680      else {
5681        unsigned Index = 0;
5682        for (const auto *I : RD->fields()) {
5683          if (Index >= ILE->getNumInits())
5684            break;
5685          if (I->isUnnamedBitfield())
5686            continue;
5687          Expr *SubInit = ILE->getInit(Index);
5688          if (I->getType()->isReferenceType())
5689            performReferenceExtension(SubInit, ExtendingEntity);
5690          else if (isa<InitListExpr>(SubInit) ||
5691                   isa<CXXStdInitializerListExpr>(SubInit))
5692            // This may be either aggregate-initialization of a member or
5693            // initialization of a std::initializer_list object. Either way,
5694            // we should recursively lifetime-extend that initializer.
5695            performLifetimeExtension(SubInit, ExtendingEntity);
5696          ++Index;
5697        }
5698      }
5699    }
5700  }
5701}
5702
5703static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5704                                    const Expr *Init, bool IsInitializerList,
5705                                    const ValueDecl *ExtendingDecl) {
5706  // Warn if a field lifetime-extends a temporary.
5707  if (isa<FieldDecl>(ExtendingDecl)) {
5708    if (IsInitializerList) {
5709      S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5710        << /*at end of constructor*/true;
5711      return;
5712    }
5713
5714    bool IsSubobjectMember = false;
5715    for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5716         Ent = Ent->getParent()) {
5717      if (Ent->getKind() != InitializedEntity::EK_Base) {
5718        IsSubobjectMember = true;
5719        break;
5720      }
5721    }
5722    S.Diag(Init->getExprLoc(),
5723           diag::warn_bind_ref_member_to_temporary)
5724      << ExtendingDecl << Init->getSourceRange()
5725      << IsSubobjectMember << IsInitializerList;
5726    if (IsSubobjectMember)
5727      S.Diag(ExtendingDecl->getLocation(),
5728             diag::note_ref_subobject_of_member_declared_here);
5729    else
5730      S.Diag(ExtendingDecl->getLocation(),
5731             diag::note_ref_or_ptr_member_declared_here)
5732        << /*is pointer*/false;
5733  }
5734}
5735
5736static void DiagnoseNarrowingInInitList(Sema &S,
5737                                        const ImplicitConversionSequence &ICS,
5738                                        QualType PreNarrowingType,
5739                                        QualType EntityType,
5740                                        const Expr *PostInit);
5741
5742ExprResult
5743InitializationSequence::Perform(Sema &S,
5744                                const InitializedEntity &Entity,
5745                                const InitializationKind &Kind,
5746                                MultiExprArg Args,
5747                                QualType *ResultType) {
5748  if (Failed()) {
5749    Diagnose(S, Entity, Kind, Args);
5750    return ExprError();
5751  }
5752
5753  if (getKind() == DependentSequence) {
5754    // If the declaration is a non-dependent, incomplete array type
5755    // that has an initializer, then its type will be completed once
5756    // the initializer is instantiated.
5757    if (ResultType && !Entity.getType()->isDependentType() &&
5758        Args.size() == 1) {
5759      QualType DeclType = Entity.getType();
5760      if (const IncompleteArrayType *ArrayT
5761                           = S.Context.getAsIncompleteArrayType(DeclType)) {
5762        // FIXME: We don't currently have the ability to accurately
5763        // compute the length of an initializer list without
5764        // performing full type-checking of the initializer list
5765        // (since we have to determine where braces are implicitly
5766        // introduced and such).  So, we fall back to making the array
5767        // type a dependently-sized array type with no specified
5768        // bound.
5769        if (isa<InitListExpr>((Expr *)Args[0])) {
5770          SourceRange Brackets;
5771
5772          // Scavange the location of the brackets from the entity, if we can.
5773          if (DeclaratorDecl *DD = Entity.getDecl()) {
5774            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5775              TypeLoc TL = TInfo->getTypeLoc();
5776              if (IncompleteArrayTypeLoc ArrayLoc =
5777                      TL.getAs<IncompleteArrayTypeLoc>())
5778                Brackets = ArrayLoc.getBracketsRange();
5779            }
5780          }
5781
5782          *ResultType
5783            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5784                                                   /*NumElts=*/nullptr,
5785                                                   ArrayT->getSizeModifier(),
5786                                       ArrayT->getIndexTypeCVRQualifiers(),
5787                                                   Brackets);
5788        }
5789
5790      }
5791    }
5792    if (Kind.getKind() == InitializationKind::IK_Direct &&
5793        !Kind.isExplicitCast()) {
5794      // Rebuild the ParenListExpr.
5795      SourceRange ParenRange = Kind.getParenRange();
5796      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5797                                  Args);
5798    }
5799    assert(Kind.getKind() == InitializationKind::IK_Copy ||
5800           Kind.isExplicitCast() ||
5801           Kind.getKind() == InitializationKind::IK_DirectList);
5802    return ExprResult(Args[0]);
5803  }
5804
5805  // No steps means no initialization.
5806  if (Steps.empty())
5807    return ExprResult((Expr *)nullptr);
5808
5809  if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5810      Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5811      !Entity.isParameterKind()) {
5812    // Produce a C++98 compatibility warning if we are initializing a reference
5813    // from an initializer list. For parameters, we produce a better warning
5814    // elsewhere.
5815    Expr *Init = Args[0];
5816    S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5817      << Init->getSourceRange();
5818  }
5819
5820  // Diagnose cases where we initialize a pointer to an array temporary, and the
5821  // pointer obviously outlives the temporary.
5822  if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5823      Entity.getType()->isPointerType() &&
5824      InitializedEntityOutlivesFullExpression(Entity)) {
5825    Expr *Init = Args[0];
5826    Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5827    if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5828      S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5829        << Init->getSourceRange();
5830  }
5831
5832  QualType DestType = Entity.getType().getNonReferenceType();
5833  // FIXME: Ugly hack around the fact that Entity.getType() is not
5834  // the same as Entity.getDecl()->getType() in cases involving type merging,
5835  //  and we want latter when it makes sense.
5836  if (ResultType)
5837    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5838                                     Entity.getType();
5839
5840  ExprResult CurInit((Expr *)nullptr);
5841
5842  // For initialization steps that start with a single initializer,
5843  // grab the only argument out the Args and place it into the "current"
5844  // initializer.
5845  switch (Steps.front().Kind) {
5846  case SK_ResolveAddressOfOverloadedFunction:
5847  case SK_CastDerivedToBaseRValue:
5848  case SK_CastDerivedToBaseXValue:
5849  case SK_CastDerivedToBaseLValue:
5850  case SK_BindReference:
5851  case SK_BindReferenceToTemporary:
5852  case SK_ExtraneousCopyToTemporary:
5853  case SK_UserConversion:
5854  case SK_QualificationConversionLValue:
5855  case SK_QualificationConversionXValue:
5856  case SK_QualificationConversionRValue:
5857  case SK_AtomicConversion:
5858  case SK_LValueToRValue:
5859  case SK_ConversionSequence:
5860  case SK_ConversionSequenceNoNarrowing:
5861  case SK_ListInitialization:
5862  case SK_UnwrapInitList:
5863  case SK_RewrapInitList:
5864  case SK_CAssignment:
5865  case SK_StringInit:
5866  case SK_ObjCObjectConversion:
5867  case SK_ArrayInit:
5868  case SK_ParenthesizedArrayInit:
5869  case SK_PassByIndirectCopyRestore:
5870  case SK_PassByIndirectRestore:
5871  case SK_ProduceObjCObject:
5872  case SK_StdInitializerList:
5873  case SK_OCLSamplerInit:
5874  case SK_OCLZeroEvent: {
5875    assert(Args.size() == 1);
5876    CurInit = Args[0];
5877    if (!CurInit.get()) return ExprError();
5878    break;
5879  }
5880
5881  case SK_ConstructorInitialization:
5882  case SK_ConstructorInitializationFromList:
5883  case SK_StdInitializerListConstructorCall:
5884  case SK_ZeroInitialization:
5885    break;
5886  }
5887
5888  // Walk through the computed steps for the initialization sequence,
5889  // performing the specified conversions along the way.
5890  bool ConstructorInitRequiresZeroInit = false;
5891  for (step_iterator Step = step_begin(), StepEnd = step_end();
5892       Step != StepEnd; ++Step) {
5893    if (CurInit.isInvalid())
5894      return ExprError();
5895
5896    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5897
5898    switch (Step->Kind) {
5899    case SK_ResolveAddressOfOverloadedFunction:
5900      // Overload resolution determined which function invoke; update the
5901      // initializer to reflect that choice.
5902      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5903      if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5904        return ExprError();
5905      CurInit = S.FixOverloadedFunctionReference(CurInit,
5906                                                 Step->Function.FoundDecl,
5907                                                 Step->Function.Function);
5908      break;
5909
5910    case SK_CastDerivedToBaseRValue:
5911    case SK_CastDerivedToBaseXValue:
5912    case SK_CastDerivedToBaseLValue: {
5913      // We have a derived-to-base cast that produces either an rvalue or an
5914      // lvalue. Perform that cast.
5915
5916      CXXCastPath BasePath;
5917
5918      // Casts to inaccessible base classes are allowed with C-style casts.
5919      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5920      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5921                                         CurInit.get()->getLocStart(),
5922                                         CurInit.get()->getSourceRange(),
5923                                         &BasePath, IgnoreBaseAccess))
5924        return ExprError();
5925
5926      ExprValueKind VK =
5927          Step->Kind == SK_CastDerivedToBaseLValue ?
5928              VK_LValue :
5929              (Step->Kind == SK_CastDerivedToBaseXValue ?
5930                   VK_XValue :
5931                   VK_RValue);
5932      CurInit =
5933          ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5934                                   CurInit.get(), &BasePath, VK);
5935      break;
5936    }
5937
5938    case SK_BindReference:
5939      // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5940      if (CurInit.get()->refersToBitField()) {
5941        // We don't necessarily have an unambiguous source bit-field.
5942        FieldDecl *BitField = CurInit.get()->getSourceBitField();
5943        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5944          << Entity.getType().isVolatileQualified()
5945          << (BitField ? BitField->getDeclName() : DeclarationName())
5946          << (BitField != nullptr)
5947          << CurInit.get()->getSourceRange();
5948        if (BitField)
5949          S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5950
5951        return ExprError();
5952      }
5953
5954      if (CurInit.get()->refersToVectorElement()) {
5955        // References cannot bind to vector elements.
5956        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5957          << Entity.getType().isVolatileQualified()
5958          << CurInit.get()->getSourceRange();
5959        PrintInitLocationNote(S, Entity);
5960        return ExprError();
5961      }
5962
5963      // Reference binding does not have any corresponding ASTs.
5964
5965      // Check exception specifications
5966      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5967        return ExprError();
5968
5969      // Even though we didn't materialize a temporary, the binding may still
5970      // extend the lifetime of a temporary. This happens if we bind a reference
5971      // to the result of a cast to reference type.
5972      if (const InitializedEntity *ExtendingEntity =
5973              getEntityForTemporaryLifetimeExtension(&Entity))
5974        if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5975          warnOnLifetimeExtension(S, Entity, CurInit.get(),
5976                                  /*IsInitializerList=*/false,
5977                                  ExtendingEntity->getDecl());
5978
5979      break;
5980
5981    case SK_BindReferenceToTemporary: {
5982      // Make sure the "temporary" is actually an rvalue.
5983      assert(CurInit.get()->isRValue() && "not a temporary");
5984
5985      // Check exception specifications
5986      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5987        return ExprError();
5988
5989      // Materialize the temporary into memory.
5990      MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
5991          Entity.getType().getNonReferenceType(), CurInit.get(),
5992          Entity.getType()->isLValueReferenceType());
5993
5994      // Maybe lifetime-extend the temporary's subobjects to match the
5995      // entity's lifetime.
5996      if (const InitializedEntity *ExtendingEntity =
5997              getEntityForTemporaryLifetimeExtension(&Entity))
5998        if (performReferenceExtension(MTE, ExtendingEntity))
5999          warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
6000                                  ExtendingEntity->getDecl());
6001
6002      // If we're binding to an Objective-C object that has lifetime, we
6003      // need cleanups. Likewise if we're extending this temporary to automatic
6004      // storage duration -- we need to register its cleanup during the
6005      // full-expression's cleanups.
6006      if ((S.getLangOpts().ObjCAutoRefCount &&
6007           MTE->getType()->isObjCLifetimeType()) ||
6008          (MTE->getStorageDuration() == SD_Automatic &&
6009           MTE->getType().isDestructedType()))
6010        S.ExprNeedsCleanups = true;
6011
6012      CurInit = MTE;
6013      break;
6014    }
6015
6016    case SK_ExtraneousCopyToTemporary:
6017      CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6018                           /*IsExtraneousCopy=*/true);
6019      break;
6020
6021    case SK_UserConversion: {
6022      // We have a user-defined conversion that invokes either a constructor
6023      // or a conversion function.
6024      CastKind CastKind;
6025      bool IsCopy = false;
6026      FunctionDecl *Fn = Step->Function.Function;
6027      DeclAccessPair FoundFn = Step->Function.FoundDecl;
6028      bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
6029      bool CreatedObject = false;
6030      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
6031        // Build a call to the selected constructor.
6032        SmallVector<Expr*, 8> ConstructorArgs;
6033        SourceLocation Loc = CurInit.get()->getLocStart();
6034        CurInit.get(); // Ownership transferred into MultiExprArg, below.
6035
6036        // Determine the arguments required to actually perform the constructor
6037        // call.
6038        Expr *Arg = CurInit.get();
6039        if (S.CompleteConstructorCall(Constructor,
6040                                      MultiExprArg(&Arg, 1),
6041                                      Loc, ConstructorArgs))
6042          return ExprError();
6043
6044        // Build an expression that constructs a temporary.
6045        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
6046                                          ConstructorArgs,
6047                                          HadMultipleCandidates,
6048                                          /*ListInit*/ false,
6049                                          /*StdInitListInit*/ false,
6050                                          /*ZeroInit*/ false,
6051                                          CXXConstructExpr::CK_Complete,
6052                                          SourceRange());
6053        if (CurInit.isInvalid())
6054          return ExprError();
6055
6056        S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
6057                                 FoundFn.getAccess());
6058        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6059          return ExprError();
6060
6061        CastKind = CK_ConstructorConversion;
6062        QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6063        if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6064            S.IsDerivedFrom(SourceType, Class))
6065          IsCopy = true;
6066
6067        CreatedObject = true;
6068      } else {
6069        // Build a call to the conversion function.
6070        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
6071        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
6072                                    FoundFn);
6073        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6074          return ExprError();
6075
6076        // FIXME: Should we move this initialization into a separate
6077        // derived-to-base conversion? I believe the answer is "no", because
6078        // we don't want to turn off access control here for c-style casts.
6079        ExprResult CurInitExprRes =
6080          S.PerformObjectArgumentInitialization(CurInit.get(),
6081                                                /*Qualifier=*/nullptr,
6082                                                FoundFn, Conversion);
6083        if(CurInitExprRes.isInvalid())
6084          return ExprError();
6085        CurInit = CurInitExprRes;
6086
6087        // Build the actual call to the conversion function.
6088        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6089                                           HadMultipleCandidates);
6090        if (CurInit.isInvalid() || !CurInit.get())
6091          return ExprError();
6092
6093        CastKind = CK_UserDefinedConversion;
6094
6095        CreatedObject = Conversion->getReturnType()->isRecordType();
6096      }
6097
6098      bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
6099      bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6100
6101      if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
6102        QualType T = CurInit.get()->getType();
6103        if (const RecordType *Record = T->getAs<RecordType>()) {
6104          CXXDestructorDecl *Destructor
6105            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
6106          S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
6107                                  S.PDiag(diag::err_access_dtor_temp) << T);
6108          S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
6109          if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6110            return ExprError();
6111        }
6112      }
6113
6114      CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6115                                         CastKind, CurInit.get(), nullptr,
6116                                         CurInit.get()->getValueKind());
6117      if (MaybeBindToTemp)
6118        CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6119      if (RequiresCopy)
6120        CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
6121                             CurInit, /*IsExtraneousCopy=*/false);
6122      break;
6123    }
6124
6125    case SK_QualificationConversionLValue:
6126    case SK_QualificationConversionXValue:
6127    case SK_QualificationConversionRValue: {
6128      // Perform a qualification conversion; these can never go wrong.
6129      ExprValueKind VK =
6130          Step->Kind == SK_QualificationConversionLValue ?
6131              VK_LValue :
6132              (Step->Kind == SK_QualificationConversionXValue ?
6133                   VK_XValue :
6134                   VK_RValue);
6135      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
6136      break;
6137    }
6138
6139    case SK_AtomicConversion: {
6140      assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6141      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6142                                    CK_NonAtomicToAtomic, VK_RValue);
6143      break;
6144    }
6145
6146    case SK_LValueToRValue: {
6147      assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
6148      CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6149                                         CK_LValueToRValue, CurInit.get(),
6150                                         /*BasePath=*/nullptr, VK_RValue);
6151      break;
6152    }
6153
6154    case SK_ConversionSequence:
6155    case SK_ConversionSequenceNoNarrowing: {
6156      Sema::CheckedConversionKind CCK
6157        = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6158        : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
6159        : Kind.isExplicitCast()? Sema::CCK_OtherCast
6160        : Sema::CCK_ImplicitConversion;
6161      ExprResult CurInitExprRes =
6162        S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
6163                                    getAssignmentAction(Entity), CCK);
6164      if (CurInitExprRes.isInvalid())
6165        return ExprError();
6166      CurInit = CurInitExprRes;
6167
6168      if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6169          S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6170        DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6171                                    CurInit.get());
6172      break;
6173    }
6174
6175    case SK_ListInitialization: {
6176      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
6177      // If we're not initializing the top-level entity, we need to create an
6178      // InitializeTemporary entity for our target type.
6179      QualType Ty = Step->Type;
6180      bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
6181      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
6182      InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6183      InitListChecker PerformInitList(S, InitEntity,
6184          InitList, Ty, /*VerifyOnly=*/false);
6185      if (PerformInitList.HadError())
6186        return ExprError();
6187
6188      // Hack: We must update *ResultType if available in order to set the
6189      // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6190      // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6191      if (ResultType &&
6192          ResultType->getNonReferenceType()->isIncompleteArrayType()) {
6193        if ((*ResultType)->isRValueReferenceType())
6194          Ty = S.Context.getRValueReferenceType(Ty);
6195        else if ((*ResultType)->isLValueReferenceType())
6196          Ty = S.Context.getLValueReferenceType(Ty,
6197            (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6198        *ResultType = Ty;
6199      }
6200
6201      InitListExpr *StructuredInitList =
6202          PerformInitList.getFullyStructuredList();
6203      CurInit.get();
6204      CurInit = shouldBindAsTemporary(InitEntity)
6205          ? S.MaybeBindToTemporary(StructuredInitList)
6206          : StructuredInitList;
6207      break;
6208    }
6209
6210    case SK_ConstructorInitializationFromList: {
6211      // When an initializer list is passed for a parameter of type "reference
6212      // to object", we don't get an EK_Temporary entity, but instead an
6213      // EK_Parameter entity with reference type.
6214      // FIXME: This is a hack. What we really should do is create a user
6215      // conversion step for this case, but this makes it considerably more
6216      // complicated. For now, this will do.
6217      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6218                                        Entity.getType().getNonReferenceType());
6219      bool UseTemporary = Entity.getType()->isReferenceType();
6220      assert(Args.size() == 1 && "expected a single argument for list init");
6221      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6222      S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6223        << InitList->getSourceRange();
6224      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
6225      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6226                                                                   Entity,
6227                                                 Kind, Arg, *Step,
6228                                               ConstructorInitRequiresZeroInit,
6229                                               /*IsListInitialization*/true,
6230                                               /*IsStdInitListInit*/false,
6231                                               InitList->getLBraceLoc(),
6232                                               InitList->getRBraceLoc());
6233      break;
6234    }
6235
6236    case SK_UnwrapInitList:
6237      CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
6238      break;
6239
6240    case SK_RewrapInitList: {
6241      Expr *E = CurInit.get();
6242      InitListExpr *Syntactic = Step->WrappingSyntacticList;
6243      InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
6244          Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
6245      ILE->setSyntacticForm(Syntactic);
6246      ILE->setType(E->getType());
6247      ILE->setValueKind(E->getValueKind());
6248      CurInit = ILE;
6249      break;
6250    }
6251
6252    case SK_ConstructorInitialization:
6253    case SK_StdInitializerListConstructorCall: {
6254      // When an initializer list is passed for a parameter of type "reference
6255      // to object", we don't get an EK_Temporary entity, but instead an
6256      // EK_Parameter entity with reference type.
6257      // FIXME: This is a hack. What we really should do is create a user
6258      // conversion step for this case, but this makes it considerably more
6259      // complicated. For now, this will do.
6260      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6261                                        Entity.getType().getNonReferenceType());
6262      bool UseTemporary = Entity.getType()->isReferenceType();
6263      bool IsStdInitListInit =
6264          Step->Kind == SK_StdInitializerListConstructorCall;
6265      CurInit = PerformConstructorInitialization(
6266          S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6267          ConstructorInitRequiresZeroInit,
6268          /*IsListInitialization*/IsStdInitListInit,
6269          /*IsStdInitListInitialization*/IsStdInitListInit,
6270          /*LBraceLoc*/SourceLocation(),
6271          /*RBraceLoc*/SourceLocation());
6272      break;
6273    }
6274
6275    case SK_ZeroInitialization: {
6276      step_iterator NextStep = Step;
6277      ++NextStep;
6278      if (NextStep != StepEnd &&
6279          (NextStep->Kind == SK_ConstructorInitialization ||
6280           NextStep->Kind == SK_ConstructorInitializationFromList)) {
6281        // The need for zero-initialization is recorded directly into
6282        // the call to the object's constructor within the next step.
6283        ConstructorInitRequiresZeroInit = true;
6284      } else if (Kind.getKind() == InitializationKind::IK_Value &&
6285                 S.getLangOpts().CPlusPlus &&
6286                 !Kind.isImplicitValueInit()) {
6287        TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6288        if (!TSInfo)
6289          TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
6290                                                    Kind.getRange().getBegin());
6291
6292        CurInit = new (S.Context) CXXScalarValueInitExpr(
6293            TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6294            Kind.getRange().getEnd());
6295      } else {
6296        CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
6297      }
6298      break;
6299    }
6300
6301    case SK_CAssignment: {
6302      QualType SourceType = CurInit.get()->getType();
6303      ExprResult Result = CurInit;
6304      Sema::AssignConvertType ConvTy =
6305        S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6306            Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
6307      if (Result.isInvalid())
6308        return ExprError();
6309      CurInit = Result;
6310
6311      // If this is a call, allow conversion to a transparent union.
6312      ExprResult CurInitExprRes = CurInit;
6313      if (ConvTy != Sema::Compatible &&
6314          Entity.isParameterKind() &&
6315          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
6316            == Sema::Compatible)
6317        ConvTy = Sema::Compatible;
6318      if (CurInitExprRes.isInvalid())
6319        return ExprError();
6320      CurInit = CurInitExprRes;
6321
6322      bool Complained;
6323      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6324                                     Step->Type, SourceType,
6325                                     CurInit.get(),
6326                                     getAssignmentAction(Entity, true),
6327                                     &Complained)) {
6328        PrintInitLocationNote(S, Entity);
6329        return ExprError();
6330      } else if (Complained)
6331        PrintInitLocationNote(S, Entity);
6332      break;
6333    }
6334
6335    case SK_StringInit: {
6336      QualType Ty = Step->Type;
6337      CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
6338                      S.Context.getAsArrayType(Ty), S);
6339      break;
6340    }
6341
6342    case SK_ObjCObjectConversion:
6343      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6344                          CK_ObjCObjectLValueCast,
6345                          CurInit.get()->getValueKind());
6346      break;
6347
6348    case SK_ArrayInit:
6349      // Okay: we checked everything before creating this step. Note that
6350      // this is a GNU extension.
6351      S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
6352        << Step->Type << CurInit.get()->getType()
6353        << CurInit.get()->getSourceRange();
6354
6355      // If the destination type is an incomplete array type, update the
6356      // type accordingly.
6357      if (ResultType) {
6358        if (const IncompleteArrayType *IncompleteDest
6359                           = S.Context.getAsIncompleteArrayType(Step->Type)) {
6360          if (const ConstantArrayType *ConstantSource
6361                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
6362            *ResultType = S.Context.getConstantArrayType(
6363                                             IncompleteDest->getElementType(),
6364                                             ConstantSource->getSize(),
6365                                             ArrayType::Normal, 0);
6366          }
6367        }
6368      }
6369      break;
6370
6371    case SK_ParenthesizedArrayInit:
6372      // Okay: we checked everything before creating this step. Note that
6373      // this is a GNU extension.
6374      S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6375        << CurInit.get()->getSourceRange();
6376      break;
6377
6378    case SK_PassByIndirectCopyRestore:
6379    case SK_PassByIndirectRestore:
6380      checkIndirectCopyRestoreSource(S, CurInit.get());
6381      CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6382          CurInit.get(), Step->Type,
6383          Step->Kind == SK_PassByIndirectCopyRestore);
6384      break;
6385
6386    case SK_ProduceObjCObject:
6387      CurInit =
6388          ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6389                                   CurInit.get(), nullptr, VK_RValue);
6390      break;
6391
6392    case SK_StdInitializerList: {
6393      S.Diag(CurInit.get()->getExprLoc(),
6394             diag::warn_cxx98_compat_initializer_list_init)
6395        << CurInit.get()->getSourceRange();
6396
6397      // Materialize the temporary into memory.
6398      MaterializeTemporaryExpr *MTE = new (S.Context)
6399          MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6400                                   /*BoundToLvalueReference=*/false);
6401
6402      // Maybe lifetime-extend the array temporary's subobjects to match the
6403      // entity's lifetime.
6404      if (const InitializedEntity *ExtendingEntity =
6405              getEntityForTemporaryLifetimeExtension(&Entity))
6406        if (performReferenceExtension(MTE, ExtendingEntity))
6407          warnOnLifetimeExtension(S, Entity, CurInit.get(),
6408                                  /*IsInitializerList=*/true,
6409                                  ExtendingEntity->getDecl());
6410
6411      // Wrap it in a construction of a std::initializer_list<T>.
6412      CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
6413
6414      // Bind the result, in case the library has given initializer_list a
6415      // non-trivial destructor.
6416      if (shouldBindAsTemporary(Entity))
6417        CurInit = S.MaybeBindToTemporary(CurInit.get());
6418      break;
6419    }
6420
6421    case SK_OCLSamplerInit: {
6422      assert(Step->Type->isSamplerT() &&
6423             "Sampler initialization on non-sampler type.");
6424
6425      QualType SourceType = CurInit.get()->getType();
6426
6427      if (Entity.isParameterKind()) {
6428        if (!SourceType->isSamplerT())
6429          S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6430            << SourceType;
6431      } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
6432        llvm_unreachable("Invalid EntityKind!");
6433      }
6434
6435      break;
6436    }
6437    case SK_OCLZeroEvent: {
6438      assert(Step->Type->isEventT() &&
6439             "Event initialization on non-event type.");
6440
6441      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6442                                    CK_ZeroToOCLEvent,
6443                                    CurInit.get()->getValueKind());
6444      break;
6445    }
6446    }
6447  }
6448
6449  // Diagnose non-fatal problems with the completed initialization.
6450  if (Entity.getKind() == InitializedEntity::EK_Member &&
6451      cast<FieldDecl>(Entity.getDecl())->isBitField())
6452    S.CheckBitFieldInitialization(Kind.getLocation(),
6453                                  cast<FieldDecl>(Entity.getDecl()),
6454                                  CurInit.get());
6455
6456  return CurInit;
6457}
6458
6459/// Somewhere within T there is an uninitialized reference subobject.
6460/// Dig it out and diagnose it.
6461static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6462                                           QualType T) {
6463  if (T->isReferenceType()) {
6464    S.Diag(Loc, diag::err_reference_without_init)
6465      << T.getNonReferenceType();
6466    return true;
6467  }
6468
6469  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6470  if (!RD || !RD->hasUninitializedReferenceMember())
6471    return false;
6472
6473  for (const auto *FI : RD->fields()) {
6474    if (FI->isUnnamedBitfield())
6475      continue;
6476
6477    if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6478      S.Diag(Loc, diag::note_value_initialization_here) << RD;
6479      return true;
6480    }
6481  }
6482
6483  for (const auto &BI : RD->bases()) {
6484    if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
6485      S.Diag(Loc, diag::note_value_initialization_here) << RD;
6486      return true;
6487    }
6488  }
6489
6490  return false;
6491}
6492
6493
6494//===----------------------------------------------------------------------===//
6495// Diagnose initialization failures
6496//===----------------------------------------------------------------------===//
6497
6498/// Emit notes associated with an initialization that failed due to a
6499/// "simple" conversion failure.
6500static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6501                                   Expr *op) {
6502  QualType destType = entity.getType();
6503  if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6504      op->getType()->isObjCObjectPointerType()) {
6505
6506    // Emit a possible note about the conversion failing because the
6507    // operand is a message send with a related result type.
6508    S.EmitRelatedResultTypeNote(op);
6509
6510    // Emit a possible note about a return failing because we're
6511    // expecting a related result type.
6512    if (entity.getKind() == InitializedEntity::EK_Result)
6513      S.EmitRelatedResultTypeNoteForReturn(destType);
6514  }
6515}
6516
6517static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6518                             InitListExpr *InitList) {
6519  QualType DestType = Entity.getType();
6520
6521  QualType E;
6522  if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6523    QualType ArrayType = S.Context.getConstantArrayType(
6524        E.withConst(),
6525        llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6526                    InitList->getNumInits()),
6527        clang::ArrayType::Normal, 0);
6528    InitializedEntity HiddenArray =
6529        InitializedEntity::InitializeTemporary(ArrayType);
6530    return diagnoseListInit(S, HiddenArray, InitList);
6531  }
6532
6533  if (DestType->isReferenceType()) {
6534    // A list-initialization failure for a reference means that we tried to
6535    // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6536    // inner initialization failed.
6537    QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6538    diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6539    SourceLocation Loc = InitList->getLocStart();
6540    if (auto *D = Entity.getDecl())
6541      Loc = D->getLocation();
6542    S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6543    return;
6544  }
6545
6546  InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6547                                   /*VerifyOnly=*/false);
6548  assert(DiagnoseInitList.HadError() &&
6549         "Inconsistent init list check result.");
6550}
6551
6552/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6553/// right after emitting a diagnostic.
6554static void maybeEmitZeroInitializationFixit(Sema &S,
6555                                             InitializationSequence &Sequence,
6556                                             const InitializedEntity &Entity) {
6557  if (Entity.getKind() != InitializedEntity::EK_Variable)
6558    return;
6559
6560  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6561  if (VD->getInit() || VD->getLocEnd().isMacroID())
6562    return;
6563
6564  QualType VariableTy = VD->getType().getCanonicalType();
6565  SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6566  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6567
6568  S.Diag(Loc, diag::note_add_initializer)
6569      << VD << FixItHint::CreateInsertion(Loc, Init);
6570}
6571
6572bool InitializationSequence::Diagnose(Sema &S,
6573                                      const InitializedEntity &Entity,
6574                                      const InitializationKind &Kind,
6575                                      ArrayRef<Expr *> Args) {
6576  if (!Failed())
6577    return false;
6578
6579  QualType DestType = Entity.getType();
6580  switch (Failure) {
6581  case FK_TooManyInitsForReference:
6582    // FIXME: Customize for the initialized entity?
6583    if (Args.empty()) {
6584      // Dig out the reference subobject which is uninitialized and diagnose it.
6585      // If this is value-initialization, this could be nested some way within
6586      // the target type.
6587      assert(Kind.getKind() == InitializationKind::IK_Value ||
6588             DestType->isReferenceType());
6589      bool Diagnosed =
6590        DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6591      assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6592      (void)Diagnosed;
6593    } else  // FIXME: diagnostic below could be better!
6594      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
6595        << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
6596    break;
6597
6598  case FK_ArrayNeedsInitList:
6599    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
6600    break;
6601  case FK_ArrayNeedsInitListOrStringLiteral:
6602    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6603    break;
6604  case FK_ArrayNeedsInitListOrWideStringLiteral:
6605    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6606    break;
6607  case FK_NarrowStringIntoWideCharArray:
6608    S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6609    break;
6610  case FK_WideStringIntoCharArray:
6611    S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6612    break;
6613  case FK_IncompatWideStringIntoWideChar:
6614    S.Diag(Kind.getLocation(),
6615           diag::err_array_init_incompat_wide_string_into_wchar);
6616    break;
6617  case FK_ArrayTypeMismatch:
6618  case FK_NonConstantArrayInit:
6619    S.Diag(Kind.getLocation(),
6620           (Failure == FK_ArrayTypeMismatch
6621              ? diag::err_array_init_different_type
6622              : diag::err_array_init_non_constant_array))
6623      << DestType.getNonReferenceType()
6624      << Args[0]->getType()
6625      << Args[0]->getSourceRange();
6626    break;
6627
6628  case FK_VariableLengthArrayHasInitializer:
6629    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6630      << Args[0]->getSourceRange();
6631    break;
6632
6633  case FK_AddressOfOverloadFailed: {
6634    DeclAccessPair Found;
6635    S.ResolveAddressOfOverloadedFunction(Args[0],
6636                                         DestType.getNonReferenceType(),
6637                                         true,
6638                                         Found);
6639    break;
6640  }
6641
6642  case FK_ReferenceInitOverloadFailed:
6643  case FK_UserConversionOverloadFailed:
6644    switch (FailedOverloadResult) {
6645    case OR_Ambiguous:
6646      if (Failure == FK_UserConversionOverloadFailed)
6647        S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6648          << Args[0]->getType() << DestType
6649          << Args[0]->getSourceRange();
6650      else
6651        S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6652          << DestType << Args[0]->getType()
6653          << Args[0]->getSourceRange();
6654
6655      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6656      break;
6657
6658    case OR_No_Viable_Function:
6659      if (!S.RequireCompleteType(Kind.getLocation(),
6660                                 DestType.getNonReferenceType(),
6661                          diag::err_typecheck_nonviable_condition_incomplete,
6662                               Args[0]->getType(), Args[0]->getSourceRange()))
6663        S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6664          << Args[0]->getType() << Args[0]->getSourceRange()
6665          << DestType.getNonReferenceType();
6666
6667      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6668      break;
6669
6670    case OR_Deleted: {
6671      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6672        << Args[0]->getType() << DestType.getNonReferenceType()
6673        << Args[0]->getSourceRange();
6674      OverloadCandidateSet::iterator Best;
6675      OverloadingResult Ovl
6676        = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6677                                                true);
6678      if (Ovl == OR_Deleted) {
6679        S.NoteDeletedFunction(Best->Function);
6680      } else {
6681        llvm_unreachable("Inconsistent overload resolution?");
6682      }
6683      break;
6684    }
6685
6686    case OR_Success:
6687      llvm_unreachable("Conversion did not fail!");
6688    }
6689    break;
6690
6691  case FK_NonConstLValueReferenceBindingToTemporary:
6692    if (isa<InitListExpr>(Args[0])) {
6693      S.Diag(Kind.getLocation(),
6694             diag::err_lvalue_reference_bind_to_initlist)
6695      << DestType.getNonReferenceType().isVolatileQualified()
6696      << DestType.getNonReferenceType()
6697      << Args[0]->getSourceRange();
6698      break;
6699    }
6700    // Intentional fallthrough
6701
6702  case FK_NonConstLValueReferenceBindingToUnrelated:
6703    S.Diag(Kind.getLocation(),
6704           Failure == FK_NonConstLValueReferenceBindingToTemporary
6705             ? diag::err_lvalue_reference_bind_to_temporary
6706             : diag::err_lvalue_reference_bind_to_unrelated)
6707      << DestType.getNonReferenceType().isVolatileQualified()
6708      << DestType.getNonReferenceType()
6709      << Args[0]->getType()
6710      << Args[0]->getSourceRange();
6711    break;
6712
6713  case FK_RValueReferenceBindingToLValue:
6714    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
6715      << DestType.getNonReferenceType() << Args[0]->getType()
6716      << Args[0]->getSourceRange();
6717    break;
6718
6719  case FK_ReferenceInitDropsQualifiers:
6720    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6721      << DestType.getNonReferenceType()
6722      << Args[0]->getType()
6723      << Args[0]->getSourceRange();
6724    break;
6725
6726  case FK_ReferenceInitFailed:
6727    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6728      << DestType.getNonReferenceType()
6729      << Args[0]->isLValue()
6730      << Args[0]->getType()
6731      << Args[0]->getSourceRange();
6732    emitBadConversionNotes(S, Entity, Args[0]);
6733    break;
6734
6735  case FK_ConversionFailed: {
6736    QualType FromType = Args[0]->getType();
6737    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
6738      << (int)Entity.getKind()
6739      << DestType
6740      << Args[0]->isLValue()
6741      << FromType
6742      << Args[0]->getSourceRange();
6743    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6744    S.Diag(Kind.getLocation(), PDiag);
6745    emitBadConversionNotes(S, Entity, Args[0]);
6746    break;
6747  }
6748
6749  case FK_ConversionFromPropertyFailed:
6750    // No-op. This error has already been reported.
6751    break;
6752
6753  case FK_TooManyInitsForScalar: {
6754    SourceRange R;
6755
6756    auto *InitList = dyn_cast<InitListExpr>(Args[0]);
6757    if (InitList && InitList->getNumInits() == 1)
6758      R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
6759    else
6760      R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
6761
6762    R.setBegin(S.getLocForEndOfToken(R.getBegin()));
6763    if (Kind.isCStyleOrFunctionalCast())
6764      S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6765        << R;
6766    else
6767      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6768        << /*scalar=*/2 << R;
6769    break;
6770  }
6771
6772  case FK_ReferenceBindingToInitList:
6773    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6774      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6775    break;
6776
6777  case FK_InitListBadDestinationType:
6778    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6779      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6780    break;
6781
6782  case FK_ListConstructorOverloadFailed:
6783  case FK_ConstructorOverloadFailed: {
6784    SourceRange ArgsRange;
6785    if (Args.size())
6786      ArgsRange = SourceRange(Args.front()->getLocStart(),
6787                              Args.back()->getLocEnd());
6788
6789    if (Failure == FK_ListConstructorOverloadFailed) {
6790      assert(Args.size() == 1 &&
6791             "List construction from other than 1 argument.");
6792      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6793      Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6794    }
6795
6796    // FIXME: Using "DestType" for the entity we're printing is probably
6797    // bad.
6798    switch (FailedOverloadResult) {
6799      case OR_Ambiguous:
6800        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6801          << DestType << ArgsRange;
6802        FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6803        break;
6804
6805      case OR_No_Viable_Function:
6806        if (Kind.getKind() == InitializationKind::IK_Default &&
6807            (Entity.getKind() == InitializedEntity::EK_Base ||
6808             Entity.getKind() == InitializedEntity::EK_Member) &&
6809            isa<CXXConstructorDecl>(S.CurContext)) {
6810          // This is implicit default initialization of a member or
6811          // base within a constructor. If no viable function was
6812          // found, notify the user that she needs to explicitly
6813          // initialize this base/member.
6814          CXXConstructorDecl *Constructor
6815            = cast<CXXConstructorDecl>(S.CurContext);
6816          if (Entity.getKind() == InitializedEntity::EK_Base) {
6817            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6818              << (Constructor->getInheritedConstructor() ? 2 :
6819                  Constructor->isImplicit() ? 1 : 0)
6820              << S.Context.getTypeDeclType(Constructor->getParent())
6821              << /*base=*/0
6822              << Entity.getType();
6823
6824            RecordDecl *BaseDecl
6825              = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6826                                                                  ->getDecl();
6827            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6828              << S.Context.getTagDeclType(BaseDecl);
6829          } else {
6830            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6831              << (Constructor->getInheritedConstructor() ? 2 :
6832                  Constructor->isImplicit() ? 1 : 0)
6833              << S.Context.getTypeDeclType(Constructor->getParent())
6834              << /*member=*/1
6835              << Entity.getName();
6836            S.Diag(Entity.getDecl()->getLocation(),
6837                   diag::note_member_declared_at);
6838
6839            if (const RecordType *Record
6840                                 = Entity.getType()->getAs<RecordType>())
6841              S.Diag(Record->getDecl()->getLocation(),
6842                     diag::note_previous_decl)
6843                << S.Context.getTagDeclType(Record->getDecl());
6844          }
6845          break;
6846        }
6847
6848        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6849          << DestType << ArgsRange;
6850        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6851        break;
6852
6853      case OR_Deleted: {
6854        OverloadCandidateSet::iterator Best;
6855        OverloadingResult Ovl
6856          = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6857        if (Ovl != OR_Deleted) {
6858          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6859            << true << DestType << ArgsRange;
6860          llvm_unreachable("Inconsistent overload resolution?");
6861          break;
6862        }
6863
6864        // If this is a defaulted or implicitly-declared function, then
6865        // it was implicitly deleted. Make it clear that the deletion was
6866        // implicit.
6867        if (S.isImplicitlyDeleted(Best->Function))
6868          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6869            << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6870            << DestType << ArgsRange;
6871        else
6872          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6873            << true << DestType << ArgsRange;
6874
6875        S.NoteDeletedFunction(Best->Function);
6876        break;
6877      }
6878
6879      case OR_Success:
6880        llvm_unreachable("Conversion did not fail!");
6881    }
6882  }
6883  break;
6884
6885  case FK_DefaultInitOfConst:
6886    if (Entity.getKind() == InitializedEntity::EK_Member &&
6887        isa<CXXConstructorDecl>(S.CurContext)) {
6888      // This is implicit default-initialization of a const member in
6889      // a constructor. Complain that it needs to be explicitly
6890      // initialized.
6891      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6892      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6893        << (Constructor->getInheritedConstructor() ? 2 :
6894            Constructor->isImplicit() ? 1 : 0)
6895        << S.Context.getTypeDeclType(Constructor->getParent())
6896        << /*const=*/1
6897        << Entity.getName();
6898      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6899        << Entity.getName();
6900    } else {
6901      S.Diag(Kind.getLocation(), diag::err_default_init_const)
6902          << DestType << (bool)DestType->getAs<RecordType>();
6903      maybeEmitZeroInitializationFixit(S, *this, Entity);
6904    }
6905    break;
6906
6907  case FK_Incomplete:
6908    S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6909                          diag::err_init_incomplete_type);
6910    break;
6911
6912  case FK_ListInitializationFailed: {
6913    // Run the init list checker again to emit diagnostics.
6914    InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6915    diagnoseListInit(S, Entity, InitList);
6916    break;
6917  }
6918
6919  case FK_PlaceholderType: {
6920    // FIXME: Already diagnosed!
6921    break;
6922  }
6923
6924  case FK_ExplicitConstructor: {
6925    S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6926      << Args[0]->getSourceRange();
6927    OverloadCandidateSet::iterator Best;
6928    OverloadingResult Ovl
6929      = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6930    (void)Ovl;
6931    assert(Ovl == OR_Success && "Inconsistent overload resolution");
6932    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6933    S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6934    break;
6935  }
6936  }
6937
6938  PrintInitLocationNote(S, Entity);
6939  return true;
6940}
6941
6942void InitializationSequence::dump(raw_ostream &OS) const {
6943  switch (SequenceKind) {
6944  case FailedSequence: {
6945    OS << "Failed sequence: ";
6946    switch (Failure) {
6947    case FK_TooManyInitsForReference:
6948      OS << "too many initializers for reference";
6949      break;
6950
6951    case FK_ArrayNeedsInitList:
6952      OS << "array requires initializer list";
6953      break;
6954
6955    case FK_ArrayNeedsInitListOrStringLiteral:
6956      OS << "array requires initializer list or string literal";
6957      break;
6958
6959    case FK_ArrayNeedsInitListOrWideStringLiteral:
6960      OS << "array requires initializer list or wide string literal";
6961      break;
6962
6963    case FK_NarrowStringIntoWideCharArray:
6964      OS << "narrow string into wide char array";
6965      break;
6966
6967    case FK_WideStringIntoCharArray:
6968      OS << "wide string into char array";
6969      break;
6970
6971    case FK_IncompatWideStringIntoWideChar:
6972      OS << "incompatible wide string into wide char array";
6973      break;
6974
6975    case FK_ArrayTypeMismatch:
6976      OS << "array type mismatch";
6977      break;
6978
6979    case FK_NonConstantArrayInit:
6980      OS << "non-constant array initializer";
6981      break;
6982
6983    case FK_AddressOfOverloadFailed:
6984      OS << "address of overloaded function failed";
6985      break;
6986
6987    case FK_ReferenceInitOverloadFailed:
6988      OS << "overload resolution for reference initialization failed";
6989      break;
6990
6991    case FK_NonConstLValueReferenceBindingToTemporary:
6992      OS << "non-const lvalue reference bound to temporary";
6993      break;
6994
6995    case FK_NonConstLValueReferenceBindingToUnrelated:
6996      OS << "non-const lvalue reference bound to unrelated type";
6997      break;
6998
6999    case FK_RValueReferenceBindingToLValue:
7000      OS << "rvalue reference bound to an lvalue";
7001      break;
7002
7003    case FK_ReferenceInitDropsQualifiers:
7004      OS << "reference initialization drops qualifiers";
7005      break;
7006
7007    case FK_ReferenceInitFailed:
7008      OS << "reference initialization failed";
7009      break;
7010
7011    case FK_ConversionFailed:
7012      OS << "conversion failed";
7013      break;
7014
7015    case FK_ConversionFromPropertyFailed:
7016      OS << "conversion from property failed";
7017      break;
7018
7019    case FK_TooManyInitsForScalar:
7020      OS << "too many initializers for scalar";
7021      break;
7022
7023    case FK_ReferenceBindingToInitList:
7024      OS << "referencing binding to initializer list";
7025      break;
7026
7027    case FK_InitListBadDestinationType:
7028      OS << "initializer list for non-aggregate, non-scalar type";
7029      break;
7030
7031    case FK_UserConversionOverloadFailed:
7032      OS << "overloading failed for user-defined conversion";
7033      break;
7034
7035    case FK_ConstructorOverloadFailed:
7036      OS << "constructor overloading failed";
7037      break;
7038
7039    case FK_DefaultInitOfConst:
7040      OS << "default initialization of a const variable";
7041      break;
7042
7043    case FK_Incomplete:
7044      OS << "initialization of incomplete type";
7045      break;
7046
7047    case FK_ListInitializationFailed:
7048      OS << "list initialization checker failure";
7049      break;
7050
7051    case FK_VariableLengthArrayHasInitializer:
7052      OS << "variable length array has an initializer";
7053      break;
7054
7055    case FK_PlaceholderType:
7056      OS << "initializer expression isn't contextually valid";
7057      break;
7058
7059    case FK_ListConstructorOverloadFailed:
7060      OS << "list constructor overloading failed";
7061      break;
7062
7063    case FK_ExplicitConstructor:
7064      OS << "list copy initialization chose explicit constructor";
7065      break;
7066    }
7067    OS << '\n';
7068    return;
7069  }
7070
7071  case DependentSequence:
7072    OS << "Dependent sequence\n";
7073    return;
7074
7075  case NormalSequence:
7076    OS << "Normal sequence: ";
7077    break;
7078  }
7079
7080  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7081    if (S != step_begin()) {
7082      OS << " -> ";
7083    }
7084
7085    switch (S->Kind) {
7086    case SK_ResolveAddressOfOverloadedFunction:
7087      OS << "resolve address of overloaded function";
7088      break;
7089
7090    case SK_CastDerivedToBaseRValue:
7091      OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7092      break;
7093
7094    case SK_CastDerivedToBaseXValue:
7095      OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7096      break;
7097
7098    case SK_CastDerivedToBaseLValue:
7099      OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7100      break;
7101
7102    case SK_BindReference:
7103      OS << "bind reference to lvalue";
7104      break;
7105
7106    case SK_BindReferenceToTemporary:
7107      OS << "bind reference to a temporary";
7108      break;
7109
7110    case SK_ExtraneousCopyToTemporary:
7111      OS << "extraneous C++03 copy to temporary";
7112      break;
7113
7114    case SK_UserConversion:
7115      OS << "user-defined conversion via " << *S->Function.Function;
7116      break;
7117
7118    case SK_QualificationConversionRValue:
7119      OS << "qualification conversion (rvalue)";
7120      break;
7121
7122    case SK_QualificationConversionXValue:
7123      OS << "qualification conversion (xvalue)";
7124      break;
7125
7126    case SK_QualificationConversionLValue:
7127      OS << "qualification conversion (lvalue)";
7128      break;
7129
7130    case SK_AtomicConversion:
7131      OS << "non-atomic-to-atomic conversion";
7132      break;
7133
7134    case SK_LValueToRValue:
7135      OS << "load (lvalue to rvalue)";
7136      break;
7137
7138    case SK_ConversionSequence:
7139      OS << "implicit conversion sequence (";
7140      S->ICS->dump(); // FIXME: use OS
7141      OS << ")";
7142      break;
7143
7144    case SK_ConversionSequenceNoNarrowing:
7145      OS << "implicit conversion sequence with narrowing prohibited (";
7146      S->ICS->dump(); // FIXME: use OS
7147      OS << ")";
7148      break;
7149
7150    case SK_ListInitialization:
7151      OS << "list aggregate initialization";
7152      break;
7153
7154    case SK_UnwrapInitList:
7155      OS << "unwrap reference initializer list";
7156      break;
7157
7158    case SK_RewrapInitList:
7159      OS << "rewrap reference initializer list";
7160      break;
7161
7162    case SK_ConstructorInitialization:
7163      OS << "constructor initialization";
7164      break;
7165
7166    case SK_ConstructorInitializationFromList:
7167      OS << "list initialization via constructor";
7168      break;
7169
7170    case SK_ZeroInitialization:
7171      OS << "zero initialization";
7172      break;
7173
7174    case SK_CAssignment:
7175      OS << "C assignment";
7176      break;
7177
7178    case SK_StringInit:
7179      OS << "string initialization";
7180      break;
7181
7182    case SK_ObjCObjectConversion:
7183      OS << "Objective-C object conversion";
7184      break;
7185
7186    case SK_ArrayInit:
7187      OS << "array initialization";
7188      break;
7189
7190    case SK_ParenthesizedArrayInit:
7191      OS << "parenthesized array initialization";
7192      break;
7193
7194    case SK_PassByIndirectCopyRestore:
7195      OS << "pass by indirect copy and restore";
7196      break;
7197
7198    case SK_PassByIndirectRestore:
7199      OS << "pass by indirect restore";
7200      break;
7201
7202    case SK_ProduceObjCObject:
7203      OS << "Objective-C object retension";
7204      break;
7205
7206    case SK_StdInitializerList:
7207      OS << "std::initializer_list from initializer list";
7208      break;
7209
7210    case SK_StdInitializerListConstructorCall:
7211      OS << "list initialization from std::initializer_list";
7212      break;
7213
7214    case SK_OCLSamplerInit:
7215      OS << "OpenCL sampler_t from integer constant";
7216      break;
7217
7218    case SK_OCLZeroEvent:
7219      OS << "OpenCL event_t from zero";
7220      break;
7221    }
7222
7223    OS << " [" << S->Type.getAsString() << ']';
7224  }
7225
7226  OS << '\n';
7227}
7228
7229void InitializationSequence::dump() const {
7230  dump(llvm::errs());
7231}
7232
7233static void DiagnoseNarrowingInInitList(Sema &S,
7234                                        const ImplicitConversionSequence &ICS,
7235                                        QualType PreNarrowingType,
7236                                        QualType EntityType,
7237                                        const Expr *PostInit) {
7238  const StandardConversionSequence *SCS = nullptr;
7239  switch (ICS.getKind()) {
7240  case ImplicitConversionSequence::StandardConversion:
7241    SCS = &ICS.Standard;
7242    break;
7243  case ImplicitConversionSequence::UserDefinedConversion:
7244    SCS = &ICS.UserDefined.After;
7245    break;
7246  case ImplicitConversionSequence::AmbiguousConversion:
7247  case ImplicitConversionSequence::EllipsisConversion:
7248  case ImplicitConversionSequence::BadConversion:
7249    return;
7250  }
7251
7252  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7253  APValue ConstantValue;
7254  QualType ConstantType;
7255  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7256                                ConstantType)) {
7257  case NK_Not_Narrowing:
7258    // No narrowing occurred.
7259    return;
7260
7261  case NK_Type_Narrowing:
7262    // This was a floating-to-integer conversion, which is always considered a
7263    // narrowing conversion even if the value is a constant and can be
7264    // represented exactly as an integer.
7265    S.Diag(PostInit->getLocStart(),
7266           (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7267               ? diag::warn_init_list_type_narrowing
7268               : diag::ext_init_list_type_narrowing)
7269      << PostInit->getSourceRange()
7270      << PreNarrowingType.getLocalUnqualifiedType()
7271      << EntityType.getLocalUnqualifiedType();
7272    break;
7273
7274  case NK_Constant_Narrowing:
7275    // A constant value was narrowed.
7276    S.Diag(PostInit->getLocStart(),
7277           (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7278               ? diag::warn_init_list_constant_narrowing
7279               : diag::ext_init_list_constant_narrowing)
7280      << PostInit->getSourceRange()
7281      << ConstantValue.getAsString(S.getASTContext(), ConstantType)
7282      << EntityType.getLocalUnqualifiedType();
7283    break;
7284
7285  case NK_Variable_Narrowing:
7286    // A variable's value may have been narrowed.
7287    S.Diag(PostInit->getLocStart(),
7288           (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7289               ? diag::warn_init_list_variable_narrowing
7290               : diag::ext_init_list_variable_narrowing)
7291      << PostInit->getSourceRange()
7292      << PreNarrowingType.getLocalUnqualifiedType()
7293      << EntityType.getLocalUnqualifiedType();
7294    break;
7295  }
7296
7297  SmallString<128> StaticCast;
7298  llvm::raw_svector_ostream OS(StaticCast);
7299  OS << "static_cast<";
7300  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7301    // It's important to use the typedef's name if there is one so that the
7302    // fixit doesn't break code using types like int64_t.
7303    //
7304    // FIXME: This will break if the typedef requires qualification.  But
7305    // getQualifiedNameAsString() includes non-machine-parsable components.
7306    OS << *TT->getDecl();
7307  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
7308    OS << BT->getName(S.getLangOpts());
7309  else {
7310    // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
7311    // with a broken cast.
7312    return;
7313  }
7314  OS << ">(";
7315  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
7316      << PostInit->getSourceRange()
7317      << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7318      << FixItHint::CreateInsertion(
7319             S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
7320}
7321
7322//===----------------------------------------------------------------------===//
7323// Initialization helper functions
7324//===----------------------------------------------------------------------===//
7325bool
7326Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7327                                   ExprResult Init) {
7328  if (Init.isInvalid())
7329    return false;
7330
7331  Expr *InitE = Init.get();
7332  assert(InitE && "No initialization expression");
7333
7334  InitializationKind Kind
7335    = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
7336  InitializationSequence Seq(*this, Entity, Kind, InitE);
7337  return !Seq.Failed();
7338}
7339
7340ExprResult
7341Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7342                                SourceLocation EqualLoc,
7343                                ExprResult Init,
7344                                bool TopLevelOfInitList,
7345                                bool AllowExplicit) {
7346  if (Init.isInvalid())
7347    return ExprError();
7348
7349  Expr *InitE = Init.get();
7350  assert(InitE && "No initialization expression?");
7351
7352  if (EqualLoc.isInvalid())
7353    EqualLoc = InitE->getLocStart();
7354
7355  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
7356                                                           EqualLoc,
7357                                                           AllowExplicit);
7358  InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
7359
7360  ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
7361
7362  return Result;
7363}
7364