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