clang API Documentation

SemaInit.cpp
Go to the documentation of this file.
00001 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements semantic analysis for initializers.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/Initialization.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/DeclObjC.h"
00017 #include "clang/AST/ExprCXX.h"
00018 #include "clang/AST/ExprObjC.h"
00019 #include "clang/AST/TypeLoc.h"
00020 #include "clang/Basic/TargetInfo.h"
00021 #include "clang/Sema/Designator.h"
00022 #include "clang/Sema/Lookup.h"
00023 #include "clang/Sema/SemaInternal.h"
00024 #include "llvm/ADT/APInt.h"
00025 #include "llvm/ADT/SmallString.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include <map>
00029 using namespace clang;
00030 
00031 //===----------------------------------------------------------------------===//
00032 // Sema Initialization Checking
00033 //===----------------------------------------------------------------------===//
00034 
00035 /// \brief Check whether T is compatible with a wide character type (wchar_t,
00036 /// char16_t or char32_t).
00037 static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
00038   if (Context.typesAreCompatible(Context.getWideCharType(), T))
00039     return true;
00040   if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
00041     return Context.typesAreCompatible(Context.Char16Ty, T) ||
00042            Context.typesAreCompatible(Context.Char32Ty, T);
00043   }
00044   return false;
00045 }
00046 
00047 enum StringInitFailureKind {
00048   SIF_None,
00049   SIF_NarrowStringIntoWideChar,
00050   SIF_WideStringIntoChar,
00051   SIF_IncompatWideStringIntoWideChar,
00052   SIF_Other
00053 };
00054 
00055 /// \brief Check whether the array of type AT can be initialized by the Init
00056 /// expression by means of string initialization. Returns SIF_None if so,
00057 /// otherwise returns a StringInitFailureKind that describes why the
00058 /// initialization would not work.
00059 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
00060                                           ASTContext &Context) {
00061   if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
00062     return SIF_Other;
00063 
00064   // See if this is a string literal or @encode.
00065   Init = Init->IgnoreParens();
00066 
00067   // Handle @encode, which is a narrow string.
00068   if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
00069     return SIF_None;
00070 
00071   // Otherwise we can only handle string literals.
00072   StringLiteral *SL = dyn_cast<StringLiteral>(Init);
00073   if (!SL)
00074     return SIF_Other;
00075 
00076   const QualType ElemTy =
00077       Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
00078 
00079   switch (SL->getKind()) {
00080   case StringLiteral::Ascii:
00081   case StringLiteral::UTF8:
00082     // char array can be initialized with a narrow string.
00083     // Only allow char x[] = "foo";  not char x[] = L"foo";
00084     if (ElemTy->isCharType())
00085       return SIF_None;
00086     if (IsWideCharCompatible(ElemTy, Context))
00087       return SIF_NarrowStringIntoWideChar;
00088     return SIF_Other;
00089   // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
00090   // "An array with element type compatible with a qualified or unqualified
00091   // version of wchar_t, char16_t, or char32_t may be initialized by a wide
00092   // string literal with the corresponding encoding prefix (L, u, or U,
00093   // respectively), optionally enclosed in braces.
00094   case StringLiteral::UTF16:
00095     if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
00096       return SIF_None;
00097     if (ElemTy->isCharType())
00098       return SIF_WideStringIntoChar;
00099     if (IsWideCharCompatible(ElemTy, Context))
00100       return SIF_IncompatWideStringIntoWideChar;
00101     return SIF_Other;
00102   case StringLiteral::UTF32:
00103     if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
00104       return SIF_None;
00105     if (ElemTy->isCharType())
00106       return SIF_WideStringIntoChar;
00107     if (IsWideCharCompatible(ElemTy, Context))
00108       return SIF_IncompatWideStringIntoWideChar;
00109     return SIF_Other;
00110   case StringLiteral::Wide:
00111     if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
00112       return SIF_None;
00113     if (ElemTy->isCharType())
00114       return SIF_WideStringIntoChar;
00115     if (IsWideCharCompatible(ElemTy, Context))
00116       return SIF_IncompatWideStringIntoWideChar;
00117     return SIF_Other;
00118   }
00119 
00120   llvm_unreachable("missed a StringLiteral kind?");
00121 }
00122 
00123 static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
00124                                           ASTContext &Context) {
00125   const ArrayType *arrayType = Context.getAsArrayType(declType);
00126   if (!arrayType)
00127     return SIF_Other;
00128   return IsStringInit(init, arrayType, Context);
00129 }
00130 
00131 /// Update the type of a string literal, including any surrounding parentheses,
00132 /// to match the type of the object which it is initializing.
00133 static void updateStringLiteralType(Expr *E, QualType Ty) {
00134   while (true) {
00135     E->setType(Ty);
00136     if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
00137       break;
00138     else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
00139       E = PE->getSubExpr();
00140     else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
00141       E = UO->getSubExpr();
00142     else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
00143       E = GSE->getResultExpr();
00144     else
00145       llvm_unreachable("unexpected expr in string literal init");
00146   }
00147 }
00148 
00149 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
00150                             Sema &S) {
00151   // Get the length of the string as parsed.
00152   uint64_t StrLength =
00153     cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
00154 
00155 
00156   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
00157     // C99 6.7.8p14. We have an array of character type with unknown size
00158     // being initialized to a string literal.
00159     llvm::APInt ConstVal(32, StrLength);
00160     // Return a new array type (C99 6.7.8p22).
00161     DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
00162                                            ConstVal,
00163                                            ArrayType::Normal, 0);
00164     updateStringLiteralType(Str, DeclT);
00165     return;
00166   }
00167 
00168   const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
00169 
00170   // We have an array of character type with known size.  However,
00171   // the size may be smaller or larger than the string we are initializing.
00172   // FIXME: Avoid truncation for 64-bit length strings.
00173   if (S.getLangOpts().CPlusPlus) {
00174     if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
00175       // For Pascal strings it's OK to strip off the terminating null character,
00176       // so the example below is valid:
00177       //
00178       // unsigned char a[2] = "\pa";
00179       if (SL->isPascal())
00180         StrLength--;
00181     }
00182   
00183     // [dcl.init.string]p2
00184     if (StrLength > CAT->getSize().getZExtValue())
00185       S.Diag(Str->getLocStart(),
00186              diag::err_initializer_string_for_char_array_too_long)
00187         << Str->getSourceRange();
00188   } else {
00189     // C99 6.7.8p14.
00190     if (StrLength-1 > CAT->getSize().getZExtValue())
00191       S.Diag(Str->getLocStart(),
00192              diag::ext_initializer_string_for_char_array_too_long)
00193         << Str->getSourceRange();
00194   }
00195 
00196   // Set the type to the actual size that we are initializing.  If we have
00197   // something like:
00198   //   char x[1] = "foo";
00199   // then this will set the string literal's type to char[1].
00200   updateStringLiteralType(Str, DeclT);
00201 }
00202 
00203 //===----------------------------------------------------------------------===//
00204 // Semantic checking for initializer lists.
00205 //===----------------------------------------------------------------------===//
00206 
00207 /// @brief Semantic checking for initializer lists.
00208 ///
00209 /// The InitListChecker class contains a set of routines that each
00210 /// handle the initialization of a certain kind of entity, e.g.,
00211 /// arrays, vectors, struct/union types, scalars, etc. The
00212 /// InitListChecker itself performs a recursive walk of the subobject
00213 /// structure of the type to be initialized, while stepping through
00214 /// the initializer list one element at a time. The IList and Index
00215 /// parameters to each of the Check* routines contain the active
00216 /// (syntactic) initializer list and the index into that initializer
00217 /// list that represents the current initializer. Each routine is
00218 /// responsible for moving that Index forward as it consumes elements.
00219 ///
00220 /// Each Check* routine also has a StructuredList/StructuredIndex
00221 /// arguments, which contains the current "structured" (semantic)
00222 /// initializer list and the index into that initializer list where we
00223 /// are copying initializers as we map them over to the semantic
00224 /// list. Once we have completed our recursive walk of the subobject
00225 /// structure, we will have constructed a full semantic initializer
00226 /// list.
00227 ///
00228 /// C99 designators cause changes in the initializer list traversal,
00229 /// because they make the initialization "jump" into a specific
00230 /// subobject and then continue the initialization from that
00231 /// point. CheckDesignatedInitializer() recursively steps into the
00232 /// designated subobject and manages backing out the recursion to
00233 /// initialize the subobjects after the one designated.
00234 namespace {
00235 class InitListChecker {
00236   Sema &SemaRef;
00237   bool hadError;
00238   bool VerifyOnly; // no diagnostics, no structure building
00239   llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
00240   InitListExpr *FullyStructuredList;
00241 
00242   void CheckImplicitInitList(const InitializedEntity &Entity,
00243                              InitListExpr *ParentIList, QualType T,
00244                              unsigned &Index, InitListExpr *StructuredList,
00245                              unsigned &StructuredIndex);
00246   void CheckExplicitInitList(const InitializedEntity &Entity,
00247                              InitListExpr *IList, QualType &T,
00248                              InitListExpr *StructuredList,
00249                              bool TopLevelObject = false);
00250   void CheckListElementTypes(const InitializedEntity &Entity,
00251                              InitListExpr *IList, QualType &DeclType,
00252                              bool SubobjectIsDesignatorContext,
00253                              unsigned &Index,
00254                              InitListExpr *StructuredList,
00255                              unsigned &StructuredIndex,
00256                              bool TopLevelObject = false);
00257   void CheckSubElementType(const InitializedEntity &Entity,
00258                            InitListExpr *IList, QualType ElemType,
00259                            unsigned &Index,
00260                            InitListExpr *StructuredList,
00261                            unsigned &StructuredIndex);
00262   void CheckComplexType(const InitializedEntity &Entity,
00263                         InitListExpr *IList, QualType DeclType,
00264                         unsigned &Index,
00265                         InitListExpr *StructuredList,
00266                         unsigned &StructuredIndex);
00267   void CheckScalarType(const InitializedEntity &Entity,
00268                        InitListExpr *IList, QualType DeclType,
00269                        unsigned &Index,
00270                        InitListExpr *StructuredList,
00271                        unsigned &StructuredIndex);
00272   void CheckReferenceType(const InitializedEntity &Entity,
00273                           InitListExpr *IList, QualType DeclType,
00274                           unsigned &Index,
00275                           InitListExpr *StructuredList,
00276                           unsigned &StructuredIndex);
00277   void CheckVectorType(const InitializedEntity &Entity,
00278                        InitListExpr *IList, QualType DeclType, unsigned &Index,
00279                        InitListExpr *StructuredList,
00280                        unsigned &StructuredIndex);
00281   void CheckStructUnionTypes(const InitializedEntity &Entity,
00282                              InitListExpr *IList, QualType DeclType,
00283                              RecordDecl::field_iterator Field,
00284                              bool SubobjectIsDesignatorContext, unsigned &Index,
00285                              InitListExpr *StructuredList,
00286                              unsigned &StructuredIndex,
00287                              bool TopLevelObject = false);
00288   void CheckArrayType(const InitializedEntity &Entity,
00289                       InitListExpr *IList, QualType &DeclType,
00290                       llvm::APSInt elementIndex,
00291                       bool SubobjectIsDesignatorContext, unsigned &Index,
00292                       InitListExpr *StructuredList,
00293                       unsigned &StructuredIndex);
00294   bool CheckDesignatedInitializer(const InitializedEntity &Entity,
00295                                   InitListExpr *IList, DesignatedInitExpr *DIE,
00296                                   unsigned DesigIdx,
00297                                   QualType &CurrentObjectType,
00298                                   RecordDecl::field_iterator *NextField,
00299                                   llvm::APSInt *NextElementIndex,
00300                                   unsigned &Index,
00301                                   InitListExpr *StructuredList,
00302                                   unsigned &StructuredIndex,
00303                                   bool FinishSubobjectInit,
00304                                   bool TopLevelObject);
00305   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
00306                                            QualType CurrentObjectType,
00307                                            InitListExpr *StructuredList,
00308                                            unsigned StructuredIndex,
00309                                            SourceRange InitRange);
00310   void UpdateStructuredListElement(InitListExpr *StructuredList,
00311                                    unsigned &StructuredIndex,
00312                                    Expr *expr);
00313   int numArrayElements(QualType DeclType);
00314   int numStructUnionElements(QualType DeclType);
00315 
00316   static ExprResult PerformEmptyInit(Sema &SemaRef,
00317                                      SourceLocation Loc,
00318                                      const InitializedEntity &Entity,
00319                                      bool VerifyOnly);
00320   void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
00321                                const InitializedEntity &ParentEntity,
00322                                InitListExpr *ILE, bool &RequiresSecondPass);
00323   void FillInEmptyInitializations(const InitializedEntity &Entity,
00324                                   InitListExpr *ILE, bool &RequiresSecondPass);
00325   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
00326                               Expr *InitExpr, FieldDecl *Field,
00327                               bool TopLevelObject);
00328   void CheckEmptyInitializable(const InitializedEntity &Entity,
00329                                SourceLocation Loc);
00330 
00331 public:
00332   InitListChecker(Sema &S, const InitializedEntity &Entity,
00333                   InitListExpr *IL, QualType &T, bool VerifyOnly);
00334   bool HadError() { return hadError; }
00335 
00336   // @brief Retrieves the fully-structured initializer list used for
00337   // semantic analysis and code generation.
00338   InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
00339 };
00340 } // end anonymous namespace
00341 
00342 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
00343                                              SourceLocation Loc,
00344                                              const InitializedEntity &Entity,
00345                                              bool VerifyOnly) {
00346   InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
00347                                                             true);
00348   MultiExprArg SubInit;
00349   Expr *InitExpr;
00350   InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
00351 
00352   // C++ [dcl.init.aggr]p7:
00353   //   If there are fewer initializer-clauses in the list than there are
00354   //   members in the aggregate, then each member not explicitly initialized
00355   //   ...
00356   bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
00357       Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
00358   if (EmptyInitList) {
00359     // C++1y / DR1070:
00360     //   shall be initialized [...] from an empty initializer list.
00361     //
00362     // We apply the resolution of this DR to C++11 but not C++98, since C++98
00363     // does not have useful semantics for initialization from an init list.
00364     // We treat this as copy-initialization, because aggregate initialization
00365     // always performs copy-initialization on its elements.
00366     //
00367     // Only do this if we're initializing a class type, to avoid filling in
00368     // the initializer list where possible.
00369     InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
00370                    InitListExpr(SemaRef.Context, Loc, None, Loc);
00371     InitExpr->setType(SemaRef.Context.VoidTy);
00372     SubInit = InitExpr;
00373     Kind = InitializationKind::CreateCopy(Loc, Loc);
00374   } else {
00375     // C++03:
00376     //   shall be value-initialized.
00377   }
00378 
00379   InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
00380   // libstdc++4.6 marks the vector default constructor as explicit in
00381   // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
00382   // stlport does so too. Look for std::__debug for libstdc++, and for
00383   // std:: for stlport.  This is effectively a compiler-side implementation of
00384   // LWG2193.
00385   if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
00386           InitializationSequence::FK_ExplicitConstructor) {
00387     OverloadCandidateSet::iterator Best;
00388     OverloadingResult O =
00389         InitSeq.getFailedCandidateSet()
00390             .BestViableFunction(SemaRef, Kind.getLocation(), Best);
00391     (void)O;
00392     assert(O == OR_Success && "Inconsistent overload resolution");
00393     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
00394     CXXRecordDecl *R = CtorDecl->getParent();
00395 
00396     if (CtorDecl->getMinRequiredArguments() == 0 &&
00397         CtorDecl->isExplicit() && R->getDeclName() &&
00398         SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
00399 
00400 
00401       bool IsInStd = false;
00402       for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
00403            ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
00404         if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
00405           IsInStd = true;
00406       }
00407 
00408       if (IsInStd && llvm::StringSwitch<bool>(R->getName()) 
00409               .Cases("basic_string", "deque", "forward_list", true)
00410               .Cases("list", "map", "multimap", "multiset", true)
00411               .Cases("priority_queue", "queue", "set", "stack", true)
00412               .Cases("unordered_map", "unordered_set", "vector", true)
00413               .Default(false)) {
00414         InitSeq.InitializeFrom(
00415             SemaRef, Entity,
00416             InitializationKind::CreateValue(Loc, Loc, Loc, true),
00417             MultiExprArg(), /*TopLevelOfInitList=*/false);
00418         // Emit a warning for this.  System header warnings aren't shown
00419         // by default, but people working on system headers should see it.
00420         if (!VerifyOnly) {
00421           SemaRef.Diag(CtorDecl->getLocation(),
00422                        diag::warn_invalid_initializer_from_system_header);
00423           SemaRef.Diag(Entity.getDecl()->getLocation(),
00424                        diag::note_used_in_initialization_here);
00425         }
00426       }
00427     }
00428   }
00429   if (!InitSeq) {
00430     if (!VerifyOnly) {
00431       InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
00432       if (Entity.getKind() == InitializedEntity::EK_Member)
00433         SemaRef.Diag(Entity.getDecl()->getLocation(),
00434                      diag::note_in_omitted_aggregate_initializer)
00435           << /*field*/1 << Entity.getDecl();
00436       else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
00437         SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
00438           << /*array element*/0 << Entity.getElementIndex();
00439     }
00440     return ExprError();
00441   }
00442 
00443   return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
00444                     : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
00445 }
00446 
00447 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
00448                                               SourceLocation Loc) {
00449   assert(VerifyOnly &&
00450          "CheckEmptyInitializable is only inteded for verification mode.");
00451   if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
00452     hadError = true;
00453 }
00454 
00455 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
00456                                         const InitializedEntity &ParentEntity,
00457                                               InitListExpr *ILE,
00458                                               bool &RequiresSecondPass) {
00459   SourceLocation Loc = ILE->getLocEnd();
00460   unsigned NumInits = ILE->getNumInits();
00461   InitializedEntity MemberEntity
00462     = InitializedEntity::InitializeMember(Field, &ParentEntity);
00463   if (Init >= NumInits || !ILE->getInit(Init)) {
00464     // C++1y [dcl.init.aggr]p7:
00465     //   If there are fewer initializer-clauses in the list than there are
00466     //   members in the aggregate, then each member not explicitly initialized
00467     //   shall be initialized from its brace-or-equal-initializer [...]
00468     if (Field->hasInClassInitializer()) {
00469       ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
00470       if (DIE.isInvalid()) {
00471         hadError = true;
00472         return;
00473       }
00474       if (Init < NumInits)
00475         ILE->setInit(Init, DIE.get());
00476       else {
00477         ILE->updateInit(SemaRef.Context, Init, DIE.get());
00478         RequiresSecondPass = true;
00479       }
00480       return;
00481     }
00482 
00483     if (Field->getType()->isReferenceType()) {
00484       // C++ [dcl.init.aggr]p9:
00485       //   If an incomplete or empty initializer-list leaves a
00486       //   member of reference type uninitialized, the program is
00487       //   ill-formed.
00488       SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
00489         << Field->getType()
00490         << ILE->getSyntacticForm()->getSourceRange();
00491       SemaRef.Diag(Field->getLocation(),
00492                    diag::note_uninit_reference_member);
00493       hadError = true;
00494       return;
00495     }
00496 
00497     ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
00498                                              /*VerifyOnly*/false);
00499     if (MemberInit.isInvalid()) {
00500       hadError = true;
00501       return;
00502     }
00503 
00504     if (hadError) {
00505       // Do nothing
00506     } else if (Init < NumInits) {
00507       ILE->setInit(Init, MemberInit.getAs<Expr>());
00508     } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
00509       // Empty initialization requires a constructor call, so
00510       // extend the initializer list to include the constructor
00511       // call and make a note that we'll need to take another pass
00512       // through the initializer list.
00513       ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
00514       RequiresSecondPass = true;
00515     }
00516   } else if (InitListExpr *InnerILE
00517                = dyn_cast<InitListExpr>(ILE->getInit(Init)))
00518     FillInEmptyInitializations(MemberEntity, InnerILE,
00519                                RequiresSecondPass);
00520 }
00521 
00522 /// Recursively replaces NULL values within the given initializer list
00523 /// with expressions that perform value-initialization of the
00524 /// appropriate type.
00525 void
00526 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
00527                                             InitListExpr *ILE,
00528                                             bool &RequiresSecondPass) {
00529   assert((ILE->getType() != SemaRef.Context.VoidTy) &&
00530          "Should not have void type");
00531 
00532   if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
00533     const RecordDecl *RDecl = RType->getDecl();
00534     if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
00535       FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
00536                               Entity, ILE, RequiresSecondPass);
00537     else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
00538              cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
00539       for (auto *Field : RDecl->fields()) {
00540         if (Field->hasInClassInitializer()) {
00541           FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
00542           break;
00543         }
00544       }
00545     } else {
00546       unsigned Init = 0;
00547       for (auto *Field : RDecl->fields()) {
00548         if (Field->isUnnamedBitfield())
00549           continue;
00550 
00551         if (hadError)
00552           return;
00553 
00554         FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
00555         if (hadError)
00556           return;
00557 
00558         ++Init;
00559 
00560         // Only look at the first initialization of a union.
00561         if (RDecl->isUnion())
00562           break;
00563       }
00564     }
00565 
00566     return;
00567   }
00568 
00569   QualType ElementType;
00570 
00571   InitializedEntity ElementEntity = Entity;
00572   unsigned NumInits = ILE->getNumInits();
00573   unsigned NumElements = NumInits;
00574   if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
00575     ElementType = AType->getElementType();
00576     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
00577       NumElements = CAType->getSize().getZExtValue();
00578     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
00579                                                          0, Entity);
00580   } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
00581     ElementType = VType->getElementType();
00582     NumElements = VType->getNumElements();
00583     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
00584                                                          0, Entity);
00585   } else
00586     ElementType = ILE->getType();
00587 
00588   for (unsigned Init = 0; Init != NumElements; ++Init) {
00589     if (hadError)
00590       return;
00591 
00592     if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
00593         ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
00594       ElementEntity.setElementIndex(Init);
00595 
00596     Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
00597     if (!InitExpr && !ILE->hasArrayFiller()) {
00598       ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
00599                                                 ElementEntity,
00600                                                 /*VerifyOnly*/false);
00601       if (ElementInit.isInvalid()) {
00602         hadError = true;
00603         return;
00604       }
00605 
00606       if (hadError) {
00607         // Do nothing
00608       } else if (Init < NumInits) {
00609         // For arrays, just set the expression used for value-initialization
00610         // of the "holes" in the array.
00611         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
00612           ILE->setArrayFiller(ElementInit.getAs<Expr>());
00613         else
00614           ILE->setInit(Init, ElementInit.getAs<Expr>());
00615       } else {
00616         // For arrays, just set the expression used for value-initialization
00617         // of the rest of elements and exit.
00618         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
00619           ILE->setArrayFiller(ElementInit.getAs<Expr>());
00620           return;
00621         }
00622 
00623         if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
00624           // Empty initialization requires a constructor call, so
00625           // extend the initializer list to include the constructor
00626           // call and make a note that we'll need to take another pass
00627           // through the initializer list.
00628           ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
00629           RequiresSecondPass = true;
00630         }
00631       }
00632     } else if (InitListExpr *InnerILE
00633                  = dyn_cast_or_null<InitListExpr>(InitExpr))
00634       FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
00635   }
00636 }
00637 
00638 
00639 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
00640                                  InitListExpr *IL, QualType &T,
00641                                  bool VerifyOnly)
00642   : SemaRef(S), VerifyOnly(VerifyOnly) {
00643   hadError = false;
00644 
00645   FullyStructuredList =
00646       getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
00647   CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
00648                         /*TopLevelObject=*/true);
00649 
00650   if (!hadError && !VerifyOnly) {
00651     bool RequiresSecondPass = false;
00652     FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
00653     if (RequiresSecondPass && !hadError)
00654       FillInEmptyInitializations(Entity, FullyStructuredList,
00655                                  RequiresSecondPass);
00656   }
00657 }
00658 
00659 int InitListChecker::numArrayElements(QualType DeclType) {
00660   // FIXME: use a proper constant
00661   int maxElements = 0x7FFFFFFF;
00662   if (const ConstantArrayType *CAT =
00663         SemaRef.Context.getAsConstantArrayType(DeclType)) {
00664     maxElements = static_cast<int>(CAT->getSize().getZExtValue());
00665   }
00666   return maxElements;
00667 }
00668 
00669 int InitListChecker::numStructUnionElements(QualType DeclType) {
00670   RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
00671   int InitializableMembers = 0;
00672   for (const auto *Field : structDecl->fields())
00673     if (!Field->isUnnamedBitfield())
00674       ++InitializableMembers;
00675 
00676   if (structDecl->isUnion())
00677     return std::min(InitializableMembers, 1);
00678   return InitializableMembers - structDecl->hasFlexibleArrayMember();
00679 }
00680 
00681 /// Check whether the range of the initializer \p ParentIList from element
00682 /// \p Index onwards can be used to initialize an object of type \p T. Update
00683 /// \p Index to indicate how many elements of the list were consumed.
00684 ///
00685 /// This also fills in \p StructuredList, from element \p StructuredIndex
00686 /// onwards, with the fully-braced, desugared form of the initialization.
00687 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
00688                                             InitListExpr *ParentIList,
00689                                             QualType T, unsigned &Index,
00690                                             InitListExpr *StructuredList,
00691                                             unsigned &StructuredIndex) {
00692   int maxElements = 0;
00693 
00694   if (T->isArrayType())
00695     maxElements = numArrayElements(T);
00696   else if (T->isRecordType())
00697     maxElements = numStructUnionElements(T);
00698   else if (T->isVectorType())
00699     maxElements = T->getAs<VectorType>()->getNumElements();
00700   else
00701     llvm_unreachable("CheckImplicitInitList(): Illegal type");
00702 
00703   if (maxElements == 0) {
00704     if (!VerifyOnly)
00705       SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
00706                    diag::err_implicit_empty_initializer);
00707     ++Index;
00708     hadError = true;
00709     return;
00710   }
00711 
00712   // Build a structured initializer list corresponding to this subobject.
00713   InitListExpr *StructuredSubobjectInitList
00714     = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
00715                                  StructuredIndex,
00716           SourceRange(ParentIList->getInit(Index)->getLocStart(),
00717                       ParentIList->getSourceRange().getEnd()));
00718   unsigned StructuredSubobjectInitIndex = 0;
00719 
00720   // Check the element types and build the structural subobject.
00721   unsigned StartIndex = Index;
00722   CheckListElementTypes(Entity, ParentIList, T,
00723                         /*SubobjectIsDesignatorContext=*/false, Index,
00724                         StructuredSubobjectInitList,
00725                         StructuredSubobjectInitIndex);
00726 
00727   if (!VerifyOnly) {
00728     StructuredSubobjectInitList->setType(T);
00729 
00730     unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
00731     // Update the structured sub-object initializer so that it's ending
00732     // range corresponds with the end of the last initializer it used.
00733     if (EndIndex < ParentIList->getNumInits()) {
00734       SourceLocation EndLoc
00735         = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
00736       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
00737     }
00738 
00739     // Complain about missing braces.
00740     if (T->isArrayType() || T->isRecordType()) {
00741       SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
00742                    diag::warn_missing_braces)
00743           << StructuredSubobjectInitList->getSourceRange()
00744           << FixItHint::CreateInsertion(
00745                  StructuredSubobjectInitList->getLocStart(), "{")
00746           << FixItHint::CreateInsertion(
00747                  SemaRef.getLocForEndOfToken(
00748                      StructuredSubobjectInitList->getLocEnd()),
00749                  "}");
00750     }
00751   }
00752 }
00753 
00754 /// Check whether the initializer \p IList (that was written with explicit
00755 /// braces) can be used to initialize an object of type \p T.
00756 ///
00757 /// This also fills in \p StructuredList with the fully-braced, desugared
00758 /// form of the initialization.
00759 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
00760                                             InitListExpr *IList, QualType &T,
00761                                             InitListExpr *StructuredList,
00762                                             bool TopLevelObject) {
00763   if (!VerifyOnly) {
00764     SyntacticToSemantic[IList] = StructuredList;
00765     StructuredList->setSyntacticForm(IList);
00766   }
00767 
00768   unsigned Index = 0, StructuredIndex = 0;
00769   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
00770                         Index, StructuredList, StructuredIndex, TopLevelObject);
00771   if (!VerifyOnly) {
00772     QualType ExprTy = T;
00773     if (!ExprTy->isArrayType())
00774       ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
00775     IList->setType(ExprTy);
00776     StructuredList->setType(ExprTy);
00777   }
00778   if (hadError)
00779     return;
00780 
00781   if (Index < IList->getNumInits()) {
00782     // We have leftover initializers
00783     if (VerifyOnly) {
00784       if (SemaRef.getLangOpts().CPlusPlus ||
00785           (SemaRef.getLangOpts().OpenCL &&
00786            IList->getType()->isVectorType())) {
00787         hadError = true;
00788       }
00789       return;
00790     }
00791 
00792     if (StructuredIndex == 1 &&
00793         IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
00794             SIF_None) {
00795       unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
00796       if (SemaRef.getLangOpts().CPlusPlus) {
00797         DK = diag::err_excess_initializers_in_char_array_initializer;
00798         hadError = true;
00799       }
00800       // Special-case
00801       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
00802         << IList->getInit(Index)->getSourceRange();
00803     } else if (!T->isIncompleteType()) {
00804       // Don't complain for incomplete types, since we'll get an error
00805       // elsewhere
00806       QualType CurrentObjectType = StructuredList->getType();
00807       int initKind =
00808         CurrentObjectType->isArrayType()? 0 :
00809         CurrentObjectType->isVectorType()? 1 :
00810         CurrentObjectType->isScalarType()? 2 :
00811         CurrentObjectType->isUnionType()? 3 :
00812         4;
00813 
00814       unsigned DK = diag::ext_excess_initializers;
00815       if (SemaRef.getLangOpts().CPlusPlus) {
00816         DK = diag::err_excess_initializers;
00817         hadError = true;
00818       }
00819       if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
00820         DK = diag::err_excess_initializers;
00821         hadError = true;
00822       }
00823 
00824       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
00825         << initKind << IList->getInit(Index)->getSourceRange();
00826     }
00827   }
00828 
00829   if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
00830       !TopLevelObject)
00831     SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
00832       << IList->getSourceRange()
00833       << FixItHint::CreateRemoval(IList->getLocStart())
00834       << FixItHint::CreateRemoval(IList->getLocEnd());
00835 }
00836 
00837 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
00838                                             InitListExpr *IList,
00839                                             QualType &DeclType,
00840                                             bool SubobjectIsDesignatorContext,
00841                                             unsigned &Index,
00842                                             InitListExpr *StructuredList,
00843                                             unsigned &StructuredIndex,
00844                                             bool TopLevelObject) {
00845   if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
00846     // Explicitly braced initializer for complex type can be real+imaginary
00847     // parts.
00848     CheckComplexType(Entity, IList, DeclType, Index,
00849                      StructuredList, StructuredIndex);
00850   } else if (DeclType->isScalarType()) {
00851     CheckScalarType(Entity, IList, DeclType, Index,
00852                     StructuredList, StructuredIndex);
00853   } else if (DeclType->isVectorType()) {
00854     CheckVectorType(Entity, IList, DeclType, Index,
00855                     StructuredList, StructuredIndex);
00856   } else if (DeclType->isRecordType()) {
00857     assert(DeclType->isAggregateType() &&
00858            "non-aggregate records should be handed in CheckSubElementType");
00859     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
00860     CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
00861                           SubobjectIsDesignatorContext, Index,
00862                           StructuredList, StructuredIndex,
00863                           TopLevelObject);
00864   } else if (DeclType->isArrayType()) {
00865     llvm::APSInt Zero(
00866                     SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
00867                     false);
00868     CheckArrayType(Entity, IList, DeclType, Zero,
00869                    SubobjectIsDesignatorContext, Index,
00870                    StructuredList, StructuredIndex);
00871   } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
00872     // This type is invalid, issue a diagnostic.
00873     ++Index;
00874     if (!VerifyOnly)
00875       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
00876         << DeclType;
00877     hadError = true;
00878   } else if (DeclType->isReferenceType()) {
00879     CheckReferenceType(Entity, IList, DeclType, Index,
00880                        StructuredList, StructuredIndex);
00881   } else if (DeclType->isObjCObjectType()) {
00882     if (!VerifyOnly)
00883       SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
00884         << DeclType;
00885     hadError = true;
00886   } else {
00887     if (!VerifyOnly)
00888       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
00889         << DeclType;
00890     hadError = true;
00891   }
00892 }
00893 
00894 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
00895                                           InitListExpr *IList,
00896                                           QualType ElemType,
00897                                           unsigned &Index,
00898                                           InitListExpr *StructuredList,
00899                                           unsigned &StructuredIndex) {
00900   Expr *expr = IList->getInit(Index);
00901 
00902   if (ElemType->isReferenceType())
00903     return CheckReferenceType(Entity, IList, ElemType, Index,
00904                               StructuredList, StructuredIndex);
00905 
00906   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
00907     if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
00908       InitListExpr *InnerStructuredList
00909         = getStructuredSubobjectInit(IList, Index, ElemType,
00910                                      StructuredList, StructuredIndex,
00911                                      SubInitList->getSourceRange());
00912       CheckExplicitInitList(Entity, SubInitList, ElemType,
00913                             InnerStructuredList);
00914       ++StructuredIndex;
00915       ++Index;
00916       return;
00917     }
00918     assert(SemaRef.getLangOpts().CPlusPlus &&
00919            "non-aggregate records are only possible in C++");
00920     // C++ initialization is handled later.
00921   } else if (isa<ImplicitValueInitExpr>(expr)) {
00922     // This happens during template instantiation when we see an InitListExpr
00923     // that we've already checked once.
00924     assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
00925            "found implicit initialization for the wrong type");
00926     if (!VerifyOnly)
00927       UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
00928     ++Index;
00929     return;
00930   }
00931 
00932   // FIXME: Need to handle atomic aggregate types with implicit init lists.
00933   if (ElemType->isScalarType() || ElemType->isAtomicType())
00934     return CheckScalarType(Entity, IList, ElemType, Index,
00935                            StructuredList, StructuredIndex);
00936 
00937   assert((ElemType->isRecordType() || ElemType->isVectorType() ||
00938           ElemType->isArrayType()) && "Unexpected type");
00939 
00940   if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
00941     // arrayType can be incomplete if we're initializing a flexible
00942     // array member.  There's nothing we can do with the completed
00943     // type here, though.
00944 
00945     if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
00946       if (!VerifyOnly) {
00947         CheckStringInit(expr, ElemType, arrayType, SemaRef);
00948         UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
00949       }
00950       ++Index;
00951       return;
00952     }
00953 
00954     // Fall through for subaggregate initialization.
00955 
00956   } else if (SemaRef.getLangOpts().CPlusPlus) {
00957     // C++ [dcl.init.aggr]p12:
00958     //   All implicit type conversions (clause 4) are considered when
00959     //   initializing the aggregate member with an initializer from
00960     //   an initializer-list. If the initializer can initialize a
00961     //   member, the member is initialized. [...]
00962 
00963     // FIXME: Better EqualLoc?
00964     InitializationKind Kind =
00965       InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
00966     InitializationSequence Seq(SemaRef, Entity, Kind, expr);
00967 
00968     if (Seq) {
00969       if (!VerifyOnly) {
00970         ExprResult Result =
00971           Seq.Perform(SemaRef, Entity, Kind, expr);
00972         if (Result.isInvalid())
00973           hadError = true;
00974 
00975         UpdateStructuredListElement(StructuredList, StructuredIndex,
00976                                     Result.getAs<Expr>());
00977       }
00978       ++Index;
00979       return;
00980     }
00981 
00982     // Fall through for subaggregate initialization
00983   } else {
00984     // C99 6.7.8p13:
00985     //
00986     //   The initializer for a structure or union object that has
00987     //   automatic storage duration shall be either an initializer
00988     //   list as described below, or a single expression that has
00989     //   compatible structure or union type. In the latter case, the
00990     //   initial value of the object, including unnamed members, is
00991     //   that of the expression.
00992     ExprResult ExprRes = expr;
00993     if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
00994         SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
00995                                                  !VerifyOnly)
00996           != Sema::Incompatible) {
00997       if (ExprRes.isInvalid())
00998         hadError = true;
00999       else {
01000         ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
01001           if (ExprRes.isInvalid())
01002             hadError = true;
01003       }
01004       UpdateStructuredListElement(StructuredList, StructuredIndex,
01005                                   ExprRes.getAs<Expr>());
01006       ++Index;
01007       return;
01008     }
01009     ExprRes.get();
01010     // Fall through for subaggregate initialization
01011   }
01012 
01013   // C++ [dcl.init.aggr]p12:
01014   //
01015   //   [...] Otherwise, if the member is itself a non-empty
01016   //   subaggregate, brace elision is assumed and the initializer is
01017   //   considered for the initialization of the first member of
01018   //   the subaggregate.
01019   if (!SemaRef.getLangOpts().OpenCL && 
01020       (ElemType->isAggregateType() || ElemType->isVectorType())) {
01021     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
01022                           StructuredIndex);
01023     ++StructuredIndex;
01024   } else {
01025     if (!VerifyOnly) {
01026       // We cannot initialize this element, so let
01027       // PerformCopyInitialization produce the appropriate diagnostic.
01028       SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
01029                                         /*TopLevelOfInitList=*/true);
01030     }
01031     hadError = true;
01032     ++Index;
01033     ++StructuredIndex;
01034   }
01035 }
01036 
01037 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
01038                                        InitListExpr *IList, QualType DeclType,
01039                                        unsigned &Index,
01040                                        InitListExpr *StructuredList,
01041                                        unsigned &StructuredIndex) {
01042   assert(Index == 0 && "Index in explicit init list must be zero");
01043 
01044   // As an extension, clang supports complex initializers, which initialize
01045   // a complex number component-wise.  When an explicit initializer list for
01046   // a complex number contains two two initializers, this extension kicks in:
01047   // it exepcts the initializer list to contain two elements convertible to
01048   // the element type of the complex type. The first element initializes
01049   // the real part, and the second element intitializes the imaginary part.
01050 
01051   if (IList->getNumInits() != 2)
01052     return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
01053                            StructuredIndex);
01054 
01055   // This is an extension in C.  (The builtin _Complex type does not exist
01056   // in the C++ standard.)
01057   if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
01058     SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
01059       << IList->getSourceRange();
01060 
01061   // Initialize the complex number.
01062   QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
01063   InitializedEntity ElementEntity =
01064     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
01065 
01066   for (unsigned i = 0; i < 2; ++i) {
01067     ElementEntity.setElementIndex(Index);
01068     CheckSubElementType(ElementEntity, IList, elementType, Index,
01069                         StructuredList, StructuredIndex);
01070   }
01071 }
01072 
01073 
01074 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
01075                                       InitListExpr *IList, QualType DeclType,
01076                                       unsigned &Index,
01077                                       InitListExpr *StructuredList,
01078                                       unsigned &StructuredIndex) {
01079   if (Index >= IList->getNumInits()) {
01080     if (!VerifyOnly)
01081       SemaRef.Diag(IList->getLocStart(),
01082                    SemaRef.getLangOpts().CPlusPlus11 ?
01083                      diag::warn_cxx98_compat_empty_scalar_initializer :
01084                      diag::err_empty_scalar_initializer)
01085         << IList->getSourceRange();
01086     hadError = !SemaRef.getLangOpts().CPlusPlus11;
01087     ++Index;
01088     ++StructuredIndex;
01089     return;
01090   }
01091 
01092   Expr *expr = IList->getInit(Index);
01093   if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
01094     // FIXME: This is invalid, and accepting it causes overload resolution
01095     // to pick the wrong overload in some corner cases.
01096     if (!VerifyOnly)
01097       SemaRef.Diag(SubIList->getLocStart(),
01098                    diag::ext_many_braces_around_scalar_init)
01099         << SubIList->getSourceRange();
01100 
01101     CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
01102                     StructuredIndex);
01103     return;
01104   } else if (isa<DesignatedInitExpr>(expr)) {
01105     if (!VerifyOnly)
01106       SemaRef.Diag(expr->getLocStart(),
01107                    diag::err_designator_for_scalar_init)
01108         << DeclType << expr->getSourceRange();
01109     hadError = true;
01110     ++Index;
01111     ++StructuredIndex;
01112     return;
01113   }
01114 
01115   if (VerifyOnly) {
01116     if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
01117       hadError = true;
01118     ++Index;
01119     return;
01120   }
01121 
01122   ExprResult Result =
01123     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
01124                                       /*TopLevelOfInitList=*/true);
01125 
01126   Expr *ResultExpr = nullptr;
01127 
01128   if (Result.isInvalid())
01129     hadError = true; // types weren't compatible.
01130   else {
01131     ResultExpr = Result.getAs<Expr>();
01132 
01133     if (ResultExpr != expr) {
01134       // The type was promoted, update initializer list.
01135       IList->setInit(Index, ResultExpr);
01136     }
01137   }
01138   if (hadError)
01139     ++StructuredIndex;
01140   else
01141     UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
01142   ++Index;
01143 }
01144 
01145 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
01146                                          InitListExpr *IList, QualType DeclType,
01147                                          unsigned &Index,
01148                                          InitListExpr *StructuredList,
01149                                          unsigned &StructuredIndex) {
01150   if (Index >= IList->getNumInits()) {
01151     // FIXME: It would be wonderful if we could point at the actual member. In
01152     // general, it would be useful to pass location information down the stack,
01153     // so that we know the location (or decl) of the "current object" being
01154     // initialized.
01155     if (!VerifyOnly)
01156       SemaRef.Diag(IList->getLocStart(),
01157                     diag::err_init_reference_member_uninitialized)
01158         << DeclType
01159         << IList->getSourceRange();
01160     hadError = true;
01161     ++Index;
01162     ++StructuredIndex;
01163     return;
01164   }
01165 
01166   Expr *expr = IList->getInit(Index);
01167   if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
01168     if (!VerifyOnly)
01169       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
01170         << DeclType << IList->getSourceRange();
01171     hadError = true;
01172     ++Index;
01173     ++StructuredIndex;
01174     return;
01175   }
01176 
01177   if (VerifyOnly) {
01178     if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
01179       hadError = true;
01180     ++Index;
01181     return;
01182   }
01183 
01184   ExprResult Result =
01185       SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
01186                                         /*TopLevelOfInitList=*/true);
01187 
01188   if (Result.isInvalid())
01189     hadError = true;
01190 
01191   expr = Result.getAs<Expr>();
01192   IList->setInit(Index, expr);
01193 
01194   if (hadError)
01195     ++StructuredIndex;
01196   else
01197     UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
01198   ++Index;
01199 }
01200 
01201 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
01202                                       InitListExpr *IList, QualType DeclType,
01203                                       unsigned &Index,
01204                                       InitListExpr *StructuredList,
01205                                       unsigned &StructuredIndex) {
01206   const VectorType *VT = DeclType->getAs<VectorType>();
01207   unsigned maxElements = VT->getNumElements();
01208   unsigned numEltsInit = 0;
01209   QualType elementType = VT->getElementType();
01210 
01211   if (Index >= IList->getNumInits()) {
01212     // Make sure the element type can be value-initialized.
01213     if (VerifyOnly)
01214       CheckEmptyInitializable(
01215           InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
01216           IList->getLocEnd());
01217     return;
01218   }
01219 
01220   if (!SemaRef.getLangOpts().OpenCL) {
01221     // If the initializing element is a vector, try to copy-initialize
01222     // instead of breaking it apart (which is doomed to failure anyway).
01223     Expr *Init = IList->getInit(Index);
01224     if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
01225       if (VerifyOnly) {
01226         if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
01227           hadError = true;
01228         ++Index;
01229         return;
01230       }
01231 
01232   ExprResult Result =
01233       SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
01234                                         /*TopLevelOfInitList=*/true);
01235 
01236       Expr *ResultExpr = nullptr;
01237       if (Result.isInvalid())
01238         hadError = true; // types weren't compatible.
01239       else {
01240         ResultExpr = Result.getAs<Expr>();
01241 
01242         if (ResultExpr != Init) {
01243           // The type was promoted, update initializer list.
01244           IList->setInit(Index, ResultExpr);
01245         }
01246       }
01247       if (hadError)
01248         ++StructuredIndex;
01249       else
01250         UpdateStructuredListElement(StructuredList, StructuredIndex,
01251                                     ResultExpr);
01252       ++Index;
01253       return;
01254     }
01255 
01256     InitializedEntity ElementEntity =
01257       InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
01258 
01259     for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
01260       // Don't attempt to go past the end of the init list
01261       if (Index >= IList->getNumInits()) {
01262         if (VerifyOnly)
01263           CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
01264         break;
01265       }
01266 
01267       ElementEntity.setElementIndex(Index);
01268       CheckSubElementType(ElementEntity, IList, elementType, Index,
01269                           StructuredList, StructuredIndex);
01270     }
01271 
01272     if (VerifyOnly)
01273       return;
01274 
01275     bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
01276     const VectorType *T = Entity.getType()->getAs<VectorType>();
01277     if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
01278                         T->getVectorKind() == VectorType::NeonPolyVector)) {
01279       // The ability to use vector initializer lists is a GNU vector extension
01280       // and is unrelated to the NEON intrinsics in arm_neon.h. On little
01281       // endian machines it works fine, however on big endian machines it 
01282       // exhibits surprising behaviour:
01283       //
01284       //   uint32x2_t x = {42, 64};
01285       //   return vget_lane_u32(x, 0); // Will return 64.
01286       //
01287       // Because of this, explicitly call out that it is non-portable.
01288       //
01289       SemaRef.Diag(IList->getLocStart(),
01290                    diag::warn_neon_vector_initializer_non_portable);
01291 
01292       const char *typeCode;
01293       unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
01294 
01295       if (elementType->isFloatingType())
01296         typeCode = "f";
01297       else if (elementType->isSignedIntegerType())
01298         typeCode = "s";
01299       else if (elementType->isUnsignedIntegerType())
01300         typeCode = "u";
01301       else
01302         llvm_unreachable("Invalid element type!");
01303 
01304       SemaRef.Diag(IList->getLocStart(),
01305                    SemaRef.Context.getTypeSize(VT) > 64 ?
01306                    diag::note_neon_vector_initializer_non_portable_q :
01307                    diag::note_neon_vector_initializer_non_portable)
01308         << typeCode << typeSize;
01309     }
01310 
01311     return;
01312   }
01313 
01314   InitializedEntity ElementEntity =
01315     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
01316 
01317   // OpenCL initializers allows vectors to be constructed from vectors.
01318   for (unsigned i = 0; i < maxElements; ++i) {
01319     // Don't attempt to go past the end of the init list
01320     if (Index >= IList->getNumInits())
01321       break;
01322 
01323     ElementEntity.setElementIndex(Index);
01324 
01325     QualType IType = IList->getInit(Index)->getType();
01326     if (!IType->isVectorType()) {
01327       CheckSubElementType(ElementEntity, IList, elementType, Index,
01328                           StructuredList, StructuredIndex);
01329       ++numEltsInit;
01330     } else {
01331       QualType VecType;
01332       const VectorType *IVT = IType->getAs<VectorType>();
01333       unsigned numIElts = IVT->getNumElements();
01334 
01335       if (IType->isExtVectorType())
01336         VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
01337       else
01338         VecType = SemaRef.Context.getVectorType(elementType, numIElts,
01339                                                 IVT->getVectorKind());
01340       CheckSubElementType(ElementEntity, IList, VecType, Index,
01341                           StructuredList, StructuredIndex);
01342       numEltsInit += numIElts;
01343     }
01344   }
01345 
01346   // OpenCL requires all elements to be initialized.
01347   if (numEltsInit != maxElements) {
01348     if (!VerifyOnly)
01349       SemaRef.Diag(IList->getLocStart(),
01350                    diag::err_vector_incorrect_num_initializers)
01351         << (numEltsInit < maxElements) << maxElements << numEltsInit;
01352     hadError = true;
01353   }
01354 }
01355 
01356 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
01357                                      InitListExpr *IList, QualType &DeclType,
01358                                      llvm::APSInt elementIndex,
01359                                      bool SubobjectIsDesignatorContext,
01360                                      unsigned &Index,
01361                                      InitListExpr *StructuredList,
01362                                      unsigned &StructuredIndex) {
01363   const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
01364 
01365   // Check for the special-case of initializing an array with a string.
01366   if (Index < IList->getNumInits()) {
01367     if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
01368         SIF_None) {
01369       // We place the string literal directly into the resulting
01370       // initializer list. This is the only place where the structure
01371       // of the structured initializer list doesn't match exactly,
01372       // because doing so would involve allocating one character
01373       // constant for each string.
01374       if (!VerifyOnly) {
01375         CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
01376         UpdateStructuredListElement(StructuredList, StructuredIndex,
01377                                     IList->getInit(Index));
01378         StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
01379       }
01380       ++Index;
01381       return;
01382     }
01383   }
01384   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
01385     // Check for VLAs; in standard C it would be possible to check this
01386     // earlier, but I don't know where clang accepts VLAs (gcc accepts
01387     // them in all sorts of strange places).
01388     if (!VerifyOnly)
01389       SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
01390                     diag::err_variable_object_no_init)
01391         << VAT->getSizeExpr()->getSourceRange();
01392     hadError = true;
01393     ++Index;
01394     ++StructuredIndex;
01395     return;
01396   }
01397 
01398   // We might know the maximum number of elements in advance.
01399   llvm::APSInt maxElements(elementIndex.getBitWidth(),
01400                            elementIndex.isUnsigned());
01401   bool maxElementsKnown = false;
01402   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
01403     maxElements = CAT->getSize();
01404     elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
01405     elementIndex.setIsUnsigned(maxElements.isUnsigned());
01406     maxElementsKnown = true;
01407   }
01408 
01409   QualType elementType = arrayType->getElementType();
01410   while (Index < IList->getNumInits()) {
01411     Expr *Init = IList->getInit(Index);
01412     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
01413       // If we're not the subobject that matches up with the '{' for
01414       // the designator, we shouldn't be handling the
01415       // designator. Return immediately.
01416       if (!SubobjectIsDesignatorContext)
01417         return;
01418 
01419       // Handle this designated initializer. elementIndex will be
01420       // updated to be the next array element we'll initialize.
01421       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
01422                                      DeclType, nullptr, &elementIndex, Index,
01423                                      StructuredList, StructuredIndex, true,
01424                                      false)) {
01425         hadError = true;
01426         continue;
01427       }
01428 
01429       if (elementIndex.getBitWidth() > maxElements.getBitWidth())
01430         maxElements = maxElements.extend(elementIndex.getBitWidth());
01431       else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
01432         elementIndex = elementIndex.extend(maxElements.getBitWidth());
01433       elementIndex.setIsUnsigned(maxElements.isUnsigned());
01434 
01435       // If the array is of incomplete type, keep track of the number of
01436       // elements in the initializer.
01437       if (!maxElementsKnown && elementIndex > maxElements)
01438         maxElements = elementIndex;
01439 
01440       continue;
01441     }
01442 
01443     // If we know the maximum number of elements, and we've already
01444     // hit it, stop consuming elements in the initializer list.
01445     if (maxElementsKnown && elementIndex == maxElements)
01446       break;
01447 
01448     InitializedEntity ElementEntity =
01449       InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
01450                                            Entity);
01451     // Check this element.
01452     CheckSubElementType(ElementEntity, IList, elementType, Index,
01453                         StructuredList, StructuredIndex);
01454     ++elementIndex;
01455 
01456     // If the array is of incomplete type, keep track of the number of
01457     // elements in the initializer.
01458     if (!maxElementsKnown && elementIndex > maxElements)
01459       maxElements = elementIndex;
01460   }
01461   if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
01462     // If this is an incomplete array type, the actual type needs to
01463     // be calculated here.
01464     llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
01465     if (maxElements == Zero) {
01466       // Sizing an array implicitly to zero is not allowed by ISO C,
01467       // but is supported by GNU.
01468       SemaRef.Diag(IList->getLocStart(),
01469                     diag::ext_typecheck_zero_array_size);
01470     }
01471 
01472     DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
01473                                                      ArrayType::Normal, 0);
01474   }
01475   if (!hadError && VerifyOnly) {
01476     // Check if there are any members of the array that get value-initialized.
01477     // If so, check if doing that is possible.
01478     // FIXME: This needs to detect holes left by designated initializers too.
01479     if (maxElementsKnown && elementIndex < maxElements)
01480       CheckEmptyInitializable(InitializedEntity::InitializeElement(
01481                                                   SemaRef.Context, 0, Entity),
01482                               IList->getLocEnd());
01483   }
01484 }
01485 
01486 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
01487                                              Expr *InitExpr,
01488                                              FieldDecl *Field,
01489                                              bool TopLevelObject) {
01490   // Handle GNU flexible array initializers.
01491   unsigned FlexArrayDiag;
01492   if (isa<InitListExpr>(InitExpr) &&
01493       cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
01494     // Empty flexible array init always allowed as an extension
01495     FlexArrayDiag = diag::ext_flexible_array_init;
01496   } else if (SemaRef.getLangOpts().CPlusPlus) {
01497     // Disallow flexible array init in C++; it is not required for gcc
01498     // compatibility, and it needs work to IRGen correctly in general.
01499     FlexArrayDiag = diag::err_flexible_array_init;
01500   } else if (!TopLevelObject) {
01501     // Disallow flexible array init on non-top-level object
01502     FlexArrayDiag = diag::err_flexible_array_init;
01503   } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
01504     // Disallow flexible array init on anything which is not a variable.
01505     FlexArrayDiag = diag::err_flexible_array_init;
01506   } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
01507     // Disallow flexible array init on local variables.
01508     FlexArrayDiag = diag::err_flexible_array_init;
01509   } else {
01510     // Allow other cases.
01511     FlexArrayDiag = diag::ext_flexible_array_init;
01512   }
01513 
01514   if (!VerifyOnly) {
01515     SemaRef.Diag(InitExpr->getLocStart(),
01516                  FlexArrayDiag)
01517       << InitExpr->getLocStart();
01518     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
01519       << Field;
01520   }
01521 
01522   return FlexArrayDiag != diag::ext_flexible_array_init;
01523 }
01524 
01525 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
01526                                             InitListExpr *IList,
01527                                             QualType DeclType,
01528                                             RecordDecl::field_iterator Field,
01529                                             bool SubobjectIsDesignatorContext,
01530                                             unsigned &Index,
01531                                             InitListExpr *StructuredList,
01532                                             unsigned &StructuredIndex,
01533                                             bool TopLevelObject) {
01534   RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
01535 
01536   // If the record is invalid, some of it's members are invalid. To avoid
01537   // confusion, we forgo checking the intializer for the entire record.
01538   if (structDecl->isInvalidDecl()) {
01539     // Assume it was supposed to consume a single initializer.
01540     ++Index;
01541     hadError = true;
01542     return;
01543   }
01544 
01545   if (DeclType->isUnionType() && IList->getNumInits() == 0) {
01546     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
01547 
01548     // If there's a default initializer, use it.
01549     if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
01550       if (VerifyOnly)
01551         return;
01552       for (RecordDecl::field_iterator FieldEnd = RD->field_end();
01553            Field != FieldEnd; ++Field) {
01554         if (Field->hasInClassInitializer()) {
01555           StructuredList->setInitializedFieldInUnion(*Field);
01556           // FIXME: Actually build a CXXDefaultInitExpr?
01557           return;
01558         }
01559       }
01560     }
01561 
01562     // Value-initialize the first member of the union that isn't an unnamed
01563     // bitfield.
01564     for (RecordDecl::field_iterator FieldEnd = RD->field_end();
01565          Field != FieldEnd; ++Field) {
01566       if (!Field->isUnnamedBitfield()) {
01567         if (VerifyOnly)
01568           CheckEmptyInitializable(
01569               InitializedEntity::InitializeMember(*Field, &Entity),
01570               IList->getLocEnd());
01571         else
01572           StructuredList->setInitializedFieldInUnion(*Field);
01573         break;
01574       }
01575     }
01576     return;
01577   }
01578 
01579   // If structDecl is a forward declaration, this loop won't do
01580   // anything except look at designated initializers; That's okay,
01581   // because an error should get printed out elsewhere. It might be
01582   // worthwhile to skip over the rest of the initializer, though.
01583   RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
01584   RecordDecl::field_iterator FieldEnd = RD->field_end();
01585   bool InitializedSomething = false;
01586   bool CheckForMissingFields = true;
01587   while (Index < IList->getNumInits()) {
01588     Expr *Init = IList->getInit(Index);
01589 
01590     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
01591       // If we're not the subobject that matches up with the '{' for
01592       // the designator, we shouldn't be handling the
01593       // designator. Return immediately.
01594       if (!SubobjectIsDesignatorContext)
01595         return;
01596 
01597       // Handle this designated initializer. Field will be updated to
01598       // the next field that we'll be initializing.
01599       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
01600                                      DeclType, &Field, nullptr, Index,
01601                                      StructuredList, StructuredIndex,
01602                                      true, TopLevelObject))
01603         hadError = true;
01604 
01605       InitializedSomething = true;
01606 
01607       // Disable check for missing fields when designators are used.
01608       // This matches gcc behaviour.
01609       CheckForMissingFields = false;
01610       continue;
01611     }
01612 
01613     if (Field == FieldEnd) {
01614       // We've run out of fields. We're done.
01615       break;
01616     }
01617 
01618     // We've already initialized a member of a union. We're done.
01619     if (InitializedSomething && DeclType->isUnionType())
01620       break;
01621 
01622     // If we've hit the flexible array member at the end, we're done.
01623     if (Field->getType()->isIncompleteArrayType())
01624       break;
01625 
01626     if (Field->isUnnamedBitfield()) {
01627       // Don't initialize unnamed bitfields, e.g. "int : 20;"
01628       ++Field;
01629       continue;
01630     }
01631 
01632     // Make sure we can use this declaration.
01633     bool InvalidUse;
01634     if (VerifyOnly)
01635       InvalidUse = !SemaRef.CanUseDecl(*Field);
01636     else
01637       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
01638                                           IList->getInit(Index)->getLocStart());
01639     if (InvalidUse) {
01640       ++Index;
01641       ++Field;
01642       hadError = true;
01643       continue;
01644     }
01645 
01646     InitializedEntity MemberEntity =
01647       InitializedEntity::InitializeMember(*Field, &Entity);
01648     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
01649                         StructuredList, StructuredIndex);
01650     InitializedSomething = true;
01651 
01652     if (DeclType->isUnionType() && !VerifyOnly) {
01653       // Initialize the first field within the union.
01654       StructuredList->setInitializedFieldInUnion(*Field);
01655     }
01656 
01657     ++Field;
01658   }
01659 
01660   // Emit warnings for missing struct field initializers.
01661   if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
01662       Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
01663       !DeclType->isUnionType()) {
01664     // It is possible we have one or more unnamed bitfields remaining.
01665     // Find first (if any) named field and emit warning.
01666     for (RecordDecl::field_iterator it = Field, end = RD->field_end();
01667          it != end; ++it) {
01668       if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
01669         SemaRef.Diag(IList->getSourceRange().getEnd(),
01670                      diag::warn_missing_field_initializers) << *it;
01671         break;
01672       }
01673     }
01674   }
01675 
01676   // Check that any remaining fields can be value-initialized.
01677   if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
01678       !Field->getType()->isIncompleteArrayType()) {
01679     // FIXME: Should check for holes left by designated initializers too.
01680     for (; Field != FieldEnd && !hadError; ++Field) {
01681       if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
01682         CheckEmptyInitializable(
01683             InitializedEntity::InitializeMember(*Field, &Entity),
01684             IList->getLocEnd());
01685     }
01686   }
01687 
01688   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
01689       Index >= IList->getNumInits())
01690     return;
01691 
01692   if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
01693                              TopLevelObject)) {
01694     hadError = true;
01695     ++Index;
01696     return;
01697   }
01698 
01699   InitializedEntity MemberEntity =
01700     InitializedEntity::InitializeMember(*Field, &Entity);
01701 
01702   if (isa<InitListExpr>(IList->getInit(Index)))
01703     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
01704                         StructuredList, StructuredIndex);
01705   else
01706     CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
01707                           StructuredList, StructuredIndex);
01708 }
01709 
01710 /// \brief Expand a field designator that refers to a member of an
01711 /// anonymous struct or union into a series of field designators that
01712 /// refers to the field within the appropriate subobject.
01713 ///
01714 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
01715                                            DesignatedInitExpr *DIE,
01716                                            unsigned DesigIdx,
01717                                            IndirectFieldDecl *IndirectField) {
01718   typedef DesignatedInitExpr::Designator Designator;
01719 
01720   // Build the replacement designators.
01721   SmallVector<Designator, 4> Replacements;
01722   for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
01723        PE = IndirectField->chain_end(); PI != PE; ++PI) {
01724     if (PI + 1 == PE)
01725       Replacements.push_back(Designator((IdentifierInfo *)nullptr,
01726                                     DIE->getDesignator(DesigIdx)->getDotLoc(),
01727                                 DIE->getDesignator(DesigIdx)->getFieldLoc()));
01728     else
01729       Replacements.push_back(Designator((IdentifierInfo *)nullptr,
01730                                         SourceLocation(), SourceLocation()));
01731     assert(isa<FieldDecl>(*PI));
01732     Replacements.back().setField(cast<FieldDecl>(*PI));
01733   }
01734 
01735   // Expand the current designator into the set of replacement
01736   // designators, so we have a full subobject path down to where the
01737   // member of the anonymous struct/union is actually stored.
01738   DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
01739                         &Replacements[0] + Replacements.size());
01740 }
01741 
01742 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
01743                                                    DesignatedInitExpr *DIE) {
01744   unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
01745   SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
01746   for (unsigned I = 0; I < NumIndexExprs; ++I)
01747     IndexExprs[I] = DIE->getSubExpr(I + 1);
01748   return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
01749                                     DIE->size(), IndexExprs,
01750                                     DIE->getEqualOrColonLoc(),
01751                                     DIE->usesGNUSyntax(), DIE->getInit());
01752 }
01753 
01754 namespace {
01755 
01756 // Callback to only accept typo corrections that are for field members of
01757 // the given struct or union.
01758 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
01759  public:
01760   explicit FieldInitializerValidatorCCC(RecordDecl *RD)
01761       : Record(RD) {}
01762 
01763   bool ValidateCandidate(const TypoCorrection &candidate) override {
01764     FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
01765     return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
01766   }
01767 
01768  private:
01769   RecordDecl *Record;
01770 };
01771 
01772 }
01773 
01774 /// @brief Check the well-formedness of a C99 designated initializer.
01775 ///
01776 /// Determines whether the designated initializer @p DIE, which
01777 /// resides at the given @p Index within the initializer list @p
01778 /// IList, is well-formed for a current object of type @p DeclType
01779 /// (C99 6.7.8). The actual subobject that this designator refers to
01780 /// within the current subobject is returned in either
01781 /// @p NextField or @p NextElementIndex (whichever is appropriate).
01782 ///
01783 /// @param IList  The initializer list in which this designated
01784 /// initializer occurs.
01785 ///
01786 /// @param DIE The designated initializer expression.
01787 ///
01788 /// @param DesigIdx  The index of the current designator.
01789 ///
01790 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
01791 /// into which the designation in @p DIE should refer.
01792 ///
01793 /// @param NextField  If non-NULL and the first designator in @p DIE is
01794 /// a field, this will be set to the field declaration corresponding
01795 /// to the field named by the designator.
01796 ///
01797 /// @param NextElementIndex  If non-NULL and the first designator in @p
01798 /// DIE is an array designator or GNU array-range designator, this
01799 /// will be set to the last index initialized by this designator.
01800 ///
01801 /// @param Index  Index into @p IList where the designated initializer
01802 /// @p DIE occurs.
01803 ///
01804 /// @param StructuredList  The initializer list expression that
01805 /// describes all of the subobject initializers in the order they'll
01806 /// actually be initialized.
01807 ///
01808 /// @returns true if there was an error, false otherwise.
01809 bool
01810 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
01811                                             InitListExpr *IList,
01812                                             DesignatedInitExpr *DIE,
01813                                             unsigned DesigIdx,
01814                                             QualType &CurrentObjectType,
01815                                           RecordDecl::field_iterator *NextField,
01816                                             llvm::APSInt *NextElementIndex,
01817                                             unsigned &Index,
01818                                             InitListExpr *StructuredList,
01819                                             unsigned &StructuredIndex,
01820                                             bool FinishSubobjectInit,
01821                                             bool TopLevelObject) {
01822   if (DesigIdx == DIE->size()) {
01823     // Check the actual initialization for the designated object type.
01824     bool prevHadError = hadError;
01825 
01826     // Temporarily remove the designator expression from the
01827     // initializer list that the child calls see, so that we don't try
01828     // to re-process the designator.
01829     unsigned OldIndex = Index;
01830     IList->setInit(OldIndex, DIE->getInit());
01831 
01832     CheckSubElementType(Entity, IList, CurrentObjectType, Index,
01833                         StructuredList, StructuredIndex);
01834 
01835     // Restore the designated initializer expression in the syntactic
01836     // form of the initializer list.
01837     if (IList->getInit(OldIndex) != DIE->getInit())
01838       DIE->setInit(IList->getInit(OldIndex));
01839     IList->setInit(OldIndex, DIE);
01840 
01841     return hadError && !prevHadError;
01842   }
01843 
01844   DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
01845   bool IsFirstDesignator = (DesigIdx == 0);
01846   if (!VerifyOnly) {
01847     assert((IsFirstDesignator || StructuredList) &&
01848            "Need a non-designated initializer list to start from");
01849 
01850     // Determine the structural initializer list that corresponds to the
01851     // current subobject.
01852     StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
01853       : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
01854                                    StructuredList, StructuredIndex,
01855                                    SourceRange(D->getLocStart(),
01856                                                DIE->getLocEnd()));
01857     assert(StructuredList && "Expected a structured initializer list");
01858   }
01859 
01860   if (D->isFieldDesignator()) {
01861     // C99 6.7.8p7:
01862     //
01863     //   If a designator has the form
01864     //
01865     //      . identifier
01866     //
01867     //   then the current object (defined below) shall have
01868     //   structure or union type and the identifier shall be the
01869     //   name of a member of that type.
01870     const RecordType *RT = CurrentObjectType->getAs<RecordType>();
01871     if (!RT) {
01872       SourceLocation Loc = D->getDotLoc();
01873       if (Loc.isInvalid())
01874         Loc = D->getFieldLoc();
01875       if (!VerifyOnly)
01876         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
01877           << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
01878       ++Index;
01879       return true;
01880     }
01881 
01882     FieldDecl *KnownField = D->getField();
01883     if (!KnownField) {
01884       IdentifierInfo *FieldName = D->getFieldName();
01885       DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
01886       for (NamedDecl *ND : Lookup) {
01887         if (auto *FD = dyn_cast<FieldDecl>(ND)) {
01888           KnownField = FD;
01889           break;
01890         }
01891         if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
01892           // In verify mode, don't modify the original.
01893           if (VerifyOnly)
01894             DIE = CloneDesignatedInitExpr(SemaRef, DIE);
01895           ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
01896           D = DIE->getDesignator(DesigIdx);
01897           KnownField = cast<FieldDecl>(*IFD->chain_begin());
01898           break;
01899         }
01900       }
01901       if (!KnownField) {
01902         if (VerifyOnly) {
01903           ++Index;
01904           return true;  // No typo correction when just trying this out.
01905         }
01906 
01907         // Name lookup found something, but it wasn't a field.
01908         if (!Lookup.empty()) {
01909           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
01910             << FieldName;
01911           SemaRef.Diag(Lookup.front()->getLocation(),
01912                        diag::note_field_designator_found);
01913           ++Index;
01914           return true;
01915         }
01916 
01917         // Name lookup didn't find anything.
01918         // Determine whether this was a typo for another field name.
01919         if (TypoCorrection Corrected = SemaRef.CorrectTypo(
01920                 DeclarationNameInfo(FieldName, D->getFieldLoc()),
01921                 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
01922                 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
01923                 Sema::CTK_ErrorRecovery, RT->getDecl())) {
01924           SemaRef.diagnoseTypo(
01925               Corrected,
01926               SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
01927                 << FieldName << CurrentObjectType);
01928           KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
01929           hadError = true;
01930         } else {
01931           // Typo correction didn't find anything.
01932           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
01933             << FieldName << CurrentObjectType;
01934           ++Index;
01935           return true;
01936         }
01937       }
01938     }
01939 
01940     unsigned FieldIndex = 0;
01941     for (auto *FI : RT->getDecl()->fields()) {
01942       if (FI->isUnnamedBitfield())
01943         continue;
01944       if (KnownField == FI)
01945         break;
01946       ++FieldIndex;
01947     }
01948 
01949     RecordDecl::field_iterator Field =
01950         RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
01951 
01952     // All of the fields of a union are located at the same place in
01953     // the initializer list.
01954     if (RT->getDecl()->isUnion()) {
01955       FieldIndex = 0;
01956       if (!VerifyOnly) {
01957         FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
01958         if (CurrentField && CurrentField != *Field) {
01959           assert(StructuredList->getNumInits() == 1
01960                  && "A union should never have more than one initializer!");
01961 
01962           // we're about to throw away an initializer, emit warning
01963           SemaRef.Diag(D->getFieldLoc(),
01964                        diag::warn_initializer_overrides)
01965             << D->getSourceRange();
01966           Expr *ExistingInit = StructuredList->getInit(0);
01967           SemaRef.Diag(ExistingInit->getLocStart(),
01968                        diag::note_previous_initializer)
01969             << /*FIXME:has side effects=*/0
01970             << ExistingInit->getSourceRange();
01971 
01972           // remove existing initializer
01973           StructuredList->resizeInits(SemaRef.Context, 0);
01974           StructuredList->setInitializedFieldInUnion(nullptr);
01975         }
01976 
01977         StructuredList->setInitializedFieldInUnion(*Field);
01978       }
01979     }
01980 
01981     // Make sure we can use this declaration.
01982     bool InvalidUse;
01983     if (VerifyOnly)
01984       InvalidUse = !SemaRef.CanUseDecl(*Field);
01985     else
01986       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
01987     if (InvalidUse) {
01988       ++Index;
01989       return true;
01990     }
01991 
01992     if (!VerifyOnly) {
01993       // Update the designator with the field declaration.
01994       D->setField(*Field);
01995 
01996       // Make sure that our non-designated initializer list has space
01997       // for a subobject corresponding to this field.
01998       if (FieldIndex >= StructuredList->getNumInits())
01999         StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
02000     }
02001 
02002     // This designator names a flexible array member.
02003     if (Field->getType()->isIncompleteArrayType()) {
02004       bool Invalid = false;
02005       if ((DesigIdx + 1) != DIE->size()) {
02006         // We can't designate an object within the flexible array
02007         // member (because GCC doesn't allow it).
02008         if (!VerifyOnly) {
02009           DesignatedInitExpr::Designator *NextD
02010             = DIE->getDesignator(DesigIdx + 1);
02011           SemaRef.Diag(NextD->getLocStart(),
02012                         diag::err_designator_into_flexible_array_member)
02013             << SourceRange(NextD->getLocStart(),
02014                            DIE->getLocEnd());
02015           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
02016             << *Field;
02017         }
02018         Invalid = true;
02019       }
02020 
02021       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
02022           !isa<StringLiteral>(DIE->getInit())) {
02023         // The initializer is not an initializer list.
02024         if (!VerifyOnly) {
02025           SemaRef.Diag(DIE->getInit()->getLocStart(),
02026                         diag::err_flexible_array_init_needs_braces)
02027             << DIE->getInit()->getSourceRange();
02028           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
02029             << *Field;
02030         }
02031         Invalid = true;
02032       }
02033 
02034       // Check GNU flexible array initializer.
02035       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
02036                                              TopLevelObject))
02037         Invalid = true;
02038 
02039       if (Invalid) {
02040         ++Index;
02041         return true;
02042       }
02043 
02044       // Initialize the array.
02045       bool prevHadError = hadError;
02046       unsigned newStructuredIndex = FieldIndex;
02047       unsigned OldIndex = Index;
02048       IList->setInit(Index, DIE->getInit());
02049 
02050       InitializedEntity MemberEntity =
02051         InitializedEntity::InitializeMember(*Field, &Entity);
02052       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
02053                           StructuredList, newStructuredIndex);
02054 
02055       IList->setInit(OldIndex, DIE);
02056       if (hadError && !prevHadError) {
02057         ++Field;
02058         ++FieldIndex;
02059         if (NextField)
02060           *NextField = Field;
02061         StructuredIndex = FieldIndex;
02062         return true;
02063       }
02064     } else {
02065       // Recurse to check later designated subobjects.
02066       QualType FieldType = Field->getType();
02067       unsigned newStructuredIndex = FieldIndex;
02068 
02069       InitializedEntity MemberEntity =
02070         InitializedEntity::InitializeMember(*Field, &Entity);
02071       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
02072                                      FieldType, nullptr, nullptr, Index,
02073                                      StructuredList, newStructuredIndex,
02074                                      true, false))
02075         return true;
02076     }
02077 
02078     // Find the position of the next field to be initialized in this
02079     // subobject.
02080     ++Field;
02081     ++FieldIndex;
02082 
02083     // If this the first designator, our caller will continue checking
02084     // the rest of this struct/class/union subobject.
02085     if (IsFirstDesignator) {
02086       if (NextField)
02087         *NextField = Field;
02088       StructuredIndex = FieldIndex;
02089       return false;
02090     }
02091 
02092     if (!FinishSubobjectInit)
02093       return false;
02094 
02095     // We've already initialized something in the union; we're done.
02096     if (RT->getDecl()->isUnion())
02097       return hadError;
02098 
02099     // Check the remaining fields within this class/struct/union subobject.
02100     bool prevHadError = hadError;
02101 
02102     CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
02103                           StructuredList, FieldIndex);
02104     return hadError && !prevHadError;
02105   }
02106 
02107   // C99 6.7.8p6:
02108   //
02109   //   If a designator has the form
02110   //
02111   //      [ constant-expression ]
02112   //
02113   //   then the current object (defined below) shall have array
02114   //   type and the expression shall be an integer constant
02115   //   expression. If the array is of unknown size, any
02116   //   nonnegative value is valid.
02117   //
02118   // Additionally, cope with the GNU extension that permits
02119   // designators of the form
02120   //
02121   //      [ constant-expression ... constant-expression ]
02122   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
02123   if (!AT) {
02124     if (!VerifyOnly)
02125       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
02126         << CurrentObjectType;
02127     ++Index;
02128     return true;
02129   }
02130 
02131   Expr *IndexExpr = nullptr;
02132   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
02133   if (D->isArrayDesignator()) {
02134     IndexExpr = DIE->getArrayIndex(*D);
02135     DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
02136     DesignatedEndIndex = DesignatedStartIndex;
02137   } else {
02138     assert(D->isArrayRangeDesignator() && "Need array-range designator");
02139 
02140     DesignatedStartIndex =
02141       DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
02142     DesignatedEndIndex =
02143       DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
02144     IndexExpr = DIE->getArrayRangeEnd(*D);
02145 
02146     // Codegen can't handle evaluating array range designators that have side
02147     // effects, because we replicate the AST value for each initialized element.
02148     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
02149     // elements with something that has a side effect, so codegen can emit an
02150     // "error unsupported" error instead of miscompiling the app.
02151     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
02152         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
02153       FullyStructuredList->sawArrayRangeDesignator();
02154   }
02155 
02156   if (isa<ConstantArrayType>(AT)) {
02157     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
02158     DesignatedStartIndex
02159       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
02160     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
02161     DesignatedEndIndex
02162       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
02163     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
02164     if (DesignatedEndIndex >= MaxElements) {
02165       if (!VerifyOnly)
02166         SemaRef.Diag(IndexExpr->getLocStart(),
02167                       diag::err_array_designator_too_large)
02168           << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
02169           << IndexExpr->getSourceRange();
02170       ++Index;
02171       return true;
02172     }
02173   } else {
02174     // Make sure the bit-widths and signedness match.
02175     if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
02176       DesignatedEndIndex
02177         = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
02178     else if (DesignatedStartIndex.getBitWidth() <
02179              DesignatedEndIndex.getBitWidth())
02180       DesignatedStartIndex
02181         = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
02182     DesignatedStartIndex.setIsUnsigned(true);
02183     DesignatedEndIndex.setIsUnsigned(true);
02184   }
02185 
02186   if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
02187     // We're modifying a string literal init; we have to decompose the string
02188     // so we can modify the individual characters.
02189     ASTContext &Context = SemaRef.Context;
02190     Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
02191 
02192     // Compute the character type
02193     QualType CharTy = AT->getElementType();
02194 
02195     // Compute the type of the integer literals.
02196     QualType PromotedCharTy = CharTy;
02197     if (CharTy->isPromotableIntegerType())
02198       PromotedCharTy = Context.getPromotedIntegerType(CharTy);
02199     unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
02200 
02201     if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
02202       // Get the length of the string.
02203       uint64_t StrLen = SL->getLength();
02204       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
02205         StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
02206       StructuredList->resizeInits(Context, StrLen);
02207 
02208       // Build a literal for each character in the string, and put them into
02209       // the init list.
02210       for (unsigned i = 0, e = StrLen; i != e; ++i) {
02211         llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
02212         Expr *Init = new (Context) IntegerLiteral(
02213             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
02214         if (CharTy != PromotedCharTy)
02215           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
02216                                           Init, nullptr, VK_RValue);
02217         StructuredList->updateInit(Context, i, Init);
02218       }
02219     } else {
02220       ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
02221       std::string Str;
02222       Context.getObjCEncodingForType(E->getEncodedType(), Str);
02223 
02224       // Get the length of the string.
02225       uint64_t StrLen = Str.size();
02226       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
02227         StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
02228       StructuredList->resizeInits(Context, StrLen);
02229 
02230       // Build a literal for each character in the string, and put them into
02231       // the init list.
02232       for (unsigned i = 0, e = StrLen; i != e; ++i) {
02233         llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
02234         Expr *Init = new (Context) IntegerLiteral(
02235             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
02236         if (CharTy != PromotedCharTy)
02237           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
02238                                           Init, nullptr, VK_RValue);
02239         StructuredList->updateInit(Context, i, Init);
02240       }
02241     }
02242   }
02243 
02244   // Make sure that our non-designated initializer list has space
02245   // for a subobject corresponding to this array element.
02246   if (!VerifyOnly &&
02247       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
02248     StructuredList->resizeInits(SemaRef.Context,
02249                                 DesignatedEndIndex.getZExtValue() + 1);
02250 
02251   // Repeatedly perform subobject initializations in the range
02252   // [DesignatedStartIndex, DesignatedEndIndex].
02253 
02254   // Move to the next designator
02255   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
02256   unsigned OldIndex = Index;
02257 
02258   InitializedEntity ElementEntity =
02259     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
02260 
02261   while (DesignatedStartIndex <= DesignatedEndIndex) {
02262     // Recurse to check later designated subobjects.
02263     QualType ElementType = AT->getElementType();
02264     Index = OldIndex;
02265 
02266     ElementEntity.setElementIndex(ElementIndex);
02267     if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
02268                                    ElementType, nullptr, nullptr, Index,
02269                                    StructuredList, ElementIndex,
02270                                    (DesignatedStartIndex == DesignatedEndIndex),
02271                                    false))
02272       return true;
02273 
02274     // Move to the next index in the array that we'll be initializing.
02275     ++DesignatedStartIndex;
02276     ElementIndex = DesignatedStartIndex.getZExtValue();
02277   }
02278 
02279   // If this the first designator, our caller will continue checking
02280   // the rest of this array subobject.
02281   if (IsFirstDesignator) {
02282     if (NextElementIndex)
02283       *NextElementIndex = DesignatedStartIndex;
02284     StructuredIndex = ElementIndex;
02285     return false;
02286   }
02287 
02288   if (!FinishSubobjectInit)
02289     return false;
02290 
02291   // Check the remaining elements within this array subobject.
02292   bool prevHadError = hadError;
02293   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
02294                  /*SubobjectIsDesignatorContext=*/false, Index,
02295                  StructuredList, ElementIndex);
02296   return hadError && !prevHadError;
02297 }
02298 
02299 // Get the structured initializer list for a subobject of type
02300 // @p CurrentObjectType.
02301 InitListExpr *
02302 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
02303                                             QualType CurrentObjectType,
02304                                             InitListExpr *StructuredList,
02305                                             unsigned StructuredIndex,
02306                                             SourceRange InitRange) {
02307   if (VerifyOnly)
02308     return nullptr; // No structured list in verification-only mode.
02309   Expr *ExistingInit = nullptr;
02310   if (!StructuredList)
02311     ExistingInit = SyntacticToSemantic.lookup(IList);
02312   else if (StructuredIndex < StructuredList->getNumInits())
02313     ExistingInit = StructuredList->getInit(StructuredIndex);
02314 
02315   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
02316     return Result;
02317 
02318   if (ExistingInit) {
02319     // We are creating an initializer list that initializes the
02320     // subobjects of the current object, but there was already an
02321     // initialization that completely initialized the current
02322     // subobject, e.g., by a compound literal:
02323     //
02324     // struct X { int a, b; };
02325     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
02326     //
02327     // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
02328     // designated initializer re-initializes the whole
02329     // subobject [0], overwriting previous initializers.
02330     SemaRef.Diag(InitRange.getBegin(),
02331                  diag::warn_subobject_initializer_overrides)
02332       << InitRange;
02333     SemaRef.Diag(ExistingInit->getLocStart(),
02334                   diag::note_previous_initializer)
02335       << /*FIXME:has side effects=*/0
02336       << ExistingInit->getSourceRange();
02337   }
02338 
02339   InitListExpr *Result
02340     = new (SemaRef.Context) InitListExpr(SemaRef.Context,
02341                                          InitRange.getBegin(), None,
02342                                          InitRange.getEnd());
02343 
02344   QualType ResultType = CurrentObjectType;
02345   if (!ResultType->isArrayType())
02346     ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
02347   Result->setType(ResultType);
02348 
02349   // Pre-allocate storage for the structured initializer list.
02350   unsigned NumElements = 0;
02351   unsigned NumInits = 0;
02352   bool GotNumInits = false;
02353   if (!StructuredList) {
02354     NumInits = IList->getNumInits();
02355     GotNumInits = true;
02356   } else if (Index < IList->getNumInits()) {
02357     if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
02358       NumInits = SubList->getNumInits();
02359       GotNumInits = true;
02360     }
02361   }
02362 
02363   if (const ArrayType *AType
02364       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
02365     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
02366       NumElements = CAType->getSize().getZExtValue();
02367       // Simple heuristic so that we don't allocate a very large
02368       // initializer with many empty entries at the end.
02369       if (GotNumInits && NumElements > NumInits)
02370         NumElements = 0;
02371     }
02372   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
02373     NumElements = VType->getNumElements();
02374   else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
02375     RecordDecl *RDecl = RType->getDecl();
02376     if (RDecl->isUnion())
02377       NumElements = 1;
02378     else
02379       NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
02380   }
02381 
02382   Result->reserveInits(SemaRef.Context, NumElements);
02383 
02384   // Link this new initializer list into the structured initializer
02385   // lists.
02386   if (StructuredList)
02387     StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
02388   else {
02389     Result->setSyntacticForm(IList);
02390     SyntacticToSemantic[IList] = Result;
02391   }
02392 
02393   return Result;
02394 }
02395 
02396 /// Update the initializer at index @p StructuredIndex within the
02397 /// structured initializer list to the value @p expr.
02398 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
02399                                                   unsigned &StructuredIndex,
02400                                                   Expr *expr) {
02401   // No structured initializer list to update
02402   if (!StructuredList)
02403     return;
02404 
02405   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
02406                                                   StructuredIndex, expr)) {
02407     // This initializer overwrites a previous initializer. Warn.
02408     SemaRef.Diag(expr->getLocStart(),
02409                   diag::warn_initializer_overrides)
02410       << expr->getSourceRange();
02411     SemaRef.Diag(PrevInit->getLocStart(),
02412                   diag::note_previous_initializer)
02413       << /*FIXME:has side effects=*/0
02414       << PrevInit->getSourceRange();
02415   }
02416 
02417   ++StructuredIndex;
02418 }
02419 
02420 /// Check that the given Index expression is a valid array designator
02421 /// value. This is essentially just a wrapper around
02422 /// VerifyIntegerConstantExpression that also checks for negative values
02423 /// and produces a reasonable diagnostic if there is a
02424 /// failure. Returns the index expression, possibly with an implicit cast
02425 /// added, on success.  If everything went okay, Value will receive the
02426 /// value of the constant expression.
02427 static ExprResult
02428 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
02429   SourceLocation Loc = Index->getLocStart();
02430 
02431   // Make sure this is an integer constant expression.
02432   ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
02433   if (Result.isInvalid())
02434     return Result;
02435 
02436   if (Value.isSigned() && Value.isNegative())
02437     return S.Diag(Loc, diag::err_array_designator_negative)
02438       << Value.toString(10) << Index->getSourceRange();
02439 
02440   Value.setIsUnsigned(true);
02441   return Result;
02442 }
02443 
02444 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
02445                                             SourceLocation Loc,
02446                                             bool GNUSyntax,
02447                                             ExprResult Init) {
02448   typedef DesignatedInitExpr::Designator ASTDesignator;
02449 
02450   bool Invalid = false;
02451   SmallVector<ASTDesignator, 32> Designators;
02452   SmallVector<Expr *, 32> InitExpressions;
02453 
02454   // Build designators and check array designator expressions.
02455   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
02456     const Designator &D = Desig.getDesignator(Idx);
02457     switch (D.getKind()) {
02458     case Designator::FieldDesignator:
02459       Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
02460                                           D.getFieldLoc()));
02461       break;
02462 
02463     case Designator::ArrayDesignator: {
02464       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
02465       llvm::APSInt IndexValue;
02466       if (!Index->isTypeDependent() && !Index->isValueDependent())
02467         Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
02468       if (!Index)
02469         Invalid = true;
02470       else {
02471         Designators.push_back(ASTDesignator(InitExpressions.size(),
02472                                             D.getLBracketLoc(),
02473                                             D.getRBracketLoc()));
02474         InitExpressions.push_back(Index);
02475       }
02476       break;
02477     }
02478 
02479     case Designator::ArrayRangeDesignator: {
02480       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
02481       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
02482       llvm::APSInt StartValue;
02483       llvm::APSInt EndValue;
02484       bool StartDependent = StartIndex->isTypeDependent() ||
02485                             StartIndex->isValueDependent();
02486       bool EndDependent = EndIndex->isTypeDependent() ||
02487                           EndIndex->isValueDependent();
02488       if (!StartDependent)
02489         StartIndex =
02490             CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
02491       if (!EndDependent)
02492         EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
02493 
02494       if (!StartIndex || !EndIndex)
02495         Invalid = true;
02496       else {
02497         // Make sure we're comparing values with the same bit width.
02498         if (StartDependent || EndDependent) {
02499           // Nothing to compute.
02500         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
02501           EndValue = EndValue.extend(StartValue.getBitWidth());
02502         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
02503           StartValue = StartValue.extend(EndValue.getBitWidth());
02504 
02505         if (!StartDependent && !EndDependent && EndValue < StartValue) {
02506           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
02507             << StartValue.toString(10) << EndValue.toString(10)
02508             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
02509           Invalid = true;
02510         } else {
02511           Designators.push_back(ASTDesignator(InitExpressions.size(),
02512                                               D.getLBracketLoc(),
02513                                               D.getEllipsisLoc(),
02514                                               D.getRBracketLoc()));
02515           InitExpressions.push_back(StartIndex);
02516           InitExpressions.push_back(EndIndex);
02517         }
02518       }
02519       break;
02520     }
02521     }
02522   }
02523 
02524   if (Invalid || Init.isInvalid())
02525     return ExprError();
02526 
02527   // Clear out the expressions within the designation.
02528   Desig.ClearExprs(*this);
02529 
02530   DesignatedInitExpr *DIE
02531     = DesignatedInitExpr::Create(Context,
02532                                  Designators.data(), Designators.size(),
02533                                  InitExpressions, Loc, GNUSyntax,
02534                                  Init.getAs<Expr>());
02535 
02536   if (!getLangOpts().C99)
02537     Diag(DIE->getLocStart(), diag::ext_designated_init)
02538       << DIE->getSourceRange();
02539 
02540   return DIE;
02541 }
02542 
02543 //===----------------------------------------------------------------------===//
02544 // Initialization entity
02545 //===----------------------------------------------------------------------===//
02546 
02547 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
02548                                      const InitializedEntity &Parent)
02549   : Parent(&Parent), Index(Index)
02550 {
02551   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
02552     Kind = EK_ArrayElement;
02553     Type = AT->getElementType();
02554   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
02555     Kind = EK_VectorElement;
02556     Type = VT->getElementType();
02557   } else {
02558     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
02559     assert(CT && "Unexpected type");
02560     Kind = EK_ComplexElement;
02561     Type = CT->getElementType();
02562   }
02563 }
02564 
02565 InitializedEntity
02566 InitializedEntity::InitializeBase(ASTContext &Context,
02567                                   const CXXBaseSpecifier *Base,
02568                                   bool IsInheritedVirtualBase) {
02569   InitializedEntity Result;
02570   Result.Kind = EK_Base;
02571   Result.Parent = nullptr;
02572   Result.Base = reinterpret_cast<uintptr_t>(Base);
02573   if (IsInheritedVirtualBase)
02574     Result.Base |= 0x01;
02575 
02576   Result.Type = Base->getType();
02577   return Result;
02578 }
02579 
02580 DeclarationName InitializedEntity::getName() const {
02581   switch (getKind()) {
02582   case EK_Parameter:
02583   case EK_Parameter_CF_Audited: {
02584     ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
02585     return (D ? D->getDeclName() : DeclarationName());
02586   }
02587 
02588   case EK_Variable:
02589   case EK_Member:
02590     return VariableOrMember->getDeclName();
02591 
02592   case EK_LambdaCapture:
02593     return DeclarationName(Capture.VarID);
02594       
02595   case EK_Result:
02596   case EK_Exception:
02597   case EK_New:
02598   case EK_Temporary:
02599   case EK_Base:
02600   case EK_Delegating:
02601   case EK_ArrayElement:
02602   case EK_VectorElement:
02603   case EK_ComplexElement:
02604   case EK_BlockElement:
02605   case EK_CompoundLiteralInit:
02606   case EK_RelatedResult:
02607     return DeclarationName();
02608   }
02609 
02610   llvm_unreachable("Invalid EntityKind!");
02611 }
02612 
02613 DeclaratorDecl *InitializedEntity::getDecl() const {
02614   switch (getKind()) {
02615   case EK_Variable:
02616   case EK_Member:
02617     return VariableOrMember;
02618 
02619   case EK_Parameter:
02620   case EK_Parameter_CF_Audited:
02621     return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
02622 
02623   case EK_Result:
02624   case EK_Exception:
02625   case EK_New:
02626   case EK_Temporary:
02627   case EK_Base:
02628   case EK_Delegating:
02629   case EK_ArrayElement:
02630   case EK_VectorElement:
02631   case EK_ComplexElement:
02632   case EK_BlockElement:
02633   case EK_LambdaCapture:
02634   case EK_CompoundLiteralInit:
02635   case EK_RelatedResult:
02636     return nullptr;
02637   }
02638 
02639   llvm_unreachable("Invalid EntityKind!");
02640 }
02641 
02642 bool InitializedEntity::allowsNRVO() const {
02643   switch (getKind()) {
02644   case EK_Result:
02645   case EK_Exception:
02646     return LocAndNRVO.NRVO;
02647 
02648   case EK_Variable:
02649   case EK_Parameter:
02650   case EK_Parameter_CF_Audited:
02651   case EK_Member:
02652   case EK_New:
02653   case EK_Temporary:
02654   case EK_CompoundLiteralInit:
02655   case EK_Base:
02656   case EK_Delegating:
02657   case EK_ArrayElement:
02658   case EK_VectorElement:
02659   case EK_ComplexElement:
02660   case EK_BlockElement:
02661   case EK_LambdaCapture:
02662   case EK_RelatedResult:
02663     break;
02664   }
02665 
02666   return false;
02667 }
02668 
02669 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
02670   assert(getParent() != this);
02671   unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
02672   for (unsigned I = 0; I != Depth; ++I)
02673     OS << "`-";
02674 
02675   switch (getKind()) {
02676   case EK_Variable: OS << "Variable"; break;
02677   case EK_Parameter: OS << "Parameter"; break;
02678   case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
02679     break;
02680   case EK_Result: OS << "Result"; break;
02681   case EK_Exception: OS << "Exception"; break;
02682   case EK_Member: OS << "Member"; break;
02683   case EK_New: OS << "New"; break;
02684   case EK_Temporary: OS << "Temporary"; break;
02685   case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
02686   case EK_RelatedResult: OS << "RelatedResult"; break;
02687   case EK_Base: OS << "Base"; break;
02688   case EK_Delegating: OS << "Delegating"; break;
02689   case EK_ArrayElement: OS << "ArrayElement " << Index; break;
02690   case EK_VectorElement: OS << "VectorElement " << Index; break;
02691   case EK_ComplexElement: OS << "ComplexElement " << Index; break;
02692   case EK_BlockElement: OS << "Block"; break;
02693   case EK_LambdaCapture:
02694     OS << "LambdaCapture ";
02695     OS << DeclarationName(Capture.VarID);
02696     break;
02697   }
02698 
02699   if (Decl *D = getDecl()) {
02700     OS << " ";
02701     cast<NamedDecl>(D)->printQualifiedName(OS);
02702   }
02703 
02704   OS << " '" << getType().getAsString() << "'\n";
02705 
02706   return Depth + 1;
02707 }
02708 
02709 void InitializedEntity::dump() const {
02710   dumpImpl(llvm::errs());
02711 }
02712 
02713 //===----------------------------------------------------------------------===//
02714 // Initialization sequence
02715 //===----------------------------------------------------------------------===//
02716 
02717 void InitializationSequence::Step::Destroy() {
02718   switch (Kind) {
02719   case SK_ResolveAddressOfOverloadedFunction:
02720   case SK_CastDerivedToBaseRValue:
02721   case SK_CastDerivedToBaseXValue:
02722   case SK_CastDerivedToBaseLValue:
02723   case SK_BindReference:
02724   case SK_BindReferenceToTemporary:
02725   case SK_ExtraneousCopyToTemporary:
02726   case SK_UserConversion:
02727   case SK_QualificationConversionRValue:
02728   case SK_QualificationConversionXValue:
02729   case SK_QualificationConversionLValue:
02730   case SK_AtomicConversion:
02731   case SK_LValueToRValue:
02732   case SK_ListInitialization:
02733   case SK_UnwrapInitList:
02734   case SK_RewrapInitList:
02735   case SK_ConstructorInitialization:
02736   case SK_ConstructorInitializationFromList:
02737   case SK_ZeroInitialization:
02738   case SK_CAssignment:
02739   case SK_StringInit:
02740   case SK_ObjCObjectConversion:
02741   case SK_ArrayInit:
02742   case SK_ParenthesizedArrayInit:
02743   case SK_PassByIndirectCopyRestore:
02744   case SK_PassByIndirectRestore:
02745   case SK_ProduceObjCObject:
02746   case SK_StdInitializerList:
02747   case SK_StdInitializerListConstructorCall:
02748   case SK_OCLSamplerInit:
02749   case SK_OCLZeroEvent:
02750     break;
02751 
02752   case SK_ConversionSequence:
02753   case SK_ConversionSequenceNoNarrowing:
02754     delete ICS;
02755   }
02756 }
02757 
02758 bool InitializationSequence::isDirectReferenceBinding() const {
02759   return !Steps.empty() && Steps.back().Kind == SK_BindReference;
02760 }
02761 
02762 bool InitializationSequence::isAmbiguous() const {
02763   if (!Failed())
02764     return false;
02765 
02766   switch (getFailureKind()) {
02767   case FK_TooManyInitsForReference:
02768   case FK_ArrayNeedsInitList:
02769   case FK_ArrayNeedsInitListOrStringLiteral:
02770   case FK_ArrayNeedsInitListOrWideStringLiteral:
02771   case FK_NarrowStringIntoWideCharArray:
02772   case FK_WideStringIntoCharArray:
02773   case FK_IncompatWideStringIntoWideChar:
02774   case FK_AddressOfOverloadFailed: // FIXME: Could do better
02775   case FK_NonConstLValueReferenceBindingToTemporary:
02776   case FK_NonConstLValueReferenceBindingToUnrelated:
02777   case FK_RValueReferenceBindingToLValue:
02778   case FK_ReferenceInitDropsQualifiers:
02779   case FK_ReferenceInitFailed:
02780   case FK_ConversionFailed:
02781   case FK_ConversionFromPropertyFailed:
02782   case FK_TooManyInitsForScalar:
02783   case FK_ReferenceBindingToInitList:
02784   case FK_InitListBadDestinationType:
02785   case FK_DefaultInitOfConst:
02786   case FK_Incomplete:
02787   case FK_ArrayTypeMismatch:
02788   case FK_NonConstantArrayInit:
02789   case FK_ListInitializationFailed:
02790   case FK_VariableLengthArrayHasInitializer:
02791   case FK_PlaceholderType:
02792   case FK_ExplicitConstructor:
02793     return false;
02794 
02795   case FK_ReferenceInitOverloadFailed:
02796   case FK_UserConversionOverloadFailed:
02797   case FK_ConstructorOverloadFailed:
02798   case FK_ListConstructorOverloadFailed:
02799     return FailedOverloadResult == OR_Ambiguous;
02800   }
02801 
02802   llvm_unreachable("Invalid EntityKind!");
02803 }
02804 
02805 bool InitializationSequence::isConstructorInitialization() const {
02806   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
02807 }
02808 
02809 void
02810 InitializationSequence
02811 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
02812                                    DeclAccessPair Found,
02813                                    bool HadMultipleCandidates) {
02814   Step S;
02815   S.Kind = SK_ResolveAddressOfOverloadedFunction;
02816   S.Type = Function->getType();
02817   S.Function.HadMultipleCandidates = HadMultipleCandidates;
02818   S.Function.Function = Function;
02819   S.Function.FoundDecl = Found;
02820   Steps.push_back(S);
02821 }
02822 
02823 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
02824                                                       ExprValueKind VK) {
02825   Step S;
02826   switch (VK) {
02827   case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
02828   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
02829   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
02830   }
02831   S.Type = BaseType;
02832   Steps.push_back(S);
02833 }
02834 
02835 void InitializationSequence::AddReferenceBindingStep(QualType T,
02836                                                      bool BindingTemporary) {
02837   Step S;
02838   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
02839   S.Type = T;
02840   Steps.push_back(S);
02841 }
02842 
02843 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
02844   Step S;
02845   S.Kind = SK_ExtraneousCopyToTemporary;
02846   S.Type = T;
02847   Steps.push_back(S);
02848 }
02849 
02850 void
02851 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
02852                                               DeclAccessPair FoundDecl,
02853                                               QualType T,
02854                                               bool HadMultipleCandidates) {
02855   Step S;
02856   S.Kind = SK_UserConversion;
02857   S.Type = T;
02858   S.Function.HadMultipleCandidates = HadMultipleCandidates;
02859   S.Function.Function = Function;
02860   S.Function.FoundDecl = FoundDecl;
02861   Steps.push_back(S);
02862 }
02863 
02864 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
02865                                                             ExprValueKind VK) {
02866   Step S;
02867   S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
02868   switch (VK) {
02869   case VK_RValue:
02870     S.Kind = SK_QualificationConversionRValue;
02871     break;
02872   case VK_XValue:
02873     S.Kind = SK_QualificationConversionXValue;
02874     break;
02875   case VK_LValue:
02876     S.Kind = SK_QualificationConversionLValue;
02877     break;
02878   }
02879   S.Type = Ty;
02880   Steps.push_back(S);
02881 }
02882 
02883 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
02884   Step S;
02885   S.Kind = SK_AtomicConversion;
02886   S.Type = Ty;
02887   Steps.push_back(S);
02888 }
02889 
02890 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
02891   assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
02892 
02893   Step S;
02894   S.Kind = SK_LValueToRValue;
02895   S.Type = Ty;
02896   Steps.push_back(S);
02897 }
02898 
02899 void InitializationSequence::AddConversionSequenceStep(
02900     const ImplicitConversionSequence &ICS, QualType T,
02901     bool TopLevelOfInitList) {
02902   Step S;
02903   S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
02904                               : SK_ConversionSequence;
02905   S.Type = T;
02906   S.ICS = new ImplicitConversionSequence(ICS);
02907   Steps.push_back(S);
02908 }
02909 
02910 void InitializationSequence::AddListInitializationStep(QualType T) {
02911   Step S;
02912   S.Kind = SK_ListInitialization;
02913   S.Type = T;
02914   Steps.push_back(S);
02915 }
02916 
02917 void
02918 InitializationSequence
02919 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
02920                                    AccessSpecifier Access,
02921                                    QualType T,
02922                                    bool HadMultipleCandidates,
02923                                    bool FromInitList, bool AsInitList) {
02924   Step S;
02925   S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
02926                                      : SK_ConstructorInitializationFromList
02927                         : SK_ConstructorInitialization;
02928   S.Type = T;
02929   S.Function.HadMultipleCandidates = HadMultipleCandidates;
02930   S.Function.Function = Constructor;
02931   S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
02932   Steps.push_back(S);
02933 }
02934 
02935 void InitializationSequence::AddZeroInitializationStep(QualType T) {
02936   Step S;
02937   S.Kind = SK_ZeroInitialization;
02938   S.Type = T;
02939   Steps.push_back(S);
02940 }
02941 
02942 void InitializationSequence::AddCAssignmentStep(QualType T) {
02943   Step S;
02944   S.Kind = SK_CAssignment;
02945   S.Type = T;
02946   Steps.push_back(S);
02947 }
02948 
02949 void InitializationSequence::AddStringInitStep(QualType T) {
02950   Step S;
02951   S.Kind = SK_StringInit;
02952   S.Type = T;
02953   Steps.push_back(S);
02954 }
02955 
02956 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
02957   Step S;
02958   S.Kind = SK_ObjCObjectConversion;
02959   S.Type = T;
02960   Steps.push_back(S);
02961 }
02962 
02963 void InitializationSequence::AddArrayInitStep(QualType T) {
02964   Step S;
02965   S.Kind = SK_ArrayInit;
02966   S.Type = T;
02967   Steps.push_back(S);
02968 }
02969 
02970 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
02971   Step S;
02972   S.Kind = SK_ParenthesizedArrayInit;
02973   S.Type = T;
02974   Steps.push_back(S);
02975 }
02976 
02977 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
02978                                                               bool shouldCopy) {
02979   Step s;
02980   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
02981                        : SK_PassByIndirectRestore);
02982   s.Type = type;
02983   Steps.push_back(s);
02984 }
02985 
02986 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
02987   Step S;
02988   S.Kind = SK_ProduceObjCObject;
02989   S.Type = T;
02990   Steps.push_back(S);
02991 }
02992 
02993 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
02994   Step S;
02995   S.Kind = SK_StdInitializerList;
02996   S.Type = T;
02997   Steps.push_back(S);
02998 }
02999 
03000 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
03001   Step S;
03002   S.Kind = SK_OCLSamplerInit;
03003   S.Type = T;
03004   Steps.push_back(S);
03005 }
03006 
03007 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
03008   Step S;
03009   S.Kind = SK_OCLZeroEvent;
03010   S.Type = T;
03011   Steps.push_back(S);
03012 }
03013 
03014 void InitializationSequence::RewrapReferenceInitList(QualType T,
03015                                                      InitListExpr *Syntactic) {
03016   assert(Syntactic->getNumInits() == 1 &&
03017          "Can only rewrap trivial init lists.");
03018   Step S;
03019   S.Kind = SK_UnwrapInitList;
03020   S.Type = Syntactic->getInit(0)->getType();
03021   Steps.insert(Steps.begin(), S);
03022 
03023   S.Kind = SK_RewrapInitList;
03024   S.Type = T;
03025   S.WrappingSyntacticList = Syntactic;
03026   Steps.push_back(S);
03027 }
03028 
03029 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
03030                                                 OverloadingResult Result) {
03031   setSequenceKind(FailedSequence);
03032   this->Failure = Failure;
03033   this->FailedOverloadResult = Result;
03034 }
03035 
03036 //===----------------------------------------------------------------------===//
03037 // Attempt initialization
03038 //===----------------------------------------------------------------------===//
03039 
03040 static void MaybeProduceObjCObject(Sema &S,
03041                                    InitializationSequence &Sequence,
03042                                    const InitializedEntity &Entity) {
03043   if (!S.getLangOpts().ObjCAutoRefCount) return;
03044 
03045   /// When initializing a parameter, produce the value if it's marked
03046   /// __attribute__((ns_consumed)).
03047   if (Entity.isParameterKind()) {
03048     if (!Entity.isParameterConsumed())
03049       return;
03050 
03051     assert(Entity.getType()->isObjCRetainableType() &&
03052            "consuming an object of unretainable type?");
03053     Sequence.AddProduceObjCObjectStep(Entity.getType());
03054 
03055   /// When initializing a return value, if the return type is a
03056   /// retainable type, then returns need to immediately retain the
03057   /// object.  If an autorelease is required, it will be done at the
03058   /// last instant.
03059   } else if (Entity.getKind() == InitializedEntity::EK_Result) {
03060     if (!Entity.getType()->isObjCRetainableType())
03061       return;
03062 
03063     Sequence.AddProduceObjCObjectStep(Entity.getType());
03064   }
03065 }
03066 
03067 static void TryListInitialization(Sema &S,
03068                                   const InitializedEntity &Entity,
03069                                   const InitializationKind &Kind,
03070                                   InitListExpr *InitList,
03071                                   InitializationSequence &Sequence);
03072 
03073 /// \brief When initializing from init list via constructor, handle
03074 /// initialization of an object of type std::initializer_list<T>.
03075 ///
03076 /// \return true if we have handled initialization of an object of type
03077 /// std::initializer_list<T>, false otherwise.
03078 static bool TryInitializerListConstruction(Sema &S,
03079                                            InitListExpr *List,
03080                                            QualType DestType,
03081                                            InitializationSequence &Sequence) {
03082   QualType E;
03083   if (!S.isStdInitializerList(DestType, &E))
03084     return false;
03085 
03086   if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
03087     Sequence.setIncompleteTypeFailure(E);
03088     return true;
03089   }
03090 
03091   // Try initializing a temporary array from the init list.
03092   QualType ArrayType = S.Context.getConstantArrayType(
03093       E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
03094                                  List->getNumInits()),
03095       clang::ArrayType::Normal, 0);
03096   InitializedEntity HiddenArray =
03097       InitializedEntity::InitializeTemporary(ArrayType);
03098   InitializationKind Kind =
03099       InitializationKind::CreateDirectList(List->getExprLoc());
03100   TryListInitialization(S, HiddenArray, Kind, List, Sequence);
03101   if (Sequence)
03102     Sequence.AddStdInitializerListConstructionStep(DestType);
03103   return true;
03104 }
03105 
03106 static OverloadingResult
03107 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
03108                            MultiExprArg Args,
03109                            OverloadCandidateSet &CandidateSet,
03110                            ArrayRef<NamedDecl *> Ctors,
03111                            OverloadCandidateSet::iterator &Best,
03112                            bool CopyInitializing, bool AllowExplicit,
03113                            bool OnlyListConstructors, bool InitListSyntax) {
03114   CandidateSet.clear();
03115 
03116   for (ArrayRef<NamedDecl *>::iterator
03117          Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
03118     NamedDecl *D = *Con;
03119     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
03120     bool SuppressUserConversions = false;
03121 
03122     // Find the constructor (which may be a template).
03123     CXXConstructorDecl *Constructor = nullptr;
03124     FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
03125     if (ConstructorTmpl)
03126       Constructor = cast<CXXConstructorDecl>(
03127                                            ConstructorTmpl->getTemplatedDecl());
03128     else {
03129       Constructor = cast<CXXConstructorDecl>(D);
03130 
03131       // C++11 [over.best.ics]p4:
03132       //   However, when considering the argument of a constructor or
03133       //   user-defined conversion function that is a candidate:
03134       //    -- by 13.3.1.3 when invoked for the copying/moving of a temporary
03135       //       in the second step of a class copy-initialization,
03136       //    -- by 13.3.1.7 when passing the initializer list as a single
03137       //       argument or when the initializer list has exactly one elementand
03138       //       a conversion to some class X or reference to (possibly
03139       //       cv-qualified) X is considered for the first parameter of a
03140       //       constructor of X, or
03141       //    -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
03142       //   only standard conversion sequences and ellipsis conversion sequences
03143       //   are considered.
03144       if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
03145           Constructor->isCopyOrMoveConstructor())
03146         SuppressUserConversions = true;
03147     }
03148 
03149     if (!Constructor->isInvalidDecl() &&
03150         (AllowExplicit || !Constructor->isExplicit()) &&
03151         (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
03152       if (ConstructorTmpl)
03153         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
03154                                        /*ExplicitArgs*/ nullptr, Args,
03155                                        CandidateSet, SuppressUserConversions);
03156       else {
03157         // C++ [over.match.copy]p1:
03158         //   - When initializing a temporary to be bound to the first parameter 
03159         //     of a constructor that takes a reference to possibly cv-qualified 
03160         //     T as its first argument, called with a single argument in the 
03161         //     context of direct-initialization, explicit conversion functions
03162         //     are also considered.
03163         bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 
03164                                  Args.size() == 1 &&
03165                                  Constructor->isCopyOrMoveConstructor();
03166         S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
03167                                SuppressUserConversions,
03168                                /*PartialOverloading=*/false,
03169                                /*AllowExplicit=*/AllowExplicitConv);
03170       }
03171     }
03172   }
03173 
03174   // Perform overload resolution and return the result.
03175   return CandidateSet.BestViableFunction(S, DeclLoc, Best);
03176 }
03177 
03178 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
03179 /// enumerates the constructors of the initialized entity and performs overload
03180 /// resolution to select the best.
03181 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
03182 /// class type.
03183 static void TryConstructorInitialization(Sema &S,
03184                                          const InitializedEntity &Entity,
03185                                          const InitializationKind &Kind,
03186                                          MultiExprArg Args, QualType DestType,
03187                                          InitializationSequence &Sequence,
03188                                          bool InitListSyntax = false) {
03189   assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
03190          "InitListSyntax must come with a single initializer list argument.");
03191 
03192   // The type we're constructing needs to be complete.
03193   if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
03194     Sequence.setIncompleteTypeFailure(DestType);
03195     return;
03196   }
03197 
03198   const RecordType *DestRecordType = DestType->getAs<RecordType>();
03199   assert(DestRecordType && "Constructor initialization requires record type");
03200   CXXRecordDecl *DestRecordDecl
03201     = cast<CXXRecordDecl>(DestRecordType->getDecl());
03202 
03203   // Build the candidate set directly in the initialization sequence
03204   // structure, so that it will persist if we fail.
03205   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
03206 
03207   // Determine whether we are allowed to call explicit constructors or
03208   // explicit conversion operators.
03209   bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
03210   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
03211 
03212   //   - Otherwise, if T is a class type, constructors are considered. The
03213   //     applicable constructors are enumerated, and the best one is chosen
03214   //     through overload resolution.
03215   DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
03216   // The container holding the constructors can under certain conditions
03217   // be changed while iterating (e.g. because of deserialization).
03218   // To be safe we copy the lookup results to a new container.
03219   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
03220 
03221   OverloadingResult Result = OR_No_Viable_Function;
03222   OverloadCandidateSet::iterator Best;
03223   bool AsInitializerList = false;
03224 
03225   // C++11 [over.match.list]p1:
03226   //   When objects of non-aggregate type T are list-initialized, overload
03227   //   resolution selects the constructor in two phases:
03228   //   - Initially, the candidate functions are the initializer-list
03229   //     constructors of the class T and the argument list consists of the
03230   //     initializer list as a single argument.
03231   if (InitListSyntax) {
03232     InitListExpr *ILE = cast<InitListExpr>(Args[0]);
03233     AsInitializerList = true;
03234 
03235     // If the initializer list has no elements and T has a default constructor,
03236     // the first phase is omitted.
03237     if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
03238       Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
03239                                           CandidateSet, Ctors, Best,
03240                                           CopyInitialization, AllowExplicit,
03241                                           /*OnlyListConstructor=*/true,
03242                                           InitListSyntax);
03243 
03244     // Time to unwrap the init list.
03245     Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
03246   }
03247 
03248   // C++11 [over.match.list]p1:
03249   //   - If no viable initializer-list constructor is found, overload resolution
03250   //     is performed again, where the candidate functions are all the
03251   //     constructors of the class T and the argument list consists of the
03252   //     elements of the initializer list.
03253   if (Result == OR_No_Viable_Function) {
03254     AsInitializerList = false;
03255     Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
03256                                         CandidateSet, Ctors, Best,
03257                                         CopyInitialization, AllowExplicit,
03258                                         /*OnlyListConstructors=*/false,
03259                                         InitListSyntax);
03260   }
03261   if (Result) {
03262     Sequence.SetOverloadFailure(InitListSyntax ?
03263                       InitializationSequence::FK_ListConstructorOverloadFailed :
03264                       InitializationSequence::FK_ConstructorOverloadFailed,
03265                                 Result);
03266     return;
03267   }
03268 
03269   // C++11 [dcl.init]p6:
03270   //   If a program calls for the default initialization of an object
03271   //   of a const-qualified type T, T shall be a class type with a
03272   //   user-provided default constructor.
03273   if (Kind.getKind() == InitializationKind::IK_Default &&
03274       Entity.getType().isConstQualified() &&
03275       !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
03276     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
03277     return;
03278   }
03279 
03280   // C++11 [over.match.list]p1:
03281   //   In copy-list-initialization, if an explicit constructor is chosen, the
03282   //   initializer is ill-formed.
03283   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
03284   if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
03285     Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
03286     return;
03287   }
03288 
03289   // Add the constructor initialization step. Any cv-qualification conversion is
03290   // subsumed by the initialization.
03291   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03292   Sequence.AddConstructorInitializationStep(CtorDecl,
03293                                             Best->FoundDecl.getAccess(),
03294                                             DestType, HadMultipleCandidates,
03295                                             InitListSyntax, AsInitializerList);
03296 }
03297 
03298 static bool
03299 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
03300                                              Expr *Initializer,
03301                                              QualType &SourceType,
03302                                              QualType &UnqualifiedSourceType,
03303                                              QualType UnqualifiedTargetType,
03304                                              InitializationSequence &Sequence) {
03305   if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
03306         S.Context.OverloadTy) {
03307     DeclAccessPair Found;
03308     bool HadMultipleCandidates = false;
03309     if (FunctionDecl *Fn
03310         = S.ResolveAddressOfOverloadedFunction(Initializer,
03311                                                UnqualifiedTargetType,
03312                                                false, Found,
03313                                                &HadMultipleCandidates)) {
03314       Sequence.AddAddressOverloadResolutionStep(Fn, Found,
03315                                                 HadMultipleCandidates);
03316       SourceType = Fn->getType();
03317       UnqualifiedSourceType = SourceType.getUnqualifiedType();
03318     } else if (!UnqualifiedTargetType->isRecordType()) {
03319       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
03320       return true;
03321     }
03322   }
03323   return false;
03324 }
03325 
03326 static void TryReferenceInitializationCore(Sema &S,
03327                                            const InitializedEntity &Entity,
03328                                            const InitializationKind &Kind,
03329                                            Expr *Initializer,
03330                                            QualType cv1T1, QualType T1,
03331                                            Qualifiers T1Quals,
03332                                            QualType cv2T2, QualType T2,
03333                                            Qualifiers T2Quals,
03334                                            InitializationSequence &Sequence);
03335 
03336 static void TryValueInitialization(Sema &S,
03337                                    const InitializedEntity &Entity,
03338                                    const InitializationKind &Kind,
03339                                    InitializationSequence &Sequence,
03340                                    InitListExpr *InitList = nullptr);
03341 
03342 /// \brief Attempt list initialization of a reference.
03343 static void TryReferenceListInitialization(Sema &S,
03344                                            const InitializedEntity &Entity,
03345                                            const InitializationKind &Kind,
03346                                            InitListExpr *InitList,
03347                                            InitializationSequence &Sequence) {
03348   // First, catch C++03 where this isn't possible.
03349   if (!S.getLangOpts().CPlusPlus11) {
03350     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
03351     return;
03352   }
03353 
03354   QualType DestType = Entity.getType();
03355   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
03356   Qualifiers T1Quals;
03357   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
03358 
03359   // Reference initialization via an initializer list works thus:
03360   // If the initializer list consists of a single element that is
03361   // reference-related to the referenced type, bind directly to that element
03362   // (possibly creating temporaries).
03363   // Otherwise, initialize a temporary with the initializer list and
03364   // bind to that.
03365   if (InitList->getNumInits() == 1) {
03366     Expr *Initializer = InitList->getInit(0);
03367     QualType cv2T2 = Initializer->getType();
03368     Qualifiers T2Quals;
03369     QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
03370 
03371     // If this fails, creating a temporary wouldn't work either.
03372     if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
03373                                                      T1, Sequence))
03374       return;
03375 
03376     SourceLocation DeclLoc = Initializer->getLocStart();
03377     bool dummy1, dummy2, dummy3;
03378     Sema::ReferenceCompareResult RefRelationship
03379       = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
03380                                        dummy2, dummy3);
03381     if (RefRelationship >= Sema::Ref_Related) {
03382       // Try to bind the reference here.
03383       TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
03384                                      T1Quals, cv2T2, T2, T2Quals, Sequence);
03385       if (Sequence)
03386         Sequence.RewrapReferenceInitList(cv1T1, InitList);
03387       return;
03388     }
03389 
03390     // Update the initializer if we've resolved an overloaded function.
03391     if (Sequence.step_begin() != Sequence.step_end())
03392       Sequence.RewrapReferenceInitList(cv1T1, InitList);
03393   }
03394 
03395   // Not reference-related. Create a temporary and bind to that.
03396   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
03397 
03398   TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
03399   if (Sequence) {
03400     if (DestType->isRValueReferenceType() ||
03401         (T1Quals.hasConst() && !T1Quals.hasVolatile()))
03402       Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
03403     else
03404       Sequence.SetFailed(
03405           InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
03406   }
03407 }
03408 
03409 /// \brief Attempt list initialization (C++0x [dcl.init.list])
03410 static void TryListInitialization(Sema &S,
03411                                   const InitializedEntity &Entity,
03412                                   const InitializationKind &Kind,
03413                                   InitListExpr *InitList,
03414                                   InitializationSequence &Sequence) {
03415   QualType DestType = Entity.getType();
03416 
03417   // C++ doesn't allow scalar initialization with more than one argument.
03418   // But C99 complex numbers are scalars and it makes sense there.
03419   if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
03420       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
03421     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
03422     return;
03423   }
03424   if (DestType->isReferenceType()) {
03425     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
03426     return;
03427   }
03428   if (DestType->isRecordType()) {
03429     if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
03430       Sequence.setIncompleteTypeFailure(DestType);
03431       return;
03432     }
03433 
03434     // C++11 [dcl.init.list]p3:
03435     //   - If T is an aggregate, aggregate initialization is performed.
03436     if (!DestType->isAggregateType()) {
03437       if (S.getLangOpts().CPlusPlus11) {
03438         //   - Otherwise, if the initializer list has no elements and T is a
03439         //     class type with a default constructor, the object is
03440         //     value-initialized.
03441         if (InitList->getNumInits() == 0) {
03442           CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
03443           if (RD->hasDefaultConstructor()) {
03444             TryValueInitialization(S, Entity, Kind, Sequence, InitList);
03445             return;
03446           }
03447         }
03448 
03449         //   - Otherwise, if T is a specialization of std::initializer_list<E>,
03450         //     an initializer_list object constructed [...]
03451         if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
03452           return;
03453 
03454         //   - Otherwise, if T is a class type, constructors are considered.
03455         Expr *InitListAsExpr = InitList;
03456         TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
03457                                      Sequence, /*InitListSyntax*/true);
03458       } else
03459         Sequence.SetFailed(
03460             InitializationSequence::FK_InitListBadDestinationType);
03461       return;
03462     }
03463   }
03464   if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
03465       InitList->getNumInits() == 1 &&
03466       InitList->getInit(0)->getType()->isRecordType()) {
03467     //   - Otherwise, if the initializer list has a single element of type E
03468     //     [...references are handled above...], the object or reference is
03469     //     initialized from that element; if a narrowing conversion is required
03470     //     to convert the element to T, the program is ill-formed.
03471     //
03472     // Per core-24034, this is direct-initialization if we were performing
03473     // direct-list-initialization and copy-initialization otherwise.
03474     // We can't use InitListChecker for this, because it always performs
03475     // copy-initialization. This only matters if we might use an 'explicit'
03476     // conversion operator, so we only need to handle the cases where the source
03477     // is of record type.
03478     InitializationKind SubKind =
03479         Kind.getKind() == InitializationKind::IK_DirectList
03480             ? InitializationKind::CreateDirect(Kind.getLocation(),
03481                                                InitList->getLBraceLoc(),
03482                                                InitList->getRBraceLoc())
03483             : Kind;
03484     Expr *SubInit[1] = { InitList->getInit(0) };
03485     Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
03486                             /*TopLevelOfInitList*/true);
03487     if (Sequence)
03488       Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
03489     return;
03490   }
03491 
03492   InitListChecker CheckInitList(S, Entity, InitList,
03493           DestType, /*VerifyOnly=*/true);
03494   if (CheckInitList.HadError()) {
03495     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
03496     return;
03497   }
03498 
03499   // Add the list initialization step with the built init list.
03500   Sequence.AddListInitializationStep(DestType);
03501 }
03502 
03503 /// \brief Try a reference initialization that involves calling a conversion
03504 /// function.
03505 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
03506                                              const InitializedEntity &Entity,
03507                                              const InitializationKind &Kind,
03508                                              Expr *Initializer,
03509                                              bool AllowRValues,
03510                                              InitializationSequence &Sequence) {
03511   QualType DestType = Entity.getType();
03512   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
03513   QualType T1 = cv1T1.getUnqualifiedType();
03514   QualType cv2T2 = Initializer->getType();
03515   QualType T2 = cv2T2.getUnqualifiedType();
03516 
03517   bool DerivedToBase;
03518   bool ObjCConversion;
03519   bool ObjCLifetimeConversion;
03520   assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
03521                                          T1, T2, DerivedToBase,
03522                                          ObjCConversion,
03523                                          ObjCLifetimeConversion) &&
03524          "Must have incompatible references when binding via conversion");
03525   (void)DerivedToBase;
03526   (void)ObjCConversion;
03527   (void)ObjCLifetimeConversion;
03528   
03529   // Build the candidate set directly in the initialization sequence
03530   // structure, so that it will persist if we fail.
03531   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
03532   CandidateSet.clear();
03533 
03534   // Determine whether we are allowed to call explicit constructors or
03535   // explicit conversion operators.
03536   bool AllowExplicit = Kind.AllowExplicit();
03537   bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
03538 
03539   const RecordType *T1RecordType = nullptr;
03540   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
03541       !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
03542     // The type we're converting to is a class type. Enumerate its constructors
03543     // to see if there is a suitable conversion.
03544     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
03545 
03546     DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
03547     // The container holding the constructors can under certain conditions
03548     // be changed while iterating (e.g. because of deserialization).
03549     // To be safe we copy the lookup results to a new container.
03550     SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
03551     for (SmallVectorImpl<NamedDecl *>::iterator
03552            CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
03553       NamedDecl *D = *CI;
03554       DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
03555 
03556       // Find the constructor (which may be a template).
03557       CXXConstructorDecl *Constructor = nullptr;
03558       FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
03559       if (ConstructorTmpl)
03560         Constructor = cast<CXXConstructorDecl>(
03561                                          ConstructorTmpl->getTemplatedDecl());
03562       else
03563         Constructor = cast<CXXConstructorDecl>(D);
03564 
03565       if (!Constructor->isInvalidDecl() &&
03566           Constructor->isConvertingConstructor(AllowExplicit)) {
03567         if (ConstructorTmpl)
03568           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
03569                                          /*ExplicitArgs*/ nullptr,
03570                                          Initializer, CandidateSet,
03571                                          /*SuppressUserConversions=*/true);
03572         else
03573           S.AddOverloadCandidate(Constructor, FoundDecl,
03574                                  Initializer, CandidateSet,
03575                                  /*SuppressUserConversions=*/true);
03576       }
03577     }
03578   }
03579   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
03580     return OR_No_Viable_Function;
03581 
03582   const RecordType *T2RecordType = nullptr;
03583   if ((T2RecordType = T2->getAs<RecordType>()) &&
03584       !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
03585     // The type we're converting from is a class type, enumerate its conversion
03586     // functions.
03587     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
03588 
03589     std::pair<CXXRecordDecl::conversion_iterator,
03590               CXXRecordDecl::conversion_iterator>
03591       Conversions = T2RecordDecl->getVisibleConversionFunctions();
03592     for (CXXRecordDecl::conversion_iterator
03593            I = Conversions.first, E = Conversions.second; I != E; ++I) {
03594       NamedDecl *D = *I;
03595       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
03596       if (isa<UsingShadowDecl>(D))
03597         D = cast<UsingShadowDecl>(D)->getTargetDecl();
03598 
03599       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
03600       CXXConversionDecl *Conv;
03601       if (ConvTemplate)
03602         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
03603       else
03604         Conv = cast<CXXConversionDecl>(D);
03605 
03606       // If the conversion function doesn't return a reference type,
03607       // it can't be considered for this conversion unless we're allowed to
03608       // consider rvalues.
03609       // FIXME: Do we need to make sure that we only consider conversion
03610       // candidates with reference-compatible results? That might be needed to
03611       // break recursion.
03612       if ((AllowExplicitConvs || !Conv->isExplicit()) &&
03613           (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
03614         if (ConvTemplate)
03615           S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
03616                                            ActingDC, Initializer,
03617                                            DestType, CandidateSet,
03618                                            /*AllowObjCConversionOnExplicit=*/
03619                                              false);
03620         else
03621           S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
03622                                    Initializer, DestType, CandidateSet,
03623                                    /*AllowObjCConversionOnExplicit=*/false);
03624       }
03625     }
03626   }
03627   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
03628     return OR_No_Viable_Function;
03629 
03630   SourceLocation DeclLoc = Initializer->getLocStart();
03631 
03632   // Perform overload resolution. If it fails, return the failed result.
03633   OverloadCandidateSet::iterator Best;
03634   if (OverloadingResult Result
03635         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
03636     return Result;
03637 
03638   FunctionDecl *Function = Best->Function;
03639   // This is the overload that will be used for this initialization step if we
03640   // use this initialization. Mark it as referenced.
03641   Function->setReferenced();
03642 
03643   // Compute the returned type of the conversion.
03644   if (isa<CXXConversionDecl>(Function))
03645     T2 = Function->getReturnType();
03646   else
03647     T2 = cv1T1;
03648 
03649   // Add the user-defined conversion step.
03650   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03651   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
03652                                  T2.getNonLValueExprType(S.Context),
03653                                  HadMultipleCandidates);
03654 
03655   // Determine whether we need to perform derived-to-base or
03656   // cv-qualification adjustments.
03657   ExprValueKind VK = VK_RValue;
03658   if (T2->isLValueReferenceType())
03659     VK = VK_LValue;
03660   else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
03661     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
03662 
03663   bool NewDerivedToBase = false;
03664   bool NewObjCConversion = false;
03665   bool NewObjCLifetimeConversion = false;
03666   Sema::ReferenceCompareResult NewRefRelationship
03667     = S.CompareReferenceRelationship(DeclLoc, T1,
03668                                      T2.getNonLValueExprType(S.Context),
03669                                      NewDerivedToBase, NewObjCConversion,
03670                                      NewObjCLifetimeConversion);
03671   if (NewRefRelationship == Sema::Ref_Incompatible) {
03672     // If the type we've converted to is not reference-related to the
03673     // type we're looking for, then there is another conversion step
03674     // we need to perform to produce a temporary of the right type
03675     // that we'll be binding to.
03676     ImplicitConversionSequence ICS;
03677     ICS.setStandard();
03678     ICS.Standard = Best->FinalConversion;
03679     T2 = ICS.Standard.getToType(2);
03680     Sequence.AddConversionSequenceStep(ICS, T2);
03681   } else if (NewDerivedToBase)
03682     Sequence.AddDerivedToBaseCastStep(
03683                                 S.Context.getQualifiedType(T1,
03684                                   T2.getNonReferenceType().getQualifiers()),
03685                                       VK);
03686   else if (NewObjCConversion)
03687     Sequence.AddObjCObjectConversionStep(
03688                                 S.Context.getQualifiedType(T1,
03689                                   T2.getNonReferenceType().getQualifiers()));
03690 
03691   if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
03692     Sequence.AddQualificationConversionStep(cv1T1, VK);
03693 
03694   Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
03695   return OR_Success;
03696 }
03697 
03698 static void CheckCXX98CompatAccessibleCopy(Sema &S,
03699                                            const InitializedEntity &Entity,
03700                                            Expr *CurInitExpr);
03701 
03702 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
03703 static void TryReferenceInitialization(Sema &S,
03704                                        const InitializedEntity &Entity,
03705                                        const InitializationKind &Kind,
03706                                        Expr *Initializer,
03707                                        InitializationSequence &Sequence) {
03708   QualType DestType = Entity.getType();
03709   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
03710   Qualifiers T1Quals;
03711   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
03712   QualType cv2T2 = Initializer->getType();
03713   Qualifiers T2Quals;
03714   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
03715 
03716   // If the initializer is the address of an overloaded function, try
03717   // to resolve the overloaded function. If all goes well, T2 is the
03718   // type of the resulting function.
03719   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
03720                                                    T1, Sequence))
03721     return;
03722 
03723   // Delegate everything else to a subfunction.
03724   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
03725                                  T1Quals, cv2T2, T2, T2Quals, Sequence);
03726 }
03727 
03728 /// Converts the target of reference initialization so that it has the
03729 /// appropriate qualifiers and value kind.
03730 ///
03731 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
03732 /// \code
03733 ///   int x;
03734 ///   const int &r = x;
03735 /// \endcode
03736 ///
03737 /// In this case the reference is binding to a bitfield lvalue, which isn't
03738 /// valid. Perform a load to create a lifetime-extended temporary instead.
03739 /// \code
03740 ///   const int &r = someStruct.bitfield;
03741 /// \endcode
03742 static ExprValueKind
03743 convertQualifiersAndValueKindIfNecessary(Sema &S,
03744                                          InitializationSequence &Sequence,
03745                                          Expr *Initializer,
03746                                          QualType cv1T1,
03747                                          Qualifiers T1Quals,
03748                                          Qualifiers T2Quals,
03749                                          bool IsLValueRef) {
03750   bool IsNonAddressableType = Initializer->refersToBitField() ||
03751                               Initializer->refersToVectorElement();
03752 
03753   if (IsNonAddressableType) {
03754     // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
03755     // lvalue reference to a non-volatile const type, or the reference shall be
03756     // an rvalue reference.
03757     //
03758     // If not, we can't make a temporary and bind to that. Give up and allow the
03759     // error to be diagnosed later.
03760     if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
03761       assert(Initializer->isGLValue());
03762       return Initializer->getValueKind();
03763     }
03764 
03765     // Force a load so we can materialize a temporary.
03766     Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
03767     return VK_RValue;
03768   }
03769 
03770   if (T1Quals != T2Quals) {
03771     Sequence.AddQualificationConversionStep(cv1T1,
03772                                             Initializer->getValueKind());
03773   }
03774 
03775   return Initializer->getValueKind();
03776 }
03777 
03778 
03779 /// \brief Reference initialization without resolving overloaded functions.
03780 static void TryReferenceInitializationCore(Sema &S,
03781                                            const InitializedEntity &Entity,
03782                                            const InitializationKind &Kind,
03783                                            Expr *Initializer,
03784                                            QualType cv1T1, QualType T1,
03785                                            Qualifiers T1Quals,
03786                                            QualType cv2T2, QualType T2,
03787                                            Qualifiers T2Quals,
03788                                            InitializationSequence &Sequence) {
03789   QualType DestType = Entity.getType();
03790   SourceLocation DeclLoc = Initializer->getLocStart();
03791   // Compute some basic properties of the types and the initializer.
03792   bool isLValueRef = DestType->isLValueReferenceType();
03793   bool isRValueRef = !isLValueRef;
03794   bool DerivedToBase = false;
03795   bool ObjCConversion = false;
03796   bool ObjCLifetimeConversion = false;
03797   Expr::Classification InitCategory = Initializer->Classify(S.Context);
03798   Sema::ReferenceCompareResult RefRelationship
03799     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
03800                                      ObjCConversion, ObjCLifetimeConversion);
03801 
03802   // C++0x [dcl.init.ref]p5:
03803   //   A reference to type "cv1 T1" is initialized by an expression of type
03804   //   "cv2 T2" as follows:
03805   //
03806   //     - If the reference is an lvalue reference and the initializer
03807   //       expression
03808   // Note the analogous bullet points for rvalue refs to functions. Because
03809   // there are no function rvalues in C++, rvalue refs to functions are treated
03810   // like lvalue refs.
03811   OverloadingResult ConvOvlResult = OR_Success;
03812   bool T1Function = T1->isFunctionType();
03813   if (isLValueRef || T1Function) {
03814     if (InitCategory.isLValue() &&
03815         (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
03816          (Kind.isCStyleOrFunctionalCast() &&
03817           RefRelationship == Sema::Ref_Related))) {
03818       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
03819       //     reference-compatible with "cv2 T2," or
03820       //
03821       // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
03822       // bit-field when we're determining whether the reference initialization
03823       // can occur. However, we do pay attention to whether it is a bit-field
03824       // to decide whether we're actually binding to a temporary created from
03825       // the bit-field.
03826       if (DerivedToBase)
03827         Sequence.AddDerivedToBaseCastStep(
03828                          S.Context.getQualifiedType(T1, T2Quals),
03829                          VK_LValue);
03830       else if (ObjCConversion)
03831         Sequence.AddObjCObjectConversionStep(
03832                                      S.Context.getQualifiedType(T1, T2Quals));
03833 
03834       ExprValueKind ValueKind =
03835         convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
03836                                                  cv1T1, T1Quals, T2Quals,
03837                                                  isLValueRef);
03838       Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
03839       return;
03840     }
03841 
03842     //     - has a class type (i.e., T2 is a class type), where T1 is not
03843     //       reference-related to T2, and can be implicitly converted to an
03844     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
03845     //       with "cv3 T3" (this conversion is selected by enumerating the
03846     //       applicable conversion functions (13.3.1.6) and choosing the best
03847     //       one through overload resolution (13.3)),
03848     // If we have an rvalue ref to function type here, the rhs must be
03849     // an rvalue. DR1287 removed the "implicitly" here.
03850     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
03851         (isLValueRef || InitCategory.isRValue())) {
03852       ConvOvlResult = TryRefInitWithConversionFunction(
03853           S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
03854       if (ConvOvlResult == OR_Success)
03855         return;
03856       if (ConvOvlResult != OR_No_Viable_Function)
03857         Sequence.SetOverloadFailure(
03858             InitializationSequence::FK_ReferenceInitOverloadFailed,
03859             ConvOvlResult);
03860     }
03861   }
03862 
03863   //     - Otherwise, the reference shall be an lvalue reference to a
03864   //       non-volatile const type (i.e., cv1 shall be const), or the reference
03865   //       shall be an rvalue reference.
03866   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
03867     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
03868       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
03869     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
03870       Sequence.SetOverloadFailure(
03871                         InitializationSequence::FK_ReferenceInitOverloadFailed,
03872                                   ConvOvlResult);
03873     else
03874       Sequence.SetFailed(InitCategory.isLValue()
03875         ? (RefRelationship == Sema::Ref_Related
03876              ? InitializationSequence::FK_ReferenceInitDropsQualifiers
03877              : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
03878         : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
03879 
03880     return;
03881   }
03882 
03883   //    - If the initializer expression
03884   //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
03885   //        "cv1 T1" is reference-compatible with "cv2 T2"
03886   // Note: functions are handled below.
03887   if (!T1Function &&
03888       (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
03889        (Kind.isCStyleOrFunctionalCast() &&
03890         RefRelationship == Sema::Ref_Related)) &&
03891       (InitCategory.isXValue() ||
03892        (InitCategory.isPRValue() && T2->isRecordType()) ||
03893        (InitCategory.isPRValue() && T2->isArrayType()))) {
03894     ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
03895     if (InitCategory.isPRValue() && T2->isRecordType()) {
03896       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
03897       // compiler the freedom to perform a copy here or bind to the
03898       // object, while C++0x requires that we bind directly to the
03899       // object. Hence, we always bind to the object without making an
03900       // extra copy. However, in C++03 requires that we check for the
03901       // presence of a suitable copy constructor:
03902       //
03903       //   The constructor that would be used to make the copy shall
03904       //   be callable whether or not the copy is actually done.
03905       if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
03906         Sequence.AddExtraneousCopyToTemporary(cv2T2);
03907       else if (S.getLangOpts().CPlusPlus11)
03908         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
03909     }
03910 
03911     if (DerivedToBase)
03912       Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
03913                                         ValueKind);
03914     else if (ObjCConversion)
03915       Sequence.AddObjCObjectConversionStep(
03916                                        S.Context.getQualifiedType(T1, T2Quals));
03917 
03918     ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
03919                                                          Initializer, cv1T1,
03920                                                          T1Quals, T2Quals,
03921                                                          isLValueRef);
03922 
03923     Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
03924     return;
03925   }
03926 
03927   //       - has a class type (i.e., T2 is a class type), where T1 is not
03928   //         reference-related to T2, and can be implicitly converted to an
03929   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
03930   //         where "cv1 T1" is reference-compatible with "cv3 T3",
03931   //
03932   // DR1287 removes the "implicitly" here.
03933   if (T2->isRecordType()) {
03934     if (RefRelationship == Sema::Ref_Incompatible) {
03935       ConvOvlResult = TryRefInitWithConversionFunction(
03936           S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
03937       if (ConvOvlResult)
03938         Sequence.SetOverloadFailure(
03939             InitializationSequence::FK_ReferenceInitOverloadFailed,
03940             ConvOvlResult);
03941 
03942       return;
03943     }
03944 
03945     if ((RefRelationship == Sema::Ref_Compatible ||
03946          RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
03947         isRValueRef && InitCategory.isLValue()) {
03948       Sequence.SetFailed(
03949         InitializationSequence::FK_RValueReferenceBindingToLValue);
03950       return;
03951     }
03952 
03953     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
03954     return;
03955   }
03956 
03957   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
03958   //        from the initializer expression using the rules for a non-reference
03959   //        copy-initialization (8.5). The reference is then bound to the
03960   //        temporary. [...]
03961 
03962   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
03963 
03964   // FIXME: Why do we use an implicit conversion here rather than trying
03965   // copy-initialization?
03966   ImplicitConversionSequence ICS
03967     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
03968                               /*SuppressUserConversions=*/false,
03969                               /*AllowExplicit=*/false,
03970                               /*FIXME:InOverloadResolution=*/false,
03971                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
03972                               /*AllowObjCWritebackConversion=*/false);
03973   
03974   if (ICS.isBad()) {
03975     // FIXME: Use the conversion function set stored in ICS to turn
03976     // this into an overloading ambiguity diagnostic. However, we need
03977     // to keep that set as an OverloadCandidateSet rather than as some
03978     // other kind of set.
03979     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
03980       Sequence.SetOverloadFailure(
03981                         InitializationSequence::FK_ReferenceInitOverloadFailed,
03982                                   ConvOvlResult);
03983     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
03984       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
03985     else
03986       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
03987     return;
03988   } else {
03989     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
03990   }
03991 
03992   //        [...] If T1 is reference-related to T2, cv1 must be the
03993   //        same cv-qualification as, or greater cv-qualification
03994   //        than, cv2; otherwise, the program is ill-formed.
03995   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
03996   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
03997   if (RefRelationship == Sema::Ref_Related &&
03998       (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
03999     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
04000     return;
04001   }
04002 
04003   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
04004   //   reference, the initializer expression shall not be an lvalue.
04005   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
04006       InitCategory.isLValue()) {
04007     Sequence.SetFailed(
04008                     InitializationSequence::FK_RValueReferenceBindingToLValue);
04009     return;
04010   }
04011 
04012   Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
04013   return;
04014 }
04015 
04016 /// \brief Attempt character array initialization from a string literal
04017 /// (C++ [dcl.init.string], C99 6.7.8).
04018 static void TryStringLiteralInitialization(Sema &S,
04019                                            const InitializedEntity &Entity,
04020                                            const InitializationKind &Kind,
04021                                            Expr *Initializer,
04022                                        InitializationSequence &Sequence) {
04023   Sequence.AddStringInitStep(Entity.getType());
04024 }
04025 
04026 /// \brief Attempt value initialization (C++ [dcl.init]p7).
04027 static void TryValueInitialization(Sema &S,
04028                                    const InitializedEntity &Entity,
04029                                    const InitializationKind &Kind,
04030                                    InitializationSequence &Sequence,
04031                                    InitListExpr *InitList) {
04032   assert((!InitList || InitList->getNumInits() == 0) &&
04033          "Shouldn't use value-init for non-empty init lists");
04034 
04035   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
04036   //
04037   //   To value-initialize an object of type T means:
04038   QualType T = Entity.getType();
04039 
04040   //     -- if T is an array type, then each element is value-initialized;
04041   T = S.Context.getBaseElementType(T);
04042 
04043   if (const RecordType *RT = T->getAs<RecordType>()) {
04044     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
04045       bool NeedZeroInitialization = true;
04046       if (!S.getLangOpts().CPlusPlus11) {
04047         // C++98:
04048         // -- if T is a class type (clause 9) with a user-declared constructor
04049         //    (12.1), then the default constructor for T is called (and the
04050         //    initialization is ill-formed if T has no accessible default
04051         //    constructor);
04052         if (ClassDecl->hasUserDeclaredConstructor())
04053           NeedZeroInitialization = false;
04054       } else {
04055         // C++11:
04056         // -- if T is a class type (clause 9) with either no default constructor
04057         //    (12.1 [class.ctor]) or a default constructor that is user-provided
04058         //    or deleted, then the object is default-initialized;
04059         CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
04060         if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
04061           NeedZeroInitialization = false;
04062       }
04063 
04064       // -- if T is a (possibly cv-qualified) non-union class type without a
04065       //    user-provided or deleted default constructor, then the object is
04066       //    zero-initialized and, if T has a non-trivial default constructor,
04067       //    default-initialized;
04068       // The 'non-union' here was removed by DR1502. The 'non-trivial default
04069       // constructor' part was removed by DR1507.
04070       if (NeedZeroInitialization)
04071         Sequence.AddZeroInitializationStep(Entity.getType());
04072 
04073       // C++03:
04074       // -- if T is a non-union class type without a user-declared constructor,
04075       //    then every non-static data member and base class component of T is
04076       //    value-initialized;
04077       // [...] A program that calls for [...] value-initialization of an
04078       // entity of reference type is ill-formed.
04079       //
04080       // C++11 doesn't need this handling, because value-initialization does not
04081       // occur recursively there, and the implicit default constructor is
04082       // defined as deleted in the problematic cases.
04083       if (!S.getLangOpts().CPlusPlus11 &&
04084           ClassDecl->hasUninitializedReferenceMember()) {
04085         Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
04086         return;
04087       }
04088 
04089       // If this is list-value-initialization, pass the empty init list on when
04090       // building the constructor call. This affects the semantics of a few
04091       // things (such as whether an explicit default constructor can be called).
04092       Expr *InitListAsExpr = InitList;
04093       MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
04094       bool InitListSyntax = InitList;
04095 
04096       return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
04097                                           InitListSyntax);
04098     }
04099   }
04100 
04101   Sequence.AddZeroInitializationStep(Entity.getType());
04102 }
04103 
04104 /// \brief Attempt default initialization (C++ [dcl.init]p6).
04105 static void TryDefaultInitialization(Sema &S,
04106                                      const InitializedEntity &Entity,
04107                                      const InitializationKind &Kind,
04108                                      InitializationSequence &Sequence) {
04109   assert(Kind.getKind() == InitializationKind::IK_Default);
04110 
04111   // C++ [dcl.init]p6:
04112   //   To default-initialize an object of type T means:
04113   //     - if T is an array type, each element is default-initialized;
04114   QualType DestType = S.Context.getBaseElementType(Entity.getType());
04115          
04116   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
04117   //       constructor for T is called (and the initialization is ill-formed if
04118   //       T has no accessible default constructor);
04119   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
04120     TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
04121     return;
04122   }
04123 
04124   //     - otherwise, no initialization is performed.
04125 
04126   //   If a program calls for the default initialization of an object of
04127   //   a const-qualified type T, T shall be a class type with a user-provided
04128   //   default constructor.
04129   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
04130     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
04131     return;
04132   }
04133 
04134   // If the destination type has a lifetime property, zero-initialize it.
04135   if (DestType.getQualifiers().hasObjCLifetime()) {
04136     Sequence.AddZeroInitializationStep(Entity.getType());
04137     return;
04138   }
04139 }
04140 
04141 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
04142 /// which enumerates all conversion functions and performs overload resolution
04143 /// to select the best.
04144 static void TryUserDefinedConversion(Sema &S,
04145                                      QualType DestType,
04146                                      const InitializationKind &Kind,
04147                                      Expr *Initializer,
04148                                      InitializationSequence &Sequence,
04149                                      bool TopLevelOfInitList) {
04150   assert(!DestType->isReferenceType() && "References are handled elsewhere");
04151   QualType SourceType = Initializer->getType();
04152   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
04153          "Must have a class type to perform a user-defined conversion");
04154 
04155   // Build the candidate set directly in the initialization sequence
04156   // structure, so that it will persist if we fail.
04157   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
04158   CandidateSet.clear();
04159 
04160   // Determine whether we are allowed to call explicit constructors or
04161   // explicit conversion operators.
04162   bool AllowExplicit = Kind.AllowExplicit();
04163 
04164   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
04165     // The type we're converting to is a class type. Enumerate its constructors
04166     // to see if there is a suitable conversion.
04167     CXXRecordDecl *DestRecordDecl
04168       = cast<CXXRecordDecl>(DestRecordType->getDecl());
04169 
04170     // Try to complete the type we're converting to.
04171     if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
04172       DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
04173       // The container holding the constructors can under certain conditions
04174       // be changed while iterating. To be safe we copy the lookup results
04175       // to a new container.
04176       SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
04177       for (SmallVectorImpl<NamedDecl *>::iterator
04178              Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
04179            Con != ConEnd; ++Con) {
04180         NamedDecl *D = *Con;
04181         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
04182 
04183         // Find the constructor (which may be a template).
04184         CXXConstructorDecl *Constructor = nullptr;
04185         FunctionTemplateDecl *ConstructorTmpl
04186           = dyn_cast<FunctionTemplateDecl>(D);
04187         if (ConstructorTmpl)
04188           Constructor = cast<CXXConstructorDecl>(
04189                                            ConstructorTmpl->getTemplatedDecl());
04190         else
04191           Constructor = cast<CXXConstructorDecl>(D);
04192 
04193         if (!Constructor->isInvalidDecl() &&
04194             Constructor->isConvertingConstructor(AllowExplicit)) {
04195           if (ConstructorTmpl)
04196             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
04197                                            /*ExplicitArgs*/ nullptr,
04198                                            Initializer, CandidateSet,
04199                                            /*SuppressUserConversions=*/true);
04200           else
04201             S.AddOverloadCandidate(Constructor, FoundDecl,
04202                                    Initializer, CandidateSet,
04203                                    /*SuppressUserConversions=*/true);
04204         }
04205       }
04206     }
04207   }
04208 
04209   SourceLocation DeclLoc = Initializer->getLocStart();
04210 
04211   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
04212     // The type we're converting from is a class type, enumerate its conversion
04213     // functions.
04214 
04215     // We can only enumerate the conversion functions for a complete type; if
04216     // the type isn't complete, simply skip this step.
04217     if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
04218       CXXRecordDecl *SourceRecordDecl
04219         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
04220 
04221       std::pair<CXXRecordDecl::conversion_iterator,
04222                 CXXRecordDecl::conversion_iterator>
04223         Conversions = SourceRecordDecl->getVisibleConversionFunctions();
04224       for (CXXRecordDecl::conversion_iterator
04225              I = Conversions.first, E = Conversions.second; I != E; ++I) {
04226         NamedDecl *D = *I;
04227         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
04228         if (isa<UsingShadowDecl>(D))
04229           D = cast<UsingShadowDecl>(D)->getTargetDecl();
04230 
04231         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
04232         CXXConversionDecl *Conv;
04233         if (ConvTemplate)
04234           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
04235         else
04236           Conv = cast<CXXConversionDecl>(D);
04237 
04238         if (AllowExplicit || !Conv->isExplicit()) {
04239           if (ConvTemplate)
04240             S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
04241                                              ActingDC, Initializer, DestType,
04242                                              CandidateSet, AllowExplicit);
04243           else
04244             S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
04245                                      Initializer, DestType, CandidateSet,
04246                                      AllowExplicit);
04247         }
04248       }
04249     }
04250   }
04251 
04252   // Perform overload resolution. If it fails, return the failed result.
04253   OverloadCandidateSet::iterator Best;
04254   if (OverloadingResult Result
04255         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
04256     Sequence.SetOverloadFailure(
04257                         InitializationSequence::FK_UserConversionOverloadFailed,
04258                                 Result);
04259     return;
04260   }
04261 
04262   FunctionDecl *Function = Best->Function;
04263   Function->setReferenced();
04264   bool HadMultipleCandidates = (CandidateSet.size() > 1);
04265 
04266   if (isa<CXXConstructorDecl>(Function)) {
04267     // Add the user-defined conversion step. Any cv-qualification conversion is
04268     // subsumed by the initialization. Per DR5, the created temporary is of the
04269     // cv-unqualified type of the destination.
04270     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
04271                                    DestType.getUnqualifiedType(),
04272                                    HadMultipleCandidates);
04273     return;
04274   }
04275 
04276   // Add the user-defined conversion step that calls the conversion function.
04277   QualType ConvType = Function->getCallResultType();
04278   if (ConvType->getAs<RecordType>()) {
04279     // If we're converting to a class type, there may be an copy of
04280     // the resulting temporary object (possible to create an object of
04281     // a base class type). That copy is not a separate conversion, so
04282     // we just make a note of the actual destination type (possibly a
04283     // base class of the type returned by the conversion function) and
04284     // let the user-defined conversion step handle the conversion.
04285     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
04286                                    HadMultipleCandidates);
04287     return;
04288   }
04289 
04290   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
04291                                  HadMultipleCandidates);
04292 
04293   // If the conversion following the call to the conversion function
04294   // is interesting, add it as a separate step.
04295   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
04296       Best->FinalConversion.Third) {
04297     ImplicitConversionSequence ICS;
04298     ICS.setStandard();
04299     ICS.Standard = Best->FinalConversion;
04300     Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
04301   }
04302 }
04303 
04304 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
04305 /// a function with a pointer return type contains a 'return false;' statement.
04306 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
04307 /// code using that header.
04308 ///
04309 /// Work around this by treating 'return false;' as zero-initializing the result
04310 /// if it's used in a pointer-returning function in a system header.
04311 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
04312                                               const InitializedEntity &Entity,
04313                                               const Expr *Init) {
04314   return S.getLangOpts().CPlusPlus11 &&
04315          Entity.getKind() == InitializedEntity::EK_Result &&
04316          Entity.getType()->isPointerType() &&
04317          isa<CXXBoolLiteralExpr>(Init) &&
04318          !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
04319          S.getSourceManager().isInSystemHeader(Init->getExprLoc());
04320 }
04321 
04322 /// The non-zero enum values here are indexes into diagnostic alternatives.
04323 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
04324 
04325 /// Determines whether this expression is an acceptable ICR source.
04326 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
04327                                          bool isAddressOf, bool &isWeakAccess) {
04328   // Skip parens.
04329   e = e->IgnoreParens();
04330 
04331   // Skip address-of nodes.
04332   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
04333     if (op->getOpcode() == UO_AddrOf)
04334       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
04335                                 isWeakAccess);
04336 
04337   // Skip certain casts.
04338   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
04339     switch (ce->getCastKind()) {
04340     case CK_Dependent:
04341     case CK_BitCast:
04342     case CK_LValueBitCast:
04343     case CK_NoOp:
04344       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
04345 
04346     case CK_ArrayToPointerDecay:
04347       return IIK_nonscalar;
04348 
04349     case CK_NullToPointer:
04350       return IIK_okay;
04351 
04352     default:
04353       break;
04354     }
04355 
04356   // If we have a declaration reference, it had better be a local variable.
04357   } else if (isa<DeclRefExpr>(e)) {
04358     // set isWeakAccess to true, to mean that there will be an implicit 
04359     // load which requires a cleanup.
04360     if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
04361       isWeakAccess = true;
04362     
04363     if (!isAddressOf) return IIK_nonlocal;
04364 
04365     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
04366     if (!var) return IIK_nonlocal;
04367 
04368     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
04369 
04370   // If we have a conditional operator, check both sides.
04371   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
04372     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
04373                                                 isWeakAccess))
04374       return iik;
04375 
04376     return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
04377 
04378   // These are never scalar.
04379   } else if (isa<ArraySubscriptExpr>(e)) {
04380     return IIK_nonscalar;
04381 
04382   // Otherwise, it needs to be a null pointer constant.
04383   } else {
04384     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
04385             ? IIK_okay : IIK_nonlocal);
04386   }
04387 
04388   return IIK_nonlocal;
04389 }
04390 
04391 /// Check whether the given expression is a valid operand for an
04392 /// indirect copy/restore.
04393 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
04394   assert(src->isRValue());
04395   bool isWeakAccess = false;
04396   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
04397   // If isWeakAccess to true, there will be an implicit 
04398   // load which requires a cleanup.
04399   if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
04400     S.ExprNeedsCleanups = true;
04401   
04402   if (iik == IIK_okay) return;
04403 
04404   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
04405     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
04406     << src->getSourceRange();
04407 }
04408 
04409 /// \brief Determine whether we have compatible array types for the
04410 /// purposes of GNU by-copy array initialization.
04411 static bool hasCompatibleArrayTypes(ASTContext &Context,
04412                                     const ArrayType *Dest, 
04413                                     const ArrayType *Source) {
04414   // If the source and destination array types are equivalent, we're
04415   // done.
04416   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
04417     return true;
04418 
04419   // Make sure that the element types are the same.
04420   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
04421     return false;
04422 
04423   // The only mismatch we allow is when the destination is an
04424   // incomplete array type and the source is a constant array type.
04425   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
04426 }
04427 
04428 static bool tryObjCWritebackConversion(Sema &S,
04429                                        InitializationSequence &Sequence,
04430                                        const InitializedEntity &Entity,
04431                                        Expr *Initializer) {
04432   bool ArrayDecay = false;
04433   QualType ArgType = Initializer->getType();
04434   QualType ArgPointee;
04435   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
04436     ArrayDecay = true;
04437     ArgPointee = ArgArrayType->getElementType();
04438     ArgType = S.Context.getPointerType(ArgPointee);
04439   }
04440       
04441   // Handle write-back conversion.
04442   QualType ConvertedArgType;
04443   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
04444                                    ConvertedArgType))
04445     return false;
04446 
04447   // We should copy unless we're passing to an argument explicitly
04448   // marked 'out'.
04449   bool ShouldCopy = true;
04450   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
04451     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
04452 
04453   // Do we need an lvalue conversion?
04454   if (ArrayDecay || Initializer->isGLValue()) {
04455     ImplicitConversionSequence ICS;
04456     ICS.setStandard();
04457     ICS.Standard.setAsIdentityConversion();
04458 
04459     QualType ResultType;
04460     if (ArrayDecay) {
04461       ICS.Standard.First = ICK_Array_To_Pointer;
04462       ResultType = S.Context.getPointerType(ArgPointee);
04463     } else {
04464       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
04465       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
04466     }
04467           
04468     Sequence.AddConversionSequenceStep(ICS, ResultType);
04469   }
04470         
04471   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
04472   return true;
04473 }
04474 
04475 static bool TryOCLSamplerInitialization(Sema &S,
04476                                         InitializationSequence &Sequence,
04477                                         QualType DestType,
04478                                         Expr *Initializer) {
04479   if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
04480     !Initializer->isIntegerConstantExpr(S.getASTContext()))
04481     return false;
04482 
04483   Sequence.AddOCLSamplerInitStep(DestType);
04484   return true;
04485 }
04486 
04487 //
04488 // OpenCL 1.2 spec, s6.12.10
04489 //
04490 // The event argument can also be used to associate the
04491 // async_work_group_copy with a previous async copy allowing
04492 // an event to be shared by multiple async copies; otherwise
04493 // event should be zero.
04494 //
04495 static bool TryOCLZeroEventInitialization(Sema &S,
04496                                           InitializationSequence &Sequence,
04497                                           QualType DestType,
04498                                           Expr *Initializer) {
04499   if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
04500       !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
04501       (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
04502     return false;
04503 
04504   Sequence.AddOCLZeroEventStep(DestType);
04505   return true;
04506 }
04507 
04508 InitializationSequence::InitializationSequence(Sema &S,
04509                                                const InitializedEntity &Entity,
04510                                                const InitializationKind &Kind,
04511                                                MultiExprArg Args,
04512                                                bool TopLevelOfInitList)
04513     : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
04514   InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
04515 }
04516 
04517 void InitializationSequence::InitializeFrom(Sema &S,
04518                                             const InitializedEntity &Entity,
04519                                             const InitializationKind &Kind,
04520                                             MultiExprArg Args,
04521                                             bool TopLevelOfInitList) {
04522   ASTContext &Context = S.Context;
04523 
04524   // Eliminate non-overload placeholder types in the arguments.  We
04525   // need to do this before checking whether types are dependent
04526   // because lowering a pseudo-object expression might well give us
04527   // something of dependent type.
04528   for (unsigned I = 0, E = Args.size(); I != E; ++I)
04529     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
04530       // FIXME: should we be doing this here?
04531       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
04532       if (result.isInvalid()) {
04533         SetFailed(FK_PlaceholderType);
04534         return;
04535       }
04536       Args[I] = result.get();
04537     }
04538 
04539   // C++0x [dcl.init]p16:
04540   //   The semantics of initializers are as follows. The destination type is
04541   //   the type of the object or reference being initialized and the source
04542   //   type is the type of the initializer expression. The source type is not
04543   //   defined when the initializer is a braced-init-list or when it is a
04544   //   parenthesized list of expressions.
04545   QualType DestType = Entity.getType();
04546 
04547   if (DestType->isDependentType() ||
04548       Expr::hasAnyTypeDependentArguments(Args)) {
04549     SequenceKind = DependentSequence;
04550     return;
04551   }
04552 
04553   // Almost everything is a normal sequence.
04554   setSequenceKind(NormalSequence);
04555 
04556   QualType SourceType;
04557   Expr *Initializer = nullptr;
04558   if (Args.size() == 1) {
04559     Initializer = Args[0];
04560     if (S.getLangOpts().ObjC1) {
04561       if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
04562                                               DestType, Initializer->getType(),
04563                                               Initializer) ||
04564           S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
04565         Args[0] = Initializer;
04566     }
04567     if (!isa<InitListExpr>(Initializer))
04568       SourceType = Initializer->getType();
04569   }
04570 
04571   //     - If the initializer is a (non-parenthesized) braced-init-list, the
04572   //       object is list-initialized (8.5.4).
04573   if (Kind.getKind() != InitializationKind::IK_Direct) {
04574     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
04575       TryListInitialization(S, Entity, Kind, InitList, *this);
04576       return;
04577     }
04578   }
04579 
04580   //     - If the destination type is a reference type, see 8.5.3.
04581   if (DestType->isReferenceType()) {
04582     // C++0x [dcl.init.ref]p1:
04583     //   A variable declared to be a T& or T&&, that is, "reference to type T"
04584     //   (8.3.2), shall be initialized by an object, or function, of type T or
04585     //   by an object that can be converted into a T.
04586     // (Therefore, multiple arguments are not permitted.)
04587     if (Args.size() != 1)
04588       SetFailed(FK_TooManyInitsForReference);
04589     else
04590       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
04591     return;
04592   }
04593 
04594   //     - If the initializer is (), the object is value-initialized.
04595   if (Kind.getKind() == InitializationKind::IK_Value ||
04596       (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
04597     TryValueInitialization(S, Entity, Kind, *this);
04598     return;
04599   }
04600 
04601   // Handle default initialization.
04602   if (Kind.getKind() == InitializationKind::IK_Default) {
04603     TryDefaultInitialization(S, Entity, Kind, *this);
04604     return;
04605   }
04606 
04607   //     - If the destination type is an array of characters, an array of
04608   //       char16_t, an array of char32_t, or an array of wchar_t, and the
04609   //       initializer is a string literal, see 8.5.2.
04610   //     - Otherwise, if the destination type is an array, the program is
04611   //       ill-formed.
04612   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
04613     if (Initializer && isa<VariableArrayType>(DestAT)) {
04614       SetFailed(FK_VariableLengthArrayHasInitializer);
04615       return;
04616     }
04617 
04618     if (Initializer) {
04619       switch (IsStringInit(Initializer, DestAT, Context)) {
04620       case SIF_None:
04621         TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
04622         return;
04623       case SIF_NarrowStringIntoWideChar:
04624         SetFailed(FK_NarrowStringIntoWideCharArray);
04625         return;
04626       case SIF_WideStringIntoChar:
04627         SetFailed(FK_WideStringIntoCharArray);
04628         return;
04629       case SIF_IncompatWideStringIntoWideChar:
04630         SetFailed(FK_IncompatWideStringIntoWideChar);
04631         return;
04632       case SIF_Other:
04633         break;
04634       }
04635     }
04636 
04637     // Note: as an GNU C extension, we allow initialization of an
04638     // array from a compound literal that creates an array of the same
04639     // type, so long as the initializer has no side effects.
04640     if (!S.getLangOpts().CPlusPlus && Initializer &&
04641         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
04642         Initializer->getType()->isArrayType()) {
04643       const ArrayType *SourceAT
04644         = Context.getAsArrayType(Initializer->getType());
04645       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
04646         SetFailed(FK_ArrayTypeMismatch);
04647       else if (Initializer->HasSideEffects(S.Context))
04648         SetFailed(FK_NonConstantArrayInit);
04649       else {
04650         AddArrayInitStep(DestType);
04651       }
04652     }
04653     // Note: as a GNU C++ extension, we allow list-initialization of a
04654     // class member of array type from a parenthesized initializer list.
04655     else if (S.getLangOpts().CPlusPlus &&
04656              Entity.getKind() == InitializedEntity::EK_Member &&
04657              Initializer && isa<InitListExpr>(Initializer)) {
04658       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
04659                             *this);
04660       AddParenthesizedArrayInitStep(DestType);
04661     } else if (DestAT->getElementType()->isCharType())
04662       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
04663     else if (IsWideCharCompatible(DestAT->getElementType(), Context))
04664       SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
04665     else
04666       SetFailed(FK_ArrayNeedsInitList);
04667 
04668     return;
04669   }
04670 
04671   // Determine whether we should consider writeback conversions for 
04672   // Objective-C ARC.
04673   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
04674          Entity.isParameterKind();
04675 
04676   // We're at the end of the line for C: it's either a write-back conversion
04677   // or it's a C assignment. There's no need to check anything else.
04678   if (!S.getLangOpts().CPlusPlus) {
04679     // If allowed, check whether this is an Objective-C writeback conversion.
04680     if (allowObjCWritebackConversion &&
04681         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
04682       return;
04683     }
04684 
04685     if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
04686       return;
04687 
04688     if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
04689       return;
04690 
04691     // Handle initialization in C
04692     AddCAssignmentStep(DestType);
04693     MaybeProduceObjCObject(S, *this, Entity);
04694     return;
04695   }
04696 
04697   assert(S.getLangOpts().CPlusPlus);
04698       
04699   //     - If the destination type is a (possibly cv-qualified) class type:
04700   if (DestType->isRecordType()) {
04701     //     - If the initialization is direct-initialization, or if it is
04702     //       copy-initialization where the cv-unqualified version of the
04703     //       source type is the same class as, or a derived class of, the
04704     //       class of the destination, constructors are considered. [...]
04705     if (Kind.getKind() == InitializationKind::IK_Direct ||
04706         (Kind.getKind() == InitializationKind::IK_Copy &&
04707          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
04708           S.IsDerivedFrom(SourceType, DestType))))
04709       TryConstructorInitialization(S, Entity, Kind, Args,
04710                                    DestType, *this);
04711     //     - Otherwise (i.e., for the remaining copy-initialization cases),
04712     //       user-defined conversion sequences that can convert from the source
04713     //       type to the destination type or (when a conversion function is
04714     //       used) to a derived class thereof are enumerated as described in
04715     //       13.3.1.4, and the best one is chosen through overload resolution
04716     //       (13.3).
04717     else
04718       TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
04719                                TopLevelOfInitList);
04720     return;
04721   }
04722 
04723   if (Args.size() > 1) {
04724     SetFailed(FK_TooManyInitsForScalar);
04725     return;
04726   }
04727   assert(Args.size() == 1 && "Zero-argument case handled above");
04728 
04729   //    - Otherwise, if the source type is a (possibly cv-qualified) class
04730   //      type, conversion functions are considered.
04731   if (!SourceType.isNull() && SourceType->isRecordType()) {
04732     // For a conversion to _Atomic(T) from either T or a class type derived
04733     // from T, initialize the T object then convert to _Atomic type.
04734     bool NeedAtomicConversion = false;
04735     if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
04736       if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
04737           S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
04738         DestType = Atomic->getValueType();
04739         NeedAtomicConversion = true;
04740       }
04741     }
04742 
04743     TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
04744                              TopLevelOfInitList);
04745     MaybeProduceObjCObject(S, *this, Entity);
04746     if (!Failed() && NeedAtomicConversion)
04747       AddAtomicConversionStep(Entity.getType());
04748     return;
04749   }
04750 
04751   //    - Otherwise, the initial value of the object being initialized is the
04752   //      (possibly converted) value of the initializer expression. Standard
04753   //      conversions (Clause 4) will be used, if necessary, to convert the
04754   //      initializer expression to the cv-unqualified version of the
04755   //      destination type; no user-defined conversions are considered.
04756 
04757   ImplicitConversionSequence ICS
04758     = S.TryImplicitConversion(Initializer, DestType,
04759                               /*SuppressUserConversions*/true,
04760                               /*AllowExplicitConversions*/ false,
04761                               /*InOverloadResolution*/ false,
04762                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
04763                               allowObjCWritebackConversion);
04764 
04765   if (ICS.isStandard() &&
04766       ICS.Standard.Second == ICK_Writeback_Conversion) {
04767     // Objective-C ARC writeback conversion.
04768     
04769     // We should copy unless we're passing to an argument explicitly
04770     // marked 'out'.
04771     bool ShouldCopy = true;
04772     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
04773       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
04774     
04775     // If there was an lvalue adjustment, add it as a separate conversion.
04776     if (ICS.Standard.First == ICK_Array_To_Pointer ||
04777         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
04778       ImplicitConversionSequence LvalueICS;
04779       LvalueICS.setStandard();
04780       LvalueICS.Standard.setAsIdentityConversion();
04781       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
04782       LvalueICS.Standard.First = ICS.Standard.First;
04783       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
04784     }
04785     
04786     AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
04787   } else if (ICS.isBad()) {
04788     DeclAccessPair dap;
04789     if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
04790       AddZeroInitializationStep(Entity.getType());
04791     } else if (Initializer->getType() == Context.OverloadTy &&
04792                !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
04793                                                      false, dap))
04794       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
04795     else
04796       SetFailed(InitializationSequence::FK_ConversionFailed);
04797   } else {
04798     AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
04799 
04800     MaybeProduceObjCObject(S, *this, Entity);
04801   }
04802 }
04803 
04804 InitializationSequence::~InitializationSequence() {
04805   for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
04806                                           StepEnd = Steps.end();
04807        Step != StepEnd; ++Step)
04808     Step->Destroy();
04809 }
04810 
04811 //===----------------------------------------------------------------------===//
04812 // Perform initialization
04813 //===----------------------------------------------------------------------===//
04814 static Sema::AssignmentAction
04815 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
04816   switch(Entity.getKind()) {
04817   case InitializedEntity::EK_Variable:
04818   case InitializedEntity::EK_New:
04819   case InitializedEntity::EK_Exception:
04820   case InitializedEntity::EK_Base:
04821   case InitializedEntity::EK_Delegating:
04822     return Sema::AA_Initializing;
04823 
04824   case InitializedEntity::EK_Parameter:
04825     if (Entity.getDecl() &&
04826         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
04827       return Sema::AA_Sending;
04828 
04829     return Sema::AA_Passing;
04830 
04831   case InitializedEntity::EK_Parameter_CF_Audited:
04832     if (Entity.getDecl() &&
04833       isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
04834       return Sema::AA_Sending;
04835       
04836     return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
04837       
04838   case InitializedEntity::EK_Result:
04839     return Sema::AA_Returning;
04840 
04841   case InitializedEntity::EK_Temporary:
04842   case InitializedEntity::EK_RelatedResult:
04843     // FIXME: Can we tell apart casting vs. converting?
04844     return Sema::AA_Casting;
04845 
04846   case InitializedEntity::EK_Member:
04847   case InitializedEntity::EK_ArrayElement:
04848   case InitializedEntity::EK_VectorElement:
04849   case InitializedEntity::EK_ComplexElement:
04850   case InitializedEntity::EK_BlockElement:
04851   case InitializedEntity::EK_LambdaCapture:
04852   case InitializedEntity::EK_CompoundLiteralInit:
04853     return Sema::AA_Initializing;
04854   }
04855 
04856   llvm_unreachable("Invalid EntityKind!");
04857 }
04858 
04859 /// \brief Whether we should bind a created object as a temporary when
04860 /// initializing the given entity.
04861 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
04862   switch (Entity.getKind()) {
04863   case InitializedEntity::EK_ArrayElement:
04864   case InitializedEntity::EK_Member:
04865   case InitializedEntity::EK_Result:
04866   case InitializedEntity::EK_New:
04867   case InitializedEntity::EK_Variable:
04868   case InitializedEntity::EK_Base:
04869   case InitializedEntity::EK_Delegating:
04870   case InitializedEntity::EK_VectorElement:
04871   case InitializedEntity::EK_ComplexElement:
04872   case InitializedEntity::EK_Exception:
04873   case InitializedEntity::EK_BlockElement:
04874   case InitializedEntity::EK_LambdaCapture:
04875   case InitializedEntity::EK_CompoundLiteralInit:
04876     return false;
04877 
04878   case InitializedEntity::EK_Parameter:
04879   case InitializedEntity::EK_Parameter_CF_Audited:
04880   case InitializedEntity::EK_Temporary:
04881   case InitializedEntity::EK_RelatedResult:
04882     return true;
04883   }
04884 
04885   llvm_unreachable("missed an InitializedEntity kind?");
04886 }
04887 
04888 /// \brief Whether the given entity, when initialized with an object
04889 /// created for that initialization, requires destruction.
04890 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
04891   switch (Entity.getKind()) {
04892     case InitializedEntity::EK_Result:
04893     case InitializedEntity::EK_New:
04894     case InitializedEntity::EK_Base:
04895     case InitializedEntity::EK_Delegating:
04896     case InitializedEntity::EK_VectorElement:
04897     case InitializedEntity::EK_ComplexElement:
04898     case InitializedEntity::EK_BlockElement:
04899     case InitializedEntity::EK_LambdaCapture:
04900       return false;
04901 
04902     case InitializedEntity::EK_Member:
04903     case InitializedEntity::EK_Variable:
04904     case InitializedEntity::EK_Parameter:
04905     case InitializedEntity::EK_Parameter_CF_Audited:
04906     case InitializedEntity::EK_Temporary:
04907     case InitializedEntity::EK_ArrayElement:
04908     case InitializedEntity::EK_Exception:
04909     case InitializedEntity::EK_CompoundLiteralInit:
04910     case InitializedEntity::EK_RelatedResult:
04911       return true;
04912   }
04913 
04914   llvm_unreachable("missed an InitializedEntity kind?");
04915 }
04916 
04917 /// \brief Look for copy and move constructors and constructor templates, for
04918 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
04919 static void LookupCopyAndMoveConstructors(Sema &S,
04920                                           OverloadCandidateSet &CandidateSet,
04921                                           CXXRecordDecl *Class,
04922                                           Expr *CurInitExpr) {
04923   DeclContext::lookup_result R = S.LookupConstructors(Class);
04924   // The container holding the constructors can under certain conditions
04925   // be changed while iterating (e.g. because of deserialization).
04926   // To be safe we copy the lookup results to a new container.
04927   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
04928   for (SmallVectorImpl<NamedDecl *>::iterator
04929          CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
04930     NamedDecl *D = *CI;
04931     CXXConstructorDecl *Constructor = nullptr;
04932 
04933     if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
04934       // Handle copy/moveconstructors, only.
04935       if (!Constructor || Constructor->isInvalidDecl() ||
04936           !Constructor->isCopyOrMoveConstructor() ||
04937           !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
04938         continue;
04939 
04940       DeclAccessPair FoundDecl
04941         = DeclAccessPair::make(Constructor, Constructor->getAccess());
04942       S.AddOverloadCandidate(Constructor, FoundDecl,
04943                              CurInitExpr, CandidateSet);
04944       continue;
04945     }
04946 
04947     // Handle constructor templates.
04948     FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
04949     if (ConstructorTmpl->isInvalidDecl())
04950       continue;
04951 
04952     Constructor = cast<CXXConstructorDecl>(
04953                                          ConstructorTmpl->getTemplatedDecl());
04954     if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
04955       continue;
04956 
04957     // FIXME: Do we need to limit this to copy-constructor-like
04958     // candidates?
04959     DeclAccessPair FoundDecl
04960       = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
04961     S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
04962                                    CurInitExpr, CandidateSet, true);
04963   }
04964 }
04965 
04966 /// \brief Get the location at which initialization diagnostics should appear.
04967 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
04968                                            Expr *Initializer) {
04969   switch (Entity.getKind()) {
04970   case InitializedEntity::EK_Result:
04971     return Entity.getReturnLoc();
04972 
04973   case InitializedEntity::EK_Exception:
04974     return Entity.getThrowLoc();
04975 
04976   case InitializedEntity::EK_Variable:
04977     return Entity.getDecl()->getLocation();
04978 
04979   case InitializedEntity::EK_LambdaCapture:
04980     return Entity.getCaptureLoc();
04981       
04982   case InitializedEntity::EK_ArrayElement:
04983   case InitializedEntity::EK_Member:
04984   case InitializedEntity::EK_Parameter:
04985   case InitializedEntity::EK_Parameter_CF_Audited:
04986   case InitializedEntity::EK_Temporary:
04987   case InitializedEntity::EK_New:
04988   case InitializedEntity::EK_Base:
04989   case InitializedEntity::EK_Delegating:
04990   case InitializedEntity::EK_VectorElement:
04991   case InitializedEntity::EK_ComplexElement:
04992   case InitializedEntity::EK_BlockElement:
04993   case InitializedEntity::EK_CompoundLiteralInit:
04994   case InitializedEntity::EK_RelatedResult:
04995     return Initializer->getLocStart();
04996   }
04997   llvm_unreachable("missed an InitializedEntity kind?");
04998 }
04999 
05000 /// \brief Make a (potentially elidable) temporary copy of the object
05001 /// provided by the given initializer by calling the appropriate copy
05002 /// constructor.
05003 ///
05004 /// \param S The Sema object used for type-checking.
05005 ///
05006 /// \param T The type of the temporary object, which must either be
05007 /// the type of the initializer expression or a superclass thereof.
05008 ///
05009 /// \param Entity The entity being initialized.
05010 ///
05011 /// \param CurInit The initializer expression.
05012 ///
05013 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
05014 /// is permitted in C++03 (but not C++0x) when binding a reference to
05015 /// an rvalue.
05016 ///
05017 /// \returns An expression that copies the initializer expression into
05018 /// a temporary object, or an error expression if a copy could not be
05019 /// created.
05020 static ExprResult CopyObject(Sema &S,
05021                              QualType T,
05022                              const InitializedEntity &Entity,
05023                              ExprResult CurInit,
05024                              bool IsExtraneousCopy) {
05025   // Determine which class type we're copying to.
05026   Expr *CurInitExpr = (Expr *)CurInit.get();
05027   CXXRecordDecl *Class = nullptr;
05028   if (const RecordType *Record = T->getAs<RecordType>())
05029     Class = cast<CXXRecordDecl>(Record->getDecl());
05030   if (!Class)
05031     return CurInit;
05032 
05033   // C++0x [class.copy]p32:
05034   //   When certain criteria are met, an implementation is allowed to
05035   //   omit the copy/move construction of a class object, even if the
05036   //   copy/move constructor and/or destructor for the object have
05037   //   side effects. [...]
05038   //     - when a temporary class object that has not been bound to a
05039   //       reference (12.2) would be copied/moved to a class object
05040   //       with the same cv-unqualified type, the copy/move operation
05041   //       can be omitted by constructing the temporary object
05042   //       directly into the target of the omitted copy/move
05043   //
05044   // Note that the other three bullets are handled elsewhere. Copy
05045   // elision for return statements and throw expressions are handled as part
05046   // of constructor initialization, while copy elision for exception handlers
05047   // is handled by the run-time.
05048   bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
05049   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
05050 
05051   // Make sure that the type we are copying is complete.
05052   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
05053     return CurInit;
05054 
05055   // Perform overload resolution using the class's copy/move constructors.
05056   // Only consider constructors and constructor templates. Per
05057   // C++0x [dcl.init]p16, second bullet to class types, this initialization
05058   // is direct-initialization.
05059   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
05060   LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
05061 
05062   bool HadMultipleCandidates = (CandidateSet.size() > 1);
05063 
05064   OverloadCandidateSet::iterator Best;
05065   switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
05066   case OR_Success:
05067     break;
05068 
05069   case OR_No_Viable_Function:
05070     S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
05071            ? diag::ext_rvalue_to_reference_temp_copy_no_viable
05072            : diag::err_temp_copy_no_viable)
05073       << (int)Entity.getKind() << CurInitExpr->getType()
05074       << CurInitExpr->getSourceRange();
05075     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
05076     if (!IsExtraneousCopy || S.isSFINAEContext())
05077       return ExprError();
05078     return CurInit;
05079 
05080   case OR_Ambiguous:
05081     S.Diag(Loc, diag::err_temp_copy_ambiguous)
05082       << (int)Entity.getKind() << CurInitExpr->getType()
05083       << CurInitExpr->getSourceRange();
05084     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
05085     return ExprError();
05086 
05087   case OR_Deleted:
05088     S.Diag(Loc, diag::err_temp_copy_deleted)
05089       << (int)Entity.getKind() << CurInitExpr->getType()
05090       << CurInitExpr->getSourceRange();
05091     S.NoteDeletedFunction(Best->Function);
05092     return ExprError();
05093   }
05094 
05095   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
05096   SmallVector<Expr*, 8> ConstructorArgs;
05097   CurInit.get(); // Ownership transferred into MultiExprArg, below.
05098 
05099   S.CheckConstructorAccess(Loc, Constructor, Entity,
05100                            Best->FoundDecl.getAccess(), IsExtraneousCopy);
05101 
05102   if (IsExtraneousCopy) {
05103     // If this is a totally extraneous copy for C++03 reference
05104     // binding purposes, just return the original initialization
05105     // expression. We don't generate an (elided) copy operation here
05106     // because doing so would require us to pass down a flag to avoid
05107     // infinite recursion, where each step adds another extraneous,
05108     // elidable copy.
05109 
05110     // Instantiate the default arguments of any extra parameters in
05111     // the selected copy constructor, as if we were going to create a
05112     // proper call to the copy constructor.
05113     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
05114       ParmVarDecl *Parm = Constructor->getParamDecl(I);
05115       if (S.RequireCompleteType(Loc, Parm->getType(),
05116                                 diag::err_call_incomplete_argument))
05117         break;
05118 
05119       // Build the default argument expression; we don't actually care
05120       // if this succeeds or not, because this routine will complain
05121       // if there was a problem.
05122       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
05123     }
05124 
05125     return CurInitExpr;
05126   }
05127 
05128   // Determine the arguments required to actually perform the
05129   // constructor call (we might have derived-to-base conversions, or
05130   // the copy constructor may have default arguments).
05131   if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
05132     return ExprError();
05133 
05134   // Actually perform the constructor call.
05135   CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
05136                                     ConstructorArgs,
05137                                     HadMultipleCandidates,
05138                                     /*ListInit*/ false,
05139                                     /*StdInitListInit*/ false,
05140                                     /*ZeroInit*/ false,
05141                                     CXXConstructExpr::CK_Complete,
05142                                     SourceRange());
05143 
05144   // If we're supposed to bind temporaries, do so.
05145   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
05146     CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
05147   return CurInit;
05148 }
05149 
05150 /// \brief Check whether elidable copy construction for binding a reference to
05151 /// a temporary would have succeeded if we were building in C++98 mode, for
05152 /// -Wc++98-compat.
05153 static void CheckCXX98CompatAccessibleCopy(Sema &S,
05154                                            const InitializedEntity &Entity,
05155                                            Expr *CurInitExpr) {
05156   assert(S.getLangOpts().CPlusPlus11);
05157 
05158   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
05159   if (!Record)
05160     return;
05161 
05162   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
05163   if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
05164     return;
05165 
05166   // Find constructors which would have been considered.
05167   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
05168   LookupCopyAndMoveConstructors(
05169       S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
05170 
05171   // Perform overload resolution.
05172   OverloadCandidateSet::iterator Best;
05173   OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
05174 
05175   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
05176     << OR << (int)Entity.getKind() << CurInitExpr->getType()
05177     << CurInitExpr->getSourceRange();
05178 
05179   switch (OR) {
05180   case OR_Success:
05181     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
05182                              Entity, Best->FoundDecl.getAccess(), Diag);
05183     // FIXME: Check default arguments as far as that's possible.
05184     break;
05185 
05186   case OR_No_Viable_Function:
05187     S.Diag(Loc, Diag);
05188     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
05189     break;
05190 
05191   case OR_Ambiguous:
05192     S.Diag(Loc, Diag);
05193     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
05194     break;
05195 
05196   case OR_Deleted:
05197     S.Diag(Loc, Diag);
05198     S.NoteDeletedFunction(Best->Function);
05199     break;
05200   }
05201 }
05202 
05203 void InitializationSequence::PrintInitLocationNote(Sema &S,
05204                                               const InitializedEntity &Entity) {
05205   if (Entity.isParameterKind() && Entity.getDecl()) {
05206     if (Entity.getDecl()->getLocation().isInvalid())
05207       return;
05208 
05209     if (Entity.getDecl()->getDeclName())
05210       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
05211         << Entity.getDecl()->getDeclName();
05212     else
05213       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
05214   }
05215   else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
05216            Entity.getMethodDecl())
05217     S.Diag(Entity.getMethodDecl()->getLocation(),
05218            diag::note_method_return_type_change)
05219       << Entity.getMethodDecl()->getDeclName();
05220 }
05221 
05222 static bool isReferenceBinding(const InitializationSequence::Step &s) {
05223   return s.Kind == InitializationSequence::SK_BindReference ||
05224          s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
05225 }
05226 
05227 /// Returns true if the parameters describe a constructor initialization of
05228 /// an explicit temporary object, e.g. "Point(x, y)".
05229 static bool isExplicitTemporary(const InitializedEntity &Entity,
05230                                 const InitializationKind &Kind,
05231                                 unsigned NumArgs) {
05232   switch (Entity.getKind()) {
05233   case InitializedEntity::EK_Temporary:
05234   case InitializedEntity::EK_CompoundLiteralInit:
05235   case InitializedEntity::EK_RelatedResult:
05236     break;
05237   default:
05238     return false;
05239   }
05240 
05241   switch (Kind.getKind()) {
05242   case InitializationKind::IK_DirectList:
05243     return true;
05244   // FIXME: Hack to work around cast weirdness.
05245   case InitializationKind::IK_Direct:
05246   case InitializationKind::IK_Value:
05247     return NumArgs != 1;
05248   default:
05249     return false;
05250   }
05251 }
05252 
05253 static ExprResult
05254 PerformConstructorInitialization(Sema &S,
05255                                  const InitializedEntity &Entity,
05256                                  const InitializationKind &Kind,
05257                                  MultiExprArg Args,
05258                                  const InitializationSequence::Step& Step,
05259                                  bool &ConstructorInitRequiresZeroInit,
05260                                  bool IsListInitialization,
05261                                  bool IsStdInitListInitialization,
05262                                  SourceLocation LBraceLoc,
05263                                  SourceLocation RBraceLoc) {
05264   unsigned NumArgs = Args.size();
05265   CXXConstructorDecl *Constructor
05266     = cast<CXXConstructorDecl>(Step.Function.Function);
05267   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
05268 
05269   // Build a call to the selected constructor.
05270   SmallVector<Expr*, 8> ConstructorArgs;
05271   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
05272                          ? Kind.getEqualLoc()
05273                          : Kind.getLocation();
05274 
05275   if (Kind.getKind() == InitializationKind::IK_Default) {
05276     // Force even a trivial, implicit default constructor to be
05277     // semantically checked. We do this explicitly because we don't build
05278     // the definition for completely trivial constructors.
05279     assert(Constructor->getParent() && "No parent class for constructor.");
05280     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
05281         Constructor->isTrivial() && !Constructor->isUsed(false))
05282       S.DefineImplicitDefaultConstructor(Loc, Constructor);
05283   }
05284 
05285   ExprResult CurInit((Expr *)nullptr);
05286 
05287   // C++ [over.match.copy]p1:
05288   //   - When initializing a temporary to be bound to the first parameter 
05289   //     of a constructor that takes a reference to possibly cv-qualified 
05290   //     T as its first argument, called with a single argument in the 
05291   //     context of direct-initialization, explicit conversion functions
05292   //     are also considered.
05293   bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
05294                            Args.size() == 1 && 
05295                            Constructor->isCopyOrMoveConstructor();
05296 
05297   // Determine the arguments required to actually perform the constructor
05298   // call.
05299   if (S.CompleteConstructorCall(Constructor, Args,
05300                                 Loc, ConstructorArgs,
05301                                 AllowExplicitConv,
05302                                 IsListInitialization))
05303     return ExprError();
05304 
05305 
05306   if (isExplicitTemporary(Entity, Kind, NumArgs)) {
05307     // An explicitly-constructed temporary, e.g., X(1, 2).
05308     S.MarkFunctionReferenced(Loc, Constructor);
05309     if (S.DiagnoseUseOfDecl(Constructor, Loc))
05310       return ExprError();
05311 
05312     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
05313     if (!TSInfo)
05314       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
05315     SourceRange ParenOrBraceRange =
05316       (Kind.getKind() == InitializationKind::IK_DirectList)
05317       ? SourceRange(LBraceLoc, RBraceLoc)
05318       : Kind.getParenRange();
05319 
05320     CurInit = new (S.Context) CXXTemporaryObjectExpr(
05321         S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
05322         HadMultipleCandidates, IsListInitialization,
05323         IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
05324   } else {
05325     CXXConstructExpr::ConstructionKind ConstructKind =
05326       CXXConstructExpr::CK_Complete;
05327 
05328     if (Entity.getKind() == InitializedEntity::EK_Base) {
05329       ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
05330         CXXConstructExpr::CK_VirtualBase :
05331         CXXConstructExpr::CK_NonVirtualBase;
05332     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
05333       ConstructKind = CXXConstructExpr::CK_Delegating;
05334     }
05335 
05336     // Only get the parenthesis or brace range if it is a list initialization or
05337     // direct construction.
05338     SourceRange ParenOrBraceRange;
05339     if (IsListInitialization)
05340       ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
05341     else if (Kind.getKind() == InitializationKind::IK_Direct)
05342       ParenOrBraceRange = Kind.getParenRange();
05343 
05344     // If the entity allows NRVO, mark the construction as elidable
05345     // unconditionally.
05346     if (Entity.allowsNRVO())
05347       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
05348                                         Constructor, /*Elidable=*/true,
05349                                         ConstructorArgs,
05350                                         HadMultipleCandidates,
05351                                         IsListInitialization,
05352                                         IsStdInitListInitialization,
05353                                         ConstructorInitRequiresZeroInit,
05354                                         ConstructKind,
05355                                         ParenOrBraceRange);
05356     else
05357       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
05358                                         Constructor,
05359                                         ConstructorArgs,
05360                                         HadMultipleCandidates,
05361                                         IsListInitialization,
05362                                         IsStdInitListInitialization,
05363                                         ConstructorInitRequiresZeroInit,
05364                                         ConstructKind,
05365                                         ParenOrBraceRange);
05366   }
05367   if (CurInit.isInvalid())
05368     return ExprError();
05369 
05370   // Only check access if all of that succeeded.
05371   S.CheckConstructorAccess(Loc, Constructor, Entity,
05372                            Step.Function.FoundDecl.getAccess());
05373   if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
05374     return ExprError();
05375 
05376   if (shouldBindAsTemporary(Entity))
05377     CurInit = S.MaybeBindToTemporary(CurInit.get());
05378 
05379   return CurInit;
05380 }
05381 
05382 /// Determine whether the specified InitializedEntity definitely has a lifetime
05383 /// longer than the current full-expression. Conservatively returns false if
05384 /// it's unclear.
05385 static bool
05386 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
05387   const InitializedEntity *Top = &Entity;
05388   while (Top->getParent())
05389     Top = Top->getParent();
05390 
05391   switch (Top->getKind()) {
05392   case InitializedEntity::EK_Variable:
05393   case InitializedEntity::EK_Result:
05394   case InitializedEntity::EK_Exception:
05395   case InitializedEntity::EK_Member:
05396   case InitializedEntity::EK_New:
05397   case InitializedEntity::EK_Base:
05398   case InitializedEntity::EK_Delegating:
05399     return true;
05400 
05401   case InitializedEntity::EK_ArrayElement:
05402   case InitializedEntity::EK_VectorElement:
05403   case InitializedEntity::EK_BlockElement:
05404   case InitializedEntity::EK_ComplexElement:
05405     // Could not determine what the full initialization is. Assume it might not
05406     // outlive the full-expression.
05407     return false;
05408 
05409   case InitializedEntity::EK_Parameter:
05410   case InitializedEntity::EK_Parameter_CF_Audited:
05411   case InitializedEntity::EK_Temporary:
05412   case InitializedEntity::EK_LambdaCapture:
05413   case InitializedEntity::EK_CompoundLiteralInit:
05414   case InitializedEntity::EK_RelatedResult:
05415     // The entity being initialized might not outlive the full-expression.
05416     return false;
05417   }
05418 
05419   llvm_unreachable("unknown entity kind");
05420 }
05421 
05422 /// Determine the declaration which an initialized entity ultimately refers to,
05423 /// for the purpose of lifetime-extending a temporary bound to a reference in
05424 /// the initialization of \p Entity.
05425 static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
05426     const InitializedEntity *Entity,
05427     const InitializedEntity *FallbackDecl = nullptr) {
05428   // C++11 [class.temporary]p5:
05429   switch (Entity->getKind()) {
05430   case InitializedEntity::EK_Variable:
05431     //   The temporary [...] persists for the lifetime of the reference
05432     return Entity;
05433 
05434   case InitializedEntity::EK_Member:
05435     // For subobjects, we look at the complete object.
05436     if (Entity->getParent())
05437       return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
05438                                                     Entity);
05439 
05440     //   except:
05441     //   -- A temporary bound to a reference member in a constructor's
05442     //      ctor-initializer persists until the constructor exits.
05443     return Entity;
05444 
05445   case InitializedEntity::EK_Parameter:
05446   case InitializedEntity::EK_Parameter_CF_Audited:
05447     //   -- A temporary bound to a reference parameter in a function call
05448     //      persists until the completion of the full-expression containing
05449     //      the call.
05450   case InitializedEntity::EK_Result:
05451     //   -- The lifetime of a temporary bound to the returned value in a
05452     //      function return statement is not extended; the temporary is
05453     //      destroyed at the end of the full-expression in the return statement.
05454   case InitializedEntity::EK_New:
05455     //   -- A temporary bound to a reference in a new-initializer persists
05456     //      until the completion of the full-expression containing the
05457     //      new-initializer.
05458     return nullptr;
05459 
05460   case InitializedEntity::EK_Temporary:
05461   case InitializedEntity::EK_CompoundLiteralInit:
05462   case InitializedEntity::EK_RelatedResult:
05463     // We don't yet know the storage duration of the surrounding temporary.
05464     // Assume it's got full-expression duration for now, it will patch up our
05465     // storage duration if that's not correct.
05466     return nullptr;
05467 
05468   case InitializedEntity::EK_ArrayElement:
05469     // For subobjects, we look at the complete object.
05470     return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
05471                                                   FallbackDecl);
05472 
05473   case InitializedEntity::EK_Base:
05474   case InitializedEntity::EK_Delegating:
05475     // We can reach this case for aggregate initialization in a constructor:
05476     //   struct A { int &&r; };
05477     //   struct B : A { B() : A{0} {} };
05478     // In this case, use the innermost field decl as the context.
05479     return FallbackDecl;
05480 
05481   case InitializedEntity::EK_BlockElement:
05482   case InitializedEntity::EK_LambdaCapture:
05483   case InitializedEntity::EK_Exception:
05484   case InitializedEntity::EK_VectorElement:
05485   case InitializedEntity::EK_ComplexElement:
05486     return nullptr;
05487   }
05488   llvm_unreachable("unknown entity kind");
05489 }
05490 
05491 static void performLifetimeExtension(Expr *Init,
05492                                      const InitializedEntity *ExtendingEntity);
05493 
05494 /// Update a glvalue expression that is used as the initializer of a reference
05495 /// to note that its lifetime is extended.
05496 /// \return \c true if any temporary had its lifetime extended.
05497 static bool
05498 performReferenceExtension(Expr *Init,
05499                           const InitializedEntity *ExtendingEntity) {
05500   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
05501     if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
05502       // This is just redundant braces around an initializer. Step over it.
05503       Init = ILE->getInit(0);
05504     }
05505   }
05506 
05507   // Walk past any constructs which we can lifetime-extend across.
05508   Expr *Old;
05509   do {
05510     Old = Init;
05511 
05512     // Step over any subobject adjustments; we may have a materialized
05513     // temporary inside them.
05514     SmallVector<const Expr *, 2> CommaLHSs;
05515     SmallVector<SubobjectAdjustment, 2> Adjustments;
05516     Init = const_cast<Expr *>(
05517         Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
05518 
05519     // Per current approach for DR1376, look through casts to reference type
05520     // when performing lifetime extension.
05521     if (CastExpr *CE = dyn_cast<CastExpr>(Init))
05522       if (CE->getSubExpr()->isGLValue())
05523         Init = CE->getSubExpr();
05524 
05525     // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
05526     // It's unclear if binding a reference to that xvalue extends the array
05527     // temporary.
05528   } while (Init != Old);
05529 
05530   if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
05531     // Update the storage duration of the materialized temporary.
05532     // FIXME: Rebuild the expression instead of mutating it.
05533     ME->setExtendingDecl(ExtendingEntity->getDecl(),
05534                          ExtendingEntity->allocateManglingNumber());
05535     performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
05536     return true;
05537   }
05538 
05539   return false;
05540 }
05541 
05542 /// Update a prvalue expression that is going to be materialized as a
05543 /// lifetime-extended temporary.
05544 static void performLifetimeExtension(Expr *Init,
05545                                      const InitializedEntity *ExtendingEntity) {
05546   // Dig out the expression which constructs the extended temporary.
05547   SmallVector<const Expr *, 2> CommaLHSs;
05548   SmallVector<SubobjectAdjustment, 2> Adjustments;
05549   Init = const_cast<Expr *>(
05550       Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
05551 
05552   if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
05553     Init = BTE->getSubExpr();
05554 
05555   if (CXXStdInitializerListExpr *ILE =
05556           dyn_cast<CXXStdInitializerListExpr>(Init)) {
05557     performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
05558     return;
05559   }
05560 
05561   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
05562     if (ILE->getType()->isArrayType()) {
05563       for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
05564         performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
05565       return;
05566     }
05567 
05568     if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
05569       assert(RD->isAggregate() && "aggregate init on non-aggregate");
05570 
05571       // If we lifetime-extend a braced initializer which is initializing an
05572       // aggregate, and that aggregate contains reference members which are
05573       // bound to temporaries, those temporaries are also lifetime-extended.
05574       if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
05575           ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
05576         performReferenceExtension(ILE->getInit(0), ExtendingEntity);
05577       else {
05578         unsigned Index = 0;
05579         for (const auto *I : RD->fields()) {
05580           if (Index >= ILE->getNumInits())
05581             break;
05582           if (I->isUnnamedBitfield())
05583             continue;
05584           Expr *SubInit = ILE->getInit(Index);
05585           if (I->getType()->isReferenceType())
05586             performReferenceExtension(SubInit, ExtendingEntity);
05587           else if (isa<InitListExpr>(SubInit) ||
05588                    isa<CXXStdInitializerListExpr>(SubInit))
05589             // This may be either aggregate-initialization of a member or
05590             // initialization of a std::initializer_list object. Either way,
05591             // we should recursively lifetime-extend that initializer.
05592             performLifetimeExtension(SubInit, ExtendingEntity);
05593           ++Index;
05594         }
05595       }
05596     }
05597   }
05598 }
05599 
05600 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
05601                                     const Expr *Init, bool IsInitializerList,
05602                                     const ValueDecl *ExtendingDecl) {
05603   // Warn if a field lifetime-extends a temporary.
05604   if (isa<FieldDecl>(ExtendingDecl)) {
05605     if (IsInitializerList) {
05606       S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
05607         << /*at end of constructor*/true;
05608       return;
05609     }
05610 
05611     bool IsSubobjectMember = false;
05612     for (const InitializedEntity *Ent = Entity.getParent(); Ent;
05613          Ent = Ent->getParent()) {
05614       if (Ent->getKind() != InitializedEntity::EK_Base) {
05615         IsSubobjectMember = true;
05616         break;
05617       }
05618     }
05619     S.Diag(Init->getExprLoc(),
05620            diag::warn_bind_ref_member_to_temporary)
05621       << ExtendingDecl << Init->getSourceRange()
05622       << IsSubobjectMember << IsInitializerList;
05623     if (IsSubobjectMember)
05624       S.Diag(ExtendingDecl->getLocation(),
05625              diag::note_ref_subobject_of_member_declared_here);
05626     else
05627       S.Diag(ExtendingDecl->getLocation(),
05628              diag::note_ref_or_ptr_member_declared_here)
05629         << /*is pointer*/false;
05630   }
05631 }
05632 
05633 static void DiagnoseNarrowingInInitList(Sema &S,
05634                                         const ImplicitConversionSequence &ICS,
05635                                         QualType PreNarrowingType,
05636                                         QualType EntityType,
05637                                         const Expr *PostInit);
05638 
05639 ExprResult
05640 InitializationSequence::Perform(Sema &S,
05641                                 const InitializedEntity &Entity,
05642                                 const InitializationKind &Kind,
05643                                 MultiExprArg Args,
05644                                 QualType *ResultType) {
05645   if (Failed()) {
05646     Diagnose(S, Entity, Kind, Args);
05647     return ExprError();
05648   }
05649 
05650   if (getKind() == DependentSequence) {
05651     // If the declaration is a non-dependent, incomplete array type
05652     // that has an initializer, then its type will be completed once
05653     // the initializer is instantiated.
05654     if (ResultType && !Entity.getType()->isDependentType() &&
05655         Args.size() == 1) {
05656       QualType DeclType = Entity.getType();
05657       if (const IncompleteArrayType *ArrayT
05658                            = S.Context.getAsIncompleteArrayType(DeclType)) {
05659         // FIXME: We don't currently have the ability to accurately
05660         // compute the length of an initializer list without
05661         // performing full type-checking of the initializer list
05662         // (since we have to determine where braces are implicitly
05663         // introduced and such).  So, we fall back to making the array
05664         // type a dependently-sized array type with no specified
05665         // bound.
05666         if (isa<InitListExpr>((Expr *)Args[0])) {
05667           SourceRange Brackets;
05668 
05669           // Scavange the location of the brackets from the entity, if we can.
05670           if (DeclaratorDecl *DD = Entity.getDecl()) {
05671             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
05672               TypeLoc TL = TInfo->getTypeLoc();
05673               if (IncompleteArrayTypeLoc ArrayLoc =
05674                       TL.getAs<IncompleteArrayTypeLoc>())
05675                 Brackets = ArrayLoc.getBracketsRange();
05676             }
05677           }
05678 
05679           *ResultType
05680             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
05681                                                    /*NumElts=*/nullptr,
05682                                                    ArrayT->getSizeModifier(),
05683                                        ArrayT->getIndexTypeCVRQualifiers(),
05684                                                    Brackets);
05685         }
05686 
05687       }
05688     }
05689     if (Kind.getKind() == InitializationKind::IK_Direct &&
05690         !Kind.isExplicitCast()) {
05691       // Rebuild the ParenListExpr.
05692       SourceRange ParenRange = Kind.getParenRange();
05693       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
05694                                   Args);
05695     }
05696     assert(Kind.getKind() == InitializationKind::IK_Copy ||
05697            Kind.isExplicitCast() || 
05698            Kind.getKind() == InitializationKind::IK_DirectList);
05699     return ExprResult(Args[0]);
05700   }
05701 
05702   // No steps means no initialization.
05703   if (Steps.empty())
05704     return ExprResult((Expr *)nullptr);
05705 
05706   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
05707       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
05708       !Entity.isParameterKind()) {
05709     // Produce a C++98 compatibility warning if we are initializing a reference
05710     // from an initializer list. For parameters, we produce a better warning
05711     // elsewhere.
05712     Expr *Init = Args[0];
05713     S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
05714       << Init->getSourceRange();
05715   }
05716 
05717   // Diagnose cases where we initialize a pointer to an array temporary, and the
05718   // pointer obviously outlives the temporary.
05719   if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
05720       Entity.getType()->isPointerType() &&
05721       InitializedEntityOutlivesFullExpression(Entity)) {
05722     Expr *Init = Args[0];
05723     Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
05724     if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
05725       S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
05726         << Init->getSourceRange();
05727   }
05728 
05729   QualType DestType = Entity.getType().getNonReferenceType();
05730   // FIXME: Ugly hack around the fact that Entity.getType() is not
05731   // the same as Entity.getDecl()->getType() in cases involving type merging,
05732   //  and we want latter when it makes sense.
05733   if (ResultType)
05734     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
05735                                      Entity.getType();
05736 
05737   ExprResult CurInit((Expr *)nullptr);
05738 
05739   // For initialization steps that start with a single initializer,
05740   // grab the only argument out the Args and place it into the "current"
05741   // initializer.
05742   switch (Steps.front().Kind) {
05743   case SK_ResolveAddressOfOverloadedFunction:
05744   case SK_CastDerivedToBaseRValue:
05745   case SK_CastDerivedToBaseXValue:
05746   case SK_CastDerivedToBaseLValue:
05747   case SK_BindReference:
05748   case SK_BindReferenceToTemporary:
05749   case SK_ExtraneousCopyToTemporary:
05750   case SK_UserConversion:
05751   case SK_QualificationConversionLValue:
05752   case SK_QualificationConversionXValue:
05753   case SK_QualificationConversionRValue:
05754   case SK_AtomicConversion:
05755   case SK_LValueToRValue:
05756   case SK_ConversionSequence:
05757   case SK_ConversionSequenceNoNarrowing:
05758   case SK_ListInitialization:
05759   case SK_UnwrapInitList:
05760   case SK_RewrapInitList:
05761   case SK_CAssignment:
05762   case SK_StringInit:
05763   case SK_ObjCObjectConversion:
05764   case SK_ArrayInit:
05765   case SK_ParenthesizedArrayInit:
05766   case SK_PassByIndirectCopyRestore:
05767   case SK_PassByIndirectRestore:
05768   case SK_ProduceObjCObject:
05769   case SK_StdInitializerList:
05770   case SK_OCLSamplerInit:
05771   case SK_OCLZeroEvent: {
05772     assert(Args.size() == 1);
05773     CurInit = Args[0];
05774     if (!CurInit.get()) return ExprError();
05775     break;
05776   }
05777 
05778   case SK_ConstructorInitialization:
05779   case SK_ConstructorInitializationFromList:
05780   case SK_StdInitializerListConstructorCall:
05781   case SK_ZeroInitialization:
05782     break;
05783   }
05784 
05785   // Walk through the computed steps for the initialization sequence,
05786   // performing the specified conversions along the way.
05787   bool ConstructorInitRequiresZeroInit = false;
05788   for (step_iterator Step = step_begin(), StepEnd = step_end();
05789        Step != StepEnd; ++Step) {
05790     if (CurInit.isInvalid())
05791       return ExprError();
05792 
05793     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
05794 
05795     switch (Step->Kind) {
05796     case SK_ResolveAddressOfOverloadedFunction:
05797       // Overload resolution determined which function invoke; update the
05798       // initializer to reflect that choice.
05799       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
05800       if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
05801         return ExprError();
05802       CurInit = S.FixOverloadedFunctionReference(CurInit,
05803                                                  Step->Function.FoundDecl,
05804                                                  Step->Function.Function);
05805       break;
05806 
05807     case SK_CastDerivedToBaseRValue:
05808     case SK_CastDerivedToBaseXValue:
05809     case SK_CastDerivedToBaseLValue: {
05810       // We have a derived-to-base cast that produces either an rvalue or an
05811       // lvalue. Perform that cast.
05812 
05813       CXXCastPath BasePath;
05814 
05815       // Casts to inaccessible base classes are allowed with C-style casts.
05816       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
05817       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
05818                                          CurInit.get()->getLocStart(),
05819                                          CurInit.get()->getSourceRange(),
05820                                          &BasePath, IgnoreBaseAccess))
05821         return ExprError();
05822 
05823       if (S.BasePathInvolvesVirtualBase(BasePath)) {
05824         QualType T = SourceType;
05825         if (const PointerType *Pointer = T->getAs<PointerType>())
05826           T = Pointer->getPointeeType();
05827         if (const RecordType *RecordTy = T->getAs<RecordType>())
05828           S.MarkVTableUsed(CurInit.get()->getLocStart(),
05829                            cast<CXXRecordDecl>(RecordTy->getDecl()));
05830       }
05831 
05832       ExprValueKind VK =
05833           Step->Kind == SK_CastDerivedToBaseLValue ?
05834               VK_LValue :
05835               (Step->Kind == SK_CastDerivedToBaseXValue ?
05836                    VK_XValue :
05837                    VK_RValue);
05838       CurInit =
05839           ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
05840                                    CurInit.get(), &BasePath, VK);
05841       break;
05842     }
05843 
05844     case SK_BindReference:
05845       // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
05846       if (CurInit.get()->refersToBitField()) {
05847         // We don't necessarily have an unambiguous source bit-field.
05848         FieldDecl *BitField = CurInit.get()->getSourceBitField();
05849         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
05850           << Entity.getType().isVolatileQualified()
05851           << (BitField ? BitField->getDeclName() : DeclarationName())
05852           << (BitField != nullptr)
05853           << CurInit.get()->getSourceRange();
05854         if (BitField)
05855           S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
05856 
05857         return ExprError();
05858       }
05859 
05860       if (CurInit.get()->refersToVectorElement()) {
05861         // References cannot bind to vector elements.
05862         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
05863           << Entity.getType().isVolatileQualified()
05864           << CurInit.get()->getSourceRange();
05865         PrintInitLocationNote(S, Entity);
05866         return ExprError();
05867       }
05868 
05869       // Reference binding does not have any corresponding ASTs.
05870 
05871       // Check exception specifications
05872       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
05873         return ExprError();
05874 
05875       // Even though we didn't materialize a temporary, the binding may still
05876       // extend the lifetime of a temporary. This happens if we bind a reference
05877       // to the result of a cast to reference type.
05878       if (const InitializedEntity *ExtendingEntity =
05879               getEntityForTemporaryLifetimeExtension(&Entity))
05880         if (performReferenceExtension(CurInit.get(), ExtendingEntity))
05881           warnOnLifetimeExtension(S, Entity, CurInit.get(),
05882                                   /*IsInitializerList=*/false,
05883                                   ExtendingEntity->getDecl());
05884 
05885       break;
05886 
05887     case SK_BindReferenceToTemporary: {
05888       // Make sure the "temporary" is actually an rvalue.
05889       assert(CurInit.get()->isRValue() && "not a temporary");
05890 
05891       // Check exception specifications
05892       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
05893         return ExprError();
05894 
05895       // Materialize the temporary into memory.
05896       MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
05897           Entity.getType().getNonReferenceType(), CurInit.get(),
05898           Entity.getType()->isLValueReferenceType());
05899 
05900       // Maybe lifetime-extend the temporary's subobjects to match the
05901       // entity's lifetime.
05902       if (const InitializedEntity *ExtendingEntity =
05903               getEntityForTemporaryLifetimeExtension(&Entity))
05904         if (performReferenceExtension(MTE, ExtendingEntity))
05905           warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
05906                                   ExtendingEntity->getDecl());
05907 
05908       // If we're binding to an Objective-C object that has lifetime, we
05909       // need cleanups. Likewise if we're extending this temporary to automatic
05910       // storage duration -- we need to register its cleanup during the
05911       // full-expression's cleanups.
05912       if ((S.getLangOpts().ObjCAutoRefCount &&
05913            MTE->getType()->isObjCLifetimeType()) ||
05914           (MTE->getStorageDuration() == SD_Automatic &&
05915            MTE->getType().isDestructedType()))
05916         S.ExprNeedsCleanups = true;
05917 
05918       CurInit = MTE;
05919       break;
05920     }
05921 
05922     case SK_ExtraneousCopyToTemporary:
05923       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
05924                            /*IsExtraneousCopy=*/true);
05925       break;
05926 
05927     case SK_UserConversion: {
05928       // We have a user-defined conversion that invokes either a constructor
05929       // or a conversion function.
05930       CastKind CastKind;
05931       bool IsCopy = false;
05932       FunctionDecl *Fn = Step->Function.Function;
05933       DeclAccessPair FoundFn = Step->Function.FoundDecl;
05934       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
05935       bool CreatedObject = false;
05936       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
05937         // Build a call to the selected constructor.
05938         SmallVector<Expr*, 8> ConstructorArgs;
05939         SourceLocation Loc = CurInit.get()->getLocStart();
05940         CurInit.get(); // Ownership transferred into MultiExprArg, below.
05941 
05942         // Determine the arguments required to actually perform the constructor
05943         // call.
05944         Expr *Arg = CurInit.get();
05945         if (S.CompleteConstructorCall(Constructor,
05946                                       MultiExprArg(&Arg, 1),
05947                                       Loc, ConstructorArgs))
05948           return ExprError();
05949 
05950         // Build an expression that constructs a temporary.
05951         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
05952                                           ConstructorArgs,
05953                                           HadMultipleCandidates,
05954                                           /*ListInit*/ false,
05955                                           /*StdInitListInit*/ false,
05956                                           /*ZeroInit*/ false,
05957                                           CXXConstructExpr::CK_Complete,
05958                                           SourceRange());
05959         if (CurInit.isInvalid())
05960           return ExprError();
05961 
05962         S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
05963                                  FoundFn.getAccess());
05964         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
05965           return ExprError();
05966 
05967         CastKind = CK_ConstructorConversion;
05968         QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
05969         if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
05970             S.IsDerivedFrom(SourceType, Class))
05971           IsCopy = true;
05972 
05973         CreatedObject = true;
05974       } else {
05975         // Build a call to the conversion function.
05976         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
05977         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
05978                                     FoundFn);
05979         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
05980           return ExprError();
05981 
05982         // FIXME: Should we move this initialization into a separate
05983         // derived-to-base conversion? I believe the answer is "no", because
05984         // we don't want to turn off access control here for c-style casts.
05985         ExprResult CurInitExprRes =
05986           S.PerformObjectArgumentInitialization(CurInit.get(),
05987                                                 /*Qualifier=*/nullptr,
05988                                                 FoundFn, Conversion);
05989         if(CurInitExprRes.isInvalid())
05990           return ExprError();
05991         CurInit = CurInitExprRes;
05992 
05993         // Build the actual call to the conversion function.
05994         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
05995                                            HadMultipleCandidates);
05996         if (CurInit.isInvalid() || !CurInit.get())
05997           return ExprError();
05998 
05999         CastKind = CK_UserDefinedConversion;
06000 
06001         CreatedObject = Conversion->getReturnType()->isRecordType();
06002       }
06003 
06004       bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
06005       bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
06006 
06007       if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
06008         QualType T = CurInit.get()->getType();
06009         if (const RecordType *Record = T->getAs<RecordType>()) {
06010           CXXDestructorDecl *Destructor
06011             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
06012           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
06013                                   S.PDiag(diag::err_access_dtor_temp) << T);
06014           S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
06015           if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
06016             return ExprError();
06017         }
06018       }
06019 
06020       CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
06021                                          CastKind, CurInit.get(), nullptr,
06022                                          CurInit.get()->getValueKind());
06023       if (MaybeBindToTemp)
06024         CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
06025       if (RequiresCopy)
06026         CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
06027                              CurInit, /*IsExtraneousCopy=*/false);
06028       break;
06029     }
06030 
06031     case SK_QualificationConversionLValue:
06032     case SK_QualificationConversionXValue:
06033     case SK_QualificationConversionRValue: {
06034       // Perform a qualification conversion; these can never go wrong.
06035       ExprValueKind VK =
06036           Step->Kind == SK_QualificationConversionLValue ?
06037               VK_LValue :
06038               (Step->Kind == SK_QualificationConversionXValue ?
06039                    VK_XValue :
06040                    VK_RValue);
06041       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
06042       break;
06043     }
06044 
06045     case SK_AtomicConversion: {
06046       assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
06047       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
06048                                     CK_NonAtomicToAtomic, VK_RValue);
06049       break;
06050     }
06051 
06052     case SK_LValueToRValue: {
06053       assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
06054       CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
06055                                          CK_LValueToRValue, CurInit.get(),
06056                                          /*BasePath=*/nullptr, VK_RValue);
06057       break;
06058     }
06059 
06060     case SK_ConversionSequence:
06061     case SK_ConversionSequenceNoNarrowing: {
06062       Sema::CheckedConversionKind CCK
06063         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
06064         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
06065         : Kind.isExplicitCast()? Sema::CCK_OtherCast
06066         : Sema::CCK_ImplicitConversion;
06067       ExprResult CurInitExprRes =
06068         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
06069                                     getAssignmentAction(Entity), CCK);
06070       if (CurInitExprRes.isInvalid())
06071         return ExprError();
06072       CurInit = CurInitExprRes;
06073 
06074       if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
06075           S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
06076         DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
06077                                     CurInit.get());
06078       break;
06079     }
06080 
06081     case SK_ListInitialization: {
06082       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
06083       // If we're not initializing the top-level entity, we need to create an
06084       // InitializeTemporary entity for our target type.
06085       QualType Ty = Step->Type;
06086       bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
06087       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
06088       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
06089       InitListChecker PerformInitList(S, InitEntity,
06090           InitList, Ty, /*VerifyOnly=*/false);
06091       if (PerformInitList.HadError())
06092         return ExprError();
06093 
06094       // Hack: We must update *ResultType if available in order to set the
06095       // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
06096       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
06097       if (ResultType &&
06098           ResultType->getNonReferenceType()->isIncompleteArrayType()) {
06099         if ((*ResultType)->isRValueReferenceType())
06100           Ty = S.Context.getRValueReferenceType(Ty);
06101         else if ((*ResultType)->isLValueReferenceType())
06102           Ty = S.Context.getLValueReferenceType(Ty,
06103             (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
06104         *ResultType = Ty;
06105       }
06106 
06107       InitListExpr *StructuredInitList =
06108           PerformInitList.getFullyStructuredList();
06109       CurInit.get();
06110       CurInit = shouldBindAsTemporary(InitEntity)
06111           ? S.MaybeBindToTemporary(StructuredInitList)
06112           : StructuredInitList;
06113       break;
06114     }
06115 
06116     case SK_ConstructorInitializationFromList: {
06117       // When an initializer list is passed for a parameter of type "reference
06118       // to object", we don't get an EK_Temporary entity, but instead an
06119       // EK_Parameter entity with reference type.
06120       // FIXME: This is a hack. What we really should do is create a user
06121       // conversion step for this case, but this makes it considerably more
06122       // complicated. For now, this will do.
06123       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
06124                                         Entity.getType().getNonReferenceType());
06125       bool UseTemporary = Entity.getType()->isReferenceType();
06126       assert(Args.size() == 1 && "expected a single argument for list init");
06127       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
06128       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
06129         << InitList->getSourceRange();
06130       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
06131       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
06132                                                                    Entity,
06133                                                  Kind, Arg, *Step,
06134                                                ConstructorInitRequiresZeroInit,
06135                                                /*IsListInitialization*/true,
06136                                                /*IsStdInitListInit*/false,
06137                                                InitList->getLBraceLoc(),
06138                                                InitList->getRBraceLoc());
06139       break;
06140     }
06141 
06142     case SK_UnwrapInitList:
06143       CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
06144       break;
06145 
06146     case SK_RewrapInitList: {
06147       Expr *E = CurInit.get();
06148       InitListExpr *Syntactic = Step->WrappingSyntacticList;
06149       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
06150           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
06151       ILE->setSyntacticForm(Syntactic);
06152       ILE->setType(E->getType());
06153       ILE->setValueKind(E->getValueKind());
06154       CurInit = ILE;
06155       break;
06156     }
06157 
06158     case SK_ConstructorInitialization:
06159     case SK_StdInitializerListConstructorCall: {
06160       // When an initializer list is passed for a parameter of type "reference
06161       // to object", we don't get an EK_Temporary entity, but instead an
06162       // EK_Parameter entity with reference type.
06163       // FIXME: This is a hack. What we really should do is create a user
06164       // conversion step for this case, but this makes it considerably more
06165       // complicated. For now, this will do.
06166       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
06167                                         Entity.getType().getNonReferenceType());
06168       bool UseTemporary = Entity.getType()->isReferenceType();
06169       bool IsStdInitListInit =
06170           Step->Kind == SK_StdInitializerListConstructorCall;
06171       CurInit = PerformConstructorInitialization(
06172           S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
06173           ConstructorInitRequiresZeroInit,
06174           /*IsListInitialization*/IsStdInitListInit,
06175           /*IsStdInitListInitialization*/IsStdInitListInit,
06176           /*LBraceLoc*/SourceLocation(),
06177           /*RBraceLoc*/SourceLocation());
06178       break;
06179     }
06180 
06181     case SK_ZeroInitialization: {
06182       step_iterator NextStep = Step;
06183       ++NextStep;
06184       if (NextStep != StepEnd &&
06185           (NextStep->Kind == SK_ConstructorInitialization ||
06186            NextStep->Kind == SK_ConstructorInitializationFromList)) {
06187         // The need for zero-initialization is recorded directly into
06188         // the call to the object's constructor within the next step.
06189         ConstructorInitRequiresZeroInit = true;
06190       } else if (Kind.getKind() == InitializationKind::IK_Value &&
06191                  S.getLangOpts().CPlusPlus &&
06192                  !Kind.isImplicitValueInit()) {
06193         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
06194         if (!TSInfo)
06195           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
06196                                                     Kind.getRange().getBegin());
06197 
06198         CurInit = new (S.Context) CXXScalarValueInitExpr(
06199             TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
06200             Kind.getRange().getEnd());
06201       } else {
06202         CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
06203       }
06204       break;
06205     }
06206 
06207     case SK_CAssignment: {
06208       QualType SourceType = CurInit.get()->getType();
06209       ExprResult Result = CurInit;
06210       Sema::AssignConvertType ConvTy =
06211         S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
06212             Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
06213       if (Result.isInvalid())
06214         return ExprError();
06215       CurInit = Result;
06216 
06217       // If this is a call, allow conversion to a transparent union.
06218       ExprResult CurInitExprRes = CurInit;
06219       if (ConvTy != Sema::Compatible &&
06220           Entity.isParameterKind() &&
06221           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
06222             == Sema::Compatible)
06223         ConvTy = Sema::Compatible;
06224       if (CurInitExprRes.isInvalid())
06225         return ExprError();
06226       CurInit = CurInitExprRes;
06227 
06228       bool Complained;
06229       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
06230                                      Step->Type, SourceType,
06231                                      CurInit.get(),
06232                                      getAssignmentAction(Entity, true),
06233                                      &Complained)) {
06234         PrintInitLocationNote(S, Entity);
06235         return ExprError();
06236       } else if (Complained)
06237         PrintInitLocationNote(S, Entity);
06238       break;
06239     }
06240 
06241     case SK_StringInit: {
06242       QualType Ty = Step->Type;
06243       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
06244                       S.Context.getAsArrayType(Ty), S);
06245       break;
06246     }
06247 
06248     case SK_ObjCObjectConversion:
06249       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
06250                           CK_ObjCObjectLValueCast,
06251                           CurInit.get()->getValueKind());
06252       break;
06253 
06254     case SK_ArrayInit:
06255       // Okay: we checked everything before creating this step. Note that
06256       // this is a GNU extension.
06257       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
06258         << Step->Type << CurInit.get()->getType()
06259         << CurInit.get()->getSourceRange();
06260 
06261       // If the destination type is an incomplete array type, update the
06262       // type accordingly.
06263       if (ResultType) {
06264         if (const IncompleteArrayType *IncompleteDest
06265                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
06266           if (const ConstantArrayType *ConstantSource
06267                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
06268             *ResultType = S.Context.getConstantArrayType(
06269                                              IncompleteDest->getElementType(),
06270                                              ConstantSource->getSize(),
06271                                              ArrayType::Normal, 0);
06272           }
06273         }
06274       }
06275       break;
06276 
06277     case SK_ParenthesizedArrayInit:
06278       // Okay: we checked everything before creating this step. Note that
06279       // this is a GNU extension.
06280       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
06281         << CurInit.get()->getSourceRange();
06282       break;
06283 
06284     case SK_PassByIndirectCopyRestore:
06285     case SK_PassByIndirectRestore:
06286       checkIndirectCopyRestoreSource(S, CurInit.get());
06287       CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
06288           CurInit.get(), Step->Type,
06289           Step->Kind == SK_PassByIndirectCopyRestore);
06290       break;
06291 
06292     case SK_ProduceObjCObject:
06293       CurInit =
06294           ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
06295                                    CurInit.get(), nullptr, VK_RValue);
06296       break;
06297 
06298     case SK_StdInitializerList: {
06299       S.Diag(CurInit.get()->getExprLoc(),
06300              diag::warn_cxx98_compat_initializer_list_init)
06301         << CurInit.get()->getSourceRange();
06302 
06303       // Materialize the temporary into memory.
06304       MaterializeTemporaryExpr *MTE = new (S.Context)
06305           MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
06306                                    /*BoundToLvalueReference=*/false);
06307 
06308       // Maybe lifetime-extend the array temporary's subobjects to match the
06309       // entity's lifetime.
06310       if (const InitializedEntity *ExtendingEntity =
06311               getEntityForTemporaryLifetimeExtension(&Entity))
06312         if (performReferenceExtension(MTE, ExtendingEntity))
06313           warnOnLifetimeExtension(S, Entity, CurInit.get(),
06314                                   /*IsInitializerList=*/true,
06315                                   ExtendingEntity->getDecl());
06316 
06317       // Wrap it in a construction of a std::initializer_list<T>.
06318       CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
06319 
06320       // Bind the result, in case the library has given initializer_list a
06321       // non-trivial destructor.
06322       if (shouldBindAsTemporary(Entity))
06323         CurInit = S.MaybeBindToTemporary(CurInit.get());
06324       break;
06325     }
06326 
06327     case SK_OCLSamplerInit: {
06328       assert(Step->Type->isSamplerT() && 
06329              "Sampler initialization on non-sampler type.");
06330 
06331       QualType SourceType = CurInit.get()->getType();
06332 
06333       if (Entity.isParameterKind()) {
06334         if (!SourceType->isSamplerT())
06335           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
06336             << SourceType;
06337       } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
06338         llvm_unreachable("Invalid EntityKind!");
06339       }
06340 
06341       break;
06342     }
06343     case SK_OCLZeroEvent: {
06344       assert(Step->Type->isEventT() && 
06345              "Event initialization on non-event type.");
06346 
06347       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
06348                                     CK_ZeroToOCLEvent,
06349                                     CurInit.get()->getValueKind());
06350       break;
06351     }
06352     }
06353   }
06354 
06355   // Diagnose non-fatal problems with the completed initialization.
06356   if (Entity.getKind() == InitializedEntity::EK_Member &&
06357       cast<FieldDecl>(Entity.getDecl())->isBitField())
06358     S.CheckBitFieldInitialization(Kind.getLocation(),
06359                                   cast<FieldDecl>(Entity.getDecl()),
06360                                   CurInit.get());
06361 
06362   return CurInit;
06363 }
06364 
06365 /// Somewhere within T there is an uninitialized reference subobject.
06366 /// Dig it out and diagnose it.
06367 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
06368                                            QualType T) {
06369   if (T->isReferenceType()) {
06370     S.Diag(Loc, diag::err_reference_without_init)
06371       << T.getNonReferenceType();
06372     return true;
06373   }
06374 
06375   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
06376   if (!RD || !RD->hasUninitializedReferenceMember())
06377     return false;
06378 
06379   for (const auto *FI : RD->fields()) {
06380     if (FI->isUnnamedBitfield())
06381       continue;
06382 
06383     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
06384       S.Diag(Loc, diag::note_value_initialization_here) << RD;
06385       return true;
06386     }
06387   }
06388 
06389   for (const auto &BI : RD->bases()) {
06390     if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
06391       S.Diag(Loc, diag::note_value_initialization_here) << RD;
06392       return true;
06393     }
06394   }
06395 
06396   return false;
06397 }
06398 
06399 
06400 //===----------------------------------------------------------------------===//
06401 // Diagnose initialization failures
06402 //===----------------------------------------------------------------------===//
06403 
06404 /// Emit notes associated with an initialization that failed due to a
06405 /// "simple" conversion failure.
06406 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
06407                                    Expr *op) {
06408   QualType destType = entity.getType();
06409   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
06410       op->getType()->isObjCObjectPointerType()) {
06411 
06412     // Emit a possible note about the conversion failing because the
06413     // operand is a message send with a related result type.
06414     S.EmitRelatedResultTypeNote(op);
06415 
06416     // Emit a possible note about a return failing because we're
06417     // expecting a related result type.
06418     if (entity.getKind() == InitializedEntity::EK_Result)
06419       S.EmitRelatedResultTypeNoteForReturn(destType);
06420   }
06421 }
06422 
06423 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
06424                              InitListExpr *InitList) {
06425   QualType DestType = Entity.getType();
06426 
06427   QualType E;
06428   if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
06429     QualType ArrayType = S.Context.getConstantArrayType(
06430         E.withConst(),
06431         llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
06432                     InitList->getNumInits()),
06433         clang::ArrayType::Normal, 0);
06434     InitializedEntity HiddenArray =
06435         InitializedEntity::InitializeTemporary(ArrayType);
06436     return diagnoseListInit(S, HiddenArray, InitList);
06437   }
06438 
06439   if (DestType->isReferenceType()) {
06440     // A list-initialization failure for a reference means that we tried to
06441     // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
06442     // inner initialization failed.
06443     QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
06444     diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
06445     SourceLocation Loc = InitList->getLocStart();
06446     if (auto *D = Entity.getDecl())
06447       Loc = D->getLocation();
06448     S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
06449     return;
06450   }
06451 
06452   InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
06453                                    /*VerifyOnly=*/false);
06454   assert(DiagnoseInitList.HadError() &&
06455          "Inconsistent init list check result.");
06456 }
06457 
06458 /// Prints a fixit for adding a null initializer for |Entity|. Call this only
06459 /// right after emitting a diagnostic.
06460 static void maybeEmitZeroInitializationFixit(Sema &S,
06461                                              InitializationSequence &Sequence,
06462                                              const InitializedEntity &Entity) {
06463   if (Entity.getKind() != InitializedEntity::EK_Variable)
06464     return;
06465 
06466   VarDecl *VD = cast<VarDecl>(Entity.getDecl());
06467   if (VD->getInit() || VD->getLocEnd().isMacroID())
06468     return;
06469 
06470   QualType VariableTy = VD->getType().getCanonicalType();
06471   SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
06472   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
06473 
06474   S.Diag(Loc, diag::note_add_initializer)
06475       << VD << FixItHint::CreateInsertion(Loc, Init);
06476 }
06477 
06478 bool InitializationSequence::Diagnose(Sema &S,
06479                                       const InitializedEntity &Entity,
06480                                       const InitializationKind &Kind,
06481                                       ArrayRef<Expr *> Args) {
06482   if (!Failed())
06483     return false;
06484 
06485   QualType DestType = Entity.getType();
06486   switch (Failure) {
06487   case FK_TooManyInitsForReference:
06488     // FIXME: Customize for the initialized entity?
06489     if (Args.empty()) {
06490       // Dig out the reference subobject which is uninitialized and diagnose it.
06491       // If this is value-initialization, this could be nested some way within
06492       // the target type.
06493       assert(Kind.getKind() == InitializationKind::IK_Value ||
06494              DestType->isReferenceType());
06495       bool Diagnosed =
06496         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
06497       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
06498       (void)Diagnosed;
06499     } else  // FIXME: diagnostic below could be better!
06500       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
06501         << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
06502     break;
06503 
06504   case FK_ArrayNeedsInitList:
06505     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
06506     break;
06507   case FK_ArrayNeedsInitListOrStringLiteral:
06508     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
06509     break;
06510   case FK_ArrayNeedsInitListOrWideStringLiteral:
06511     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
06512     break;
06513   case FK_NarrowStringIntoWideCharArray:
06514     S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
06515     break;
06516   case FK_WideStringIntoCharArray:
06517     S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
06518     break;
06519   case FK_IncompatWideStringIntoWideChar:
06520     S.Diag(Kind.getLocation(),
06521            diag::err_array_init_incompat_wide_string_into_wchar);
06522     break;
06523   case FK_ArrayTypeMismatch:
06524   case FK_NonConstantArrayInit:
06525     S.Diag(Kind.getLocation(),
06526            (Failure == FK_ArrayTypeMismatch
06527               ? diag::err_array_init_different_type
06528               : diag::err_array_init_non_constant_array))
06529       << DestType.getNonReferenceType()
06530       << Args[0]->getType()
06531       << Args[0]->getSourceRange();
06532     break;
06533 
06534   case FK_VariableLengthArrayHasInitializer:
06535     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
06536       << Args[0]->getSourceRange();
06537     break;
06538 
06539   case FK_AddressOfOverloadFailed: {
06540     DeclAccessPair Found;
06541     S.ResolveAddressOfOverloadedFunction(Args[0],
06542                                          DestType.getNonReferenceType(),
06543                                          true,
06544                                          Found);
06545     break;
06546   }
06547 
06548   case FK_ReferenceInitOverloadFailed:
06549   case FK_UserConversionOverloadFailed:
06550     switch (FailedOverloadResult) {
06551     case OR_Ambiguous:
06552       if (Failure == FK_UserConversionOverloadFailed)
06553         S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
06554           << Args[0]->getType() << DestType
06555           << Args[0]->getSourceRange();
06556       else
06557         S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
06558           << DestType << Args[0]->getType()
06559           << Args[0]->getSourceRange();
06560 
06561       FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
06562       break;
06563 
06564     case OR_No_Viable_Function:
06565       if (!S.RequireCompleteType(Kind.getLocation(),
06566                                  DestType.getNonReferenceType(),
06567                           diag::err_typecheck_nonviable_condition_incomplete,
06568                                Args[0]->getType(), Args[0]->getSourceRange()))
06569         S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
06570           << Args[0]->getType() << Args[0]->getSourceRange()
06571           << DestType.getNonReferenceType();
06572 
06573       FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
06574       break;
06575 
06576     case OR_Deleted: {
06577       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
06578         << Args[0]->getType() << DestType.getNonReferenceType()
06579         << Args[0]->getSourceRange();
06580       OverloadCandidateSet::iterator Best;
06581       OverloadingResult Ovl
06582         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
06583                                                 true);
06584       if (Ovl == OR_Deleted) {
06585         S.NoteDeletedFunction(Best->Function);
06586       } else {
06587         llvm_unreachable("Inconsistent overload resolution?");
06588       }
06589       break;
06590     }
06591 
06592     case OR_Success:
06593       llvm_unreachable("Conversion did not fail!");
06594     }
06595     break;
06596 
06597   case FK_NonConstLValueReferenceBindingToTemporary:
06598     if (isa<InitListExpr>(Args[0])) {
06599       S.Diag(Kind.getLocation(),
06600              diag::err_lvalue_reference_bind_to_initlist)
06601       << DestType.getNonReferenceType().isVolatileQualified()
06602       << DestType.getNonReferenceType()
06603       << Args[0]->getSourceRange();
06604       break;
06605     }
06606     // Intentional fallthrough
06607 
06608   case FK_NonConstLValueReferenceBindingToUnrelated:
06609     S.Diag(Kind.getLocation(),
06610            Failure == FK_NonConstLValueReferenceBindingToTemporary
06611              ? diag::err_lvalue_reference_bind_to_temporary
06612              : diag::err_lvalue_reference_bind_to_unrelated)
06613       << DestType.getNonReferenceType().isVolatileQualified()
06614       << DestType.getNonReferenceType()
06615       << Args[0]->getType()
06616       << Args[0]->getSourceRange();
06617     break;
06618 
06619   case FK_RValueReferenceBindingToLValue:
06620     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
06621       << DestType.getNonReferenceType() << Args[0]->getType()
06622       << Args[0]->getSourceRange();
06623     break;
06624 
06625   case FK_ReferenceInitDropsQualifiers:
06626     S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
06627       << DestType.getNonReferenceType()
06628       << Args[0]->getType()
06629       << Args[0]->getSourceRange();
06630     break;
06631 
06632   case FK_ReferenceInitFailed:
06633     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
06634       << DestType.getNonReferenceType()
06635       << Args[0]->isLValue()
06636       << Args[0]->getType()
06637       << Args[0]->getSourceRange();
06638     emitBadConversionNotes(S, Entity, Args[0]);
06639     break;
06640 
06641   case FK_ConversionFailed: {
06642     QualType FromType = Args[0]->getType();
06643     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
06644       << (int)Entity.getKind()
06645       << DestType
06646       << Args[0]->isLValue()
06647       << FromType
06648       << Args[0]->getSourceRange();
06649     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
06650     S.Diag(Kind.getLocation(), PDiag);
06651     emitBadConversionNotes(S, Entity, Args[0]);
06652     break;
06653   }
06654 
06655   case FK_ConversionFromPropertyFailed:
06656     // No-op. This error has already been reported.
06657     break;
06658 
06659   case FK_TooManyInitsForScalar: {
06660     SourceRange R;
06661 
06662     if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
06663       R = SourceRange(InitList->getInit(0)->getLocEnd(),
06664                       InitList->getLocEnd());
06665     else
06666       R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
06667 
06668     R.setBegin(S.getLocForEndOfToken(R.getBegin()));
06669     if (Kind.isCStyleOrFunctionalCast())
06670       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
06671         << R;
06672     else
06673       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
06674         << /*scalar=*/2 << R;
06675     break;
06676   }
06677 
06678   case FK_ReferenceBindingToInitList:
06679     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
06680       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
06681     break;
06682 
06683   case FK_InitListBadDestinationType:
06684     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
06685       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
06686     break;
06687 
06688   case FK_ListConstructorOverloadFailed:
06689   case FK_ConstructorOverloadFailed: {
06690     SourceRange ArgsRange;
06691     if (Args.size())
06692       ArgsRange = SourceRange(Args.front()->getLocStart(),
06693                               Args.back()->getLocEnd());
06694 
06695     if (Failure == FK_ListConstructorOverloadFailed) {
06696       assert(Args.size() == 1 &&
06697              "List construction from other than 1 argument.");
06698       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
06699       Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
06700     }
06701 
06702     // FIXME: Using "DestType" for the entity we're printing is probably
06703     // bad.
06704     switch (FailedOverloadResult) {
06705       case OR_Ambiguous:
06706         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
06707           << DestType << ArgsRange;
06708         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
06709         break;
06710 
06711       case OR_No_Viable_Function:
06712         if (Kind.getKind() == InitializationKind::IK_Default &&
06713             (Entity.getKind() == InitializedEntity::EK_Base ||
06714              Entity.getKind() == InitializedEntity::EK_Member) &&
06715             isa<CXXConstructorDecl>(S.CurContext)) {
06716           // This is implicit default initialization of a member or
06717           // base within a constructor. If no viable function was
06718           // found, notify the user that she needs to explicitly
06719           // initialize this base/member.
06720           CXXConstructorDecl *Constructor
06721             = cast<CXXConstructorDecl>(S.CurContext);
06722           if (Entity.getKind() == InitializedEntity::EK_Base) {
06723             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
06724               << (Constructor->getInheritedConstructor() ? 2 :
06725                   Constructor->isImplicit() ? 1 : 0)
06726               << S.Context.getTypeDeclType(Constructor->getParent())
06727               << /*base=*/0
06728               << Entity.getType();
06729 
06730             RecordDecl *BaseDecl
06731               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
06732                                                                   ->getDecl();
06733             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
06734               << S.Context.getTagDeclType(BaseDecl);
06735           } else {
06736             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
06737               << (Constructor->getInheritedConstructor() ? 2 :
06738                   Constructor->isImplicit() ? 1 : 0)
06739               << S.Context.getTypeDeclType(Constructor->getParent())
06740               << /*member=*/1
06741               << Entity.getName();
06742             S.Diag(Entity.getDecl()->getLocation(),
06743                    diag::note_member_declared_at);
06744 
06745             if (const RecordType *Record
06746                                  = Entity.getType()->getAs<RecordType>())
06747               S.Diag(Record->getDecl()->getLocation(),
06748                      diag::note_previous_decl)
06749                 << S.Context.getTagDeclType(Record->getDecl());
06750           }
06751           break;
06752         }
06753 
06754         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
06755           << DestType << ArgsRange;
06756         FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
06757         break;
06758 
06759       case OR_Deleted: {
06760         OverloadCandidateSet::iterator Best;
06761         OverloadingResult Ovl
06762           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
06763         if (Ovl != OR_Deleted) {
06764           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
06765             << true << DestType << ArgsRange;
06766           llvm_unreachable("Inconsistent overload resolution?");
06767           break;
06768         }
06769        
06770         // If this is a defaulted or implicitly-declared function, then
06771         // it was implicitly deleted. Make it clear that the deletion was
06772         // implicit.
06773         if (S.isImplicitlyDeleted(Best->Function))
06774           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
06775             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
06776             << DestType << ArgsRange;
06777         else
06778           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
06779             << true << DestType << ArgsRange;
06780 
06781         S.NoteDeletedFunction(Best->Function);
06782         break;
06783       }
06784 
06785       case OR_Success:
06786         llvm_unreachable("Conversion did not fail!");
06787     }
06788   }
06789   break;
06790 
06791   case FK_DefaultInitOfConst:
06792     if (Entity.getKind() == InitializedEntity::EK_Member &&
06793         isa<CXXConstructorDecl>(S.CurContext)) {
06794       // This is implicit default-initialization of a const member in
06795       // a constructor. Complain that it needs to be explicitly
06796       // initialized.
06797       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
06798       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
06799         << (Constructor->getInheritedConstructor() ? 2 :
06800             Constructor->isImplicit() ? 1 : 0)
06801         << S.Context.getTypeDeclType(Constructor->getParent())
06802         << /*const=*/1
06803         << Entity.getName();
06804       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
06805         << Entity.getName();
06806     } else {
06807       S.Diag(Kind.getLocation(), diag::err_default_init_const)
06808           << DestType << (bool)DestType->getAs<RecordType>();
06809       maybeEmitZeroInitializationFixit(S, *this, Entity);
06810     }
06811     break;
06812 
06813   case FK_Incomplete:
06814     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
06815                           diag::err_init_incomplete_type);
06816     break;
06817 
06818   case FK_ListInitializationFailed: {
06819     // Run the init list checker again to emit diagnostics.
06820     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
06821     diagnoseListInit(S, Entity, InitList);
06822     break;
06823   }
06824 
06825   case FK_PlaceholderType: {
06826     // FIXME: Already diagnosed!
06827     break;
06828   }
06829 
06830   case FK_ExplicitConstructor: {
06831     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
06832       << Args[0]->getSourceRange();
06833     OverloadCandidateSet::iterator Best;
06834     OverloadingResult Ovl
06835       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
06836     (void)Ovl;
06837     assert(Ovl == OR_Success && "Inconsistent overload resolution");
06838     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
06839     S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
06840     break;
06841   }
06842   }
06843 
06844   PrintInitLocationNote(S, Entity);
06845   return true;
06846 }
06847 
06848 void InitializationSequence::dump(raw_ostream &OS) const {
06849   switch (SequenceKind) {
06850   case FailedSequence: {
06851     OS << "Failed sequence: ";
06852     switch (Failure) {
06853     case FK_TooManyInitsForReference:
06854       OS << "too many initializers for reference";
06855       break;
06856 
06857     case FK_ArrayNeedsInitList:
06858       OS << "array requires initializer list";
06859       break;
06860 
06861     case FK_ArrayNeedsInitListOrStringLiteral:
06862       OS << "array requires initializer list or string literal";
06863       break;
06864 
06865     case FK_ArrayNeedsInitListOrWideStringLiteral:
06866       OS << "array requires initializer list or wide string literal";
06867       break;
06868 
06869     case FK_NarrowStringIntoWideCharArray:
06870       OS << "narrow string into wide char array";
06871       break;
06872 
06873     case FK_WideStringIntoCharArray:
06874       OS << "wide string into char array";
06875       break;
06876 
06877     case FK_IncompatWideStringIntoWideChar:
06878       OS << "incompatible wide string into wide char array";
06879       break;
06880 
06881     case FK_ArrayTypeMismatch:
06882       OS << "array type mismatch";
06883       break;
06884 
06885     case FK_NonConstantArrayInit:
06886       OS << "non-constant array initializer";
06887       break;
06888 
06889     case FK_AddressOfOverloadFailed:
06890       OS << "address of overloaded function failed";
06891       break;
06892 
06893     case FK_ReferenceInitOverloadFailed:
06894       OS << "overload resolution for reference initialization failed";
06895       break;
06896 
06897     case FK_NonConstLValueReferenceBindingToTemporary:
06898       OS << "non-const lvalue reference bound to temporary";
06899       break;
06900 
06901     case FK_NonConstLValueReferenceBindingToUnrelated:
06902       OS << "non-const lvalue reference bound to unrelated type";
06903       break;
06904 
06905     case FK_RValueReferenceBindingToLValue:
06906       OS << "rvalue reference bound to an lvalue";
06907       break;
06908 
06909     case FK_ReferenceInitDropsQualifiers:
06910       OS << "reference initialization drops qualifiers";
06911       break;
06912 
06913     case FK_ReferenceInitFailed:
06914       OS << "reference initialization failed";
06915       break;
06916 
06917     case FK_ConversionFailed:
06918       OS << "conversion failed";
06919       break;
06920 
06921     case FK_ConversionFromPropertyFailed:
06922       OS << "conversion from property failed";
06923       break;
06924 
06925     case FK_TooManyInitsForScalar:
06926       OS << "too many initializers for scalar";
06927       break;
06928 
06929     case FK_ReferenceBindingToInitList:
06930       OS << "referencing binding to initializer list";
06931       break;
06932 
06933     case FK_InitListBadDestinationType:
06934       OS << "initializer list for non-aggregate, non-scalar type";
06935       break;
06936 
06937     case FK_UserConversionOverloadFailed:
06938       OS << "overloading failed for user-defined conversion";
06939       break;
06940 
06941     case FK_ConstructorOverloadFailed:
06942       OS << "constructor overloading failed";
06943       break;
06944 
06945     case FK_DefaultInitOfConst:
06946       OS << "default initialization of a const variable";
06947       break;
06948 
06949     case FK_Incomplete:
06950       OS << "initialization of incomplete type";
06951       break;
06952 
06953     case FK_ListInitializationFailed:
06954       OS << "list initialization checker failure";
06955       break;
06956 
06957     case FK_VariableLengthArrayHasInitializer:
06958       OS << "variable length array has an initializer";
06959       break;
06960 
06961     case FK_PlaceholderType:
06962       OS << "initializer expression isn't contextually valid";
06963       break;
06964 
06965     case FK_ListConstructorOverloadFailed:
06966       OS << "list constructor overloading failed";
06967       break;
06968 
06969     case FK_ExplicitConstructor:
06970       OS << "list copy initialization chose explicit constructor";
06971       break;
06972     }
06973     OS << '\n';
06974     return;
06975   }
06976 
06977   case DependentSequence:
06978     OS << "Dependent sequence\n";
06979     return;
06980 
06981   case NormalSequence:
06982     OS << "Normal sequence: ";
06983     break;
06984   }
06985 
06986   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
06987     if (S != step_begin()) {
06988       OS << " -> ";
06989     }
06990 
06991     switch (S->Kind) {
06992     case SK_ResolveAddressOfOverloadedFunction:
06993       OS << "resolve address of overloaded function";
06994       break;
06995 
06996     case SK_CastDerivedToBaseRValue:
06997       OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
06998       break;
06999 
07000     case SK_CastDerivedToBaseXValue:
07001       OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
07002       break;
07003 
07004     case SK_CastDerivedToBaseLValue:
07005       OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
07006       break;
07007 
07008     case SK_BindReference:
07009       OS << "bind reference to lvalue";
07010       break;
07011 
07012     case SK_BindReferenceToTemporary:
07013       OS << "bind reference to a temporary";
07014       break;
07015 
07016     case SK_ExtraneousCopyToTemporary:
07017       OS << "extraneous C++03 copy to temporary";
07018       break;
07019 
07020     case SK_UserConversion:
07021       OS << "user-defined conversion via " << *S->Function.Function;
07022       break;
07023 
07024     case SK_QualificationConversionRValue:
07025       OS << "qualification conversion (rvalue)";
07026       break;
07027 
07028     case SK_QualificationConversionXValue:
07029       OS << "qualification conversion (xvalue)";
07030       break;
07031 
07032     case SK_QualificationConversionLValue:
07033       OS << "qualification conversion (lvalue)";
07034       break;
07035 
07036     case SK_AtomicConversion:
07037       OS << "non-atomic-to-atomic conversion";
07038       break;
07039 
07040     case SK_LValueToRValue:
07041       OS << "load (lvalue to rvalue)";
07042       break;
07043 
07044     case SK_ConversionSequence:
07045       OS << "implicit conversion sequence (";
07046       S->ICS->dump(); // FIXME: use OS
07047       OS << ")";
07048       break;
07049 
07050     case SK_ConversionSequenceNoNarrowing:
07051       OS << "implicit conversion sequence with narrowing prohibited (";
07052       S->ICS->dump(); // FIXME: use OS
07053       OS << ")";
07054       break;
07055 
07056     case SK_ListInitialization:
07057       OS << "list aggregate initialization";
07058       break;
07059 
07060     case SK_UnwrapInitList:
07061       OS << "unwrap reference initializer list";
07062       break;
07063 
07064     case SK_RewrapInitList:
07065       OS << "rewrap reference initializer list";
07066       break;
07067 
07068     case SK_ConstructorInitialization:
07069       OS << "constructor initialization";
07070       break;
07071 
07072     case SK_ConstructorInitializationFromList:
07073       OS << "list initialization via constructor";
07074       break;
07075 
07076     case SK_ZeroInitialization:
07077       OS << "zero initialization";
07078       break;
07079 
07080     case SK_CAssignment:
07081       OS << "C assignment";
07082       break;
07083 
07084     case SK_StringInit:
07085       OS << "string initialization";
07086       break;
07087 
07088     case SK_ObjCObjectConversion:
07089       OS << "Objective-C object conversion";
07090       break;
07091 
07092     case SK_ArrayInit:
07093       OS << "array initialization";
07094       break;
07095 
07096     case SK_ParenthesizedArrayInit:
07097       OS << "parenthesized array initialization";
07098       break;
07099 
07100     case SK_PassByIndirectCopyRestore:
07101       OS << "pass by indirect copy and restore";
07102       break;
07103 
07104     case SK_PassByIndirectRestore:
07105       OS << "pass by indirect restore";
07106       break;
07107 
07108     case SK_ProduceObjCObject:
07109       OS << "Objective-C object retension";
07110       break;
07111 
07112     case SK_StdInitializerList:
07113       OS << "std::initializer_list from initializer list";
07114       break;
07115 
07116     case SK_StdInitializerListConstructorCall:
07117       OS << "list initialization from std::initializer_list";
07118       break;
07119 
07120     case SK_OCLSamplerInit:
07121       OS << "OpenCL sampler_t from integer constant";
07122       break;
07123 
07124     case SK_OCLZeroEvent:
07125       OS << "OpenCL event_t from zero";
07126       break;
07127     }
07128 
07129     OS << " [" << S->Type.getAsString() << ']';
07130   }
07131 
07132   OS << '\n';
07133 }
07134 
07135 void InitializationSequence::dump() const {
07136   dump(llvm::errs());
07137 }
07138 
07139 static void DiagnoseNarrowingInInitList(Sema &S,
07140                                         const ImplicitConversionSequence &ICS,
07141                                         QualType PreNarrowingType,
07142                                         QualType EntityType,
07143                                         const Expr *PostInit) {
07144   const StandardConversionSequence *SCS = nullptr;
07145   switch (ICS.getKind()) {
07146   case ImplicitConversionSequence::StandardConversion:
07147     SCS = &ICS.Standard;
07148     break;
07149   case ImplicitConversionSequence::UserDefinedConversion:
07150     SCS = &ICS.UserDefined.After;
07151     break;
07152   case ImplicitConversionSequence::AmbiguousConversion:
07153   case ImplicitConversionSequence::EllipsisConversion:
07154   case ImplicitConversionSequence::BadConversion:
07155     return;
07156   }
07157 
07158   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
07159   APValue ConstantValue;
07160   QualType ConstantType;
07161   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
07162                                 ConstantType)) {
07163   case NK_Not_Narrowing:
07164     // No narrowing occurred.
07165     return;
07166 
07167   case NK_Type_Narrowing:
07168     // This was a floating-to-integer conversion, which is always considered a
07169     // narrowing conversion even if the value is a constant and can be
07170     // represented exactly as an integer.
07171     S.Diag(PostInit->getLocStart(),
07172            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
07173                ? diag::warn_init_list_type_narrowing
07174                : diag::ext_init_list_type_narrowing)
07175       << PostInit->getSourceRange()
07176       << PreNarrowingType.getLocalUnqualifiedType()
07177       << EntityType.getLocalUnqualifiedType();
07178     break;
07179 
07180   case NK_Constant_Narrowing:
07181     // A constant value was narrowed.
07182     S.Diag(PostInit->getLocStart(),
07183            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
07184                ? diag::warn_init_list_constant_narrowing
07185                : diag::ext_init_list_constant_narrowing)
07186       << PostInit->getSourceRange()
07187       << ConstantValue.getAsString(S.getASTContext(), ConstantType)
07188       << EntityType.getLocalUnqualifiedType();
07189     break;
07190 
07191   case NK_Variable_Narrowing:
07192     // A variable's value may have been narrowed.
07193     S.Diag(PostInit->getLocStart(),
07194            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
07195                ? diag::warn_init_list_variable_narrowing
07196                : diag::ext_init_list_variable_narrowing)
07197       << PostInit->getSourceRange()
07198       << PreNarrowingType.getLocalUnqualifiedType()
07199       << EntityType.getLocalUnqualifiedType();
07200     break;
07201   }
07202 
07203   SmallString<128> StaticCast;
07204   llvm::raw_svector_ostream OS(StaticCast);
07205   OS << "static_cast<";
07206   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
07207     // It's important to use the typedef's name if there is one so that the
07208     // fixit doesn't break code using types like int64_t.
07209     //
07210     // FIXME: This will break if the typedef requires qualification.  But
07211     // getQualifiedNameAsString() includes non-machine-parsable components.
07212     OS << *TT->getDecl();
07213   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
07214     OS << BT->getName(S.getLangOpts());
07215   else {
07216     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
07217     // with a broken cast.
07218     return;
07219   }
07220   OS << ">(";
07221   S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
07222       << PostInit->getSourceRange()
07223       << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
07224       << FixItHint::CreateInsertion(
07225              S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
07226 }
07227 
07228 //===----------------------------------------------------------------------===//
07229 // Initialization helper functions
07230 //===----------------------------------------------------------------------===//
07231 bool
07232 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
07233                                    ExprResult Init) {
07234   if (Init.isInvalid())
07235     return false;
07236 
07237   Expr *InitE = Init.get();
07238   assert(InitE && "No initialization expression");
07239 
07240   InitializationKind Kind
07241     = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
07242   InitializationSequence Seq(*this, Entity, Kind, InitE);
07243   return !Seq.Failed();
07244 }
07245 
07246 ExprResult
07247 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
07248                                 SourceLocation EqualLoc,
07249                                 ExprResult Init,
07250                                 bool TopLevelOfInitList,
07251                                 bool AllowExplicit) {
07252   if (Init.isInvalid())
07253     return ExprError();
07254 
07255   Expr *InitE = Init.get();
07256   assert(InitE && "No initialization expression?");
07257 
07258   if (EqualLoc.isInvalid())
07259     EqualLoc = InitE->getLocStart();
07260 
07261   InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
07262                                                            EqualLoc,
07263                                                            AllowExplicit);
07264   InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
07265   Init.get();
07266 
07267   ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
07268 
07269   return Result;
07270 }