1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for initializers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Designator.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <map>
27 using namespace clang;
28 
29 //===----------------------------------------------------------------------===//
30 // Sema Initialization Checking
31 //===----------------------------------------------------------------------===//
32 
33 static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34                           ASTContext &Context) {
35   if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36     return 0;
37 
38   // See if this is a string literal or @encode.
39   Init = Init->IgnoreParens();
40 
41   // Handle @encode, which is a narrow string.
42   if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
43     return Init;
44 
45   // Otherwise we can only handle string literals.
46   StringLiteral *SL = dyn_cast<StringLiteral>(Init);
47   if (SL == 0) return 0;
48 
49   QualType ElemTy = Context.getCanonicalType(AT->getElementType());
50 
51   switch (SL->getKind()) {
52   case StringLiteral::Ascii:
53   case StringLiteral::UTF8:
54     // char array can be initialized with a narrow string.
55     // Only allow char x[] = "foo";  not char x[] = L"foo";
56     return ElemTy->isCharType() ? Init : 0;
57   case StringLiteral::UTF16:
58     return ElemTy->isChar16Type() ? Init : 0;
59   case StringLiteral::UTF32:
60     return ElemTy->isChar32Type() ? Init : 0;
61   case StringLiteral::Wide:
62     // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63     // correction from DR343): "An array with element type compatible with a
64     // qualified or unqualified version of wchar_t may be initialized by a wide
65     // string literal, optionally enclosed in braces."
66     if (Context.typesAreCompatible(Context.getWCharType(),
67                                    ElemTy.getUnqualifiedType()))
68       return Init;
69 
70     return 0;
71   }
72 
73   llvm_unreachable("missed a StringLiteral kind?");
74 }
75 
76 static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77   const ArrayType *arrayType = Context.getAsArrayType(declType);
78   if (!arrayType) return 0;
79 
80   return IsStringInit(init, arrayType, Context);
81 }
82 
83 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84                             Sema &S) {
85   // Get the length of the string as parsed.
86   uint64_t StrLength =
87     cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
88 
89 
90   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
91     // C99 6.7.8p14. We have an array of character type with unknown size
92     // being initialized to a string literal.
93     llvm::APSInt ConstVal(32);
94     ConstVal = StrLength;
95     // Return a new array type (C99 6.7.8p22).
96     DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97                                            ConstVal,
98                                            ArrayType::Normal, 0);
99     return;
100   }
101 
102   const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
103 
104   // We have an array of character type with known size.  However,
105   // the size may be smaller or larger than the string we are initializing.
106   // FIXME: Avoid truncation for 64-bit length strings.
107   if (S.getLangOptions().CPlusPlus) {
108     if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109       // For Pascal strings it's OK to strip off the terminating null character,
110       // so the example below is valid:
111       //
112       // unsigned char a[2] = "\pa";
113       if (SL->isPascal())
114         StrLength--;
115     }
116 
117     // [dcl.init.string]p2
118     if (StrLength > CAT->getSize().getZExtValue())
119       S.Diag(Str->getSourceRange().getBegin(),
120              diag::err_initializer_string_for_char_array_too_long)
121         << Str->getSourceRange();
122   } else {
123     // C99 6.7.8p14.
124     if (StrLength-1 > CAT->getSize().getZExtValue())
125       S.Diag(Str->getSourceRange().getBegin(),
126              diag::warn_initializer_string_for_char_array_too_long)
127         << Str->getSourceRange();
128   }
129 
130   // Set the type to the actual size that we are initializing.  If we have
131   // something like:
132   //   char x[1] = "foo";
133   // then this will set the string literal's type to char[1].
134   Str->setType(DeclT);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Semantic checking for initializer lists.
139 //===----------------------------------------------------------------------===//
140 
141 /// @brief Semantic checking for initializer lists.
142 ///
143 /// The InitListChecker class contains a set of routines that each
144 /// handle the initialization of a certain kind of entity, e.g.,
145 /// arrays, vectors, struct/union types, scalars, etc. The
146 /// InitListChecker itself performs a recursive walk of the subobject
147 /// structure of the type to be initialized, while stepping through
148 /// the initializer list one element at a time. The IList and Index
149 /// parameters to each of the Check* routines contain the active
150 /// (syntactic) initializer list and the index into that initializer
151 /// list that represents the current initializer. Each routine is
152 /// responsible for moving that Index forward as it consumes elements.
153 ///
154 /// Each Check* routine also has a StructuredList/StructuredIndex
155 /// arguments, which contains the current "structured" (semantic)
156 /// initializer list and the index into that initializer list where we
157 /// are copying initializers as we map them over to the semantic
158 /// list. Once we have completed our recursive walk of the subobject
159 /// structure, we will have constructed a full semantic initializer
160 /// list.
161 ///
162 /// C99 designators cause changes in the initializer list traversal,
163 /// because they make the initialization "jump" into a specific
164 /// subobject and then continue the initialization from that
165 /// point. CheckDesignatedInitializer() recursively steps into the
166 /// designated subobject and manages backing out the recursion to
167 /// initialize the subobjects after the one designated.
168 namespace {
169 class InitListChecker {
170   Sema &SemaRef;
171   bool hadError;
172   bool VerifyOnly; // no diagnostics, no structure building
173   std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174   InitListExpr *FullyStructuredList;
175 
176   void CheckImplicitInitList(const InitializedEntity &Entity,
177                              InitListExpr *ParentIList, QualType T,
178                              unsigned &Index, InitListExpr *StructuredList,
179                              unsigned &StructuredIndex);
180   void CheckExplicitInitList(const InitializedEntity &Entity,
181                              InitListExpr *IList, QualType &T,
182                              unsigned &Index, InitListExpr *StructuredList,
183                              unsigned &StructuredIndex,
184                              bool TopLevelObject = false);
185   void CheckListElementTypes(const InitializedEntity &Entity,
186                              InitListExpr *IList, QualType &DeclType,
187                              bool SubobjectIsDesignatorContext,
188                              unsigned &Index,
189                              InitListExpr *StructuredList,
190                              unsigned &StructuredIndex,
191                              bool TopLevelObject = false);
192   void CheckSubElementType(const InitializedEntity &Entity,
193                            InitListExpr *IList, QualType ElemType,
194                            unsigned &Index,
195                            InitListExpr *StructuredList,
196                            unsigned &StructuredIndex);
197   void CheckComplexType(const InitializedEntity &Entity,
198                         InitListExpr *IList, QualType DeclType,
199                         unsigned &Index,
200                         InitListExpr *StructuredList,
201                         unsigned &StructuredIndex);
202   void CheckScalarType(const InitializedEntity &Entity,
203                        InitListExpr *IList, QualType DeclType,
204                        unsigned &Index,
205                        InitListExpr *StructuredList,
206                        unsigned &StructuredIndex);
207   void CheckReferenceType(const InitializedEntity &Entity,
208                           InitListExpr *IList, QualType DeclType,
209                           unsigned &Index,
210                           InitListExpr *StructuredList,
211                           unsigned &StructuredIndex);
212   void CheckVectorType(const InitializedEntity &Entity,
213                        InitListExpr *IList, QualType DeclType, unsigned &Index,
214                        InitListExpr *StructuredList,
215                        unsigned &StructuredIndex);
216   void CheckStructUnionTypes(const InitializedEntity &Entity,
217                              InitListExpr *IList, QualType DeclType,
218                              RecordDecl::field_iterator Field,
219                              bool SubobjectIsDesignatorContext, unsigned &Index,
220                              InitListExpr *StructuredList,
221                              unsigned &StructuredIndex,
222                              bool TopLevelObject = false);
223   void CheckArrayType(const InitializedEntity &Entity,
224                       InitListExpr *IList, QualType &DeclType,
225                       llvm::APSInt elementIndex,
226                       bool SubobjectIsDesignatorContext, unsigned &Index,
227                       InitListExpr *StructuredList,
228                       unsigned &StructuredIndex);
229   bool CheckDesignatedInitializer(const InitializedEntity &Entity,
230                                   InitListExpr *IList, DesignatedInitExpr *DIE,
231                                   unsigned DesigIdx,
232                                   QualType &CurrentObjectType,
233                                   RecordDecl::field_iterator *NextField,
234                                   llvm::APSInt *NextElementIndex,
235                                   unsigned &Index,
236                                   InitListExpr *StructuredList,
237                                   unsigned &StructuredIndex,
238                                   bool FinishSubobjectInit,
239                                   bool TopLevelObject);
240   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
241                                            QualType CurrentObjectType,
242                                            InitListExpr *StructuredList,
243                                            unsigned StructuredIndex,
244                                            SourceRange InitRange);
245   void UpdateStructuredListElement(InitListExpr *StructuredList,
246                                    unsigned &StructuredIndex,
247                                    Expr *expr);
248   int numArrayElements(QualType DeclType);
249   int numStructUnionElements(QualType DeclType);
250 
251   void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252                                const InitializedEntity &ParentEntity,
253                                InitListExpr *ILE, bool &RequiresSecondPass);
254   void FillInValueInitializations(const InitializedEntity &Entity,
255                                   InitListExpr *ILE, bool &RequiresSecondPass);
256   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257                               Expr *InitExpr, FieldDecl *Field,
258                               bool TopLevelObject);
259 public:
260   InitListChecker(Sema &S, const InitializedEntity &Entity,
261                   InitListExpr *IL, QualType &T, bool VerifyOnly);
262   bool HadError() { return hadError; }
263 
264   // @brief Retrieves the fully-structured initializer list used for
265   // semantic analysis and code generation.
266   InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
267 };
268 } // end anonymous namespace
269 
270 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
271                                         const InitializedEntity &ParentEntity,
272                                               InitListExpr *ILE,
273                                               bool &RequiresSecondPass) {
274   SourceLocation Loc = ILE->getSourceRange().getBegin();
275   unsigned NumInits = ILE->getNumInits();
276   InitializedEntity MemberEntity
277     = InitializedEntity::InitializeMember(Field, &ParentEntity);
278   if (Init >= NumInits || !ILE->getInit(Init)) {
279     // FIXME: We probably don't need to handle references
280     // specially here, since value-initialization of references is
281     // handled in InitializationSequence.
282     if (Field->getType()->isReferenceType()) {
283       // C++ [dcl.init.aggr]p9:
284       //   If an incomplete or empty initializer-list leaves a
285       //   member of reference type uninitialized, the program is
286       //   ill-formed.
287       SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
288         << Field->getType()
289         << ILE->getSyntacticForm()->getSourceRange();
290       SemaRef.Diag(Field->getLocation(),
291                    diag::note_uninit_reference_member);
292       hadError = true;
293       return;
294     }
295 
296     InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
297                                                               true);
298     InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
299     if (!InitSeq) {
300       InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
301       hadError = true;
302       return;
303     }
304 
305     ExprResult MemberInit
306       = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
307     if (MemberInit.isInvalid()) {
308       hadError = true;
309       return;
310     }
311 
312     if (hadError) {
313       // Do nothing
314     } else if (Init < NumInits) {
315       ILE->setInit(Init, MemberInit.takeAs<Expr>());
316     } else if (InitSeq.isConstructorInitialization()) {
317       // Value-initialization requires a constructor call, so
318       // extend the initializer list to include the constructor
319       // call and make a note that we'll need to take another pass
320       // through the initializer list.
321       ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
322       RequiresSecondPass = true;
323     }
324   } else if (InitListExpr *InnerILE
325                = dyn_cast<InitListExpr>(ILE->getInit(Init)))
326     FillInValueInitializations(MemberEntity, InnerILE,
327                                RequiresSecondPass);
328 }
329 
330 /// Recursively replaces NULL values within the given initializer list
331 /// with expressions that perform value-initialization of the
332 /// appropriate type.
333 void
334 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
335                                             InitListExpr *ILE,
336                                             bool &RequiresSecondPass) {
337   assert((ILE->getType() != SemaRef.Context.VoidTy) &&
338          "Should not have void type");
339   SourceLocation Loc = ILE->getSourceRange().getBegin();
340   if (ILE->getSyntacticForm())
341     Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
342 
343   if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
344     if (RType->getDecl()->isUnion() &&
345         ILE->getInitializedFieldInUnion())
346       FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347                               Entity, ILE, RequiresSecondPass);
348     else {
349       unsigned Init = 0;
350       for (RecordDecl::field_iterator
351              Field = RType->getDecl()->field_begin(),
352              FieldEnd = RType->getDecl()->field_end();
353            Field != FieldEnd; ++Field) {
354         if (Field->isUnnamedBitfield())
355           continue;
356 
357         if (hadError)
358           return;
359 
360         FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
361         if (hadError)
362           return;
363 
364         ++Init;
365 
366         // Only look at the first initialization of a union.
367         if (RType->getDecl()->isUnion())
368           break;
369       }
370     }
371 
372     return;
373   }
374 
375   QualType ElementType;
376 
377   InitializedEntity ElementEntity = Entity;
378   unsigned NumInits = ILE->getNumInits();
379   unsigned NumElements = NumInits;
380   if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
381     ElementType = AType->getElementType();
382     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383       NumElements = CAType->getSize().getZExtValue();
384     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
385                                                          0, Entity);
386   } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
387     ElementType = VType->getElementType();
388     NumElements = VType->getNumElements();
389     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
390                                                          0, Entity);
391   } else
392     ElementType = ILE->getType();
393 
394 
395   for (unsigned Init = 0; Init != NumElements; ++Init) {
396     if (hadError)
397       return;
398 
399     if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400         ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
401       ElementEntity.setElementIndex(Init);
402 
403     if (Init >= NumInits || !ILE->getInit(Init)) {
404       InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
405                                                                 true);
406       InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
407       if (!InitSeq) {
408         InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
409         hadError = true;
410         return;
411       }
412 
413       ExprResult ElementInit
414         = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
415       if (ElementInit.isInvalid()) {
416         hadError = true;
417         return;
418       }
419 
420       if (hadError) {
421         // Do nothing
422       } else if (Init < NumInits) {
423         // For arrays, just set the expression used for value-initialization
424         // of the "holes" in the array.
425         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
426           ILE->setArrayFiller(ElementInit.takeAs<Expr>());
427         else
428           ILE->setInit(Init, ElementInit.takeAs<Expr>());
429       } else {
430         // For arrays, just set the expression used for value-initialization
431         // of the rest of elements and exit.
432         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
433           ILE->setArrayFiller(ElementInit.takeAs<Expr>());
434           return;
435         }
436 
437         if (InitSeq.isConstructorInitialization()) {
438           // Value-initialization requires a constructor call, so
439           // extend the initializer list to include the constructor
440           // call and make a note that we'll need to take another pass
441           // through the initializer list.
442           ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
443           RequiresSecondPass = true;
444         }
445       }
446     } else if (InitListExpr *InnerILE
447                  = dyn_cast<InitListExpr>(ILE->getInit(Init)))
448       FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
449   }
450 }
451 
452 
453 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
454                                  InitListExpr *IL, QualType &T,
455                                  bool VerifyOnly)
456   : SemaRef(S), VerifyOnly(VerifyOnly) {
457   hadError = false;
458 
459   unsigned newIndex = 0;
460   unsigned newStructuredIndex = 0;
461   FullyStructuredList
462     = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
463   CheckExplicitInitList(Entity, IL, T, newIndex,
464                         FullyStructuredList, newStructuredIndex,
465                         /*TopLevelObject=*/true);
466 
467   if (!hadError && !VerifyOnly) {
468     bool RequiresSecondPass = false;
469     FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
470     if (RequiresSecondPass && !hadError)
471       FillInValueInitializations(Entity, FullyStructuredList,
472                                  RequiresSecondPass);
473   }
474 }
475 
476 int InitListChecker::numArrayElements(QualType DeclType) {
477   // FIXME: use a proper constant
478   int maxElements = 0x7FFFFFFF;
479   if (const ConstantArrayType *CAT =
480         SemaRef.Context.getAsConstantArrayType(DeclType)) {
481     maxElements = static_cast<int>(CAT->getSize().getZExtValue());
482   }
483   return maxElements;
484 }
485 
486 int InitListChecker::numStructUnionElements(QualType DeclType) {
487   RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
488   int InitializableMembers = 0;
489   for (RecordDecl::field_iterator
490          Field = structDecl->field_begin(),
491          FieldEnd = structDecl->field_end();
492        Field != FieldEnd; ++Field) {
493     if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494       ++InitializableMembers;
495   }
496   if (structDecl->isUnion())
497     return std::min(InitializableMembers, 1);
498   return InitializableMembers - structDecl->hasFlexibleArrayMember();
499 }
500 
501 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
502                                             InitListExpr *ParentIList,
503                                             QualType T, unsigned &Index,
504                                             InitListExpr *StructuredList,
505                                             unsigned &StructuredIndex) {
506   int maxElements = 0;
507 
508   if (T->isArrayType())
509     maxElements = numArrayElements(T);
510   else if (T->isRecordType())
511     maxElements = numStructUnionElements(T);
512   else if (T->isVectorType())
513     maxElements = T->getAs<VectorType>()->getNumElements();
514   else
515     llvm_unreachable("CheckImplicitInitList(): Illegal type");
516 
517   if (maxElements == 0) {
518     if (!VerifyOnly)
519       SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
520                    diag::err_implicit_empty_initializer);
521     ++Index;
522     hadError = true;
523     return;
524   }
525 
526   // Build a structured initializer list corresponding to this subobject.
527   InitListExpr *StructuredSubobjectInitList
528     = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
529                                  StructuredIndex,
530           SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
531                       ParentIList->getSourceRange().getEnd()));
532   unsigned StructuredSubobjectInitIndex = 0;
533 
534   // Check the element types and build the structural subobject.
535   unsigned StartIndex = Index;
536   CheckListElementTypes(Entity, ParentIList, T,
537                         /*SubobjectIsDesignatorContext=*/false, Index,
538                         StructuredSubobjectInitList,
539                         StructuredSubobjectInitIndex);
540   unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
541   if (!VerifyOnly) {
542     StructuredSubobjectInitList->setType(T);
543 
544     // Update the structured sub-object initializer so that it's ending
545     // range corresponds with the end of the last initializer it used.
546     if (EndIndex < ParentIList->getNumInits()) {
547       SourceLocation EndLoc
548         = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
549       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
550     }
551 
552     // Warn about missing braces.
553     if (T->isArrayType() || T->isRecordType()) {
554       SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
555                    diag::warn_missing_braces)
556         << StructuredSubobjectInitList->getSourceRange()
557         << FixItHint::CreateInsertion(
558               StructuredSubobjectInitList->getLocStart(), "{")
559         << FixItHint::CreateInsertion(
560               SemaRef.PP.getLocForEndOfToken(
561                                       StructuredSubobjectInitList->getLocEnd()),
562               "}");
563     }
564   }
565 }
566 
567 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
568                                             InitListExpr *IList, QualType &T,
569                                             unsigned &Index,
570                                             InitListExpr *StructuredList,
571                                             unsigned &StructuredIndex,
572                                             bool TopLevelObject) {
573   assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
574   if (!VerifyOnly) {
575     SyntacticToSemantic[IList] = StructuredList;
576     StructuredList->setSyntacticForm(IList);
577   }
578   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
579                         Index, StructuredList, StructuredIndex, TopLevelObject);
580   if (!VerifyOnly) {
581     QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
582     IList->setType(ExprTy);
583     StructuredList->setType(ExprTy);
584   }
585   if (hadError)
586     return;
587 
588   if (Index < IList->getNumInits()) {
589     // We have leftover initializers
590     if (VerifyOnly) {
591       if (SemaRef.getLangOptions().CPlusPlus ||
592           (SemaRef.getLangOptions().OpenCL &&
593            IList->getType()->isVectorType())) {
594         hadError = true;
595       }
596       return;
597     }
598 
599     if (StructuredIndex == 1 &&
600         IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
601       unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
602       if (SemaRef.getLangOptions().CPlusPlus) {
603         DK = diag::err_excess_initializers_in_char_array_initializer;
604         hadError = true;
605       }
606       // Special-case
607       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
608         << IList->getInit(Index)->getSourceRange();
609     } else if (!T->isIncompleteType()) {
610       // Don't complain for incomplete types, since we'll get an error
611       // elsewhere
612       QualType CurrentObjectType = StructuredList->getType();
613       int initKind =
614         CurrentObjectType->isArrayType()? 0 :
615         CurrentObjectType->isVectorType()? 1 :
616         CurrentObjectType->isScalarType()? 2 :
617         CurrentObjectType->isUnionType()? 3 :
618         4;
619 
620       unsigned DK = diag::warn_excess_initializers;
621       if (SemaRef.getLangOptions().CPlusPlus) {
622         DK = diag::err_excess_initializers;
623         hadError = true;
624       }
625       if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
626         DK = diag::err_excess_initializers;
627         hadError = true;
628       }
629 
630       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
631         << initKind << IList->getInit(Index)->getSourceRange();
632     }
633   }
634 
635   if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
636       !TopLevelObject)
637     SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
638       << IList->getSourceRange()
639       << FixItHint::CreateRemoval(IList->getLocStart())
640       << FixItHint::CreateRemoval(IList->getLocEnd());
641 }
642 
643 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
644                                             InitListExpr *IList,
645                                             QualType &DeclType,
646                                             bool SubobjectIsDesignatorContext,
647                                             unsigned &Index,
648                                             InitListExpr *StructuredList,
649                                             unsigned &StructuredIndex,
650                                             bool TopLevelObject) {
651   if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
652     // Explicitly braced initializer for complex type can be real+imaginary
653     // parts.
654     CheckComplexType(Entity, IList, DeclType, Index,
655                      StructuredList, StructuredIndex);
656   } else if (DeclType->isScalarType()) {
657     CheckScalarType(Entity, IList, DeclType, Index,
658                     StructuredList, StructuredIndex);
659   } else if (DeclType->isVectorType()) {
660     CheckVectorType(Entity, IList, DeclType, Index,
661                     StructuredList, StructuredIndex);
662   } else if (DeclType->isAggregateType()) {
663     if (DeclType->isRecordType()) {
664       RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
665       CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
666                             SubobjectIsDesignatorContext, Index,
667                             StructuredList, StructuredIndex,
668                             TopLevelObject);
669     } else if (DeclType->isArrayType()) {
670       llvm::APSInt Zero(
671                       SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
672                       false);
673       CheckArrayType(Entity, IList, DeclType, Zero,
674                      SubobjectIsDesignatorContext, Index,
675                      StructuredList, StructuredIndex);
676     } else
677       llvm_unreachable("Aggregate that isn't a structure or array?!");
678   } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
679     // This type is invalid, issue a diagnostic.
680     ++Index;
681     if (!VerifyOnly)
682       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
683         << DeclType;
684     hadError = true;
685   } else if (DeclType->isRecordType()) {
686     // C++ [dcl.init]p14:
687     //   [...] If the class is an aggregate (8.5.1), and the initializer
688     //   is a brace-enclosed list, see 8.5.1.
689     //
690     // Note: 8.5.1 is handled below; here, we diagnose the case where
691     // we have an initializer list and a destination type that is not
692     // an aggregate.
693     // FIXME: In C++0x, this is yet another form of initialization.
694     if (!VerifyOnly)
695       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
696         << DeclType << IList->getSourceRange();
697     hadError = true;
698   } else if (DeclType->isReferenceType()) {
699     CheckReferenceType(Entity, IList, DeclType, Index,
700                        StructuredList, StructuredIndex);
701   } else if (DeclType->isObjCObjectType()) {
702     if (!VerifyOnly)
703       SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
704         << DeclType;
705     hadError = true;
706   } else {
707     if (!VerifyOnly)
708       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709         << DeclType;
710     hadError = true;
711   }
712 }
713 
714 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
715                                           InitListExpr *IList,
716                                           QualType ElemType,
717                                           unsigned &Index,
718                                           InitListExpr *StructuredList,
719                                           unsigned &StructuredIndex) {
720   Expr *expr = IList->getInit(Index);
721   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
722     unsigned newIndex = 0;
723     unsigned newStructuredIndex = 0;
724     InitListExpr *newStructuredList
725       = getStructuredSubobjectInit(IList, Index, ElemType,
726                                    StructuredList, StructuredIndex,
727                                    SubInitList->getSourceRange());
728     CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
729                           newStructuredList, newStructuredIndex);
730     ++StructuredIndex;
731     ++Index;
732     return;
733   } else if (ElemType->isScalarType()) {
734     return CheckScalarType(Entity, IList, ElemType, Index,
735                            StructuredList, StructuredIndex);
736   } else if (ElemType->isReferenceType()) {
737     return CheckReferenceType(Entity, IList, ElemType, Index,
738                               StructuredList, StructuredIndex);
739   }
740 
741   if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
742     // arrayType can be incomplete if we're initializing a flexible
743     // array member.  There's nothing we can do with the completed
744     // type here, though.
745 
746     if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
747       if (!VerifyOnly) {
748         CheckStringInit(Str, ElemType, arrayType, SemaRef);
749         UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
750       }
751       ++Index;
752       return;
753     }
754 
755     // Fall through for subaggregate initialization.
756 
757   } else if (SemaRef.getLangOptions().CPlusPlus) {
758     // C++ [dcl.init.aggr]p12:
759     //   All implicit type conversions (clause 4) are considered when
760     //   initializing the aggregate member with an initializer from
761     //   an initializer-list. If the initializer can initialize a
762     //   member, the member is initialized. [...]
763 
764     // FIXME: Better EqualLoc?
765     InitializationKind Kind =
766       InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
767     InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
768 
769     if (Seq) {
770       if (!VerifyOnly) {
771         ExprResult Result =
772           Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
773         if (Result.isInvalid())
774           hadError = true;
775 
776         UpdateStructuredListElement(StructuredList, StructuredIndex,
777                                     Result.takeAs<Expr>());
778       }
779       ++Index;
780       return;
781     }
782 
783     // Fall through for subaggregate initialization
784   } else {
785     // C99 6.7.8p13:
786     //
787     //   The initializer for a structure or union object that has
788     //   automatic storage duration shall be either an initializer
789     //   list as described below, or a single expression that has
790     //   compatible structure or union type. In the latter case, the
791     //   initial value of the object, including unnamed members, is
792     //   that of the expression.
793     ExprResult ExprRes = SemaRef.Owned(expr);
794     if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
795         SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
796                                                  !VerifyOnly)
797           == Sema::Compatible) {
798       if (ExprRes.isInvalid())
799         hadError = true;
800       else {
801         ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
802 	      if (ExprRes.isInvalid())
803 	        hadError = true;
804       }
805       UpdateStructuredListElement(StructuredList, StructuredIndex,
806                                   ExprRes.takeAs<Expr>());
807       ++Index;
808       return;
809     }
810     ExprRes.release();
811     // Fall through for subaggregate initialization
812   }
813 
814   // C++ [dcl.init.aggr]p12:
815   //
816   //   [...] Otherwise, if the member is itself a non-empty
817   //   subaggregate, brace elision is assumed and the initializer is
818   //   considered for the initialization of the first member of
819   //   the subaggregate.
820   if (!SemaRef.getLangOptions().OpenCL &&
821       (ElemType->isAggregateType() || ElemType->isVectorType())) {
822     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
823                           StructuredIndex);
824     ++StructuredIndex;
825   } else {
826     if (!VerifyOnly) {
827       // We cannot initialize this element, so let
828       // PerformCopyInitialization produce the appropriate diagnostic.
829       SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
830                                         SemaRef.Owned(expr),
831                                         /*TopLevelOfInitList=*/true);
832     }
833     hadError = true;
834     ++Index;
835     ++StructuredIndex;
836   }
837 }
838 
839 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
840                                        InitListExpr *IList, QualType DeclType,
841                                        unsigned &Index,
842                                        InitListExpr *StructuredList,
843                                        unsigned &StructuredIndex) {
844   assert(Index == 0 && "Index in explicit init list must be zero");
845 
846   // As an extension, clang supports complex initializers, which initialize
847   // a complex number component-wise.  When an explicit initializer list for
848   // a complex number contains two two initializers, this extension kicks in:
849   // it exepcts the initializer list to contain two elements convertible to
850   // the element type of the complex type. The first element initializes
851   // the real part, and the second element intitializes the imaginary part.
852 
853   if (IList->getNumInits() != 2)
854     return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
855                            StructuredIndex);
856 
857   // This is an extension in C.  (The builtin _Complex type does not exist
858   // in the C++ standard.)
859   if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
860     SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
861       << IList->getSourceRange();
862 
863   // Initialize the complex number.
864   QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
865   InitializedEntity ElementEntity =
866     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
867 
868   for (unsigned i = 0; i < 2; ++i) {
869     ElementEntity.setElementIndex(Index);
870     CheckSubElementType(ElementEntity, IList, elementType, Index,
871                         StructuredList, StructuredIndex);
872   }
873 }
874 
875 
876 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
877                                       InitListExpr *IList, QualType DeclType,
878                                       unsigned &Index,
879                                       InitListExpr *StructuredList,
880                                       unsigned &StructuredIndex) {
881   if (Index >= IList->getNumInits()) {
882     if (!SemaRef.getLangOptions().CPlusPlus0x) {
883       if (!VerifyOnly)
884         SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
885           << IList->getSourceRange();
886       hadError = true;
887     }
888     ++Index;
889     ++StructuredIndex;
890     return;
891   }
892 
893   Expr *expr = IList->getInit(Index);
894   if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
895     if (!VerifyOnly)
896       SemaRef.Diag(SubIList->getLocStart(),
897                    diag::warn_many_braces_around_scalar_init)
898         << SubIList->getSourceRange();
899 
900     CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
901                     StructuredIndex);
902     return;
903   } else if (isa<DesignatedInitExpr>(expr)) {
904     if (!VerifyOnly)
905       SemaRef.Diag(expr->getSourceRange().getBegin(),
906                    diag::err_designator_for_scalar_init)
907         << DeclType << expr->getSourceRange();
908     hadError = true;
909     ++Index;
910     ++StructuredIndex;
911     return;
912   }
913 
914   if (VerifyOnly) {
915     if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
916       hadError = true;
917     ++Index;
918     return;
919   }
920 
921   ExprResult Result =
922     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
923                                       SemaRef.Owned(expr),
924                                       /*TopLevelOfInitList=*/true);
925 
926   Expr *ResultExpr = 0;
927 
928   if (Result.isInvalid())
929     hadError = true; // types weren't compatible.
930   else {
931     ResultExpr = Result.takeAs<Expr>();
932 
933     if (ResultExpr != expr) {
934       // The type was promoted, update initializer list.
935       IList->setInit(Index, ResultExpr);
936     }
937   }
938   if (hadError)
939     ++StructuredIndex;
940   else
941     UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
942   ++Index;
943 }
944 
945 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
946                                          InitListExpr *IList, QualType DeclType,
947                                          unsigned &Index,
948                                          InitListExpr *StructuredList,
949                                          unsigned &StructuredIndex) {
950   if (Index >= IList->getNumInits()) {
951     // FIXME: It would be wonderful if we could point at the actual member. In
952     // general, it would be useful to pass location information down the stack,
953     // so that we know the location (or decl) of the "current object" being
954     // initialized.
955     if (!VerifyOnly)
956       SemaRef.Diag(IList->getLocStart(),
957                     diag::err_init_reference_member_uninitialized)
958         << DeclType
959         << IList->getSourceRange();
960     hadError = true;
961     ++Index;
962     ++StructuredIndex;
963     return;
964   }
965 
966   Expr *expr = IList->getInit(Index);
967   if (isa<InitListExpr>(expr)) {
968     // FIXME: Allowed in C++11.
969     if (!VerifyOnly)
970       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
971         << DeclType << IList->getSourceRange();
972     hadError = true;
973     ++Index;
974     ++StructuredIndex;
975     return;
976   }
977 
978   if (VerifyOnly) {
979     if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
980       hadError = true;
981     ++Index;
982     return;
983   }
984 
985   ExprResult Result =
986     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
987                                       SemaRef.Owned(expr),
988                                       /*TopLevelOfInitList=*/true);
989 
990   if (Result.isInvalid())
991     hadError = true;
992 
993   expr = Result.takeAs<Expr>();
994   IList->setInit(Index, expr);
995 
996   if (hadError)
997     ++StructuredIndex;
998   else
999     UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1000   ++Index;
1001 }
1002 
1003 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1004                                       InitListExpr *IList, QualType DeclType,
1005                                       unsigned &Index,
1006                                       InitListExpr *StructuredList,
1007                                       unsigned &StructuredIndex) {
1008   if (Index >= IList->getNumInits())
1009     return;
1010 
1011   const VectorType *VT = DeclType->getAs<VectorType>();
1012   unsigned maxElements = VT->getNumElements();
1013   unsigned numEltsInit = 0;
1014   QualType elementType = VT->getElementType();
1015 
1016   if (!SemaRef.getLangOptions().OpenCL) {
1017     // If the initializing element is a vector, try to copy-initialize
1018     // instead of breaking it apart (which is doomed to failure anyway).
1019     Expr *Init = IList->getInit(Index);
1020     if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1021       if (VerifyOnly) {
1022         if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1023           hadError = true;
1024         ++Index;
1025         return;
1026       }
1027 
1028       ExprResult Result =
1029         SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1030                                           SemaRef.Owned(Init),
1031                                           /*TopLevelOfInitList=*/true);
1032 
1033       Expr *ResultExpr = 0;
1034       if (Result.isInvalid())
1035         hadError = true; // types weren't compatible.
1036       else {
1037         ResultExpr = Result.takeAs<Expr>();
1038 
1039         if (ResultExpr != Init) {
1040           // The type was promoted, update initializer list.
1041           IList->setInit(Index, ResultExpr);
1042         }
1043       }
1044       if (hadError)
1045         ++StructuredIndex;
1046       else
1047         UpdateStructuredListElement(StructuredList, StructuredIndex,
1048                                     ResultExpr);
1049       ++Index;
1050       return;
1051     }
1052 
1053     InitializedEntity ElementEntity =
1054       InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1055 
1056     for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1057       // Don't attempt to go past the end of the init list
1058       if (Index >= IList->getNumInits())
1059         break;
1060 
1061       ElementEntity.setElementIndex(Index);
1062       CheckSubElementType(ElementEntity, IList, elementType, Index,
1063                           StructuredList, StructuredIndex);
1064     }
1065     return;
1066   }
1067 
1068   InitializedEntity ElementEntity =
1069     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1070 
1071   // OpenCL initializers allows vectors to be constructed from vectors.
1072   for (unsigned i = 0; i < maxElements; ++i) {
1073     // Don't attempt to go past the end of the init list
1074     if (Index >= IList->getNumInits())
1075       break;
1076 
1077     ElementEntity.setElementIndex(Index);
1078 
1079     QualType IType = IList->getInit(Index)->getType();
1080     if (!IType->isVectorType()) {
1081       CheckSubElementType(ElementEntity, IList, elementType, Index,
1082                           StructuredList, StructuredIndex);
1083       ++numEltsInit;
1084     } else {
1085       QualType VecType;
1086       const VectorType *IVT = IType->getAs<VectorType>();
1087       unsigned numIElts = IVT->getNumElements();
1088 
1089       if (IType->isExtVectorType())
1090         VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1091       else
1092         VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1093                                                 IVT->getVectorKind());
1094       CheckSubElementType(ElementEntity, IList, VecType, Index,
1095                           StructuredList, StructuredIndex);
1096       numEltsInit += numIElts;
1097     }
1098   }
1099 
1100   // OpenCL requires all elements to be initialized.
1101   // FIXME: Shouldn't this set hadError to true then?
1102   if (numEltsInit != maxElements && !VerifyOnly)
1103     SemaRef.Diag(IList->getSourceRange().getBegin(),
1104                  diag::err_vector_incorrect_num_initializers)
1105       << (numEltsInit < maxElements) << maxElements << numEltsInit;
1106 }
1107 
1108 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1109                                      InitListExpr *IList, QualType &DeclType,
1110                                      llvm::APSInt elementIndex,
1111                                      bool SubobjectIsDesignatorContext,
1112                                      unsigned &Index,
1113                                      InitListExpr *StructuredList,
1114                                      unsigned &StructuredIndex) {
1115   const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1116 
1117   // Check for the special-case of initializing an array with a string.
1118   if (Index < IList->getNumInits()) {
1119     if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1120                                  SemaRef.Context)) {
1121       // We place the string literal directly into the resulting
1122       // initializer list. This is the only place where the structure
1123       // of the structured initializer list doesn't match exactly,
1124       // because doing so would involve allocating one character
1125       // constant for each string.
1126       if (!VerifyOnly) {
1127         CheckStringInit(Str, DeclType, arrayType, SemaRef);
1128         UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1129         StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1130       }
1131       ++Index;
1132       return;
1133     }
1134   }
1135   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1136     // Check for VLAs; in standard C it would be possible to check this
1137     // earlier, but I don't know where clang accepts VLAs (gcc accepts
1138     // them in all sorts of strange places).
1139     if (!VerifyOnly)
1140       SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1141                     diag::err_variable_object_no_init)
1142         << VAT->getSizeExpr()->getSourceRange();
1143     hadError = true;
1144     ++Index;
1145     ++StructuredIndex;
1146     return;
1147   }
1148 
1149   // We might know the maximum number of elements in advance.
1150   llvm::APSInt maxElements(elementIndex.getBitWidth(),
1151                            elementIndex.isUnsigned());
1152   bool maxElementsKnown = false;
1153   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1154     maxElements = CAT->getSize();
1155     elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1156     elementIndex.setIsUnsigned(maxElements.isUnsigned());
1157     maxElementsKnown = true;
1158   }
1159 
1160   QualType elementType = arrayType->getElementType();
1161   while (Index < IList->getNumInits()) {
1162     Expr *Init = IList->getInit(Index);
1163     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1164       // If we're not the subobject that matches up with the '{' for
1165       // the designator, we shouldn't be handling the
1166       // designator. Return immediately.
1167       if (!SubobjectIsDesignatorContext)
1168         return;
1169 
1170       // Handle this designated initializer. elementIndex will be
1171       // updated to be the next array element we'll initialize.
1172       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1173                                      DeclType, 0, &elementIndex, Index,
1174                                      StructuredList, StructuredIndex, true,
1175                                      false)) {
1176         hadError = true;
1177         continue;
1178       }
1179 
1180       if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1181         maxElements = maxElements.extend(elementIndex.getBitWidth());
1182       else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1183         elementIndex = elementIndex.extend(maxElements.getBitWidth());
1184       elementIndex.setIsUnsigned(maxElements.isUnsigned());
1185 
1186       // If the array is of incomplete type, keep track of the number of
1187       // elements in the initializer.
1188       if (!maxElementsKnown && elementIndex > maxElements)
1189         maxElements = elementIndex;
1190 
1191       continue;
1192     }
1193 
1194     // If we know the maximum number of elements, and we've already
1195     // hit it, stop consuming elements in the initializer list.
1196     if (maxElementsKnown && elementIndex == maxElements)
1197       break;
1198 
1199     InitializedEntity ElementEntity =
1200       InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1201                                            Entity);
1202     // Check this element.
1203     CheckSubElementType(ElementEntity, IList, elementType, Index,
1204                         StructuredList, StructuredIndex);
1205     ++elementIndex;
1206 
1207     // If the array is of incomplete type, keep track of the number of
1208     // elements in the initializer.
1209     if (!maxElementsKnown && elementIndex > maxElements)
1210       maxElements = elementIndex;
1211   }
1212   if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1213     // If this is an incomplete array type, the actual type needs to
1214     // be calculated here.
1215     llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1216     if (maxElements == Zero) {
1217       // Sizing an array implicitly to zero is not allowed by ISO C,
1218       // but is supported by GNU.
1219       SemaRef.Diag(IList->getLocStart(),
1220                     diag::ext_typecheck_zero_array_size);
1221     }
1222 
1223     DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1224                                                      ArrayType::Normal, 0);
1225   }
1226 }
1227 
1228 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1229                                              Expr *InitExpr,
1230                                              FieldDecl *Field,
1231                                              bool TopLevelObject) {
1232   // Handle GNU flexible array initializers.
1233   unsigned FlexArrayDiag;
1234   if (isa<InitListExpr>(InitExpr) &&
1235       cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1236     // Empty flexible array init always allowed as an extension
1237     FlexArrayDiag = diag::ext_flexible_array_init;
1238   } else if (SemaRef.getLangOptions().CPlusPlus) {
1239     // Disallow flexible array init in C++; it is not required for gcc
1240     // compatibility, and it needs work to IRGen correctly in general.
1241     FlexArrayDiag = diag::err_flexible_array_init;
1242   } else if (!TopLevelObject) {
1243     // Disallow flexible array init on non-top-level object
1244     FlexArrayDiag = diag::err_flexible_array_init;
1245   } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1246     // Disallow flexible array init on anything which is not a variable.
1247     FlexArrayDiag = diag::err_flexible_array_init;
1248   } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1249     // Disallow flexible array init on local variables.
1250     FlexArrayDiag = diag::err_flexible_array_init;
1251   } else {
1252     // Allow other cases.
1253     FlexArrayDiag = diag::ext_flexible_array_init;
1254   }
1255 
1256   if (!VerifyOnly) {
1257     SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1258                  FlexArrayDiag)
1259       << InitExpr->getSourceRange().getBegin();
1260     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1261       << Field;
1262   }
1263 
1264   return FlexArrayDiag != diag::ext_flexible_array_init;
1265 }
1266 
1267 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1268                                             InitListExpr *IList,
1269                                             QualType DeclType,
1270                                             RecordDecl::field_iterator Field,
1271                                             bool SubobjectIsDesignatorContext,
1272                                             unsigned &Index,
1273                                             InitListExpr *StructuredList,
1274                                             unsigned &StructuredIndex,
1275                                             bool TopLevelObject) {
1276   RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1277 
1278   // If the record is invalid, some of it's members are invalid. To avoid
1279   // confusion, we forgo checking the intializer for the entire record.
1280   if (structDecl->isInvalidDecl()) {
1281     hadError = true;
1282     return;
1283   }
1284 
1285   if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1286     if (!VerifyOnly) {
1287       // Value-initialize the first named member of the union.
1288       RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1289       for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1290            Field != FieldEnd; ++Field) {
1291         if (Field->getDeclName()) {
1292           StructuredList->setInitializedFieldInUnion(*Field);
1293           break;
1294         }
1295       }
1296     }
1297     return;
1298   }
1299 
1300   // If structDecl is a forward declaration, this loop won't do
1301   // anything except look at designated initializers; That's okay,
1302   // because an error should get printed out elsewhere. It might be
1303   // worthwhile to skip over the rest of the initializer, though.
1304   RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1305   RecordDecl::field_iterator FieldEnd = RD->field_end();
1306   bool InitializedSomething = false;
1307   bool CheckForMissingFields = true;
1308   while (Index < IList->getNumInits()) {
1309     Expr *Init = IList->getInit(Index);
1310 
1311     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1312       // If we're not the subobject that matches up with the '{' for
1313       // the designator, we shouldn't be handling the
1314       // designator. Return immediately.
1315       if (!SubobjectIsDesignatorContext)
1316         return;
1317 
1318       // Handle this designated initializer. Field will be updated to
1319       // the next field that we'll be initializing.
1320       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1321                                      DeclType, &Field, 0, Index,
1322                                      StructuredList, StructuredIndex,
1323                                      true, TopLevelObject))
1324         hadError = true;
1325 
1326       InitializedSomething = true;
1327 
1328       // Disable check for missing fields when designators are used.
1329       // This matches gcc behaviour.
1330       CheckForMissingFields = false;
1331       continue;
1332     }
1333 
1334     if (Field == FieldEnd) {
1335       // We've run out of fields. We're done.
1336       break;
1337     }
1338 
1339     // We've already initialized a member of a union. We're done.
1340     if (InitializedSomething && DeclType->isUnionType())
1341       break;
1342 
1343     // If we've hit the flexible array member at the end, we're done.
1344     if (Field->getType()->isIncompleteArrayType())
1345       break;
1346 
1347     if (Field->isUnnamedBitfield()) {
1348       // Don't initialize unnamed bitfields, e.g. "int : 20;"
1349       ++Field;
1350       continue;
1351     }
1352 
1353     // Make sure we can use this declaration.
1354     bool InvalidUse;
1355     if (VerifyOnly)
1356       InvalidUse = !SemaRef.CanUseDecl(*Field);
1357     else
1358       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1359                                           IList->getInit(Index)->getLocStart());
1360     if (InvalidUse) {
1361       ++Index;
1362       ++Field;
1363       hadError = true;
1364       continue;
1365     }
1366 
1367     InitializedEntity MemberEntity =
1368       InitializedEntity::InitializeMember(*Field, &Entity);
1369     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1370                         StructuredList, StructuredIndex);
1371     InitializedSomething = true;
1372 
1373     if (DeclType->isUnionType() && !VerifyOnly) {
1374       // Initialize the first field within the union.
1375       StructuredList->setInitializedFieldInUnion(*Field);
1376     }
1377 
1378     ++Field;
1379   }
1380 
1381   // Emit warnings for missing struct field initializers.
1382   if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1383       Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1384       !DeclType->isUnionType()) {
1385     // It is possible we have one or more unnamed bitfields remaining.
1386     // Find first (if any) named field and emit warning.
1387     for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1388          it != end; ++it) {
1389       if (!it->isUnnamedBitfield()) {
1390         SemaRef.Diag(IList->getSourceRange().getEnd(),
1391                      diag::warn_missing_field_initializers) << it->getName();
1392         break;
1393       }
1394     }
1395   }
1396 
1397   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1398       Index >= IList->getNumInits())
1399     return;
1400 
1401   if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1402                              TopLevelObject)) {
1403     hadError = true;
1404     ++Index;
1405     return;
1406   }
1407 
1408   InitializedEntity MemberEntity =
1409     InitializedEntity::InitializeMember(*Field, &Entity);
1410 
1411   if (isa<InitListExpr>(IList->getInit(Index)))
1412     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1413                         StructuredList, StructuredIndex);
1414   else
1415     CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1416                           StructuredList, StructuredIndex);
1417 }
1418 
1419 /// \brief Expand a field designator that refers to a member of an
1420 /// anonymous struct or union into a series of field designators that
1421 /// refers to the field within the appropriate subobject.
1422 ///
1423 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1424                                            DesignatedInitExpr *DIE,
1425                                            unsigned DesigIdx,
1426                                            IndirectFieldDecl *IndirectField) {
1427   typedef DesignatedInitExpr::Designator Designator;
1428 
1429   // Build the replacement designators.
1430   SmallVector<Designator, 4> Replacements;
1431   for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1432        PE = IndirectField->chain_end(); PI != PE; ++PI) {
1433     if (PI + 1 == PE)
1434       Replacements.push_back(Designator((IdentifierInfo *)0,
1435                                     DIE->getDesignator(DesigIdx)->getDotLoc(),
1436                                 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1437     else
1438       Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1439                                         SourceLocation()));
1440     assert(isa<FieldDecl>(*PI));
1441     Replacements.back().setField(cast<FieldDecl>(*PI));
1442   }
1443 
1444   // Expand the current designator into the set of replacement
1445   // designators, so we have a full subobject path down to where the
1446   // member of the anonymous struct/union is actually stored.
1447   DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1448                         &Replacements[0] + Replacements.size());
1449 }
1450 
1451 /// \brief Given an implicit anonymous field, search the IndirectField that
1452 ///  corresponds to FieldName.
1453 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1454                                                  IdentifierInfo *FieldName) {
1455   assert(AnonField->isAnonymousStructOrUnion());
1456   Decl *NextDecl = AnonField->getNextDeclInContext();
1457   while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1458     if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1459       return IF;
1460     NextDecl = NextDecl->getNextDeclInContext();
1461   }
1462   return 0;
1463 }
1464 
1465 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1466                                                    DesignatedInitExpr *DIE) {
1467   unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1468   SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1469   for (unsigned I = 0; I < NumIndexExprs; ++I)
1470     IndexExprs[I] = DIE->getSubExpr(I + 1);
1471   return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1472                                     DIE->size(), IndexExprs.data(),
1473                                     NumIndexExprs, DIE->getEqualOrColonLoc(),
1474                                     DIE->usesGNUSyntax(), DIE->getInit());
1475 }
1476 
1477 /// @brief Check the well-formedness of a C99 designated initializer.
1478 ///
1479 /// Determines whether the designated initializer @p DIE, which
1480 /// resides at the given @p Index within the initializer list @p
1481 /// IList, is well-formed for a current object of type @p DeclType
1482 /// (C99 6.7.8). The actual subobject that this designator refers to
1483 /// within the current subobject is returned in either
1484 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1485 ///
1486 /// @param IList  The initializer list in which this designated
1487 /// initializer occurs.
1488 ///
1489 /// @param DIE The designated initializer expression.
1490 ///
1491 /// @param DesigIdx  The index of the current designator.
1492 ///
1493 /// @param DeclType  The type of the "current object" (C99 6.7.8p17),
1494 /// into which the designation in @p DIE should refer.
1495 ///
1496 /// @param NextField  If non-NULL and the first designator in @p DIE is
1497 /// a field, this will be set to the field declaration corresponding
1498 /// to the field named by the designator.
1499 ///
1500 /// @param NextElementIndex  If non-NULL and the first designator in @p
1501 /// DIE is an array designator or GNU array-range designator, this
1502 /// will be set to the last index initialized by this designator.
1503 ///
1504 /// @param Index  Index into @p IList where the designated initializer
1505 /// @p DIE occurs.
1506 ///
1507 /// @param StructuredList  The initializer list expression that
1508 /// describes all of the subobject initializers in the order they'll
1509 /// actually be initialized.
1510 ///
1511 /// @returns true if there was an error, false otherwise.
1512 bool
1513 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1514                                             InitListExpr *IList,
1515                                             DesignatedInitExpr *DIE,
1516                                             unsigned DesigIdx,
1517                                             QualType &CurrentObjectType,
1518                                           RecordDecl::field_iterator *NextField,
1519                                             llvm::APSInt *NextElementIndex,
1520                                             unsigned &Index,
1521                                             InitListExpr *StructuredList,
1522                                             unsigned &StructuredIndex,
1523                                             bool FinishSubobjectInit,
1524                                             bool TopLevelObject) {
1525   if (DesigIdx == DIE->size()) {
1526     // Check the actual initialization for the designated object type.
1527     bool prevHadError = hadError;
1528 
1529     // Temporarily remove the designator expression from the
1530     // initializer list that the child calls see, so that we don't try
1531     // to re-process the designator.
1532     unsigned OldIndex = Index;
1533     IList->setInit(OldIndex, DIE->getInit());
1534 
1535     CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1536                         StructuredList, StructuredIndex);
1537 
1538     // Restore the designated initializer expression in the syntactic
1539     // form of the initializer list.
1540     if (IList->getInit(OldIndex) != DIE->getInit())
1541       DIE->setInit(IList->getInit(OldIndex));
1542     IList->setInit(OldIndex, DIE);
1543 
1544     return hadError && !prevHadError;
1545   }
1546 
1547   DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1548   bool IsFirstDesignator = (DesigIdx == 0);
1549   if (!VerifyOnly) {
1550     assert((IsFirstDesignator || StructuredList) &&
1551            "Need a non-designated initializer list to start from");
1552 
1553     // Determine the structural initializer list that corresponds to the
1554     // current subobject.
1555     StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1556       : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1557                                    StructuredList, StructuredIndex,
1558                                    SourceRange(D->getStartLocation(),
1559                                                DIE->getSourceRange().getEnd()));
1560     assert(StructuredList && "Expected a structured initializer list");
1561   }
1562 
1563   if (D->isFieldDesignator()) {
1564     // C99 6.7.8p7:
1565     //
1566     //   If a designator has the form
1567     //
1568     //      . identifier
1569     //
1570     //   then the current object (defined below) shall have
1571     //   structure or union type and the identifier shall be the
1572     //   name of a member of that type.
1573     const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1574     if (!RT) {
1575       SourceLocation Loc = D->getDotLoc();
1576       if (Loc.isInvalid())
1577         Loc = D->getFieldLoc();
1578       if (!VerifyOnly)
1579         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1580           << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1581       ++Index;
1582       return true;
1583     }
1584 
1585     // Note: we perform a linear search of the fields here, despite
1586     // the fact that we have a faster lookup method, because we always
1587     // need to compute the field's index.
1588     FieldDecl *KnownField = D->getField();
1589     IdentifierInfo *FieldName = D->getFieldName();
1590     unsigned FieldIndex = 0;
1591     RecordDecl::field_iterator
1592       Field = RT->getDecl()->field_begin(),
1593       FieldEnd = RT->getDecl()->field_end();
1594     for (; Field != FieldEnd; ++Field) {
1595       if (Field->isUnnamedBitfield())
1596         continue;
1597 
1598       // If we find a field representing an anonymous field, look in the
1599       // IndirectFieldDecl that follow for the designated initializer.
1600       if (!KnownField && Field->isAnonymousStructOrUnion()) {
1601         if (IndirectFieldDecl *IF =
1602             FindIndirectFieldDesignator(*Field, FieldName)) {
1603           // In verify mode, don't modify the original.
1604           if (VerifyOnly)
1605             DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1606           ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1607           D = DIE->getDesignator(DesigIdx);
1608           break;
1609         }
1610       }
1611       if (KnownField && KnownField == *Field)
1612         break;
1613       if (FieldName && FieldName == Field->getIdentifier())
1614         break;
1615 
1616       ++FieldIndex;
1617     }
1618 
1619     if (Field == FieldEnd) {
1620       if (VerifyOnly) {
1621         ++Index;
1622         return true; // No typo correction when just trying this out.
1623       }
1624 
1625       // There was no normal field in the struct with the designated
1626       // name. Perform another lookup for this name, which may find
1627       // something that we can't designate (e.g., a member function),
1628       // may find nothing, or may find a member of an anonymous
1629       // struct/union.
1630       DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1631       FieldDecl *ReplacementField = 0;
1632       if (Lookup.first == Lookup.second) {
1633         // Name lookup didn't find anything. Determine whether this
1634         // was a typo for another field name.
1635         LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1636                        Sema::LookupMemberName);
1637         TypoCorrection Corrected = SemaRef.CorrectTypo(
1638             DeclarationNameInfo(FieldName, D->getFieldLoc()),
1639             Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1640             RT->getDecl(), false, Sema::CTC_NoKeywords);
1641         if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
1642             ReplacementField->getDeclContext()->getRedeclContext()
1643                                                       ->Equals(RT->getDecl())) {
1644           std::string CorrectedStr(
1645               Corrected.getAsString(SemaRef.getLangOptions()));
1646           std::string CorrectedQuotedStr(
1647               Corrected.getQuoted(SemaRef.getLangOptions()));
1648           SemaRef.Diag(D->getFieldLoc(),
1649                        diag::err_field_designator_unknown_suggest)
1650             << FieldName << CurrentObjectType << CorrectedQuotedStr
1651             << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1652           SemaRef.Diag(ReplacementField->getLocation(),
1653                        diag::note_previous_decl) << CorrectedQuotedStr;
1654           hadError = true;
1655         } else {
1656           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1657             << FieldName << CurrentObjectType;
1658           ++Index;
1659           return true;
1660         }
1661       }
1662 
1663       if (!ReplacementField) {
1664         // Name lookup found something, but it wasn't a field.
1665         SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1666           << FieldName;
1667         SemaRef.Diag((*Lookup.first)->getLocation(),
1668                       diag::note_field_designator_found);
1669         ++Index;
1670         return true;
1671       }
1672 
1673       if (!KnownField) {
1674         // The replacement field comes from typo correction; find it
1675         // in the list of fields.
1676         FieldIndex = 0;
1677         Field = RT->getDecl()->field_begin();
1678         for (; Field != FieldEnd; ++Field) {
1679           if (Field->isUnnamedBitfield())
1680             continue;
1681 
1682           if (ReplacementField == *Field ||
1683               Field->getIdentifier() == ReplacementField->getIdentifier())
1684             break;
1685 
1686           ++FieldIndex;
1687         }
1688       }
1689     }
1690 
1691     // All of the fields of a union are located at the same place in
1692     // the initializer list.
1693     if (RT->getDecl()->isUnion()) {
1694       FieldIndex = 0;
1695       if (!VerifyOnly)
1696         StructuredList->setInitializedFieldInUnion(*Field);
1697     }
1698 
1699     // Make sure we can use this declaration.
1700     bool InvalidUse;
1701     if (VerifyOnly)
1702       InvalidUse = !SemaRef.CanUseDecl(*Field);
1703     else
1704       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1705     if (InvalidUse) {
1706       ++Index;
1707       return true;
1708     }
1709 
1710     if (!VerifyOnly) {
1711       // Update the designator with the field declaration.
1712       D->setField(*Field);
1713 
1714       // Make sure that our non-designated initializer list has space
1715       // for a subobject corresponding to this field.
1716       if (FieldIndex >= StructuredList->getNumInits())
1717         StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1718     }
1719 
1720     // This designator names a flexible array member.
1721     if (Field->getType()->isIncompleteArrayType()) {
1722       bool Invalid = false;
1723       if ((DesigIdx + 1) != DIE->size()) {
1724         // We can't designate an object within the flexible array
1725         // member (because GCC doesn't allow it).
1726         if (!VerifyOnly) {
1727           DesignatedInitExpr::Designator *NextD
1728             = DIE->getDesignator(DesigIdx + 1);
1729           SemaRef.Diag(NextD->getStartLocation(),
1730                         diag::err_designator_into_flexible_array_member)
1731             << SourceRange(NextD->getStartLocation(),
1732                            DIE->getSourceRange().getEnd());
1733           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1734             << *Field;
1735         }
1736         Invalid = true;
1737       }
1738 
1739       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1740           !isa<StringLiteral>(DIE->getInit())) {
1741         // The initializer is not an initializer list.
1742         if (!VerifyOnly) {
1743           SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1744                         diag::err_flexible_array_init_needs_braces)
1745             << DIE->getInit()->getSourceRange();
1746           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1747             << *Field;
1748         }
1749         Invalid = true;
1750       }
1751 
1752       // Check GNU flexible array initializer.
1753       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1754                                              TopLevelObject))
1755         Invalid = true;
1756 
1757       if (Invalid) {
1758         ++Index;
1759         return true;
1760       }
1761 
1762       // Initialize the array.
1763       bool prevHadError = hadError;
1764       unsigned newStructuredIndex = FieldIndex;
1765       unsigned OldIndex = Index;
1766       IList->setInit(Index, DIE->getInit());
1767 
1768       InitializedEntity MemberEntity =
1769         InitializedEntity::InitializeMember(*Field, &Entity);
1770       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1771                           StructuredList, newStructuredIndex);
1772 
1773       IList->setInit(OldIndex, DIE);
1774       if (hadError && !prevHadError) {
1775         ++Field;
1776         ++FieldIndex;
1777         if (NextField)
1778           *NextField = Field;
1779         StructuredIndex = FieldIndex;
1780         return true;
1781       }
1782     } else {
1783       // Recurse to check later designated subobjects.
1784       QualType FieldType = (*Field)->getType();
1785       unsigned newStructuredIndex = FieldIndex;
1786 
1787       InitializedEntity MemberEntity =
1788         InitializedEntity::InitializeMember(*Field, &Entity);
1789       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1790                                      FieldType, 0, 0, Index,
1791                                      StructuredList, newStructuredIndex,
1792                                      true, false))
1793         return true;
1794     }
1795 
1796     // Find the position of the next field to be initialized in this
1797     // subobject.
1798     ++Field;
1799     ++FieldIndex;
1800 
1801     // If this the first designator, our caller will continue checking
1802     // the rest of this struct/class/union subobject.
1803     if (IsFirstDesignator) {
1804       if (NextField)
1805         *NextField = Field;
1806       StructuredIndex = FieldIndex;
1807       return false;
1808     }
1809 
1810     if (!FinishSubobjectInit)
1811       return false;
1812 
1813     // We've already initialized something in the union; we're done.
1814     if (RT->getDecl()->isUnion())
1815       return hadError;
1816 
1817     // Check the remaining fields within this class/struct/union subobject.
1818     bool prevHadError = hadError;
1819 
1820     CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1821                           StructuredList, FieldIndex);
1822     return hadError && !prevHadError;
1823   }
1824 
1825   // C99 6.7.8p6:
1826   //
1827   //   If a designator has the form
1828   //
1829   //      [ constant-expression ]
1830   //
1831   //   then the current object (defined below) shall have array
1832   //   type and the expression shall be an integer constant
1833   //   expression. If the array is of unknown size, any
1834   //   nonnegative value is valid.
1835   //
1836   // Additionally, cope with the GNU extension that permits
1837   // designators of the form
1838   //
1839   //      [ constant-expression ... constant-expression ]
1840   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1841   if (!AT) {
1842     if (!VerifyOnly)
1843       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1844         << CurrentObjectType;
1845     ++Index;
1846     return true;
1847   }
1848 
1849   Expr *IndexExpr = 0;
1850   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1851   if (D->isArrayDesignator()) {
1852     IndexExpr = DIE->getArrayIndex(*D);
1853     DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
1854     DesignatedEndIndex = DesignatedStartIndex;
1855   } else {
1856     assert(D->isArrayRangeDesignator() && "Need array-range designator");
1857 
1858     DesignatedStartIndex =
1859       DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1860     DesignatedEndIndex =
1861       DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
1862     IndexExpr = DIE->getArrayRangeEnd(*D);
1863 
1864     // Codegen can't handle evaluating array range designators that have side
1865     // effects, because we replicate the AST value for each initialized element.
1866     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1867     // elements with something that has a side effect, so codegen can emit an
1868     // "error unsupported" error instead of miscompiling the app.
1869     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1870         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
1871       FullyStructuredList->sawArrayRangeDesignator();
1872   }
1873 
1874   if (isa<ConstantArrayType>(AT)) {
1875     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1876     DesignatedStartIndex
1877       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1878     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1879     DesignatedEndIndex
1880       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1881     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1882     if (DesignatedEndIndex >= MaxElements) {
1883       if (!VerifyOnly)
1884         SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1885                       diag::err_array_designator_too_large)
1886           << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1887           << IndexExpr->getSourceRange();
1888       ++Index;
1889       return true;
1890     }
1891   } else {
1892     // Make sure the bit-widths and signedness match.
1893     if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1894       DesignatedEndIndex
1895         = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1896     else if (DesignatedStartIndex.getBitWidth() <
1897              DesignatedEndIndex.getBitWidth())
1898       DesignatedStartIndex
1899         = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1900     DesignatedStartIndex.setIsUnsigned(true);
1901     DesignatedEndIndex.setIsUnsigned(true);
1902   }
1903 
1904   // Make sure that our non-designated initializer list has space
1905   // for a subobject corresponding to this array element.
1906   if (!VerifyOnly &&
1907       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1908     StructuredList->resizeInits(SemaRef.Context,
1909                                 DesignatedEndIndex.getZExtValue() + 1);
1910 
1911   // Repeatedly perform subobject initializations in the range
1912   // [DesignatedStartIndex, DesignatedEndIndex].
1913 
1914   // Move to the next designator
1915   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1916   unsigned OldIndex = Index;
1917 
1918   InitializedEntity ElementEntity =
1919     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1920 
1921   while (DesignatedStartIndex <= DesignatedEndIndex) {
1922     // Recurse to check later designated subobjects.
1923     QualType ElementType = AT->getElementType();
1924     Index = OldIndex;
1925 
1926     ElementEntity.setElementIndex(ElementIndex);
1927     if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1928                                    ElementType, 0, 0, Index,
1929                                    StructuredList, ElementIndex,
1930                                    (DesignatedStartIndex == DesignatedEndIndex),
1931                                    false))
1932       return true;
1933 
1934     // Move to the next index in the array that we'll be initializing.
1935     ++DesignatedStartIndex;
1936     ElementIndex = DesignatedStartIndex.getZExtValue();
1937   }
1938 
1939   // If this the first designator, our caller will continue checking
1940   // the rest of this array subobject.
1941   if (IsFirstDesignator) {
1942     if (NextElementIndex)
1943       *NextElementIndex = DesignatedStartIndex;
1944     StructuredIndex = ElementIndex;
1945     return false;
1946   }
1947 
1948   if (!FinishSubobjectInit)
1949     return false;
1950 
1951   // Check the remaining elements within this array subobject.
1952   bool prevHadError = hadError;
1953   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
1954                  /*SubobjectIsDesignatorContext=*/false, Index,
1955                  StructuredList, ElementIndex);
1956   return hadError && !prevHadError;
1957 }
1958 
1959 // Get the structured initializer list for a subobject of type
1960 // @p CurrentObjectType.
1961 InitListExpr *
1962 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1963                                             QualType CurrentObjectType,
1964                                             InitListExpr *StructuredList,
1965                                             unsigned StructuredIndex,
1966                                             SourceRange InitRange) {
1967   if (VerifyOnly)
1968     return 0; // No structured list in verification-only mode.
1969   Expr *ExistingInit = 0;
1970   if (!StructuredList)
1971     ExistingInit = SyntacticToSemantic[IList];
1972   else if (StructuredIndex < StructuredList->getNumInits())
1973     ExistingInit = StructuredList->getInit(StructuredIndex);
1974 
1975   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1976     return Result;
1977 
1978   if (ExistingInit) {
1979     // We are creating an initializer list that initializes the
1980     // subobjects of the current object, but there was already an
1981     // initialization that completely initialized the current
1982     // subobject, e.g., by a compound literal:
1983     //
1984     // struct X { int a, b; };
1985     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1986     //
1987     // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1988     // designated initializer re-initializes the whole
1989     // subobject [0], overwriting previous initializers.
1990     SemaRef.Diag(InitRange.getBegin(),
1991                  diag::warn_subobject_initializer_overrides)
1992       << InitRange;
1993     SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
1994                   diag::note_previous_initializer)
1995       << /*FIXME:has side effects=*/0
1996       << ExistingInit->getSourceRange();
1997   }
1998 
1999   InitListExpr *Result
2000     = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2001                                          InitRange.getBegin(), 0, 0,
2002                                          InitRange.getEnd());
2003 
2004   Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
2005 
2006   // Pre-allocate storage for the structured initializer list.
2007   unsigned NumElements = 0;
2008   unsigned NumInits = 0;
2009   bool GotNumInits = false;
2010   if (!StructuredList) {
2011     NumInits = IList->getNumInits();
2012     GotNumInits = true;
2013   } else if (Index < IList->getNumInits()) {
2014     if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2015       NumInits = SubList->getNumInits();
2016       GotNumInits = true;
2017     }
2018   }
2019 
2020   if (const ArrayType *AType
2021       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2022     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2023       NumElements = CAType->getSize().getZExtValue();
2024       // Simple heuristic so that we don't allocate a very large
2025       // initializer with many empty entries at the end.
2026       if (GotNumInits && NumElements > NumInits)
2027         NumElements = 0;
2028     }
2029   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2030     NumElements = VType->getNumElements();
2031   else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2032     RecordDecl *RDecl = RType->getDecl();
2033     if (RDecl->isUnion())
2034       NumElements = 1;
2035     else
2036       NumElements = std::distance(RDecl->field_begin(),
2037                                   RDecl->field_end());
2038   }
2039 
2040   if (NumElements < NumInits)
2041     NumElements = IList->getNumInits();
2042 
2043   Result->reserveInits(SemaRef.Context, NumElements);
2044 
2045   // Link this new initializer list into the structured initializer
2046   // lists.
2047   if (StructuredList)
2048     StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2049   else {
2050     Result->setSyntacticForm(IList);
2051     SyntacticToSemantic[IList] = Result;
2052   }
2053 
2054   return Result;
2055 }
2056 
2057 /// Update the initializer at index @p StructuredIndex within the
2058 /// structured initializer list to the value @p expr.
2059 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2060                                                   unsigned &StructuredIndex,
2061                                                   Expr *expr) {
2062   // No structured initializer list to update
2063   if (!StructuredList)
2064     return;
2065 
2066   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2067                                                   StructuredIndex, expr)) {
2068     // This initializer overwrites a previous initializer. Warn.
2069     SemaRef.Diag(expr->getSourceRange().getBegin(),
2070                   diag::warn_initializer_overrides)
2071       << expr->getSourceRange();
2072     SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
2073                   diag::note_previous_initializer)
2074       << /*FIXME:has side effects=*/0
2075       << PrevInit->getSourceRange();
2076   }
2077 
2078   ++StructuredIndex;
2079 }
2080 
2081 /// Check that the given Index expression is a valid array designator
2082 /// value. This is essentailly just a wrapper around
2083 /// VerifyIntegerConstantExpression that also checks for negative values
2084 /// and produces a reasonable diagnostic if there is a
2085 /// failure. Returns true if there was an error, false otherwise.  If
2086 /// everything went okay, Value will receive the value of the constant
2087 /// expression.
2088 static bool
2089 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2090   SourceLocation Loc = Index->getSourceRange().getBegin();
2091 
2092   // Make sure this is an integer constant expression.
2093   if (S.VerifyIntegerConstantExpression(Index, &Value))
2094     return true;
2095 
2096   if (Value.isSigned() && Value.isNegative())
2097     return S.Diag(Loc, diag::err_array_designator_negative)
2098       << Value.toString(10) << Index->getSourceRange();
2099 
2100   Value.setIsUnsigned(true);
2101   return false;
2102 }
2103 
2104 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2105                                             SourceLocation Loc,
2106                                             bool GNUSyntax,
2107                                             ExprResult Init) {
2108   typedef DesignatedInitExpr::Designator ASTDesignator;
2109 
2110   bool Invalid = false;
2111   SmallVector<ASTDesignator, 32> Designators;
2112   SmallVector<Expr *, 32> InitExpressions;
2113 
2114   // Build designators and check array designator expressions.
2115   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2116     const Designator &D = Desig.getDesignator(Idx);
2117     switch (D.getKind()) {
2118     case Designator::FieldDesignator:
2119       Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2120                                           D.getFieldLoc()));
2121       break;
2122 
2123     case Designator::ArrayDesignator: {
2124       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2125       llvm::APSInt IndexValue;
2126       if (!Index->isTypeDependent() &&
2127           !Index->isValueDependent() &&
2128           CheckArrayDesignatorExpr(*this, Index, IndexValue))
2129         Invalid = true;
2130       else {
2131         Designators.push_back(ASTDesignator(InitExpressions.size(),
2132                                             D.getLBracketLoc(),
2133                                             D.getRBracketLoc()));
2134         InitExpressions.push_back(Index);
2135       }
2136       break;
2137     }
2138 
2139     case Designator::ArrayRangeDesignator: {
2140       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2141       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2142       llvm::APSInt StartValue;
2143       llvm::APSInt EndValue;
2144       bool StartDependent = StartIndex->isTypeDependent() ||
2145                             StartIndex->isValueDependent();
2146       bool EndDependent = EndIndex->isTypeDependent() ||
2147                           EndIndex->isValueDependent();
2148       if ((!StartDependent &&
2149            CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2150           (!EndDependent &&
2151            CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
2152         Invalid = true;
2153       else {
2154         // Make sure we're comparing values with the same bit width.
2155         if (StartDependent || EndDependent) {
2156           // Nothing to compute.
2157         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2158           EndValue = EndValue.extend(StartValue.getBitWidth());
2159         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2160           StartValue = StartValue.extend(EndValue.getBitWidth());
2161 
2162         if (!StartDependent && !EndDependent && EndValue < StartValue) {
2163           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2164             << StartValue.toString(10) << EndValue.toString(10)
2165             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2166           Invalid = true;
2167         } else {
2168           Designators.push_back(ASTDesignator(InitExpressions.size(),
2169                                               D.getLBracketLoc(),
2170                                               D.getEllipsisLoc(),
2171                                               D.getRBracketLoc()));
2172           InitExpressions.push_back(StartIndex);
2173           InitExpressions.push_back(EndIndex);
2174         }
2175       }
2176       break;
2177     }
2178     }
2179   }
2180 
2181   if (Invalid || Init.isInvalid())
2182     return ExprError();
2183 
2184   // Clear out the expressions within the designation.
2185   Desig.ClearExprs(*this);
2186 
2187   DesignatedInitExpr *DIE
2188     = DesignatedInitExpr::Create(Context,
2189                                  Designators.data(), Designators.size(),
2190                                  InitExpressions.data(), InitExpressions.size(),
2191                                  Loc, GNUSyntax, Init.takeAs<Expr>());
2192 
2193   if (getLangOptions().CPlusPlus)
2194     Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2195       << DIE->getSourceRange();
2196   else if (!getLangOptions().C99)
2197     Diag(DIE->getLocStart(), diag::ext_designated_init)
2198       << DIE->getSourceRange();
2199 
2200   return Owned(DIE);
2201 }
2202 
2203 //===----------------------------------------------------------------------===//
2204 // Initialization entity
2205 //===----------------------------------------------------------------------===//
2206 
2207 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2208                                      const InitializedEntity &Parent)
2209   : Parent(&Parent), Index(Index)
2210 {
2211   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2212     Kind = EK_ArrayElement;
2213     Type = AT->getElementType();
2214   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2215     Kind = EK_VectorElement;
2216     Type = VT->getElementType();
2217   } else {
2218     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2219     assert(CT && "Unexpected type");
2220     Kind = EK_ComplexElement;
2221     Type = CT->getElementType();
2222   }
2223 }
2224 
2225 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2226                                                     CXXBaseSpecifier *Base,
2227                                                     bool IsInheritedVirtualBase)
2228 {
2229   InitializedEntity Result;
2230   Result.Kind = EK_Base;
2231   Result.Base = reinterpret_cast<uintptr_t>(Base);
2232   if (IsInheritedVirtualBase)
2233     Result.Base |= 0x01;
2234 
2235   Result.Type = Base->getType();
2236   return Result;
2237 }
2238 
2239 DeclarationName InitializedEntity::getName() const {
2240   switch (getKind()) {
2241   case EK_Parameter: {
2242     ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2243     return (D ? D->getDeclName() : DeclarationName());
2244   }
2245 
2246   case EK_Variable:
2247   case EK_Member:
2248     return VariableOrMember->getDeclName();
2249 
2250   case EK_Result:
2251   case EK_Exception:
2252   case EK_New:
2253   case EK_Temporary:
2254   case EK_Base:
2255   case EK_Delegating:
2256   case EK_ArrayElement:
2257   case EK_VectorElement:
2258   case EK_ComplexElement:
2259   case EK_BlockElement:
2260     return DeclarationName();
2261   }
2262 
2263   // Silence GCC warning
2264   return DeclarationName();
2265 }
2266 
2267 DeclaratorDecl *InitializedEntity::getDecl() const {
2268   switch (getKind()) {
2269   case EK_Variable:
2270   case EK_Member:
2271     return VariableOrMember;
2272 
2273   case EK_Parameter:
2274     return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2275 
2276   case EK_Result:
2277   case EK_Exception:
2278   case EK_New:
2279   case EK_Temporary:
2280   case EK_Base:
2281   case EK_Delegating:
2282   case EK_ArrayElement:
2283   case EK_VectorElement:
2284   case EK_ComplexElement:
2285   case EK_BlockElement:
2286     return 0;
2287   }
2288 
2289   // Silence GCC warning
2290   return 0;
2291 }
2292 
2293 bool InitializedEntity::allowsNRVO() const {
2294   switch (getKind()) {
2295   case EK_Result:
2296   case EK_Exception:
2297     return LocAndNRVO.NRVO;
2298 
2299   case EK_Variable:
2300   case EK_Parameter:
2301   case EK_Member:
2302   case EK_New:
2303   case EK_Temporary:
2304   case EK_Base:
2305   case EK_Delegating:
2306   case EK_ArrayElement:
2307   case EK_VectorElement:
2308   case EK_ComplexElement:
2309   case EK_BlockElement:
2310     break;
2311   }
2312 
2313   return false;
2314 }
2315 
2316 //===----------------------------------------------------------------------===//
2317 // Initialization sequence
2318 //===----------------------------------------------------------------------===//
2319 
2320 void InitializationSequence::Step::Destroy() {
2321   switch (Kind) {
2322   case SK_ResolveAddressOfOverloadedFunction:
2323   case SK_CastDerivedToBaseRValue:
2324   case SK_CastDerivedToBaseXValue:
2325   case SK_CastDerivedToBaseLValue:
2326   case SK_BindReference:
2327   case SK_BindReferenceToTemporary:
2328   case SK_ExtraneousCopyToTemporary:
2329   case SK_UserConversion:
2330   case SK_QualificationConversionRValue:
2331   case SK_QualificationConversionXValue:
2332   case SK_QualificationConversionLValue:
2333   case SK_ListInitialization:
2334   case SK_ListConstructorCall:
2335   case SK_ConstructorInitialization:
2336   case SK_ZeroInitialization:
2337   case SK_CAssignment:
2338   case SK_StringInit:
2339   case SK_ObjCObjectConversion:
2340   case SK_ArrayInit:
2341   case SK_PassByIndirectCopyRestore:
2342   case SK_PassByIndirectRestore:
2343   case SK_ProduceObjCObject:
2344     break;
2345 
2346   case SK_ConversionSequence:
2347     delete ICS;
2348   }
2349 }
2350 
2351 bool InitializationSequence::isDirectReferenceBinding() const {
2352   return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2353 }
2354 
2355 bool InitializationSequence::isAmbiguous() const {
2356   if (!Failed())
2357     return false;
2358 
2359   switch (getFailureKind()) {
2360   case FK_TooManyInitsForReference:
2361   case FK_ArrayNeedsInitList:
2362   case FK_ArrayNeedsInitListOrStringLiteral:
2363   case FK_AddressOfOverloadFailed: // FIXME: Could do better
2364   case FK_NonConstLValueReferenceBindingToTemporary:
2365   case FK_NonConstLValueReferenceBindingToUnrelated:
2366   case FK_RValueReferenceBindingToLValue:
2367   case FK_ReferenceInitDropsQualifiers:
2368   case FK_ReferenceInitFailed:
2369   case FK_ConversionFailed:
2370   case FK_ConversionFromPropertyFailed:
2371   case FK_TooManyInitsForScalar:
2372   case FK_ReferenceBindingToInitList:
2373   case FK_InitListBadDestinationType:
2374   case FK_DefaultInitOfConst:
2375   case FK_Incomplete:
2376   case FK_ArrayTypeMismatch:
2377   case FK_NonConstantArrayInit:
2378   case FK_ListInitializationFailed:
2379     return false;
2380 
2381   case FK_ReferenceInitOverloadFailed:
2382   case FK_UserConversionOverloadFailed:
2383   case FK_ConstructorOverloadFailed:
2384     return FailedOverloadResult == OR_Ambiguous;
2385   }
2386 
2387   return false;
2388 }
2389 
2390 bool InitializationSequence::isConstructorInitialization() const {
2391   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2392 }
2393 
2394 bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2395                                                const Expr *Initializer,
2396                                                bool *isInitializerConstant,
2397                                                APValue *ConstantValue) const {
2398   if (Steps.empty() || Initializer->isValueDependent())
2399     return false;
2400 
2401   const Step &LastStep = Steps.back();
2402   if (LastStep.Kind != SK_ConversionSequence)
2403     return false;
2404 
2405   const ImplicitConversionSequence &ICS = *LastStep.ICS;
2406   const StandardConversionSequence *SCS = NULL;
2407   switch (ICS.getKind()) {
2408   case ImplicitConversionSequence::StandardConversion:
2409     SCS = &ICS.Standard;
2410     break;
2411   case ImplicitConversionSequence::UserDefinedConversion:
2412     SCS = &ICS.UserDefined.After;
2413     break;
2414   case ImplicitConversionSequence::AmbiguousConversion:
2415   case ImplicitConversionSequence::EllipsisConversion:
2416   case ImplicitConversionSequence::BadConversion:
2417     return false;
2418   }
2419 
2420   // Check if SCS represents a narrowing conversion, according to C++0x
2421   // [dcl.init.list]p7:
2422   //
2423   // A narrowing conversion is an implicit conversion ...
2424   ImplicitConversionKind PossibleNarrowing = SCS->Second;
2425   QualType FromType = SCS->getToType(0);
2426   QualType ToType = SCS->getToType(1);
2427   switch (PossibleNarrowing) {
2428   // * from a floating-point type to an integer type, or
2429   //
2430   // * from an integer type or unscoped enumeration type to a floating-point
2431   //   type, except where the source is a constant expression and the actual
2432   //   value after conversion will fit into the target type and will produce
2433   //   the original value when converted back to the original type, or
2434   case ICK_Floating_Integral:
2435     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2436       *isInitializerConstant = false;
2437       return true;
2438     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2439       llvm::APSInt IntConstantValue;
2440       if (Initializer &&
2441           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2442         // Convert the integer to the floating type.
2443         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2444         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2445                                 llvm::APFloat::rmNearestTiesToEven);
2446         // And back.
2447         llvm::APSInt ConvertedValue = IntConstantValue;
2448         bool ignored;
2449         Result.convertToInteger(ConvertedValue,
2450                                 llvm::APFloat::rmTowardZero, &ignored);
2451         // If the resulting value is different, this was a narrowing conversion.
2452         if (IntConstantValue != ConvertedValue) {
2453           *isInitializerConstant = true;
2454           *ConstantValue = APValue(IntConstantValue);
2455           return true;
2456         }
2457       } else {
2458         // Variables are always narrowings.
2459         *isInitializerConstant = false;
2460         return true;
2461       }
2462     }
2463     return false;
2464 
2465   // * from long double to double or float, or from double to float, except
2466   //   where the source is a constant expression and the actual value after
2467   //   conversion is within the range of values that can be represented (even
2468   //   if it cannot be represented exactly), or
2469   case ICK_Floating_Conversion:
2470     if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2471       // FromType is larger than ToType.
2472       Expr::EvalResult InitializerValue;
2473       // FIXME: Check whether Initializer is a constant expression according
2474       // to C++0x [expr.const], rather than just whether it can be folded.
2475       if (Initializer->Evaluate(InitializerValue, Ctx) &&
2476           !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2477         // Constant! (Except for FIXME above.)
2478         llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2479         // Convert the source value into the target type.
2480         bool ignored;
2481         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2482           Ctx.getFloatTypeSemantics(ToType),
2483           llvm::APFloat::rmNearestTiesToEven, &ignored);
2484         // If there was no overflow, the source value is within the range of
2485         // values that can be represented.
2486         if (ConvertStatus & llvm::APFloat::opOverflow) {
2487           *isInitializerConstant = true;
2488           *ConstantValue = InitializerValue.Val;
2489           return true;
2490         }
2491       } else {
2492         *isInitializerConstant = false;
2493         return true;
2494       }
2495     }
2496     return false;
2497 
2498   // * from an integer type or unscoped enumeration type to an integer type
2499   //   that cannot represent all the values of the original type, except where
2500   //   the source is a constant expression and the actual value after
2501   //   conversion will fit into the target type and will produce the original
2502   //   value when converted back to the original type.
2503   case ICK_Boolean_Conversion:  // Bools are integers too.
2504     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2505       // Boolean conversions can be from pointers and pointers to members
2506       // [conv.bool], and those aren't considered narrowing conversions.
2507       return false;
2508     }  // Otherwise, fall through to the integral case.
2509   case ICK_Integral_Conversion: {
2510     assert(FromType->isIntegralOrUnscopedEnumerationType());
2511     assert(ToType->isIntegralOrUnscopedEnumerationType());
2512     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2513     const unsigned FromWidth = Ctx.getIntWidth(FromType);
2514     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2515     const unsigned ToWidth = Ctx.getIntWidth(ToType);
2516 
2517     if (FromWidth > ToWidth ||
2518         (FromWidth == ToWidth && FromSigned != ToSigned)) {
2519       // Not all values of FromType can be represented in ToType.
2520       llvm::APSInt InitializerValue;
2521       if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2522         *isInitializerConstant = true;
2523         *ConstantValue = APValue(InitializerValue);
2524 
2525         // Add a bit to the InitializerValue so we don't have to worry about
2526         // signed vs. unsigned comparisons.
2527         InitializerValue = InitializerValue.extend(
2528           InitializerValue.getBitWidth() + 1);
2529         // Convert the initializer to and from the target width and signed-ness.
2530         llvm::APSInt ConvertedValue = InitializerValue;
2531         ConvertedValue = ConvertedValue.trunc(ToWidth);
2532         ConvertedValue.setIsSigned(ToSigned);
2533         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2534         ConvertedValue.setIsSigned(InitializerValue.isSigned());
2535         // If the result is different, this was a narrowing conversion.
2536         return ConvertedValue != InitializerValue;
2537       } else {
2538         // Variables are always narrowings.
2539         *isInitializerConstant = false;
2540         return true;
2541       }
2542     }
2543     return false;
2544   }
2545 
2546   default:
2547     // Other kinds of conversions are not narrowings.
2548     return false;
2549   }
2550 }
2551 
2552 void InitializationSequence::AddAddressOverloadResolutionStep(
2553                                                       FunctionDecl *Function,
2554                                                       DeclAccessPair Found) {
2555   Step S;
2556   S.Kind = SK_ResolveAddressOfOverloadedFunction;
2557   S.Type = Function->getType();
2558   S.Function.Function = Function;
2559   S.Function.FoundDecl = Found;
2560   Steps.push_back(S);
2561 }
2562 
2563 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2564                                                       ExprValueKind VK) {
2565   Step S;
2566   switch (VK) {
2567   case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2568   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2569   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2570   default: llvm_unreachable("No such category");
2571   }
2572   S.Type = BaseType;
2573   Steps.push_back(S);
2574 }
2575 
2576 void InitializationSequence::AddReferenceBindingStep(QualType T,
2577                                                      bool BindingTemporary) {
2578   Step S;
2579   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2580   S.Type = T;
2581   Steps.push_back(S);
2582 }
2583 
2584 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2585   Step S;
2586   S.Kind = SK_ExtraneousCopyToTemporary;
2587   S.Type = T;
2588   Steps.push_back(S);
2589 }
2590 
2591 void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2592                                                    DeclAccessPair FoundDecl,
2593                                                    QualType T) {
2594   Step S;
2595   S.Kind = SK_UserConversion;
2596   S.Type = T;
2597   S.Function.Function = Function;
2598   S.Function.FoundDecl = FoundDecl;
2599   Steps.push_back(S);
2600 }
2601 
2602 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2603                                                             ExprValueKind VK) {
2604   Step S;
2605   S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2606   switch (VK) {
2607   case VK_RValue:
2608     S.Kind = SK_QualificationConversionRValue;
2609     break;
2610   case VK_XValue:
2611     S.Kind = SK_QualificationConversionXValue;
2612     break;
2613   case VK_LValue:
2614     S.Kind = SK_QualificationConversionLValue;
2615     break;
2616   }
2617   S.Type = Ty;
2618   Steps.push_back(S);
2619 }
2620 
2621 void InitializationSequence::AddConversionSequenceStep(
2622                                        const ImplicitConversionSequence &ICS,
2623                                                        QualType T) {
2624   Step S;
2625   S.Kind = SK_ConversionSequence;
2626   S.Type = T;
2627   S.ICS = new ImplicitConversionSequence(ICS);
2628   Steps.push_back(S);
2629 }
2630 
2631 void InitializationSequence::AddListInitializationStep(QualType T) {
2632   Step S;
2633   S.Kind = SK_ListInitialization;
2634   S.Type = T;
2635   Steps.push_back(S);
2636 }
2637 
2638 void
2639 InitializationSequence::AddConstructorInitializationStep(
2640                                               CXXConstructorDecl *Constructor,
2641                                                        AccessSpecifier Access,
2642                                                          QualType T) {
2643   Step S;
2644   S.Kind = SK_ConstructorInitialization;
2645   S.Type = T;
2646   S.Function.Function = Constructor;
2647   S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2648   Steps.push_back(S);
2649 }
2650 
2651 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2652   Step S;
2653   S.Kind = SK_ZeroInitialization;
2654   S.Type = T;
2655   Steps.push_back(S);
2656 }
2657 
2658 void InitializationSequence::AddCAssignmentStep(QualType T) {
2659   Step S;
2660   S.Kind = SK_CAssignment;
2661   S.Type = T;
2662   Steps.push_back(S);
2663 }
2664 
2665 void InitializationSequence::AddStringInitStep(QualType T) {
2666   Step S;
2667   S.Kind = SK_StringInit;
2668   S.Type = T;
2669   Steps.push_back(S);
2670 }
2671 
2672 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2673   Step S;
2674   S.Kind = SK_ObjCObjectConversion;
2675   S.Type = T;
2676   Steps.push_back(S);
2677 }
2678 
2679 void InitializationSequence::AddArrayInitStep(QualType T) {
2680   Step S;
2681   S.Kind = SK_ArrayInit;
2682   S.Type = T;
2683   Steps.push_back(S);
2684 }
2685 
2686 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2687                                                               bool shouldCopy) {
2688   Step s;
2689   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2690                        : SK_PassByIndirectRestore);
2691   s.Type = type;
2692   Steps.push_back(s);
2693 }
2694 
2695 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2696   Step S;
2697   S.Kind = SK_ProduceObjCObject;
2698   S.Type = T;
2699   Steps.push_back(S);
2700 }
2701 
2702 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2703                                                 OverloadingResult Result) {
2704   setSequenceKind(FailedSequence);
2705   this->Failure = Failure;
2706   this->FailedOverloadResult = Result;
2707 }
2708 
2709 //===----------------------------------------------------------------------===//
2710 // Attempt initialization
2711 //===----------------------------------------------------------------------===//
2712 
2713 static void MaybeProduceObjCObject(Sema &S,
2714                                    InitializationSequence &Sequence,
2715                                    const InitializedEntity &Entity) {
2716   if (!S.getLangOptions().ObjCAutoRefCount) return;
2717 
2718   /// When initializing a parameter, produce the value if it's marked
2719   /// __attribute__((ns_consumed)).
2720   if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2721     if (!Entity.isParameterConsumed())
2722       return;
2723 
2724     assert(Entity.getType()->isObjCRetainableType() &&
2725            "consuming an object of unretainable type?");
2726     Sequence.AddProduceObjCObjectStep(Entity.getType());
2727 
2728   /// When initializing a return value, if the return type is a
2729   /// retainable type, then returns need to immediately retain the
2730   /// object.  If an autorelease is required, it will be done at the
2731   /// last instant.
2732   } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2733     if (!Entity.getType()->isObjCRetainableType())
2734       return;
2735 
2736     Sequence.AddProduceObjCObjectStep(Entity.getType());
2737   }
2738 }
2739 
2740 /// \brief Attempt list initialization (C++0x [dcl.init.list])
2741 static void TryListInitialization(Sema &S,
2742                                   const InitializedEntity &Entity,
2743                                   const InitializationKind &Kind,
2744                                   InitListExpr *InitList,
2745                                   InitializationSequence &Sequence) {
2746   QualType DestType = Entity.getType();
2747 
2748   // C++ doesn't allow scalar initialization with more than one argument.
2749   // But C99 complex numbers are scalars and it makes sense there.
2750   if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2751       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2752     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2753     return;
2754   }
2755   // FIXME: C++0x defines behavior for these two cases.
2756   if (DestType->isReferenceType()) {
2757     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2758     return;
2759   }
2760   if (DestType->isRecordType() && !DestType->isAggregateType()) {
2761     Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2762     return;
2763   }
2764 
2765   InitListChecker CheckInitList(S, Entity, InitList,
2766           DestType, /*VerifyOnly=*/true);
2767   if (CheckInitList.HadError()) {
2768     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2769     return;
2770   }
2771 
2772   // Add the list initialization step with the built init list.
2773   Sequence.AddListInitializationStep(DestType);
2774 }
2775 
2776 /// \brief Try a reference initialization that involves calling a conversion
2777 /// function.
2778 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2779                                              const InitializedEntity &Entity,
2780                                              const InitializationKind &Kind,
2781                                                           Expr *Initializer,
2782                                                           bool AllowRValues,
2783                                              InitializationSequence &Sequence) {
2784   QualType DestType = Entity.getType();
2785   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2786   QualType T1 = cv1T1.getUnqualifiedType();
2787   QualType cv2T2 = Initializer->getType();
2788   QualType T2 = cv2T2.getUnqualifiedType();
2789 
2790   bool DerivedToBase;
2791   bool ObjCConversion;
2792   bool ObjCLifetimeConversion;
2793   assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2794                                          T1, T2, DerivedToBase,
2795                                          ObjCConversion,
2796                                          ObjCLifetimeConversion) &&
2797          "Must have incompatible references when binding via conversion");
2798   (void)DerivedToBase;
2799   (void)ObjCConversion;
2800   (void)ObjCLifetimeConversion;
2801 
2802   // Build the candidate set directly in the initialization sequence
2803   // structure, so that it will persist if we fail.
2804   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2805   CandidateSet.clear();
2806 
2807   // Determine whether we are allowed to call explicit constructors or
2808   // explicit conversion operators.
2809   bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2810 
2811   const RecordType *T1RecordType = 0;
2812   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2813       !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
2814     // The type we're converting to is a class type. Enumerate its constructors
2815     // to see if there is a suitable conversion.
2816     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2817 
2818     DeclContext::lookup_iterator Con, ConEnd;
2819     for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
2820          Con != ConEnd; ++Con) {
2821       NamedDecl *D = *Con;
2822       DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2823 
2824       // Find the constructor (which may be a template).
2825       CXXConstructorDecl *Constructor = 0;
2826       FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2827       if (ConstructorTmpl)
2828         Constructor = cast<CXXConstructorDecl>(
2829                                          ConstructorTmpl->getTemplatedDecl());
2830       else
2831         Constructor = cast<CXXConstructorDecl>(D);
2832 
2833       if (!Constructor->isInvalidDecl() &&
2834           Constructor->isConvertingConstructor(AllowExplicit)) {
2835         if (ConstructorTmpl)
2836           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2837                                          /*ExplicitArgs*/ 0,
2838                                          &Initializer, 1, CandidateSet,
2839                                          /*SuppressUserConversions=*/true);
2840         else
2841           S.AddOverloadCandidate(Constructor, FoundDecl,
2842                                  &Initializer, 1, CandidateSet,
2843                                  /*SuppressUserConversions=*/true);
2844       }
2845     }
2846   }
2847   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2848     return OR_No_Viable_Function;
2849 
2850   const RecordType *T2RecordType = 0;
2851   if ((T2RecordType = T2->getAs<RecordType>()) &&
2852       !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
2853     // The type we're converting from is a class type, enumerate its conversion
2854     // functions.
2855     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2856 
2857     const UnresolvedSetImpl *Conversions
2858       = T2RecordDecl->getVisibleConversionFunctions();
2859     for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2860            E = Conversions->end(); I != E; ++I) {
2861       NamedDecl *D = *I;
2862       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2863       if (isa<UsingShadowDecl>(D))
2864         D = cast<UsingShadowDecl>(D)->getTargetDecl();
2865 
2866       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2867       CXXConversionDecl *Conv;
2868       if (ConvTemplate)
2869         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2870       else
2871         Conv = cast<CXXConversionDecl>(D);
2872 
2873       // If the conversion function doesn't return a reference type,
2874       // it can't be considered for this conversion unless we're allowed to
2875       // consider rvalues.
2876       // FIXME: Do we need to make sure that we only consider conversion
2877       // candidates with reference-compatible results? That might be needed to
2878       // break recursion.
2879       if ((AllowExplicit || !Conv->isExplicit()) &&
2880           (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2881         if (ConvTemplate)
2882           S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
2883                                            ActingDC, Initializer,
2884                                            DestType, CandidateSet);
2885         else
2886           S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
2887                                    Initializer, DestType, CandidateSet);
2888       }
2889     }
2890   }
2891   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2892     return OR_No_Viable_Function;
2893 
2894   SourceLocation DeclLoc = Initializer->getLocStart();
2895 
2896   // Perform overload resolution. If it fails, return the failed result.
2897   OverloadCandidateSet::iterator Best;
2898   if (OverloadingResult Result
2899         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
2900     return Result;
2901 
2902   FunctionDecl *Function = Best->Function;
2903 
2904   // This is the overload that will actually be used for the initialization, so
2905   // mark it as used.
2906   S.MarkDeclarationReferenced(DeclLoc, Function);
2907 
2908   // Compute the returned type of the conversion.
2909   if (isa<CXXConversionDecl>(Function))
2910     T2 = Function->getResultType();
2911   else
2912     T2 = cv1T1;
2913 
2914   // Add the user-defined conversion step.
2915   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
2916                                  T2.getNonLValueExprType(S.Context));
2917 
2918   // Determine whether we need to perform derived-to-base or
2919   // cv-qualification adjustments.
2920   ExprValueKind VK = VK_RValue;
2921   if (T2->isLValueReferenceType())
2922     VK = VK_LValue;
2923   else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
2924     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
2925 
2926   bool NewDerivedToBase = false;
2927   bool NewObjCConversion = false;
2928   bool NewObjCLifetimeConversion = false;
2929   Sema::ReferenceCompareResult NewRefRelationship
2930     = S.CompareReferenceRelationship(DeclLoc, T1,
2931                                      T2.getNonLValueExprType(S.Context),
2932                                      NewDerivedToBase, NewObjCConversion,
2933                                      NewObjCLifetimeConversion);
2934   if (NewRefRelationship == Sema::Ref_Incompatible) {
2935     // If the type we've converted to is not reference-related to the
2936     // type we're looking for, then there is another conversion step
2937     // we need to perform to produce a temporary of the right type
2938     // that we'll be binding to.
2939     ImplicitConversionSequence ICS;
2940     ICS.setStandard();
2941     ICS.Standard = Best->FinalConversion;
2942     T2 = ICS.Standard.getToType(2);
2943     Sequence.AddConversionSequenceStep(ICS, T2);
2944   } else if (NewDerivedToBase)
2945     Sequence.AddDerivedToBaseCastStep(
2946                                 S.Context.getQualifiedType(T1,
2947                                   T2.getNonReferenceType().getQualifiers()),
2948                                       VK);
2949   else if (NewObjCConversion)
2950     Sequence.AddObjCObjectConversionStep(
2951                                 S.Context.getQualifiedType(T1,
2952                                   T2.getNonReferenceType().getQualifiers()));
2953 
2954   if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2955     Sequence.AddQualificationConversionStep(cv1T1, VK);
2956 
2957   Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2958   return OR_Success;
2959 }
2960 
2961 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2962 static void TryReferenceInitialization(Sema &S,
2963                                        const InitializedEntity &Entity,
2964                                        const InitializationKind &Kind,
2965                                        Expr *Initializer,
2966                                        InitializationSequence &Sequence) {
2967   QualType DestType = Entity.getType();
2968   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2969   Qualifiers T1Quals;
2970   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2971   QualType cv2T2 = Initializer->getType();
2972   Qualifiers T2Quals;
2973   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2974   SourceLocation DeclLoc = Initializer->getLocStart();
2975 
2976   // If the initializer is the address of an overloaded function, try
2977   // to resolve the overloaded function. If all goes well, T2 is the
2978   // type of the resulting function.
2979   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2980     DeclAccessPair Found;
2981     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2982                                                                 T1,
2983                                                                 false,
2984                                                                 Found)) {
2985       Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2986       cv2T2 = Fn->getType();
2987       T2 = cv2T2.getUnqualifiedType();
2988     } else if (!T1->isRecordType()) {
2989       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2990       return;
2991     }
2992   }
2993 
2994   // Compute some basic properties of the types and the initializer.
2995   bool isLValueRef = DestType->isLValueReferenceType();
2996   bool isRValueRef = !isLValueRef;
2997   bool DerivedToBase = false;
2998   bool ObjCConversion = false;
2999   bool ObjCLifetimeConversion = false;
3000   Expr::Classification InitCategory = Initializer->Classify(S.Context);
3001   Sema::ReferenceCompareResult RefRelationship
3002     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3003                                      ObjCConversion, ObjCLifetimeConversion);
3004 
3005   // C++0x [dcl.init.ref]p5:
3006   //   A reference to type "cv1 T1" is initialized by an expression of type
3007   //   "cv2 T2" as follows:
3008   //
3009   //     - If the reference is an lvalue reference and the initializer
3010   //       expression
3011   // Note the analogous bullet points for rvlaue refs to functions. Because
3012   // there are no function rvalues in C++, rvalue refs to functions are treated
3013   // like lvalue refs.
3014   OverloadingResult ConvOvlResult = OR_Success;
3015   bool T1Function = T1->isFunctionType();
3016   if (isLValueRef || T1Function) {
3017     if (InitCategory.isLValue() &&
3018         (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3019          (Kind.isCStyleOrFunctionalCast() &&
3020           RefRelationship == Sema::Ref_Related))) {
3021       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3022       //     reference-compatible with "cv2 T2," or
3023       //
3024       // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3025       // bit-field when we're determining whether the reference initialization
3026       // can occur. However, we do pay attention to whether it is a bit-field
3027       // to decide whether we're actually binding to a temporary created from
3028       // the bit-field.
3029       if (DerivedToBase)
3030         Sequence.AddDerivedToBaseCastStep(
3031                          S.Context.getQualifiedType(T1, T2Quals),
3032                          VK_LValue);
3033       else if (ObjCConversion)
3034         Sequence.AddObjCObjectConversionStep(
3035                                      S.Context.getQualifiedType(T1, T2Quals));
3036 
3037       if (T1Quals != T2Quals)
3038         Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
3039       bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
3040         (Initializer->getBitField() || Initializer->refersToVectorElement());
3041       Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
3042       return;
3043     }
3044 
3045     //     - has a class type (i.e., T2 is a class type), where T1 is not
3046     //       reference-related to T2, and can be implicitly converted to an
3047     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3048     //       with "cv3 T3" (this conversion is selected by enumerating the
3049     //       applicable conversion functions (13.3.1.6) and choosing the best
3050     //       one through overload resolution (13.3)),
3051     // If we have an rvalue ref to function type here, the rhs must be
3052     // an rvalue.
3053     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3054         (isLValueRef || InitCategory.isRValue())) {
3055       ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3056                                                        Initializer,
3057                                                    /*AllowRValues=*/isRValueRef,
3058                                                        Sequence);
3059       if (ConvOvlResult == OR_Success)
3060         return;
3061       if (ConvOvlResult != OR_No_Viable_Function) {
3062         Sequence.SetOverloadFailure(
3063                       InitializationSequence::FK_ReferenceInitOverloadFailed,
3064                                     ConvOvlResult);
3065       }
3066     }
3067   }
3068 
3069   //     - Otherwise, the reference shall be an lvalue reference to a
3070   //       non-volatile const type (i.e., cv1 shall be const), or the reference
3071   //       shall be an rvalue reference.
3072   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3073     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3074       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3075     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3076       Sequence.SetOverloadFailure(
3077                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3078                                   ConvOvlResult);
3079     else
3080       Sequence.SetFailed(InitCategory.isLValue()
3081         ? (RefRelationship == Sema::Ref_Related
3082              ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3083              : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3084         : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3085 
3086     return;
3087   }
3088 
3089   //    - If the initializer expression
3090   //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3091   //        "cv1 T1" is reference-compatible with "cv2 T2"
3092   // Note: functions are handled below.
3093   if (!T1Function &&
3094       (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3095        (Kind.isCStyleOrFunctionalCast() &&
3096         RefRelationship == Sema::Ref_Related)) &&
3097       (InitCategory.isXValue() ||
3098        (InitCategory.isPRValue() && T2->isRecordType()) ||
3099        (InitCategory.isPRValue() && T2->isArrayType()))) {
3100     ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3101     if (InitCategory.isPRValue() && T2->isRecordType()) {
3102       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3103       // compiler the freedom to perform a copy here or bind to the
3104       // object, while C++0x requires that we bind directly to the
3105       // object. Hence, we always bind to the object without making an
3106       // extra copy. However, in C++03 requires that we check for the
3107       // presence of a suitable copy constructor:
3108       //
3109       //   The constructor that would be used to make the copy shall
3110       //   be callable whether or not the copy is actually done.
3111       if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
3112         Sequence.AddExtraneousCopyToTemporary(cv2T2);
3113     }
3114 
3115     if (DerivedToBase)
3116       Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3117                                         ValueKind);
3118     else if (ObjCConversion)
3119       Sequence.AddObjCObjectConversionStep(
3120                                        S.Context.getQualifiedType(T1, T2Quals));
3121 
3122     if (T1Quals != T2Quals)
3123       Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
3124     Sequence.AddReferenceBindingStep(cv1T1,
3125          /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
3126     return;
3127   }
3128 
3129   //       - has a class type (i.e., T2 is a class type), where T1 is not
3130   //         reference-related to T2, and can be implicitly converted to an
3131   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3132   //         where "cv1 T1" is reference-compatible with "cv3 T3",
3133   if (T2->isRecordType()) {
3134     if (RefRelationship == Sema::Ref_Incompatible) {
3135       ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3136                                                        Kind, Initializer,
3137                                                        /*AllowRValues=*/true,
3138                                                        Sequence);
3139       if (ConvOvlResult)
3140         Sequence.SetOverloadFailure(
3141                       InitializationSequence::FK_ReferenceInitOverloadFailed,
3142                                     ConvOvlResult);
3143 
3144       return;
3145     }
3146 
3147     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3148     return;
3149   }
3150 
3151   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3152   //        from the initializer expression using the rules for a non-reference
3153   //        copy initialization (8.5). The reference is then bound to the
3154   //        temporary. [...]
3155 
3156   // Determine whether we are allowed to call explicit constructors or
3157   // explicit conversion operators.
3158   bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
3159 
3160   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3161 
3162   ImplicitConversionSequence ICS
3163     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3164                               /*SuppressUserConversions*/ false,
3165                               AllowExplicit,
3166                               /*FIXME:InOverloadResolution=*/false,
3167                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3168                               /*AllowObjCWritebackConversion=*/false);
3169 
3170   if (ICS.isBad()) {
3171     // FIXME: Use the conversion function set stored in ICS to turn
3172     // this into an overloading ambiguity diagnostic. However, we need
3173     // to keep that set as an OverloadCandidateSet rather than as some
3174     // other kind of set.
3175     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3176       Sequence.SetOverloadFailure(
3177                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3178                                   ConvOvlResult);
3179     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3180       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3181     else
3182       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3183     return;
3184   } else {
3185     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3186   }
3187 
3188   //        [...] If T1 is reference-related to T2, cv1 must be the
3189   //        same cv-qualification as, or greater cv-qualification
3190   //        than, cv2; otherwise, the program is ill-formed.
3191   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3192   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3193   if (RefRelationship == Sema::Ref_Related &&
3194       (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3195     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3196     return;
3197   }
3198 
3199   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3200   //   reference, the initializer expression shall not be an lvalue.
3201   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3202       InitCategory.isLValue()) {
3203     Sequence.SetFailed(
3204                     InitializationSequence::FK_RValueReferenceBindingToLValue);
3205     return;
3206   }
3207 
3208   Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3209   return;
3210 }
3211 
3212 /// \brief Attempt character array initialization from a string literal
3213 /// (C++ [dcl.init.string], C99 6.7.8).
3214 static void TryStringLiteralInitialization(Sema &S,
3215                                            const InitializedEntity &Entity,
3216                                            const InitializationKind &Kind,
3217                                            Expr *Initializer,
3218                                        InitializationSequence &Sequence) {
3219   Sequence.AddStringInitStep(Entity.getType());
3220 }
3221 
3222 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3223 /// enumerates the constructors of the initialized entity and performs overload
3224 /// resolution to select the best.
3225 static void TryConstructorInitialization(Sema &S,
3226                                          const InitializedEntity &Entity,
3227                                          const InitializationKind &Kind,
3228                                          Expr **Args, unsigned NumArgs,
3229                                          QualType DestType,
3230                                          InitializationSequence &Sequence) {
3231   // Check constructor arguments for self reference.
3232   if (DeclaratorDecl *DD = Entity.getDecl())
3233     // Parameters arguments are occassionially constructed with itself,
3234     // for instance, in recursive functions.  Skip them.
3235     if (!isa<ParmVarDecl>(DD))
3236       for (unsigned i = 0; i < NumArgs; ++i)
3237         S.CheckSelfReference(DD, Args[i]);
3238 
3239   // Build the candidate set directly in the initialization sequence
3240   // structure, so that it will persist if we fail.
3241   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3242   CandidateSet.clear();
3243 
3244   // Determine whether we are allowed to call explicit constructors or
3245   // explicit conversion operators.
3246   bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3247                         Kind.getKind() == InitializationKind::IK_Value ||
3248                         Kind.getKind() == InitializationKind::IK_Default);
3249 
3250   // The type we're constructing needs to be complete.
3251   if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3252     Sequence.SetFailed(InitializationSequence::FK_Incomplete);
3253     return;
3254   }
3255 
3256   // The type we're converting to is a class type. Enumerate its constructors
3257   // to see if one is suitable.
3258   const RecordType *DestRecordType = DestType->getAs<RecordType>();
3259   assert(DestRecordType && "Constructor initialization requires record type");
3260   CXXRecordDecl *DestRecordDecl
3261     = cast<CXXRecordDecl>(DestRecordType->getDecl());
3262 
3263   DeclContext::lookup_iterator Con, ConEnd;
3264   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3265        Con != ConEnd; ++Con) {
3266     NamedDecl *D = *Con;
3267     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3268     bool SuppressUserConversions = false;
3269 
3270     // Find the constructor (which may be a template).
3271     CXXConstructorDecl *Constructor = 0;
3272     FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3273     if (ConstructorTmpl)
3274       Constructor = cast<CXXConstructorDecl>(
3275                                            ConstructorTmpl->getTemplatedDecl());
3276     else {
3277       Constructor = cast<CXXConstructorDecl>(D);
3278 
3279       // If we're performing copy initialization using a copy constructor, we
3280       // suppress user-defined conversions on the arguments.
3281       // FIXME: Move constructors?
3282       if (Kind.getKind() == InitializationKind::IK_Copy &&
3283           Constructor->isCopyConstructor())
3284         SuppressUserConversions = true;
3285     }
3286 
3287     if (!Constructor->isInvalidDecl() &&
3288         (AllowExplicit || !Constructor->isExplicit())) {
3289       if (ConstructorTmpl)
3290         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3291                                        /*ExplicitArgs*/ 0,
3292                                        Args, NumArgs, CandidateSet,
3293                                        SuppressUserConversions);
3294       else
3295         S.AddOverloadCandidate(Constructor, FoundDecl,
3296                                Args, NumArgs, CandidateSet,
3297                                SuppressUserConversions);
3298     }
3299   }
3300 
3301   SourceLocation DeclLoc = Kind.getLocation();
3302 
3303   // Perform overload resolution. If it fails, return the failed result.
3304   OverloadCandidateSet::iterator Best;
3305   if (OverloadingResult Result
3306         = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
3307     Sequence.SetOverloadFailure(
3308                           InitializationSequence::FK_ConstructorOverloadFailed,
3309                                 Result);
3310     return;
3311   }
3312 
3313   // C++0x [dcl.init]p6:
3314   //   If a program calls for the default initialization of an object
3315   //   of a const-qualified type T, T shall be a class type with a
3316   //   user-provided default constructor.
3317   if (Kind.getKind() == InitializationKind::IK_Default &&
3318       Entity.getType().isConstQualified() &&
3319       cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3320     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3321     return;
3322   }
3323 
3324   // Add the constructor initialization step. Any cv-qualification conversion is
3325   // subsumed by the initialization.
3326   Sequence.AddConstructorInitializationStep(
3327                                       cast<CXXConstructorDecl>(Best->Function),
3328                                       Best->FoundDecl.getAccess(),
3329                                       DestType);
3330 }
3331 
3332 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3333 static void TryValueInitialization(Sema &S,
3334                                    const InitializedEntity &Entity,
3335                                    const InitializationKind &Kind,
3336                                    InitializationSequence &Sequence) {
3337   // C++ [dcl.init]p5:
3338   //
3339   //   To value-initialize an object of type T means:
3340   QualType T = Entity.getType();
3341 
3342   //     -- if T is an array type, then each element is value-initialized;
3343   while (const ArrayType *AT = S.Context.getAsArrayType(T))
3344     T = AT->getElementType();
3345 
3346   if (const RecordType *RT = T->getAs<RecordType>()) {
3347     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3348       // -- if T is a class type (clause 9) with a user-declared
3349       //    constructor (12.1), then the default constructor for T is
3350       //    called (and the initialization is ill-formed if T has no
3351       //    accessible default constructor);
3352       //
3353       // FIXME: we really want to refer to a single subobject of the array,
3354       // but Entity doesn't have a way to capture that (yet).
3355       if (ClassDecl->hasUserDeclaredConstructor())
3356         return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3357 
3358       // -- if T is a (possibly cv-qualified) non-union class type
3359       //    without a user-provided constructor, then the object is
3360       //    zero-initialized and, if T's implicitly-declared default
3361       //    constructor is non-trivial, that constructor is called.
3362       if ((ClassDecl->getTagKind() == TTK_Class ||
3363            ClassDecl->getTagKind() == TTK_Struct)) {
3364         Sequence.AddZeroInitializationStep(Entity.getType());
3365         return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3366       }
3367     }
3368   }
3369 
3370   Sequence.AddZeroInitializationStep(Entity.getType());
3371 }
3372 
3373 /// \brief Attempt default initialization (C++ [dcl.init]p6).
3374 static void TryDefaultInitialization(Sema &S,
3375                                      const InitializedEntity &Entity,
3376                                      const InitializationKind &Kind,
3377                                      InitializationSequence &Sequence) {
3378   assert(Kind.getKind() == InitializationKind::IK_Default);
3379 
3380   // C++ [dcl.init]p6:
3381   //   To default-initialize an object of type T means:
3382   //     - if T is an array type, each element is default-initialized;
3383   QualType DestType = S.Context.getBaseElementType(Entity.getType());
3384 
3385   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
3386   //       constructor for T is called (and the initialization is ill-formed if
3387   //       T has no accessible default constructor);
3388   if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
3389     TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3390     return;
3391   }
3392 
3393   //     - otherwise, no initialization is performed.
3394 
3395   //   If a program calls for the default initialization of an object of
3396   //   a const-qualified type T, T shall be a class type with a user-provided
3397   //   default constructor.
3398   if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
3399     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3400     return;
3401   }
3402 
3403   // If the destination type has a lifetime property, zero-initialize it.
3404   if (DestType.getQualifiers().hasObjCLifetime()) {
3405     Sequence.AddZeroInitializationStep(Entity.getType());
3406     return;
3407   }
3408 }
3409 
3410 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3411 /// which enumerates all conversion functions and performs overload resolution
3412 /// to select the best.
3413 static void TryUserDefinedConversion(Sema &S,
3414                                      const InitializedEntity &Entity,
3415                                      const InitializationKind &Kind,
3416                                      Expr *Initializer,
3417                                      InitializationSequence &Sequence) {
3418   QualType DestType = Entity.getType();
3419   assert(!DestType->isReferenceType() && "References are handled elsewhere");
3420   QualType SourceType = Initializer->getType();
3421   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3422          "Must have a class type to perform a user-defined conversion");
3423 
3424   // Build the candidate set directly in the initialization sequence
3425   // structure, so that it will persist if we fail.
3426   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3427   CandidateSet.clear();
3428 
3429   // Determine whether we are allowed to call explicit constructors or
3430   // explicit conversion operators.
3431   bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
3432 
3433   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3434     // The type we're converting to is a class type. Enumerate its constructors
3435     // to see if there is a suitable conversion.
3436     CXXRecordDecl *DestRecordDecl
3437       = cast<CXXRecordDecl>(DestRecordType->getDecl());
3438 
3439     // Try to complete the type we're converting to.
3440     if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3441       DeclContext::lookup_iterator Con, ConEnd;
3442       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3443            Con != ConEnd; ++Con) {
3444         NamedDecl *D = *Con;
3445         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3446 
3447         // Find the constructor (which may be a template).
3448         CXXConstructorDecl *Constructor = 0;
3449         FunctionTemplateDecl *ConstructorTmpl
3450           = dyn_cast<FunctionTemplateDecl>(D);
3451         if (ConstructorTmpl)
3452           Constructor = cast<CXXConstructorDecl>(
3453                                            ConstructorTmpl->getTemplatedDecl());
3454         else
3455           Constructor = cast<CXXConstructorDecl>(D);
3456 
3457         if (!Constructor->isInvalidDecl() &&
3458             Constructor->isConvertingConstructor(AllowExplicit)) {
3459           if (ConstructorTmpl)
3460             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3461                                            /*ExplicitArgs*/ 0,
3462                                            &Initializer, 1, CandidateSet,
3463                                            /*SuppressUserConversions=*/true);
3464           else
3465             S.AddOverloadCandidate(Constructor, FoundDecl,
3466                                    &Initializer, 1, CandidateSet,
3467                                    /*SuppressUserConversions=*/true);
3468         }
3469       }
3470     }
3471   }
3472 
3473   SourceLocation DeclLoc = Initializer->getLocStart();
3474 
3475   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3476     // The type we're converting from is a class type, enumerate its conversion
3477     // functions.
3478 
3479     // We can only enumerate the conversion functions for a complete type; if
3480     // the type isn't complete, simply skip this step.
3481     if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3482       CXXRecordDecl *SourceRecordDecl
3483         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3484 
3485       const UnresolvedSetImpl *Conversions
3486         = SourceRecordDecl->getVisibleConversionFunctions();
3487       for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3488            E = Conversions->end();
3489            I != E; ++I) {
3490         NamedDecl *D = *I;
3491         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3492         if (isa<UsingShadowDecl>(D))
3493           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3494 
3495         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3496         CXXConversionDecl *Conv;
3497         if (ConvTemplate)
3498           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3499         else
3500           Conv = cast<CXXConversionDecl>(D);
3501 
3502         if (AllowExplicit || !Conv->isExplicit()) {
3503           if (ConvTemplate)
3504             S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3505                                              ActingDC, Initializer, DestType,
3506                                              CandidateSet);
3507           else
3508             S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3509                                      Initializer, DestType, CandidateSet);
3510         }
3511       }
3512     }
3513   }
3514 
3515   // Perform overload resolution. If it fails, return the failed result.
3516   OverloadCandidateSet::iterator Best;
3517   if (OverloadingResult Result
3518         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3519     Sequence.SetOverloadFailure(
3520                         InitializationSequence::FK_UserConversionOverloadFailed,
3521                                 Result);
3522     return;
3523   }
3524 
3525   FunctionDecl *Function = Best->Function;
3526   S.MarkDeclarationReferenced(DeclLoc, Function);
3527 
3528   if (isa<CXXConstructorDecl>(Function)) {
3529     // Add the user-defined conversion step. Any cv-qualification conversion is
3530     // subsumed by the initialization.
3531     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3532     return;
3533   }
3534 
3535   // Add the user-defined conversion step that calls the conversion function.
3536   QualType ConvType = Function->getCallResultType();
3537   if (ConvType->getAs<RecordType>()) {
3538     // If we're converting to a class type, there may be an copy if
3539     // the resulting temporary object (possible to create an object of
3540     // a base class type). That copy is not a separate conversion, so
3541     // we just make a note of the actual destination type (possibly a
3542     // base class of the type returned by the conversion function) and
3543     // let the user-defined conversion step handle the conversion.
3544     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3545     return;
3546   }
3547 
3548   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3549 
3550   // If the conversion following the call to the conversion function
3551   // is interesting, add it as a separate step.
3552   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3553       Best->FinalConversion.Third) {
3554     ImplicitConversionSequence ICS;
3555     ICS.setStandard();
3556     ICS.Standard = Best->FinalConversion;
3557     Sequence.AddConversionSequenceStep(ICS, DestType);
3558   }
3559 }
3560 
3561 /// The non-zero enum values here are indexes into diagnostic alternatives.
3562 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3563 
3564 /// Determines whether this expression is an acceptable ICR source.
3565 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3566                                          bool isAddressOf) {
3567   // Skip parens.
3568   e = e->IgnoreParens();
3569 
3570   // Skip address-of nodes.
3571   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3572     if (op->getOpcode() == UO_AddrOf)
3573       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
3574 
3575   // Skip certain casts.
3576   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3577     switch (ce->getCastKind()) {
3578     case CK_Dependent:
3579     case CK_BitCast:
3580     case CK_LValueBitCast:
3581     case CK_NoOp:
3582       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
3583 
3584     case CK_ArrayToPointerDecay:
3585       return IIK_nonscalar;
3586 
3587     case CK_NullToPointer:
3588       return IIK_okay;
3589 
3590     default:
3591       break;
3592     }
3593 
3594   // If we have a declaration reference, it had better be a local variable.
3595   } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3596     if (!isAddressOf) return IIK_nonlocal;
3597 
3598     VarDecl *var;
3599     if (isa<DeclRefExpr>(e)) {
3600       var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3601       if (!var) return IIK_nonlocal;
3602     } else {
3603       var = cast<BlockDeclRefExpr>(e)->getDecl();
3604     }
3605 
3606     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3607 
3608   // If we have a conditional operator, check both sides.
3609   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3610     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
3611       return iik;
3612 
3613     return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
3614 
3615   // These are never scalar.
3616   } else if (isa<ArraySubscriptExpr>(e)) {
3617     return IIK_nonscalar;
3618 
3619   // Otherwise, it needs to be a null pointer constant.
3620   } else {
3621     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3622             ? IIK_okay : IIK_nonlocal);
3623   }
3624 
3625   return IIK_nonlocal;
3626 }
3627 
3628 /// Check whether the given expression is a valid operand for an
3629 /// indirect copy/restore.
3630 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3631   assert(src->isRValue());
3632 
3633   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
3634   if (iik == IIK_okay) return;
3635 
3636   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3637     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
3638     << src->getSourceRange();
3639 }
3640 
3641 /// \brief Determine whether we have compatible array types for the
3642 /// purposes of GNU by-copy array initialization.
3643 static bool hasCompatibleArrayTypes(ASTContext &Context,
3644                                     const ArrayType *Dest,
3645                                     const ArrayType *Source) {
3646   // If the source and destination array types are equivalent, we're
3647   // done.
3648   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3649     return true;
3650 
3651   // Make sure that the element types are the same.
3652   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3653     return false;
3654 
3655   // The only mismatch we allow is when the destination is an
3656   // incomplete array type and the source is a constant array type.
3657   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3658 }
3659 
3660 static bool tryObjCWritebackConversion(Sema &S,
3661                                        InitializationSequence &Sequence,
3662                                        const InitializedEntity &Entity,
3663                                        Expr *Initializer) {
3664   bool ArrayDecay = false;
3665   QualType ArgType = Initializer->getType();
3666   QualType ArgPointee;
3667   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3668     ArrayDecay = true;
3669     ArgPointee = ArgArrayType->getElementType();
3670     ArgType = S.Context.getPointerType(ArgPointee);
3671   }
3672 
3673   // Handle write-back conversion.
3674   QualType ConvertedArgType;
3675   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3676                                    ConvertedArgType))
3677     return false;
3678 
3679   // We should copy unless we're passing to an argument explicitly
3680   // marked 'out'.
3681   bool ShouldCopy = true;
3682   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3683     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3684 
3685   // Do we need an lvalue conversion?
3686   if (ArrayDecay || Initializer->isGLValue()) {
3687     ImplicitConversionSequence ICS;
3688     ICS.setStandard();
3689     ICS.Standard.setAsIdentityConversion();
3690 
3691     QualType ResultType;
3692     if (ArrayDecay) {
3693       ICS.Standard.First = ICK_Array_To_Pointer;
3694       ResultType = S.Context.getPointerType(ArgPointee);
3695     } else {
3696       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3697       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3698     }
3699 
3700     Sequence.AddConversionSequenceStep(ICS, ResultType);
3701   }
3702 
3703   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3704   return true;
3705 }
3706 
3707 InitializationSequence::InitializationSequence(Sema &S,
3708                                                const InitializedEntity &Entity,
3709                                                const InitializationKind &Kind,
3710                                                Expr **Args,
3711                                                unsigned NumArgs)
3712     : FailedCandidateSet(Kind.getLocation()) {
3713   ASTContext &Context = S.Context;
3714 
3715   // C++0x [dcl.init]p16:
3716   //   The semantics of initializers are as follows. The destination type is
3717   //   the type of the object or reference being initialized and the source
3718   //   type is the type of the initializer expression. The source type is not
3719   //   defined when the initializer is a braced-init-list or when it is a
3720   //   parenthesized list of expressions.
3721   QualType DestType = Entity.getType();
3722 
3723   if (DestType->isDependentType() ||
3724       Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3725     SequenceKind = DependentSequence;
3726     return;
3727   }
3728 
3729   // Almost everything is a normal sequence.
3730   setSequenceKind(NormalSequence);
3731 
3732   for (unsigned I = 0; I != NumArgs; ++I)
3733     if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3734       ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3735       if (Result.isInvalid()) {
3736         SetFailed(FK_ConversionFromPropertyFailed);
3737         return;
3738       }
3739       Args[I] = Result.take();
3740     }
3741 
3742   QualType SourceType;
3743   Expr *Initializer = 0;
3744   if (NumArgs == 1) {
3745     Initializer = Args[0];
3746     if (!isa<InitListExpr>(Initializer))
3747       SourceType = Initializer->getType();
3748   }
3749 
3750   //     - If the initializer is a braced-init-list, the object is
3751   //       list-initialized (8.5.4).
3752   if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3753     TryListInitialization(S, Entity, Kind, InitList, *this);
3754     return;
3755   }
3756 
3757   //     - If the destination type is a reference type, see 8.5.3.
3758   if (DestType->isReferenceType()) {
3759     // C++0x [dcl.init.ref]p1:
3760     //   A variable declared to be a T& or T&&, that is, "reference to type T"
3761     //   (8.3.2), shall be initialized by an object, or function, of type T or
3762     //   by an object that can be converted into a T.
3763     // (Therefore, multiple arguments are not permitted.)
3764     if (NumArgs != 1)
3765       SetFailed(FK_TooManyInitsForReference);
3766     else
3767       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3768     return;
3769   }
3770 
3771   //     - If the initializer is (), the object is value-initialized.
3772   if (Kind.getKind() == InitializationKind::IK_Value ||
3773       (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
3774     TryValueInitialization(S, Entity, Kind, *this);
3775     return;
3776   }
3777 
3778   // Handle default initialization.
3779   if (Kind.getKind() == InitializationKind::IK_Default) {
3780     TryDefaultInitialization(S, Entity, Kind, *this);
3781     return;
3782   }
3783 
3784   //     - If the destination type is an array of characters, an array of
3785   //       char16_t, an array of char32_t, or an array of wchar_t, and the
3786   //       initializer is a string literal, see 8.5.2.
3787   //     - Otherwise, if the destination type is an array, the program is
3788   //       ill-formed.
3789   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3790     if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
3791       TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3792       return;
3793     }
3794 
3795     // Note: as an GNU C extension, we allow initialization of an
3796     // array from a compound literal that creates an array of the same
3797     // type, so long as the initializer has no side effects.
3798     if (!S.getLangOptions().CPlusPlus && Initializer &&
3799         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3800         Initializer->getType()->isArrayType()) {
3801       const ArrayType *SourceAT
3802         = Context.getAsArrayType(Initializer->getType());
3803       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3804         SetFailed(FK_ArrayTypeMismatch);
3805       else if (Initializer->HasSideEffects(S.Context))
3806         SetFailed(FK_NonConstantArrayInit);
3807       else {
3808         AddArrayInitStep(DestType);
3809       }
3810     } else if (DestAT->getElementType()->isAnyCharacterType())
3811       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3812     else
3813       SetFailed(FK_ArrayNeedsInitList);
3814 
3815     return;
3816   }
3817 
3818   // Determine whether we should consider writeback conversions for
3819   // Objective-C ARC.
3820   bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3821     Entity.getKind() == InitializedEntity::EK_Parameter;
3822 
3823   // We're at the end of the line for C: it's either a write-back conversion
3824   // or it's a C assignment. There's no need to check anything else.
3825   if (!S.getLangOptions().CPlusPlus) {
3826     // If allowed, check whether this is an Objective-C writeback conversion.
3827     if (allowObjCWritebackConversion &&
3828         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
3829       return;
3830     }
3831 
3832     // Handle initialization in C
3833     AddCAssignmentStep(DestType);
3834     MaybeProduceObjCObject(S, *this, Entity);
3835     return;
3836   }
3837 
3838   assert(S.getLangOptions().CPlusPlus);
3839 
3840   //     - If the destination type is a (possibly cv-qualified) class type:
3841   if (DestType->isRecordType()) {
3842     //     - If the initialization is direct-initialization, or if it is
3843     //       copy-initialization where the cv-unqualified version of the
3844     //       source type is the same class as, or a derived class of, the
3845     //       class of the destination, constructors are considered. [...]
3846     if (Kind.getKind() == InitializationKind::IK_Direct ||
3847         (Kind.getKind() == InitializationKind::IK_Copy &&
3848          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3849           S.IsDerivedFrom(SourceType, DestType))))
3850       TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
3851                                    Entity.getType(), *this);
3852     //     - Otherwise (i.e., for the remaining copy-initialization cases),
3853     //       user-defined conversion sequences that can convert from the source
3854     //       type to the destination type or (when a conversion function is
3855     //       used) to a derived class thereof are enumerated as described in
3856     //       13.3.1.4, and the best one is chosen through overload resolution
3857     //       (13.3).
3858     else
3859       TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3860     return;
3861   }
3862 
3863   if (NumArgs > 1) {
3864     SetFailed(FK_TooManyInitsForScalar);
3865     return;
3866   }
3867   assert(NumArgs == 1 && "Zero-argument case handled above");
3868 
3869   //    - Otherwise, if the source type is a (possibly cv-qualified) class
3870   //      type, conversion functions are considered.
3871   if (!SourceType.isNull() && SourceType->isRecordType()) {
3872     TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3873     MaybeProduceObjCObject(S, *this, Entity);
3874     return;
3875   }
3876 
3877   //    - Otherwise, the initial value of the object being initialized is the
3878   //      (possibly converted) value of the initializer expression. Standard
3879   //      conversions (Clause 4) will be used, if necessary, to convert the
3880   //      initializer expression to the cv-unqualified version of the
3881   //      destination type; no user-defined conversions are considered.
3882 
3883   ImplicitConversionSequence ICS
3884     = S.TryImplicitConversion(Initializer, Entity.getType(),
3885                               /*SuppressUserConversions*/true,
3886                               /*AllowExplicitConversions*/ false,
3887                               /*InOverloadResolution*/ false,
3888                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3889                               allowObjCWritebackConversion);
3890 
3891   if (ICS.isStandard() &&
3892       ICS.Standard.Second == ICK_Writeback_Conversion) {
3893     // Objective-C ARC writeback conversion.
3894 
3895     // We should copy unless we're passing to an argument explicitly
3896     // marked 'out'.
3897     bool ShouldCopy = true;
3898     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3899       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3900 
3901     // If there was an lvalue adjustment, add it as a separate conversion.
3902     if (ICS.Standard.First == ICK_Array_To_Pointer ||
3903         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3904       ImplicitConversionSequence LvalueICS;
3905       LvalueICS.setStandard();
3906       LvalueICS.Standard.setAsIdentityConversion();
3907       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3908       LvalueICS.Standard.First = ICS.Standard.First;
3909       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
3910     }
3911 
3912     AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3913   } else if (ICS.isBad()) {
3914     DeclAccessPair dap;
3915     if (Initializer->getType() == Context.OverloadTy &&
3916           !S.ResolveAddressOfOverloadedFunction(Initializer
3917                       , DestType, false, dap))
3918       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3919     else
3920       SetFailed(InitializationSequence::FK_ConversionFailed);
3921   } else {
3922     AddConversionSequenceStep(ICS, Entity.getType());
3923 
3924     MaybeProduceObjCObject(S, *this, Entity);
3925   }
3926 }
3927 
3928 InitializationSequence::~InitializationSequence() {
3929   for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3930                                           StepEnd = Steps.end();
3931        Step != StepEnd; ++Step)
3932     Step->Destroy();
3933 }
3934 
3935 //===----------------------------------------------------------------------===//
3936 // Perform initialization
3937 //===----------------------------------------------------------------------===//
3938 static Sema::AssignmentAction
3939 getAssignmentAction(const InitializedEntity &Entity) {
3940   switch(Entity.getKind()) {
3941   case InitializedEntity::EK_Variable:
3942   case InitializedEntity::EK_New:
3943   case InitializedEntity::EK_Exception:
3944   case InitializedEntity::EK_Base:
3945   case InitializedEntity::EK_Delegating:
3946     return Sema::AA_Initializing;
3947 
3948   case InitializedEntity::EK_Parameter:
3949     if (Entity.getDecl() &&
3950         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3951       return Sema::AA_Sending;
3952 
3953     return Sema::AA_Passing;
3954 
3955   case InitializedEntity::EK_Result:
3956     return Sema::AA_Returning;
3957 
3958   case InitializedEntity::EK_Temporary:
3959     // FIXME: Can we tell apart casting vs. converting?
3960     return Sema::AA_Casting;
3961 
3962   case InitializedEntity::EK_Member:
3963   case InitializedEntity::EK_ArrayElement:
3964   case InitializedEntity::EK_VectorElement:
3965   case InitializedEntity::EK_ComplexElement:
3966   case InitializedEntity::EK_BlockElement:
3967     return Sema::AA_Initializing;
3968   }
3969 
3970   return Sema::AA_Converting;
3971 }
3972 
3973 /// \brief Whether we should binding a created object as a temporary when
3974 /// initializing the given entity.
3975 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
3976   switch (Entity.getKind()) {
3977   case InitializedEntity::EK_ArrayElement:
3978   case InitializedEntity::EK_Member:
3979   case InitializedEntity::EK_Result:
3980   case InitializedEntity::EK_New:
3981   case InitializedEntity::EK_Variable:
3982   case InitializedEntity::EK_Base:
3983   case InitializedEntity::EK_Delegating:
3984   case InitializedEntity::EK_VectorElement:
3985   case InitializedEntity::EK_ComplexElement:
3986   case InitializedEntity::EK_Exception:
3987   case InitializedEntity::EK_BlockElement:
3988     return false;
3989 
3990   case InitializedEntity::EK_Parameter:
3991   case InitializedEntity::EK_Temporary:
3992     return true;
3993   }
3994 
3995   llvm_unreachable("missed an InitializedEntity kind?");
3996 }
3997 
3998 /// \brief Whether the given entity, when initialized with an object
3999 /// created for that initialization, requires destruction.
4000 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4001   switch (Entity.getKind()) {
4002     case InitializedEntity::EK_Member:
4003     case InitializedEntity::EK_Result:
4004     case InitializedEntity::EK_New:
4005     case InitializedEntity::EK_Base:
4006     case InitializedEntity::EK_Delegating:
4007     case InitializedEntity::EK_VectorElement:
4008     case InitializedEntity::EK_ComplexElement:
4009     case InitializedEntity::EK_BlockElement:
4010       return false;
4011 
4012     case InitializedEntity::EK_Variable:
4013     case InitializedEntity::EK_Parameter:
4014     case InitializedEntity::EK_Temporary:
4015     case InitializedEntity::EK_ArrayElement:
4016     case InitializedEntity::EK_Exception:
4017       return true;
4018   }
4019 
4020   llvm_unreachable("missed an InitializedEntity kind?");
4021 }
4022 
4023 /// \brief Make a (potentially elidable) temporary copy of the object
4024 /// provided by the given initializer by calling the appropriate copy
4025 /// constructor.
4026 ///
4027 /// \param S The Sema object used for type-checking.
4028 ///
4029 /// \param T The type of the temporary object, which must either be
4030 /// the type of the initializer expression or a superclass thereof.
4031 ///
4032 /// \param Enter The entity being initialized.
4033 ///
4034 /// \param CurInit The initializer expression.
4035 ///
4036 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4037 /// is permitted in C++03 (but not C++0x) when binding a reference to
4038 /// an rvalue.
4039 ///
4040 /// \returns An expression that copies the initializer expression into
4041 /// a temporary object, or an error expression if a copy could not be
4042 /// created.
4043 static ExprResult CopyObject(Sema &S,
4044                              QualType T,
4045                              const InitializedEntity &Entity,
4046                              ExprResult CurInit,
4047                              bool IsExtraneousCopy) {
4048   // Determine which class type we're copying to.
4049   Expr *CurInitExpr = (Expr *)CurInit.get();
4050   CXXRecordDecl *Class = 0;
4051   if (const RecordType *Record = T->getAs<RecordType>())
4052     Class = cast<CXXRecordDecl>(Record->getDecl());
4053   if (!Class)
4054     return move(CurInit);
4055 
4056   // C++0x [class.copy]p32:
4057   //   When certain criteria are met, an implementation is allowed to
4058   //   omit the copy/move construction of a class object, even if the
4059   //   copy/move constructor and/or destructor for the object have
4060   //   side effects. [...]
4061   //     - when a temporary class object that has not been bound to a
4062   //       reference (12.2) would be copied/moved to a class object
4063   //       with the same cv-unqualified type, the copy/move operation
4064   //       can be omitted by constructing the temporary object
4065   //       directly into the target of the omitted copy/move
4066   //
4067   // Note that the other three bullets are handled elsewhere. Copy
4068   // elision for return statements and throw expressions are handled as part
4069   // of constructor initialization, while copy elision for exception handlers
4070   // is handled by the run-time.
4071   bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4072   SourceLocation Loc;
4073   switch (Entity.getKind()) {
4074   case InitializedEntity::EK_Result:
4075     Loc = Entity.getReturnLoc();
4076     break;
4077 
4078   case InitializedEntity::EK_Exception:
4079     Loc = Entity.getThrowLoc();
4080     break;
4081 
4082   case InitializedEntity::EK_Variable:
4083     Loc = Entity.getDecl()->getLocation();
4084     break;
4085 
4086   case InitializedEntity::EK_ArrayElement:
4087   case InitializedEntity::EK_Member:
4088   case InitializedEntity::EK_Parameter:
4089   case InitializedEntity::EK_Temporary:
4090   case InitializedEntity::EK_New:
4091   case InitializedEntity::EK_Base:
4092   case InitializedEntity::EK_Delegating:
4093   case InitializedEntity::EK_VectorElement:
4094   case InitializedEntity::EK_ComplexElement:
4095   case InitializedEntity::EK_BlockElement:
4096     Loc = CurInitExpr->getLocStart();
4097     break;
4098   }
4099 
4100   // Make sure that the type we are copying is complete.
4101   if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4102     return move(CurInit);
4103 
4104   // Perform overload resolution using the class's copy/move constructors.
4105   DeclContext::lookup_iterator Con, ConEnd;
4106   OverloadCandidateSet CandidateSet(Loc);
4107   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4108        Con != ConEnd; ++Con) {
4109     // Only consider copy/move constructors and constructor templates. Per
4110     // C++0x [dcl.init]p16, second bullet to class types, this
4111     // initialization is direct-initialization.
4112     CXXConstructorDecl *Constructor = 0;
4113 
4114     if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4115       // Handle copy/moveconstructors, only.
4116       if (!Constructor || Constructor->isInvalidDecl() ||
4117           !Constructor->isCopyOrMoveConstructor() ||
4118           !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4119         continue;
4120 
4121       DeclAccessPair FoundDecl
4122         = DeclAccessPair::make(Constructor, Constructor->getAccess());
4123       S.AddOverloadCandidate(Constructor, FoundDecl,
4124                              &CurInitExpr, 1, CandidateSet);
4125       continue;
4126     }
4127 
4128     // Handle constructor templates.
4129     FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4130     if (ConstructorTmpl->isInvalidDecl())
4131       continue;
4132 
4133     Constructor = cast<CXXConstructorDecl>(
4134                                          ConstructorTmpl->getTemplatedDecl());
4135     if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4136       continue;
4137 
4138     // FIXME: Do we need to limit this to copy-constructor-like
4139     // candidates?
4140     DeclAccessPair FoundDecl
4141       = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4142     S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4143                                    &CurInitExpr, 1, CandidateSet, true);
4144   }
4145 
4146   OverloadCandidateSet::iterator Best;
4147   switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4148   case OR_Success:
4149     break;
4150 
4151   case OR_No_Viable_Function:
4152     S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4153            ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4154            : diag::err_temp_copy_no_viable)
4155       << (int)Entity.getKind() << CurInitExpr->getType()
4156       << CurInitExpr->getSourceRange();
4157     CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4158     if (!IsExtraneousCopy || S.isSFINAEContext())
4159       return ExprError();
4160     return move(CurInit);
4161 
4162   case OR_Ambiguous:
4163     S.Diag(Loc, diag::err_temp_copy_ambiguous)
4164       << (int)Entity.getKind() << CurInitExpr->getType()
4165       << CurInitExpr->getSourceRange();
4166     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4167     return ExprError();
4168 
4169   case OR_Deleted:
4170     S.Diag(Loc, diag::err_temp_copy_deleted)
4171       << (int)Entity.getKind() << CurInitExpr->getType()
4172       << CurInitExpr->getSourceRange();
4173     S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4174       << 1 << Best->Function->isDeleted();
4175     return ExprError();
4176   }
4177 
4178   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4179   ASTOwningVector<Expr*> ConstructorArgs(S);
4180   CurInit.release(); // Ownership transferred into MultiExprArg, below.
4181 
4182   S.CheckConstructorAccess(Loc, Constructor, Entity,
4183                            Best->FoundDecl.getAccess(), IsExtraneousCopy);
4184 
4185   if (IsExtraneousCopy) {
4186     // If this is a totally extraneous copy for C++03 reference
4187     // binding purposes, just return the original initialization
4188     // expression. We don't generate an (elided) copy operation here
4189     // because doing so would require us to pass down a flag to avoid
4190     // infinite recursion, where each step adds another extraneous,
4191     // elidable copy.
4192 
4193     // Instantiate the default arguments of any extra parameters in
4194     // the selected copy constructor, as if we were going to create a
4195     // proper call to the copy constructor.
4196     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4197       ParmVarDecl *Parm = Constructor->getParamDecl(I);
4198       if (S.RequireCompleteType(Loc, Parm->getType(),
4199                                 S.PDiag(diag::err_call_incomplete_argument)))
4200         break;
4201 
4202       // Build the default argument expression; we don't actually care
4203       // if this succeeds or not, because this routine will complain
4204       // if there was a problem.
4205       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4206     }
4207 
4208     return S.Owned(CurInitExpr);
4209   }
4210 
4211   S.MarkDeclarationReferenced(Loc, Constructor);
4212 
4213   // Determine the arguments required to actually perform the
4214   // constructor call (we might have derived-to-base conversions, or
4215   // the copy constructor may have default arguments).
4216   if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4217                                 Loc, ConstructorArgs))
4218     return ExprError();
4219 
4220   // Actually perform the constructor call.
4221   CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4222                                     move_arg(ConstructorArgs),
4223                                     /*ZeroInit*/ false,
4224                                     CXXConstructExpr::CK_Complete,
4225                                     SourceRange());
4226 
4227   // If we're supposed to bind temporaries, do so.
4228   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4229     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4230   return move(CurInit);
4231 }
4232 
4233 void InitializationSequence::PrintInitLocationNote(Sema &S,
4234                                               const InitializedEntity &Entity) {
4235   if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4236     if (Entity.getDecl()->getLocation().isInvalid())
4237       return;
4238 
4239     if (Entity.getDecl()->getDeclName())
4240       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4241         << Entity.getDecl()->getDeclName();
4242     else
4243       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4244   }
4245 }
4246 
4247 static bool isReferenceBinding(const InitializationSequence::Step &s) {
4248   return s.Kind == InitializationSequence::SK_BindReference ||
4249          s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4250 }
4251 
4252 ExprResult
4253 InitializationSequence::Perform(Sema &S,
4254                                 const InitializedEntity &Entity,
4255                                 const InitializationKind &Kind,
4256                                 MultiExprArg Args,
4257                                 QualType *ResultType) {
4258   if (Failed()) {
4259     unsigned NumArgs = Args.size();
4260     Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
4261     return ExprError();
4262   }
4263 
4264   if (getKind() == DependentSequence) {
4265     // If the declaration is a non-dependent, incomplete array type
4266     // that has an initializer, then its type will be completed once
4267     // the initializer is instantiated.
4268     if (ResultType && !Entity.getType()->isDependentType() &&
4269         Args.size() == 1) {
4270       QualType DeclType = Entity.getType();
4271       if (const IncompleteArrayType *ArrayT
4272                            = S.Context.getAsIncompleteArrayType(DeclType)) {
4273         // FIXME: We don't currently have the ability to accurately
4274         // compute the length of an initializer list without
4275         // performing full type-checking of the initializer list
4276         // (since we have to determine where braces are implicitly
4277         // introduced and such).  So, we fall back to making the array
4278         // type a dependently-sized array type with no specified
4279         // bound.
4280         if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4281           SourceRange Brackets;
4282 
4283           // Scavange the location of the brackets from the entity, if we can.
4284           if (DeclaratorDecl *DD = Entity.getDecl()) {
4285             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4286               TypeLoc TL = TInfo->getTypeLoc();
4287               if (IncompleteArrayTypeLoc *ArrayLoc
4288                                       = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4289               Brackets = ArrayLoc->getBracketsRange();
4290             }
4291           }
4292 
4293           *ResultType
4294             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4295                                                    /*NumElts=*/0,
4296                                                    ArrayT->getSizeModifier(),
4297                                        ArrayT->getIndexTypeCVRQualifiers(),
4298                                                    Brackets);
4299         }
4300 
4301       }
4302     }
4303     assert(Kind.getKind() == InitializationKind::IK_Copy ||
4304            Kind.isExplicitCast());
4305     return ExprResult(Args.release()[0]);
4306   }
4307 
4308   // No steps means no initialization.
4309   if (Steps.empty())
4310     return S.Owned((Expr *)0);
4311 
4312   QualType DestType = Entity.getType().getNonReferenceType();
4313   // FIXME: Ugly hack around the fact that Entity.getType() is not
4314   // the same as Entity.getDecl()->getType() in cases involving type merging,
4315   //  and we want latter when it makes sense.
4316   if (ResultType)
4317     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
4318                                      Entity.getType();
4319 
4320   ExprResult CurInit = S.Owned((Expr *)0);
4321 
4322   // For initialization steps that start with a single initializer,
4323   // grab the only argument out the Args and place it into the "current"
4324   // initializer.
4325   switch (Steps.front().Kind) {
4326   case SK_ResolveAddressOfOverloadedFunction:
4327   case SK_CastDerivedToBaseRValue:
4328   case SK_CastDerivedToBaseXValue:
4329   case SK_CastDerivedToBaseLValue:
4330   case SK_BindReference:
4331   case SK_BindReferenceToTemporary:
4332   case SK_ExtraneousCopyToTemporary:
4333   case SK_UserConversion:
4334   case SK_QualificationConversionLValue:
4335   case SK_QualificationConversionXValue:
4336   case SK_QualificationConversionRValue:
4337   case SK_ConversionSequence:
4338   case SK_ListConstructorCall:
4339   case SK_ListInitialization:
4340   case SK_CAssignment:
4341   case SK_StringInit:
4342   case SK_ObjCObjectConversion:
4343   case SK_ArrayInit:
4344   case SK_PassByIndirectCopyRestore:
4345   case SK_PassByIndirectRestore:
4346   case SK_ProduceObjCObject: {
4347     assert(Args.size() == 1);
4348     CurInit = Args.get()[0];
4349     if (!CurInit.get()) return ExprError();
4350 
4351     // Read from a property when initializing something with it.
4352     if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4353       CurInit = S.ConvertPropertyForRValue(CurInit.take());
4354       if (CurInit.isInvalid())
4355         return ExprError();
4356     }
4357     break;
4358   }
4359 
4360   case SK_ConstructorInitialization:
4361   case SK_ZeroInitialization:
4362     break;
4363   }
4364 
4365   // Walk through the computed steps for the initialization sequence,
4366   // performing the specified conversions along the way.
4367   bool ConstructorInitRequiresZeroInit = false;
4368   for (step_iterator Step = step_begin(), StepEnd = step_end();
4369        Step != StepEnd; ++Step) {
4370     if (CurInit.isInvalid())
4371       return ExprError();
4372 
4373     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
4374 
4375     switch (Step->Kind) {
4376     case SK_ResolveAddressOfOverloadedFunction:
4377       // Overload resolution determined which function invoke; update the
4378       // initializer to reflect that choice.
4379       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
4380       S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
4381       CurInit = S.FixOverloadedFunctionReference(move(CurInit),
4382                                                  Step->Function.FoundDecl,
4383                                                  Step->Function.Function);
4384       break;
4385 
4386     case SK_CastDerivedToBaseRValue:
4387     case SK_CastDerivedToBaseXValue:
4388     case SK_CastDerivedToBaseLValue: {
4389       // We have a derived-to-base cast that produces either an rvalue or an
4390       // lvalue. Perform that cast.
4391 
4392       CXXCastPath BasePath;
4393 
4394       // Casts to inaccessible base classes are allowed with C-style casts.
4395       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4396       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
4397                                          CurInit.get()->getLocStart(),
4398                                          CurInit.get()->getSourceRange(),
4399                                          &BasePath, IgnoreBaseAccess))
4400         return ExprError();
4401 
4402       if (S.BasePathInvolvesVirtualBase(BasePath)) {
4403         QualType T = SourceType;
4404         if (const PointerType *Pointer = T->getAs<PointerType>())
4405           T = Pointer->getPointeeType();
4406         if (const RecordType *RecordTy = T->getAs<RecordType>())
4407           S.MarkVTableUsed(CurInit.get()->getLocStart(),
4408                            cast<CXXRecordDecl>(RecordTy->getDecl()));
4409       }
4410 
4411       ExprValueKind VK =
4412           Step->Kind == SK_CastDerivedToBaseLValue ?
4413               VK_LValue :
4414               (Step->Kind == SK_CastDerivedToBaseXValue ?
4415                    VK_XValue :
4416                    VK_RValue);
4417       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4418                                                  Step->Type,
4419                                                  CK_DerivedToBase,
4420                                                  CurInit.get(),
4421                                                  &BasePath, VK));
4422       break;
4423     }
4424 
4425     case SK_BindReference:
4426       if (FieldDecl *BitField = CurInit.get()->getBitField()) {
4427         // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4428         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
4429           << Entity.getType().isVolatileQualified()
4430           << BitField->getDeclName()
4431           << CurInit.get()->getSourceRange();
4432         S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
4433         return ExprError();
4434       }
4435 
4436       if (CurInit.get()->refersToVectorElement()) {
4437         // References cannot bind to vector elements.
4438         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4439           << Entity.getType().isVolatileQualified()
4440           << CurInit.get()->getSourceRange();
4441         PrintInitLocationNote(S, Entity);
4442         return ExprError();
4443       }
4444 
4445       // Reference binding does not have any corresponding ASTs.
4446 
4447       // Check exception specifications
4448       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4449         return ExprError();
4450 
4451       break;
4452 
4453     case SK_BindReferenceToTemporary:
4454       // Check exception specifications
4455       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4456         return ExprError();
4457 
4458       // Materialize the temporary into memory.
4459       CurInit = new (S.Context) MaterializeTemporaryExpr(
4460                                          Entity.getType().getNonReferenceType(),
4461                                                          CurInit.get(),
4462                                      Entity.getType()->isLValueReferenceType());
4463 
4464       // If we're binding to an Objective-C object that has lifetime, we
4465       // need cleanups.
4466       if (S.getLangOptions().ObjCAutoRefCount &&
4467           CurInit.get()->getType()->isObjCLifetimeType())
4468         S.ExprNeedsCleanups = true;
4469 
4470       break;
4471 
4472     case SK_ExtraneousCopyToTemporary:
4473       CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
4474                            /*IsExtraneousCopy=*/true);
4475       break;
4476 
4477     case SK_UserConversion: {
4478       // We have a user-defined conversion that invokes either a constructor
4479       // or a conversion function.
4480       CastKind CastKind;
4481       bool IsCopy = false;
4482       FunctionDecl *Fn = Step->Function.Function;
4483       DeclAccessPair FoundFn = Step->Function.FoundDecl;
4484       bool CreatedObject = false;
4485       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
4486         // Build a call to the selected constructor.
4487         ASTOwningVector<Expr*> ConstructorArgs(S);
4488         SourceLocation Loc = CurInit.get()->getLocStart();
4489         CurInit.release(); // Ownership transferred into MultiExprArg, below.
4490 
4491         // Determine the arguments required to actually perform the constructor
4492         // call.
4493         Expr *Arg = CurInit.get();
4494         if (S.CompleteConstructorCall(Constructor,
4495                                       MultiExprArg(&Arg, 1),
4496                                       Loc, ConstructorArgs))
4497           return ExprError();
4498 
4499         // Build the an expression that constructs a temporary.
4500         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
4501                                           move_arg(ConstructorArgs),
4502                                           /*ZeroInit*/ false,
4503                                           CXXConstructExpr::CK_Complete,
4504                                           SourceRange());
4505         if (CurInit.isInvalid())
4506           return ExprError();
4507 
4508         S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
4509                                  FoundFn.getAccess());
4510         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4511 
4512         CastKind = CK_ConstructorConversion;
4513         QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4514         if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4515             S.IsDerivedFrom(SourceType, Class))
4516           IsCopy = true;
4517 
4518         CreatedObject = true;
4519       } else {
4520         // Build a call to the conversion function.
4521         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
4522         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
4523                                     FoundFn);
4524         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4525 
4526         // FIXME: Should we move this initialization into a separate
4527         // derived-to-base conversion? I believe the answer is "no", because
4528         // we don't want to turn off access control here for c-style casts.
4529         ExprResult CurInitExprRes =
4530           S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4531                                                 FoundFn, Conversion);
4532         if(CurInitExprRes.isInvalid())
4533           return ExprError();
4534         CurInit = move(CurInitExprRes);
4535 
4536         // Build the actual call to the conversion function.
4537         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
4538         if (CurInit.isInvalid() || !CurInit.get())
4539           return ExprError();
4540 
4541         CastKind = CK_UserDefinedConversion;
4542 
4543         CreatedObject = Conversion->getResultType()->isRecordType();
4544       }
4545 
4546       bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
4547       if (RequiresCopy || shouldBindAsTemporary(Entity))
4548         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4549       else if (CreatedObject && shouldDestroyTemporary(Entity)) {
4550         QualType T = CurInit.get()->getType();
4551         if (const RecordType *Record = T->getAs<RecordType>()) {
4552           CXXDestructorDecl *Destructor
4553             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
4554           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
4555                                   S.PDiag(diag::err_access_dtor_temp) << T);
4556           S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4557           S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
4558         }
4559       }
4560 
4561       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4562                                                  CurInit.get()->getType(),
4563                                                  CastKind, CurInit.get(), 0,
4564                                                 CurInit.get()->getValueKind()));
4565 
4566       if (RequiresCopy)
4567         CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4568                              move(CurInit), /*IsExtraneousCopy=*/false);
4569 
4570       break;
4571     }
4572 
4573     case SK_QualificationConversionLValue:
4574     case SK_QualificationConversionXValue:
4575     case SK_QualificationConversionRValue: {
4576       // Perform a qualification conversion; these can never go wrong.
4577       ExprValueKind VK =
4578           Step->Kind == SK_QualificationConversionLValue ?
4579               VK_LValue :
4580               (Step->Kind == SK_QualificationConversionXValue ?
4581                    VK_XValue :
4582                    VK_RValue);
4583       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
4584       break;
4585     }
4586 
4587     case SK_ConversionSequence: {
4588       Sema::CheckedConversionKind CCK
4589         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4590         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4591         : Kind.isExplicitCast()? Sema::CCK_OtherCast
4592         : Sema::CCK_ImplicitConversion;
4593       ExprResult CurInitExprRes =
4594         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
4595                                     getAssignmentAction(Entity), CCK);
4596       if (CurInitExprRes.isInvalid())
4597         return ExprError();
4598       CurInit = move(CurInitExprRes);
4599       break;
4600     }
4601 
4602     case SK_ListInitialization: {
4603       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
4604       QualType Ty = Step->Type;
4605       InitListChecker PerformInitList(S, Entity, InitList,
4606           ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4607       if (PerformInitList.HadError())
4608         return ExprError();
4609 
4610       CurInit.release();
4611       CurInit = S.Owned(PerformInitList.getFullyStructuredList());
4612       break;
4613     }
4614 
4615     case SK_ListConstructorCall:
4616       assert(false && "List constructor calls not yet supported.");
4617 
4618     case SK_ConstructorInitialization: {
4619       unsigned NumArgs = Args.size();
4620       CXXConstructorDecl *Constructor
4621         = cast<CXXConstructorDecl>(Step->Function.Function);
4622 
4623       // Build a call to the selected constructor.
4624       ASTOwningVector<Expr*> ConstructorArgs(S);
4625       SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4626                              ? Kind.getEqualLoc()
4627                              : Kind.getLocation();
4628 
4629       if (Kind.getKind() == InitializationKind::IK_Default) {
4630         // Force even a trivial, implicit default constructor to be
4631         // semantically checked. We do this explicitly because we don't build
4632         // the definition for completely trivial constructors.
4633         CXXRecordDecl *ClassDecl = Constructor->getParent();
4634         assert(ClassDecl && "No parent class for constructor.");
4635         if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4636             ClassDecl->hasTrivialDefaultConstructor() &&
4637             !Constructor->isUsed(false))
4638           S.DefineImplicitDefaultConstructor(Loc, Constructor);
4639       }
4640 
4641       // Determine the arguments required to actually perform the constructor
4642       // call.
4643       if (S.CompleteConstructorCall(Constructor, move(Args),
4644                                     Loc, ConstructorArgs))
4645         return ExprError();
4646 
4647 
4648       if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4649           NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4650           (Kind.getKind() == InitializationKind::IK_Direct ||
4651            Kind.getKind() == InitializationKind::IK_Value)) {
4652         // An explicitly-constructed temporary, e.g., X(1, 2).
4653         unsigned NumExprs = ConstructorArgs.size();
4654         Expr **Exprs = (Expr **)ConstructorArgs.take();
4655         S.MarkDeclarationReferenced(Loc, Constructor);
4656         S.DiagnoseUseOfDecl(Constructor, Loc);
4657 
4658         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4659         if (!TSInfo)
4660           TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4661 
4662         CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4663                                                                  Constructor,
4664                                                                  TSInfo,
4665                                                                  Exprs,
4666                                                                  NumExprs,
4667                                                          Kind.getParenRange(),
4668                                              ConstructorInitRequiresZeroInit));
4669       } else {
4670         CXXConstructExpr::ConstructionKind ConstructKind =
4671           CXXConstructExpr::CK_Complete;
4672 
4673         if (Entity.getKind() == InitializedEntity::EK_Base) {
4674           ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4675             CXXConstructExpr::CK_VirtualBase :
4676             CXXConstructExpr::CK_NonVirtualBase;
4677         } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4678           ConstructKind = CXXConstructExpr::CK_Delegating;
4679         }
4680 
4681         // Only get the parenthesis range if it is a direct construction.
4682         SourceRange parenRange =
4683             Kind.getKind() == InitializationKind::IK_Direct ?
4684             Kind.getParenRange() : SourceRange();
4685 
4686         // If the entity allows NRVO, mark the construction as elidable
4687         // unconditionally.
4688         if (Entity.allowsNRVO())
4689           CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4690                                             Constructor, /*Elidable=*/true,
4691                                             move_arg(ConstructorArgs),
4692                                             ConstructorInitRequiresZeroInit,
4693                                             ConstructKind,
4694                                             parenRange);
4695         else
4696           CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4697                                             Constructor,
4698                                             move_arg(ConstructorArgs),
4699                                             ConstructorInitRequiresZeroInit,
4700                                             ConstructKind,
4701                                             parenRange);
4702       }
4703       if (CurInit.isInvalid())
4704         return ExprError();
4705 
4706       // Only check access if all of that succeeded.
4707       S.CheckConstructorAccess(Loc, Constructor, Entity,
4708                                Step->Function.FoundDecl.getAccess());
4709       S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
4710 
4711       if (shouldBindAsTemporary(Entity))
4712         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4713 
4714       break;
4715     }
4716 
4717     case SK_ZeroInitialization: {
4718       step_iterator NextStep = Step;
4719       ++NextStep;
4720       if (NextStep != StepEnd &&
4721           NextStep->Kind == SK_ConstructorInitialization) {
4722         // The need for zero-initialization is recorded directly into
4723         // the call to the object's constructor within the next step.
4724         ConstructorInitRequiresZeroInit = true;
4725       } else if (Kind.getKind() == InitializationKind::IK_Value &&
4726                  S.getLangOptions().CPlusPlus &&
4727                  !Kind.isImplicitValueInit()) {
4728         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4729         if (!TSInfo)
4730           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
4731                                                     Kind.getRange().getBegin());
4732 
4733         CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4734                               TSInfo->getType().getNonLValueExprType(S.Context),
4735                                                                  TSInfo,
4736                                                     Kind.getRange().getEnd()));
4737       } else {
4738         CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
4739       }
4740       break;
4741     }
4742 
4743     case SK_CAssignment: {
4744       QualType SourceType = CurInit.get()->getType();
4745       ExprResult Result = move(CurInit);
4746       Sema::AssignConvertType ConvTy =
4747         S.CheckSingleAssignmentConstraints(Step->Type, Result);
4748       if (Result.isInvalid())
4749         return ExprError();
4750       CurInit = move(Result);
4751 
4752       // If this is a call, allow conversion to a transparent union.
4753       ExprResult CurInitExprRes = move(CurInit);
4754       if (ConvTy != Sema::Compatible &&
4755           Entity.getKind() == InitializedEntity::EK_Parameter &&
4756           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
4757             == Sema::Compatible)
4758         ConvTy = Sema::Compatible;
4759       if (CurInitExprRes.isInvalid())
4760         return ExprError();
4761       CurInit = move(CurInitExprRes);
4762 
4763       bool Complained;
4764       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4765                                      Step->Type, SourceType,
4766                                      CurInit.get(),
4767                                      getAssignmentAction(Entity),
4768                                      &Complained)) {
4769         PrintInitLocationNote(S, Entity);
4770         return ExprError();
4771       } else if (Complained)
4772         PrintInitLocationNote(S, Entity);
4773       break;
4774     }
4775 
4776     case SK_StringInit: {
4777       QualType Ty = Step->Type;
4778       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
4779                       S.Context.getAsArrayType(Ty), S);
4780       break;
4781     }
4782 
4783     case SK_ObjCObjectConversion:
4784       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
4785                           CK_ObjCObjectLValueCast,
4786                           CurInit.get()->getValueKind());
4787       break;
4788 
4789     case SK_ArrayInit:
4790       // Okay: we checked everything before creating this step. Note that
4791       // this is a GNU extension.
4792       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
4793         << Step->Type << CurInit.get()->getType()
4794         << CurInit.get()->getSourceRange();
4795 
4796       // If the destination type is an incomplete array type, update the
4797       // type accordingly.
4798       if (ResultType) {
4799         if (const IncompleteArrayType *IncompleteDest
4800                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
4801           if (const ConstantArrayType *ConstantSource
4802                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
4803             *ResultType = S.Context.getConstantArrayType(
4804                                              IncompleteDest->getElementType(),
4805                                              ConstantSource->getSize(),
4806                                              ArrayType::Normal, 0);
4807           }
4808         }
4809       }
4810       break;
4811 
4812     case SK_PassByIndirectCopyRestore:
4813     case SK_PassByIndirectRestore:
4814       checkIndirectCopyRestoreSource(S, CurInit.get());
4815       CurInit = S.Owned(new (S.Context)
4816                         ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4817                                 Step->Kind == SK_PassByIndirectCopyRestore));
4818       break;
4819 
4820     case SK_ProduceObjCObject:
4821       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4822                                                  CK_ARCProduceObject,
4823                                                  CurInit.take(), 0, VK_RValue));
4824       break;
4825     }
4826   }
4827 
4828   // Diagnose non-fatal problems with the completed initialization.
4829   if (Entity.getKind() == InitializedEntity::EK_Member &&
4830       cast<FieldDecl>(Entity.getDecl())->isBitField())
4831     S.CheckBitFieldInitialization(Kind.getLocation(),
4832                                   cast<FieldDecl>(Entity.getDecl()),
4833                                   CurInit.get());
4834 
4835   return move(CurInit);
4836 }
4837 
4838 //===----------------------------------------------------------------------===//
4839 // Diagnose initialization failures
4840 //===----------------------------------------------------------------------===//
4841 bool InitializationSequence::Diagnose(Sema &S,
4842                                       const InitializedEntity &Entity,
4843                                       const InitializationKind &Kind,
4844                                       Expr **Args, unsigned NumArgs) {
4845   if (!Failed())
4846     return false;
4847 
4848   QualType DestType = Entity.getType();
4849   switch (Failure) {
4850   case FK_TooManyInitsForReference:
4851     // FIXME: Customize for the initialized entity?
4852     if (NumArgs == 0)
4853       S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4854         << DestType.getNonReferenceType();
4855     else  // FIXME: diagnostic below could be better!
4856       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4857         << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
4858     break;
4859 
4860   case FK_ArrayNeedsInitList:
4861   case FK_ArrayNeedsInitListOrStringLiteral:
4862     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4863       << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4864     break;
4865 
4866   case FK_ArrayTypeMismatch:
4867   case FK_NonConstantArrayInit:
4868     S.Diag(Kind.getLocation(),
4869            (Failure == FK_ArrayTypeMismatch
4870               ? diag::err_array_init_different_type
4871               : diag::err_array_init_non_constant_array))
4872       << DestType.getNonReferenceType()
4873       << Args[0]->getType()
4874       << Args[0]->getSourceRange();
4875     break;
4876 
4877   case FK_AddressOfOverloadFailed: {
4878     DeclAccessPair Found;
4879     S.ResolveAddressOfOverloadedFunction(Args[0],
4880                                          DestType.getNonReferenceType(),
4881                                          true,
4882                                          Found);
4883     break;
4884   }
4885 
4886   case FK_ReferenceInitOverloadFailed:
4887   case FK_UserConversionOverloadFailed:
4888     switch (FailedOverloadResult) {
4889     case OR_Ambiguous:
4890       if (Failure == FK_UserConversionOverloadFailed)
4891         S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4892           << Args[0]->getType() << DestType
4893           << Args[0]->getSourceRange();
4894       else
4895         S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4896           << DestType << Args[0]->getType()
4897           << Args[0]->getSourceRange();
4898 
4899       FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
4900       break;
4901 
4902     case OR_No_Viable_Function:
4903       S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4904         << Args[0]->getType() << DestType.getNonReferenceType()
4905         << Args[0]->getSourceRange();
4906       FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
4907       break;
4908 
4909     case OR_Deleted: {
4910       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4911         << Args[0]->getType() << DestType.getNonReferenceType()
4912         << Args[0]->getSourceRange();
4913       OverloadCandidateSet::iterator Best;
4914       OverloadingResult Ovl
4915         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4916                                                 true);
4917       if (Ovl == OR_Deleted) {
4918         S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4919           << 1 << Best->Function->isDeleted();
4920       } else {
4921         llvm_unreachable("Inconsistent overload resolution?");
4922       }
4923       break;
4924     }
4925 
4926     case OR_Success:
4927       llvm_unreachable("Conversion did not fail!");
4928       break;
4929     }
4930     break;
4931 
4932   case FK_NonConstLValueReferenceBindingToTemporary:
4933   case FK_NonConstLValueReferenceBindingToUnrelated:
4934     S.Diag(Kind.getLocation(),
4935            Failure == FK_NonConstLValueReferenceBindingToTemporary
4936              ? diag::err_lvalue_reference_bind_to_temporary
4937              : diag::err_lvalue_reference_bind_to_unrelated)
4938       << DestType.getNonReferenceType().isVolatileQualified()
4939       << DestType.getNonReferenceType()
4940       << Args[0]->getType()
4941       << Args[0]->getSourceRange();
4942     break;
4943 
4944   case FK_RValueReferenceBindingToLValue:
4945     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4946       << DestType.getNonReferenceType() << Args[0]->getType()
4947       << Args[0]->getSourceRange();
4948     break;
4949 
4950   case FK_ReferenceInitDropsQualifiers:
4951     S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4952       << DestType.getNonReferenceType()
4953       << Args[0]->getType()
4954       << Args[0]->getSourceRange();
4955     break;
4956 
4957   case FK_ReferenceInitFailed:
4958     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4959       << DestType.getNonReferenceType()
4960       << Args[0]->isLValue()
4961       << Args[0]->getType()
4962       << Args[0]->getSourceRange();
4963     if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4964         Args[0]->getType()->isObjCObjectPointerType())
4965       S.EmitRelatedResultTypeNote(Args[0]);
4966     break;
4967 
4968   case FK_ConversionFailed: {
4969     QualType FromType = Args[0]->getType();
4970     S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4971       << (int)Entity.getKind()
4972       << DestType
4973       << Args[0]->isLValue()
4974       << FromType
4975       << Args[0]->getSourceRange();
4976     if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4977         Args[0]->getType()->isObjCObjectPointerType())
4978       S.EmitRelatedResultTypeNote(Args[0]);
4979     break;
4980   }
4981 
4982   case FK_ConversionFromPropertyFailed:
4983     // No-op. This error has already been reported.
4984     break;
4985 
4986   case FK_TooManyInitsForScalar: {
4987     SourceRange R;
4988 
4989     if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4990       R = SourceRange(InitList->getInit(0)->getLocEnd(),
4991                       InitList->getLocEnd());
4992     else
4993       R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
4994 
4995     R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4996     if (Kind.isCStyleOrFunctionalCast())
4997       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4998         << R;
4999     else
5000       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5001         << /*scalar=*/2 << R;
5002     break;
5003   }
5004 
5005   case FK_ReferenceBindingToInitList:
5006     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5007       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5008     break;
5009 
5010   case FK_InitListBadDestinationType:
5011     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5012       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5013     break;
5014 
5015   case FK_ConstructorOverloadFailed: {
5016     SourceRange ArgsRange;
5017     if (NumArgs)
5018       ArgsRange = SourceRange(Args[0]->getLocStart(),
5019                               Args[NumArgs - 1]->getLocEnd());
5020 
5021     // FIXME: Using "DestType" for the entity we're printing is probably
5022     // bad.
5023     switch (FailedOverloadResult) {
5024       case OR_Ambiguous:
5025         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5026           << DestType << ArgsRange;
5027         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5028                                           Args, NumArgs);
5029         break;
5030 
5031       case OR_No_Viable_Function:
5032         if (Kind.getKind() == InitializationKind::IK_Default &&
5033             (Entity.getKind() == InitializedEntity::EK_Base ||
5034              Entity.getKind() == InitializedEntity::EK_Member) &&
5035             isa<CXXConstructorDecl>(S.CurContext)) {
5036           // This is implicit default initialization of a member or
5037           // base within a constructor. If no viable function was
5038           // found, notify the user that she needs to explicitly
5039           // initialize this base/member.
5040           CXXConstructorDecl *Constructor
5041             = cast<CXXConstructorDecl>(S.CurContext);
5042           if (Entity.getKind() == InitializedEntity::EK_Base) {
5043             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5044               << Constructor->isImplicit()
5045               << S.Context.getTypeDeclType(Constructor->getParent())
5046               << /*base=*/0
5047               << Entity.getType();
5048 
5049             RecordDecl *BaseDecl
5050               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5051                                                                   ->getDecl();
5052             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5053               << S.Context.getTagDeclType(BaseDecl);
5054           } else {
5055             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5056               << Constructor->isImplicit()
5057               << S.Context.getTypeDeclType(Constructor->getParent())
5058               << /*member=*/1
5059               << Entity.getName();
5060             S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5061 
5062             if (const RecordType *Record
5063                                  = Entity.getType()->getAs<RecordType>())
5064               S.Diag(Record->getDecl()->getLocation(),
5065                      diag::note_previous_decl)
5066                 << S.Context.getTagDeclType(Record->getDecl());
5067           }
5068           break;
5069         }
5070 
5071         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5072           << DestType << ArgsRange;
5073         FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
5074         break;
5075 
5076       case OR_Deleted: {
5077         S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5078           << true << DestType << ArgsRange;
5079         OverloadCandidateSet::iterator Best;
5080         OverloadingResult Ovl
5081           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5082         if (Ovl == OR_Deleted) {
5083           S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5084             << 1 << Best->Function->isDeleted();
5085         } else {
5086           llvm_unreachable("Inconsistent overload resolution?");
5087         }
5088         break;
5089       }
5090 
5091       case OR_Success:
5092         llvm_unreachable("Conversion did not fail!");
5093         break;
5094     }
5095     break;
5096   }
5097 
5098   case FK_DefaultInitOfConst:
5099     if (Entity.getKind() == InitializedEntity::EK_Member &&
5100         isa<CXXConstructorDecl>(S.CurContext)) {
5101       // This is implicit default-initialization of a const member in
5102       // a constructor. Complain that it needs to be explicitly
5103       // initialized.
5104       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5105       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5106         << Constructor->isImplicit()
5107         << S.Context.getTypeDeclType(Constructor->getParent())
5108         << /*const=*/1
5109         << Entity.getName();
5110       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5111         << Entity.getName();
5112     } else {
5113       S.Diag(Kind.getLocation(), diag::err_default_init_const)
5114         << DestType << (bool)DestType->getAs<RecordType>();
5115     }
5116     break;
5117 
5118   case FK_Incomplete:
5119     S.RequireCompleteType(Kind.getLocation(), DestType,
5120                           diag::err_init_incomplete_type);
5121     break;
5122 
5123   case FK_ListInitializationFailed: {
5124     // Run the init list checker again to emit diagnostics.
5125     InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5126     QualType DestType = Entity.getType();
5127     InitListChecker DiagnoseInitList(S, Entity, InitList,
5128             DestType, /*VerifyOnly=*/false);
5129     assert(DiagnoseInitList.HadError() &&
5130            "Inconsistent init list check result.");
5131     break;
5132   }
5133   }
5134 
5135   PrintInitLocationNote(S, Entity);
5136   return true;
5137 }
5138 
5139 void InitializationSequence::dump(raw_ostream &OS) const {
5140   switch (SequenceKind) {
5141   case FailedSequence: {
5142     OS << "Failed sequence: ";
5143     switch (Failure) {
5144     case FK_TooManyInitsForReference:
5145       OS << "too many initializers for reference";
5146       break;
5147 
5148     case FK_ArrayNeedsInitList:
5149       OS << "array requires initializer list";
5150       break;
5151 
5152     case FK_ArrayNeedsInitListOrStringLiteral:
5153       OS << "array requires initializer list or string literal";
5154       break;
5155 
5156     case FK_ArrayTypeMismatch:
5157       OS << "array type mismatch";
5158       break;
5159 
5160     case FK_NonConstantArrayInit:
5161       OS << "non-constant array initializer";
5162       break;
5163 
5164     case FK_AddressOfOverloadFailed:
5165       OS << "address of overloaded function failed";
5166       break;
5167 
5168     case FK_ReferenceInitOverloadFailed:
5169       OS << "overload resolution for reference initialization failed";
5170       break;
5171 
5172     case FK_NonConstLValueReferenceBindingToTemporary:
5173       OS << "non-const lvalue reference bound to temporary";
5174       break;
5175 
5176     case FK_NonConstLValueReferenceBindingToUnrelated:
5177       OS << "non-const lvalue reference bound to unrelated type";
5178       break;
5179 
5180     case FK_RValueReferenceBindingToLValue:
5181       OS << "rvalue reference bound to an lvalue";
5182       break;
5183 
5184     case FK_ReferenceInitDropsQualifiers:
5185       OS << "reference initialization drops qualifiers";
5186       break;
5187 
5188     case FK_ReferenceInitFailed:
5189       OS << "reference initialization failed";
5190       break;
5191 
5192     case FK_ConversionFailed:
5193       OS << "conversion failed";
5194       break;
5195 
5196     case FK_ConversionFromPropertyFailed:
5197       OS << "conversion from property failed";
5198       break;
5199 
5200     case FK_TooManyInitsForScalar:
5201       OS << "too many initializers for scalar";
5202       break;
5203 
5204     case FK_ReferenceBindingToInitList:
5205       OS << "referencing binding to initializer list";
5206       break;
5207 
5208     case FK_InitListBadDestinationType:
5209       OS << "initializer list for non-aggregate, non-scalar type";
5210       break;
5211 
5212     case FK_UserConversionOverloadFailed:
5213       OS << "overloading failed for user-defined conversion";
5214       break;
5215 
5216     case FK_ConstructorOverloadFailed:
5217       OS << "constructor overloading failed";
5218       break;
5219 
5220     case FK_DefaultInitOfConst:
5221       OS << "default initialization of a const variable";
5222       break;
5223 
5224     case FK_Incomplete:
5225       OS << "initialization of incomplete type";
5226       break;
5227 
5228     case FK_ListInitializationFailed:
5229       OS << "list initialization checker failure";
5230     }
5231     OS << '\n';
5232     return;
5233   }
5234 
5235   case DependentSequence:
5236     OS << "Dependent sequence\n";
5237     return;
5238 
5239   case NormalSequence:
5240     OS << "Normal sequence: ";
5241     break;
5242   }
5243 
5244   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5245     if (S != step_begin()) {
5246       OS << " -> ";
5247     }
5248 
5249     switch (S->Kind) {
5250     case SK_ResolveAddressOfOverloadedFunction:
5251       OS << "resolve address of overloaded function";
5252       break;
5253 
5254     case SK_CastDerivedToBaseRValue:
5255       OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5256       break;
5257 
5258     case SK_CastDerivedToBaseXValue:
5259       OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5260       break;
5261 
5262     case SK_CastDerivedToBaseLValue:
5263       OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5264       break;
5265 
5266     case SK_BindReference:
5267       OS << "bind reference to lvalue";
5268       break;
5269 
5270     case SK_BindReferenceToTemporary:
5271       OS << "bind reference to a temporary";
5272       break;
5273 
5274     case SK_ExtraneousCopyToTemporary:
5275       OS << "extraneous C++03 copy to temporary";
5276       break;
5277 
5278     case SK_UserConversion:
5279       OS << "user-defined conversion via " << S->Function.Function;
5280       break;
5281 
5282     case SK_QualificationConversionRValue:
5283       OS << "qualification conversion (rvalue)";
5284 
5285     case SK_QualificationConversionXValue:
5286       OS << "qualification conversion (xvalue)";
5287 
5288     case SK_QualificationConversionLValue:
5289       OS << "qualification conversion (lvalue)";
5290       break;
5291 
5292     case SK_ConversionSequence:
5293       OS << "implicit conversion sequence (";
5294       S->ICS->DebugPrint(); // FIXME: use OS
5295       OS << ")";
5296       break;
5297 
5298     case SK_ListInitialization:
5299       OS << "list aggregate initialization";
5300       break;
5301 
5302     case SK_ListConstructorCall:
5303       OS << "list initialization via constructor";
5304       break;
5305 
5306     case SK_ConstructorInitialization:
5307       OS << "constructor initialization";
5308       break;
5309 
5310     case SK_ZeroInitialization:
5311       OS << "zero initialization";
5312       break;
5313 
5314     case SK_CAssignment:
5315       OS << "C assignment";
5316       break;
5317 
5318     case SK_StringInit:
5319       OS << "string initialization";
5320       break;
5321 
5322     case SK_ObjCObjectConversion:
5323       OS << "Objective-C object conversion";
5324       break;
5325 
5326     case SK_ArrayInit:
5327       OS << "array initialization";
5328       break;
5329 
5330     case SK_PassByIndirectCopyRestore:
5331       OS << "pass by indirect copy and restore";
5332       break;
5333 
5334     case SK_PassByIndirectRestore:
5335       OS << "pass by indirect restore";
5336       break;
5337 
5338     case SK_ProduceObjCObject:
5339       OS << "Objective-C object retension";
5340       break;
5341     }
5342   }
5343 }
5344 
5345 void InitializationSequence::dump() const {
5346   dump(llvm::errs());
5347 }
5348 
5349 static void DiagnoseNarrowingInInitList(
5350     Sema& S, QualType EntityType, const Expr *InitE,
5351     bool Constant, const APValue &ConstantValue) {
5352   if (Constant) {
5353     S.Diag(InitE->getLocStart(),
5354            S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
5355            ? diag::err_init_list_constant_narrowing
5356            : diag::warn_init_list_constant_narrowing)
5357       << InitE->getSourceRange()
5358       << ConstantValue
5359       << EntityType.getLocalUnqualifiedType();
5360   } else
5361     S.Diag(InitE->getLocStart(),
5362            S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
5363            ? diag::err_init_list_variable_narrowing
5364            : diag::warn_init_list_variable_narrowing)
5365       << InitE->getSourceRange()
5366       << InitE->getType().getLocalUnqualifiedType()
5367       << EntityType.getLocalUnqualifiedType();
5368 
5369   llvm::SmallString<128> StaticCast;
5370   llvm::raw_svector_ostream OS(StaticCast);
5371   OS << "static_cast<";
5372   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5373     // It's important to use the typedef's name if there is one so that the
5374     // fixit doesn't break code using types like int64_t.
5375     //
5376     // FIXME: This will break if the typedef requires qualification.  But
5377     // getQualifiedNameAsString() includes non-machine-parsable components.
5378     OS << TT->getDecl();
5379   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5380     OS << BT->getName(S.getLangOptions());
5381   else {
5382     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
5383     // with a broken cast.
5384     return;
5385   }
5386   OS << ">(";
5387   S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5388     << InitE->getSourceRange()
5389     << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5390     << FixItHint::CreateInsertion(
5391       S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5392 }
5393 
5394 //===----------------------------------------------------------------------===//
5395 // Initialization helper functions
5396 //===----------------------------------------------------------------------===//
5397 bool
5398 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5399                                    ExprResult Init) {
5400   if (Init.isInvalid())
5401     return false;
5402 
5403   Expr *InitE = Init.get();
5404   assert(InitE && "No initialization expression");
5405 
5406   InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5407                                                            SourceLocation());
5408   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5409   return !Seq.Failed();
5410 }
5411 
5412 ExprResult
5413 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5414                                 SourceLocation EqualLoc,
5415                                 ExprResult Init,
5416                                 bool TopLevelOfInitList) {
5417   if (Init.isInvalid())
5418     return ExprError();
5419 
5420   Expr *InitE = Init.get();
5421   assert(InitE && "No initialization expression?");
5422 
5423   if (EqualLoc.isInvalid())
5424     EqualLoc = InitE->getLocStart();
5425 
5426   InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5427                                                            EqualLoc);
5428   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5429   Init.release();
5430 
5431   bool Constant = false;
5432   APValue Result;
5433   if (TopLevelOfInitList &&
5434       Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5435     DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5436                                 Constant, Result);
5437   }
5438   return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5439 }
5440