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