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