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