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