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