SemaInit.cpp revision 66e0718d80152ad92684c5ec8863839e92bed7eb
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
14// This file also implements Sema::CheckInitializerTypes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "SemaInit.h"
19#include "Sema.h"
20#include "clang/Parse/Designator.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <map>
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
32static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
33  const ArrayType *AT = Context.getAsArrayType(DeclType);
34  if (!AT) return 0;
35
36  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37    return 0;
38
39  // See if this is a string literal or @encode.
40  Init = Init->IgnoreParens();
41
42  // Handle @encode, which is a narrow string.
43  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44    return Init;
45
46  // Otherwise we can only handle string literals.
47  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
48  if (SL == 0) return 0;
49
50  QualType ElemTy = Context.getCanonicalType(AT->getElementType());
51  // char array can be initialized with a narrow string.
52  // Only allow char x[] = "foo";  not char x[] = L"foo";
53  if (!SL->isWide())
54    return ElemTy->isCharType() ? Init : 0;
55
56  // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57  // correction from DR343): "An array with element type compatible with a
58  // qualified or unqualified version of wchar_t may be initialized by a wide
59  // string literal, optionally enclosed in braces."
60  if (Context.typesAreCompatible(Context.getWCharType(),
61                                 ElemTy.getUnqualifiedType()))
62    return Init;
63
64  return 0;
65}
66
67static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
68                                   bool DirectInit, Sema &S) {
69  // Get the type before calling CheckSingleAssignmentConstraints(), since
70  // it can promote the expression.
71  QualType InitType = Init->getType();
72
73  if (S.getLangOptions().CPlusPlus) {
74    // FIXME: I dislike this error message. A lot.
75    if (S.PerformImplicitConversion(Init, DeclType,
76                                    Sema::AA_Initializing, DirectInit)) {
77      ImplicitConversionSequence ICS;
78      OverloadCandidateSet CandidateSet;
79      if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80                              CandidateSet,
81                              true, false, false) != OR_Ambiguous)
82        return S.Diag(Init->getSourceRange().getBegin(),
83                      diag::err_typecheck_convert_incompatible)
84                      << DeclType << Init->getType() << Sema::AA_Initializing
85                      << Init->getSourceRange();
86      S.Diag(Init->getSourceRange().getBegin(),
87             diag::err_typecheck_convert_ambiguous)
88            << DeclType << Init->getType() << Init->getSourceRange();
89      S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
90      return true;
91    }
92    return false;
93  }
94
95  Sema::AssignConvertType ConvTy =
96    S.CheckSingleAssignmentConstraints(DeclType, Init);
97  return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
98                                    InitType, Init, Sema::AA_Initializing);
99}
100
101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102  // Get the length of the string as parsed.
103  uint64_t StrLength =
104    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
106
107  const ArrayType *AT = S.Context.getAsArrayType(DeclT);
108  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
109    // C99 6.7.8p14. We have an array of character type with unknown size
110    // being initialized to a string literal.
111    llvm::APSInt ConstVal(32);
112    ConstVal = StrLength;
113    // Return a new array type (C99 6.7.8p22).
114    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115                                           ConstVal,
116                                           ArrayType::Normal, 0);
117    return;
118  }
119
120  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
121
122  // C99 6.7.8p14. We have an array of character type with known size.  However,
123  // the size may be smaller or larger than the string we are initializing.
124  // FIXME: Avoid truncation for 64-bit length strings.
125  if (StrLength-1 > CAT->getSize().getZExtValue())
126    S.Diag(Str->getSourceRange().getBegin(),
127           diag::warn_initializer_string_for_char_array_too_long)
128      << Str->getSourceRange();
129
130  // Set the type to the actual size that we are initializing.  If we have
131  // something like:
132  //   char x[1] = "foo";
133  // then this will set the string literal's type to char[1].
134  Str->setType(DeclT);
135}
136
137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
138                                 const InitializedEntity &Entity,
139                                 const InitializationKind &Kind) {
140  SourceLocation InitLoc = Kind.getLocation();
141  DeclarationName InitEntity = Entity.getName();
142  bool DirectInit = (Kind.getKind() == InitializationKind::IK_Direct);
143
144  if (DeclType->isDependentType() ||
145      Init->isTypeDependent() || Init->isValueDependent()) {
146    // We have either a dependent type or a type- or value-dependent
147    // initializer, so we don't perform any additional checking at
148    // this point.
149
150    // If the declaration is a non-dependent, incomplete array type
151    // that has an initializer, then its type will be completed once
152    // the initializer is instantiated.
153    if (!DeclType->isDependentType()) {
154      if (const IncompleteArrayType *ArrayT
155                           = Context.getAsIncompleteArrayType(DeclType)) {
156        if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
157          if (!ILE->isTypeDependent()) {
158            // Compute the constant array type from the length of the
159            // initializer list.
160            // FIXME: This will be wrong if there are designated
161            // initializations. Good thing they don't exist in C++!
162            llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
163                                    ILE->getNumInits());
164            llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
165            if (NumElements == Zero) {
166              // Sizing an array implicitly to zero is not allowed by ISO C,
167              // but is supported by GNU.
168              Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
169            }
170
171            DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
172                                                    NumElements,
173                                                    ArrayT->getSizeModifier(),
174                                           ArrayT->getIndexTypeCVRQualifiers());
175            return false;
176          }
177        }
178
179        // Make the array type-dependent by making it dependently-sized.
180        DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
181                                                      /*NumElts=*/0,
182                                                     ArrayT->getSizeModifier(),
183                                           ArrayT->getIndexTypeCVRQualifiers(),
184                                                      SourceRange());
185      }
186    }
187
188    return false;
189  }
190
191  // C++ [dcl.init.ref]p1:
192  //   A variable declared to be a T& or T&&, that is "reference to type T"
193  //   (8.3.2), shall be initialized by an object, or function, of
194  //   type T or by an object that can be converted into a T.
195  if (DeclType->isReferenceType())
196    return CheckReferenceInit(Init, DeclType, InitLoc,
197                              /*SuppressUserConversions=*/false,
198                              /*AllowExplicit=*/DirectInit,
199                              /*ForceRValue=*/false);
200
201  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
202  // of unknown size ("[]") or an object type that is not a variable array type.
203  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
204    return Diag(InitLoc,  diag::err_variable_object_no_init)
205    << VAT->getSizeExpr()->getSourceRange();
206
207  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
208  if (!InitList) {
209    // FIXME: Handle wide strings
210    if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
211      CheckStringInit(Str, DeclType, *this);
212      return false;
213    }
214
215    // C++ [dcl.init]p14:
216    //   -- If the destination type is a (possibly cv-qualified) class
217    //      type:
218    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
219      QualType DeclTypeC = Context.getCanonicalType(DeclType);
220      QualType InitTypeC = Context.getCanonicalType(Init->getType());
221
222      //   -- If the initialization is direct-initialization, or if it is
223      //      copy-initialization where the cv-unqualified version of the
224      //      source type is the same class as, or a derived class of, the
225      //      class of the destination, constructors are considered.
226      if ((DeclTypeC.getLocalUnqualifiedType()
227                                     == InitTypeC.getLocalUnqualifiedType()) ||
228          IsDerivedFrom(InitTypeC, DeclTypeC)) {
229        const CXXRecordDecl *RD =
230          cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
231
232        // No need to make a CXXConstructExpr if both the ctor and dtor are
233        // trivial.
234        if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
235          return false;
236
237        ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
238
239        // FIXME: Poor location information
240        InitializationKind InitKind
241          = InitializationKind::CreateCopy(Init->getLocStart(),
242                                           SourceLocation());
243        if (DirectInit)
244          InitKind = InitializationKind::CreateDirect(Init->getLocStart(),
245                                                      SourceLocation(),
246                                                      SourceLocation());
247        CXXConstructorDecl *Constructor
248          = PerformInitializationByConstructor(DeclType,
249                                               MultiExprArg(*this,
250                                                            (void **)&Init, 1),
251                                               InitLoc, Init->getSourceRange(),
252                                               InitEntity, InitKind,
253                                               ConstructorArgs);
254        if (!Constructor)
255          return true;
256
257        OwningExprResult InitResult =
258          BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
259                                DeclType, Constructor,
260                                move_arg(ConstructorArgs));
261        if (InitResult.isInvalid())
262          return true;
263
264        Init = InitResult.takeAs<Expr>();
265        return false;
266      }
267
268      //   -- Otherwise (i.e., for the remaining copy-initialization
269      //      cases), user-defined conversion sequences that can
270      //      convert from the source type to the destination type or
271      //      (when a conversion function is used) to a derived class
272      //      thereof are enumerated as described in 13.3.1.4, and the
273      //      best one is chosen through overload resolution
274      //      (13.3). If the conversion cannot be done or is
275      //      ambiguous, the initialization is ill-formed. The
276      //      function selected is called with the initializer
277      //      expression as its argument; if the function is a
278      //      constructor, the call initializes a temporary of the
279      //      destination type.
280      // FIXME: We're pretending to do copy elision here; return to this when we
281      // have ASTs for such things.
282      if (!PerformImplicitConversion(Init, DeclType, Sema::AA_Initializing))
283        return false;
284
285      if (InitEntity)
286        return Diag(InitLoc, diag::err_cannot_initialize_decl)
287          << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
288          << Init->getType() << Init->getSourceRange();
289      return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
290        << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
291        << Init->getType() << Init->getSourceRange();
292    }
293
294    // C99 6.7.8p16.
295    if (DeclType->isArrayType())
296      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
297        << Init->getSourceRange();
298
299    return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
300  }
301
302  bool hadError = CheckInitList(Entity, InitList, DeclType);
303  Init = InitList;
304  return hadError;
305}
306
307//===----------------------------------------------------------------------===//
308// Semantic checking for initializer lists.
309//===----------------------------------------------------------------------===//
310
311/// @brief Semantic checking for initializer lists.
312///
313/// The InitListChecker class contains a set of routines that each
314/// handle the initialization of a certain kind of entity, e.g.,
315/// arrays, vectors, struct/union types, scalars, etc. The
316/// InitListChecker itself performs a recursive walk of the subobject
317/// structure of the type to be initialized, while stepping through
318/// the initializer list one element at a time. The IList and Index
319/// parameters to each of the Check* routines contain the active
320/// (syntactic) initializer list and the index into that initializer
321/// list that represents the current initializer. Each routine is
322/// responsible for moving that Index forward as it consumes elements.
323///
324/// Each Check* routine also has a StructuredList/StructuredIndex
325/// arguments, which contains the current the "structured" (semantic)
326/// initializer list and the index into that initializer list where we
327/// are copying initializers as we map them over to the semantic
328/// list. Once we have completed our recursive walk of the subobject
329/// structure, we will have constructed a full semantic initializer
330/// list.
331///
332/// C99 designators cause changes in the initializer list traversal,
333/// because they make the initialization "jump" into a specific
334/// subobject and then continue the initialization from that
335/// point. CheckDesignatedInitializer() recursively steps into the
336/// designated subobject and manages backing out the recursion to
337/// initialize the subobjects after the one designated.
338namespace {
339class InitListChecker {
340  Sema &SemaRef;
341  bool hadError;
342  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
343  InitListExpr *FullyStructuredList;
344
345  void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
346                             unsigned &Index, InitListExpr *StructuredList,
347                             unsigned &StructuredIndex,
348                             bool TopLevelObject = false);
349  void CheckExplicitInitList(InitListExpr *IList, QualType &T,
350                             unsigned &Index, InitListExpr *StructuredList,
351                             unsigned &StructuredIndex,
352                             bool TopLevelObject = false);
353  void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
354                             bool SubobjectIsDesignatorContext,
355                             unsigned &Index,
356                             InitListExpr *StructuredList,
357                             unsigned &StructuredIndex,
358                             bool TopLevelObject = false);
359  void CheckSubElementType(InitListExpr *IList, QualType ElemType,
360                           unsigned &Index,
361                           InitListExpr *StructuredList,
362                           unsigned &StructuredIndex);
363  void CheckScalarType(InitListExpr *IList, QualType DeclType,
364                       unsigned &Index,
365                       InitListExpr *StructuredList,
366                       unsigned &StructuredIndex);
367  void CheckReferenceType(InitListExpr *IList, QualType DeclType,
368                          unsigned &Index,
369                          InitListExpr *StructuredList,
370                          unsigned &StructuredIndex);
371  void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
372                       InitListExpr *StructuredList,
373                       unsigned &StructuredIndex);
374  void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
375                             RecordDecl::field_iterator Field,
376                             bool SubobjectIsDesignatorContext, unsigned &Index,
377                             InitListExpr *StructuredList,
378                             unsigned &StructuredIndex,
379                             bool TopLevelObject = false);
380  void CheckArrayType(InitListExpr *IList, QualType &DeclType,
381                      llvm::APSInt elementIndex,
382                      bool SubobjectIsDesignatorContext, unsigned &Index,
383                      InitListExpr *StructuredList,
384                      unsigned &StructuredIndex);
385  bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
386                                  unsigned DesigIdx,
387                                  QualType &CurrentObjectType,
388                                  RecordDecl::field_iterator *NextField,
389                                  llvm::APSInt *NextElementIndex,
390                                  unsigned &Index,
391                                  InitListExpr *StructuredList,
392                                  unsigned &StructuredIndex,
393                                  bool FinishSubobjectInit,
394                                  bool TopLevelObject);
395  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
396                                           QualType CurrentObjectType,
397                                           InitListExpr *StructuredList,
398                                           unsigned StructuredIndex,
399                                           SourceRange InitRange);
400  void UpdateStructuredListElement(InitListExpr *StructuredList,
401                                   unsigned &StructuredIndex,
402                                   Expr *expr);
403  int numArrayElements(QualType DeclType);
404  int numStructUnionElements(QualType DeclType);
405
406  void FillInValueInitializations(const InitializedEntity &Entity,
407                                  InitListExpr *ILE, bool &RequiresSecondPass);
408public:
409  InitListChecker(Sema &S, const InitializedEntity &Entity,
410                  InitListExpr *IL, QualType &T);
411  bool HadError() { return hadError; }
412
413  // @brief Retrieves the fully-structured initializer list used for
414  // semantic analysis and code generation.
415  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
416};
417} // end anonymous namespace
418
419/// Recursively replaces NULL values within the given initializer list
420/// with expressions that perform value-initialization of the
421/// appropriate type.
422void
423InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
424                                            InitListExpr *ILE,
425                                            bool &RequiresSecondPass) {
426  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
427         "Should not have void type");
428  SourceLocation Loc = ILE->getSourceRange().getBegin();
429  if (ILE->getSyntacticForm())
430    Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
431
432  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
433    unsigned Init = 0, NumInits = ILE->getNumInits();
434    for (RecordDecl::field_iterator
435           Field = RType->getDecl()->field_begin(),
436           FieldEnd = RType->getDecl()->field_end();
437         Field != FieldEnd; ++Field) {
438      if (Field->isUnnamedBitfield())
439        continue;
440
441      InitializedEntity MemberEntity
442        = InitializedEntity::InitializeMember(*Field, &Entity);
443      if (Init >= NumInits || !ILE->getInit(Init)) {
444        // FIXME: We probably don't need to handle references
445        // specially here, since value-initialization of references is
446        // handled in InitializationSequence.
447        if (Field->getType()->isReferenceType()) {
448          // C++ [dcl.init.aggr]p9:
449          //   If an incomplete or empty initializer-list leaves a
450          //   member of reference type uninitialized, the program is
451          //   ill-formed.
452          SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
453            << Field->getType()
454            << ILE->getSyntacticForm()->getSourceRange();
455          SemaRef.Diag(Field->getLocation(),
456                        diag::note_uninit_reference_member);
457          hadError = true;
458          return;
459        }
460
461        InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
462                                                                  true);
463        InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
464        if (!InitSeq) {
465          InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
466          hadError = true;
467          return;
468        }
469
470        Sema::OwningExprResult MemberInit
471          = InitSeq.Perform(SemaRef, MemberEntity, Kind,
472                            Sema::MultiExprArg(SemaRef, 0, 0));
473        if (MemberInit.isInvalid()) {
474          hadError = 0;
475          return;
476        }
477
478        if (hadError) {
479          // Do nothing
480        } else if (Init < NumInits) {
481          ILE->setInit(Init, MemberInit.takeAs<Expr>());
482        } else if (InitSeq.getKind()
483                         == InitializationSequence::ConstructorInitialization) {
484          // Value-initialization requires a constructor call, so
485          // extend the initializer list to include the constructor
486          // call and make a note that we'll need to take another pass
487          // through the initializer list.
488          ILE->updateInit(Init, MemberInit.takeAs<Expr>());
489          RequiresSecondPass = true;
490        }
491      } else if (InitListExpr *InnerILE
492                 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
493          FillInValueInitializations(MemberEntity, InnerILE,
494                                     RequiresSecondPass);
495      ++Init;
496
497      // Only look at the first initialization of a union.
498      if (RType->getDecl()->isUnion())
499        break;
500    }
501
502    return;
503  }
504
505  QualType ElementType;
506
507  InitializedEntity ElementEntity = Entity;
508  unsigned NumInits = ILE->getNumInits();
509  unsigned NumElements = NumInits;
510  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
511    ElementType = AType->getElementType();
512    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
513      NumElements = CAType->getSize().getZExtValue();
514    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
515                                                         0, Entity);
516  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
517    ElementType = VType->getElementType();
518    NumElements = VType->getNumElements();
519    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
520                                                         0, Entity);
521  } else
522    ElementType = ILE->getType();
523
524
525  for (unsigned Init = 0; Init != NumElements; ++Init) {
526    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
527      ElementEntity.setElementIndex(Init);
528
529    if (Init >= NumInits || !ILE->getInit(Init)) {
530      InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
531                                                                true);
532      InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
533      if (!InitSeq) {
534        InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
535        hadError = true;
536        return;
537      }
538
539      Sema::OwningExprResult ElementInit
540        = InitSeq.Perform(SemaRef, ElementEntity, Kind,
541                          Sema::MultiExprArg(SemaRef, 0, 0));
542      if (ElementInit.isInvalid()) {
543        hadError = 0;
544        return;
545      }
546
547      if (hadError) {
548        // Do nothing
549      } else if (Init < NumInits) {
550        ILE->setInit(Init, ElementInit.takeAs<Expr>());
551      } else if (InitSeq.getKind()
552                   == InitializationSequence::ConstructorInitialization) {
553        // Value-initialization requires a constructor call, so
554        // extend the initializer list to include the constructor
555        // call and make a note that we'll need to take another pass
556        // through the initializer list.
557        ILE->updateInit(Init, ElementInit.takeAs<Expr>());
558        RequiresSecondPass = true;
559      }
560    } else if (InitListExpr *InnerILE
561                 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
562      FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
563  }
564}
565
566
567InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
568                                 InitListExpr *IL, QualType &T)
569  : SemaRef(S) {
570  hadError = false;
571
572  unsigned newIndex = 0;
573  unsigned newStructuredIndex = 0;
574  FullyStructuredList
575    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
576  CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
577                        /*TopLevelObject=*/true);
578
579  if (!hadError) {
580    bool RequiresSecondPass = false;
581    FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
582    if (RequiresSecondPass)
583      FillInValueInitializations(Entity, FullyStructuredList,
584                                 RequiresSecondPass);
585  }
586}
587
588int InitListChecker::numArrayElements(QualType DeclType) {
589  // FIXME: use a proper constant
590  int maxElements = 0x7FFFFFFF;
591  if (const ConstantArrayType *CAT =
592        SemaRef.Context.getAsConstantArrayType(DeclType)) {
593    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
594  }
595  return maxElements;
596}
597
598int InitListChecker::numStructUnionElements(QualType DeclType) {
599  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
600  int InitializableMembers = 0;
601  for (RecordDecl::field_iterator
602         Field = structDecl->field_begin(),
603         FieldEnd = structDecl->field_end();
604       Field != FieldEnd; ++Field) {
605    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
606      ++InitializableMembers;
607  }
608  if (structDecl->isUnion())
609    return std::min(InitializableMembers, 1);
610  return InitializableMembers - structDecl->hasFlexibleArrayMember();
611}
612
613void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
614                                            QualType T, unsigned &Index,
615                                            InitListExpr *StructuredList,
616                                            unsigned &StructuredIndex,
617                                            bool TopLevelObject) {
618  int maxElements = 0;
619
620  if (T->isArrayType())
621    maxElements = numArrayElements(T);
622  else if (T->isStructureType() || T->isUnionType())
623    maxElements = numStructUnionElements(T);
624  else if (T->isVectorType())
625    maxElements = T->getAs<VectorType>()->getNumElements();
626  else
627    assert(0 && "CheckImplicitInitList(): Illegal type");
628
629  if (maxElements == 0) {
630    SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
631                  diag::err_implicit_empty_initializer);
632    ++Index;
633    hadError = true;
634    return;
635  }
636
637  // Build a structured initializer list corresponding to this subobject.
638  InitListExpr *StructuredSubobjectInitList
639    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
640                                 StructuredIndex,
641          SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
642                      ParentIList->getSourceRange().getEnd()));
643  unsigned StructuredSubobjectInitIndex = 0;
644
645  // Check the element types and build the structural subobject.
646  unsigned StartIndex = Index;
647  CheckListElementTypes(ParentIList, T, false, Index,
648                        StructuredSubobjectInitList,
649                        StructuredSubobjectInitIndex,
650                        TopLevelObject);
651  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
652  StructuredSubobjectInitList->setType(T);
653
654  // Update the structured sub-object initializer so that it's ending
655  // range corresponds with the end of the last initializer it used.
656  if (EndIndex < ParentIList->getNumInits()) {
657    SourceLocation EndLoc
658      = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
659    StructuredSubobjectInitList->setRBraceLoc(EndLoc);
660  }
661}
662
663void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
664                                            unsigned &Index,
665                                            InitListExpr *StructuredList,
666                                            unsigned &StructuredIndex,
667                                            bool TopLevelObject) {
668  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
669  SyntacticToSemantic[IList] = StructuredList;
670  StructuredList->setSyntacticForm(IList);
671  CheckListElementTypes(IList, T, true, Index, StructuredList,
672                        StructuredIndex, TopLevelObject);
673  IList->setType(T);
674  StructuredList->setType(T);
675  if (hadError)
676    return;
677
678  if (Index < IList->getNumInits()) {
679    // We have leftover initializers
680    if (StructuredIndex == 1 &&
681        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
682      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
683      if (SemaRef.getLangOptions().CPlusPlus) {
684        DK = diag::err_excess_initializers_in_char_array_initializer;
685        hadError = true;
686      }
687      // Special-case
688      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
689        << IList->getInit(Index)->getSourceRange();
690    } else if (!T->isIncompleteType()) {
691      // Don't complain for incomplete types, since we'll get an error
692      // elsewhere
693      QualType CurrentObjectType = StructuredList->getType();
694      int initKind =
695        CurrentObjectType->isArrayType()? 0 :
696        CurrentObjectType->isVectorType()? 1 :
697        CurrentObjectType->isScalarType()? 2 :
698        CurrentObjectType->isUnionType()? 3 :
699        4;
700
701      unsigned DK = diag::warn_excess_initializers;
702      if (SemaRef.getLangOptions().CPlusPlus) {
703        DK = diag::err_excess_initializers;
704        hadError = true;
705      }
706      if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
707        DK = diag::err_excess_initializers;
708        hadError = true;
709      }
710
711      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
712        << initKind << IList->getInit(Index)->getSourceRange();
713    }
714  }
715
716  if (T->isScalarType() && !TopLevelObject)
717    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
718      << IList->getSourceRange()
719      << CodeModificationHint::CreateRemoval(IList->getLocStart())
720      << CodeModificationHint::CreateRemoval(IList->getLocEnd());
721}
722
723void InitListChecker::CheckListElementTypes(InitListExpr *IList,
724                                            QualType &DeclType,
725                                            bool SubobjectIsDesignatorContext,
726                                            unsigned &Index,
727                                            InitListExpr *StructuredList,
728                                            unsigned &StructuredIndex,
729                                            bool TopLevelObject) {
730  if (DeclType->isScalarType()) {
731    CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
732  } else if (DeclType->isVectorType()) {
733    CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
734  } else if (DeclType->isAggregateType()) {
735    if (DeclType->isRecordType()) {
736      RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
737      CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
738                            SubobjectIsDesignatorContext, Index,
739                            StructuredList, StructuredIndex,
740                            TopLevelObject);
741    } else if (DeclType->isArrayType()) {
742      llvm::APSInt Zero(
743                      SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
744                      false);
745      CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
746                     StructuredList, StructuredIndex);
747    } else
748      assert(0 && "Aggregate that isn't a structure or array?!");
749  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
750    // This type is invalid, issue a diagnostic.
751    ++Index;
752    SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
753      << DeclType;
754    hadError = true;
755  } else if (DeclType->isRecordType()) {
756    // C++ [dcl.init]p14:
757    //   [...] If the class is an aggregate (8.5.1), and the initializer
758    //   is a brace-enclosed list, see 8.5.1.
759    //
760    // Note: 8.5.1 is handled below; here, we diagnose the case where
761    // we have an initializer list and a destination type that is not
762    // an aggregate.
763    // FIXME: In C++0x, this is yet another form of initialization.
764    SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
765      << DeclType << IList->getSourceRange();
766    hadError = true;
767  } else if (DeclType->isReferenceType()) {
768    CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
769  } else {
770    // In C, all types are either scalars or aggregates, but
771    // additional handling is needed here for C++ (and possibly others?).
772    assert(0 && "Unsupported initializer type");
773  }
774}
775
776void InitListChecker::CheckSubElementType(InitListExpr *IList,
777                                          QualType ElemType,
778                                          unsigned &Index,
779                                          InitListExpr *StructuredList,
780                                          unsigned &StructuredIndex) {
781  Expr *expr = IList->getInit(Index);
782  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
783    unsigned newIndex = 0;
784    unsigned newStructuredIndex = 0;
785    InitListExpr *newStructuredList
786      = getStructuredSubobjectInit(IList, Index, ElemType,
787                                   StructuredList, StructuredIndex,
788                                   SubInitList->getSourceRange());
789    CheckExplicitInitList(SubInitList, ElemType, newIndex,
790                          newStructuredList, newStructuredIndex);
791    ++StructuredIndex;
792    ++Index;
793  } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
794    CheckStringInit(Str, ElemType, SemaRef);
795    UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
796    ++Index;
797  } else if (ElemType->isScalarType()) {
798    CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
799  } else if (ElemType->isReferenceType()) {
800    CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
801  } else {
802    if (SemaRef.getLangOptions().CPlusPlus) {
803      // C++ [dcl.init.aggr]p12:
804      //   All implicit type conversions (clause 4) are considered when
805      //   initializing the aggregate member with an ini- tializer from
806      //   an initializer-list. If the initializer can initialize a
807      //   member, the member is initialized. [...]
808      ImplicitConversionSequence ICS
809        = SemaRef.TryCopyInitialization(expr, ElemType,
810                                        /*SuppressUserConversions=*/false,
811                                        /*ForceRValue=*/false,
812                                        /*InOverloadResolution=*/false);
813
814      if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
815        if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
816                                              Sema::AA_Initializing))
817          hadError = true;
818        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
819        ++Index;
820        return;
821      }
822
823      // Fall through for subaggregate initialization
824    } else {
825      // C99 6.7.8p13:
826      //
827      //   The initializer for a structure or union object that has
828      //   automatic storage duration shall be either an initializer
829      //   list as described below, or a single expression that has
830      //   compatible structure or union type. In the latter case, the
831      //   initial value of the object, including unnamed members, is
832      //   that of the expression.
833      if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
834          SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
835        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
836        ++Index;
837        return;
838      }
839
840      // Fall through for subaggregate initialization
841    }
842
843    // C++ [dcl.init.aggr]p12:
844    //
845    //   [...] Otherwise, if the member is itself a non-empty
846    //   subaggregate, brace elision is assumed and the initializer is
847    //   considered for the initialization of the first member of
848    //   the subaggregate.
849    if (ElemType->isAggregateType() || ElemType->isVectorType()) {
850      CheckImplicitInitList(IList, ElemType, Index, StructuredList,
851                            StructuredIndex);
852      ++StructuredIndex;
853    } else {
854      // We cannot initialize this element, so let
855      // PerformCopyInitialization produce the appropriate diagnostic.
856      SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
857      hadError = true;
858      ++Index;
859      ++StructuredIndex;
860    }
861  }
862}
863
864void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
865                                      unsigned &Index,
866                                      InitListExpr *StructuredList,
867                                      unsigned &StructuredIndex) {
868  if (Index < IList->getNumInits()) {
869    Expr *expr = IList->getInit(Index);
870    if (isa<InitListExpr>(expr)) {
871      SemaRef.Diag(IList->getLocStart(),
872                    diag::err_many_braces_around_scalar_init)
873        << IList->getSourceRange();
874      hadError = true;
875      ++Index;
876      ++StructuredIndex;
877      return;
878    } else if (isa<DesignatedInitExpr>(expr)) {
879      SemaRef.Diag(expr->getSourceRange().getBegin(),
880                    diag::err_designator_for_scalar_init)
881        << DeclType << expr->getSourceRange();
882      hadError = true;
883      ++Index;
884      ++StructuredIndex;
885      return;
886    }
887
888    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
889    if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
890      hadError = true; // types weren't compatible.
891    else if (savExpr != expr) {
892      // The type was promoted, update initializer list.
893      IList->setInit(Index, expr);
894    }
895    if (hadError)
896      ++StructuredIndex;
897    else
898      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
899    ++Index;
900  } else {
901    SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
902      << IList->getSourceRange();
903    hadError = true;
904    ++Index;
905    ++StructuredIndex;
906    return;
907  }
908}
909
910void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
911                                         unsigned &Index,
912                                         InitListExpr *StructuredList,
913                                         unsigned &StructuredIndex) {
914  if (Index < IList->getNumInits()) {
915    Expr *expr = IList->getInit(Index);
916    if (isa<InitListExpr>(expr)) {
917      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
918        << DeclType << IList->getSourceRange();
919      hadError = true;
920      ++Index;
921      ++StructuredIndex;
922      return;
923    }
924
925    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
926    if (SemaRef.CheckReferenceInit(expr, DeclType,
927                                   /*FIXME:*/expr->getLocStart(),
928                                   /*SuppressUserConversions=*/false,
929                                   /*AllowExplicit=*/false,
930                                   /*ForceRValue=*/false))
931      hadError = true;
932    else if (savExpr != expr) {
933      // The type was promoted, update initializer list.
934      IList->setInit(Index, expr);
935    }
936    if (hadError)
937      ++StructuredIndex;
938    else
939      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
940    ++Index;
941  } else {
942    // FIXME: It would be wonderful if we could point at the actual member. In
943    // general, it would be useful to pass location information down the stack,
944    // so that we know the location (or decl) of the "current object" being
945    // initialized.
946    SemaRef.Diag(IList->getLocStart(),
947                  diag::err_init_reference_member_uninitialized)
948      << DeclType
949      << IList->getSourceRange();
950    hadError = true;
951    ++Index;
952    ++StructuredIndex;
953    return;
954  }
955}
956
957void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
958                                      unsigned &Index,
959                                      InitListExpr *StructuredList,
960                                      unsigned &StructuredIndex) {
961  if (Index < IList->getNumInits()) {
962    const VectorType *VT = DeclType->getAs<VectorType>();
963    unsigned maxElements = VT->getNumElements();
964    unsigned numEltsInit = 0;
965    QualType elementType = VT->getElementType();
966
967    if (!SemaRef.getLangOptions().OpenCL) {
968      for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
969        // Don't attempt to go past the end of the init list
970        if (Index >= IList->getNumInits())
971          break;
972        CheckSubElementType(IList, elementType, Index,
973                            StructuredList, StructuredIndex);
974      }
975    } else {
976      // OpenCL initializers allows vectors to be constructed from vectors.
977      for (unsigned i = 0; i < maxElements; ++i) {
978        // Don't attempt to go past the end of the init list
979        if (Index >= IList->getNumInits())
980          break;
981        QualType IType = IList->getInit(Index)->getType();
982        if (!IType->isVectorType()) {
983          CheckSubElementType(IList, elementType, Index,
984                              StructuredList, StructuredIndex);
985          ++numEltsInit;
986        } else {
987          const VectorType *IVT = IType->getAs<VectorType>();
988          unsigned numIElts = IVT->getNumElements();
989          QualType VecType = SemaRef.Context.getExtVectorType(elementType,
990                                                              numIElts);
991          CheckSubElementType(IList, VecType, Index,
992                              StructuredList, StructuredIndex);
993          numEltsInit += numIElts;
994        }
995      }
996    }
997
998    // OpenCL & AltiVec require all elements to be initialized.
999    if (numEltsInit != maxElements)
1000      if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
1001        SemaRef.Diag(IList->getSourceRange().getBegin(),
1002                     diag::err_vector_incorrect_num_initializers)
1003          << (numEltsInit < maxElements) << maxElements << numEltsInit;
1004  }
1005}
1006
1007void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
1008                                     llvm::APSInt elementIndex,
1009                                     bool SubobjectIsDesignatorContext,
1010                                     unsigned &Index,
1011                                     InitListExpr *StructuredList,
1012                                     unsigned &StructuredIndex) {
1013  // Check for the special-case of initializing an array with a string.
1014  if (Index < IList->getNumInits()) {
1015    if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
1016                                 SemaRef.Context)) {
1017      CheckStringInit(Str, DeclType, SemaRef);
1018      // We place the string literal directly into the resulting
1019      // initializer list. This is the only place where the structure
1020      // of the structured initializer list doesn't match exactly,
1021      // because doing so would involve allocating one character
1022      // constant for each string.
1023      UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1024      StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1025      ++Index;
1026      return;
1027    }
1028  }
1029  if (const VariableArrayType *VAT =
1030        SemaRef.Context.getAsVariableArrayType(DeclType)) {
1031    // Check for VLAs; in standard C it would be possible to check this
1032    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1033    // them in all sorts of strange places).
1034    SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1035                  diag::err_variable_object_no_init)
1036      << VAT->getSizeExpr()->getSourceRange();
1037    hadError = true;
1038    ++Index;
1039    ++StructuredIndex;
1040    return;
1041  }
1042
1043  // We might know the maximum number of elements in advance.
1044  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1045                           elementIndex.isUnsigned());
1046  bool maxElementsKnown = false;
1047  if (const ConstantArrayType *CAT =
1048        SemaRef.Context.getAsConstantArrayType(DeclType)) {
1049    maxElements = CAT->getSize();
1050    elementIndex.extOrTrunc(maxElements.getBitWidth());
1051    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1052    maxElementsKnown = true;
1053  }
1054
1055  QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
1056                             ->getElementType();
1057  while (Index < IList->getNumInits()) {
1058    Expr *Init = IList->getInit(Index);
1059    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1060      // If we're not the subobject that matches up with the '{' for
1061      // the designator, we shouldn't be handling the
1062      // designator. Return immediately.
1063      if (!SubobjectIsDesignatorContext)
1064        return;
1065
1066      // Handle this designated initializer. elementIndex will be
1067      // updated to be the next array element we'll initialize.
1068      if (CheckDesignatedInitializer(IList, DIE, 0,
1069                                     DeclType, 0, &elementIndex, Index,
1070                                     StructuredList, StructuredIndex, true,
1071                                     false)) {
1072        hadError = true;
1073        continue;
1074      }
1075
1076      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1077        maxElements.extend(elementIndex.getBitWidth());
1078      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1079        elementIndex.extend(maxElements.getBitWidth());
1080      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1081
1082      // If the array is of incomplete type, keep track of the number of
1083      // elements in the initializer.
1084      if (!maxElementsKnown && elementIndex > maxElements)
1085        maxElements = elementIndex;
1086
1087      continue;
1088    }
1089
1090    // If we know the maximum number of elements, and we've already
1091    // hit it, stop consuming elements in the initializer list.
1092    if (maxElementsKnown && elementIndex == maxElements)
1093      break;
1094
1095    // Check this element.
1096    CheckSubElementType(IList, elementType, Index,
1097                        StructuredList, StructuredIndex);
1098    ++elementIndex;
1099
1100    // If the array is of incomplete type, keep track of the number of
1101    // elements in the initializer.
1102    if (!maxElementsKnown && elementIndex > maxElements)
1103      maxElements = elementIndex;
1104  }
1105  if (!hadError && DeclType->isIncompleteArrayType()) {
1106    // If this is an incomplete array type, the actual type needs to
1107    // be calculated here.
1108    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1109    if (maxElements == Zero) {
1110      // Sizing an array implicitly to zero is not allowed by ISO C,
1111      // but is supported by GNU.
1112      SemaRef.Diag(IList->getLocStart(),
1113                    diag::ext_typecheck_zero_array_size);
1114    }
1115
1116    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1117                                                     ArrayType::Normal, 0);
1118  }
1119}
1120
1121void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1122                                            QualType DeclType,
1123                                            RecordDecl::field_iterator Field,
1124                                            bool SubobjectIsDesignatorContext,
1125                                            unsigned &Index,
1126                                            InitListExpr *StructuredList,
1127                                            unsigned &StructuredIndex,
1128                                            bool TopLevelObject) {
1129  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1130
1131  // If the record is invalid, some of it's members are invalid. To avoid
1132  // confusion, we forgo checking the intializer for the entire record.
1133  if (structDecl->isInvalidDecl()) {
1134    hadError = true;
1135    return;
1136  }
1137
1138  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1139    // Value-initialize the first named member of the union.
1140    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1141    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1142         Field != FieldEnd; ++Field) {
1143      if (Field->getDeclName()) {
1144        StructuredList->setInitializedFieldInUnion(*Field);
1145        break;
1146      }
1147    }
1148    return;
1149  }
1150
1151  // If structDecl is a forward declaration, this loop won't do
1152  // anything except look at designated initializers; That's okay,
1153  // because an error should get printed out elsewhere. It might be
1154  // worthwhile to skip over the rest of the initializer, though.
1155  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1156  RecordDecl::field_iterator FieldEnd = RD->field_end();
1157  bool InitializedSomething = false;
1158  while (Index < IList->getNumInits()) {
1159    Expr *Init = IList->getInit(Index);
1160
1161    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1162      // If we're not the subobject that matches up with the '{' for
1163      // the designator, we shouldn't be handling the
1164      // designator. Return immediately.
1165      if (!SubobjectIsDesignatorContext)
1166        return;
1167
1168      // Handle this designated initializer. Field will be updated to
1169      // the next field that we'll be initializing.
1170      if (CheckDesignatedInitializer(IList, DIE, 0,
1171                                     DeclType, &Field, 0, Index,
1172                                     StructuredList, StructuredIndex,
1173                                     true, TopLevelObject))
1174        hadError = true;
1175
1176      InitializedSomething = true;
1177      continue;
1178    }
1179
1180    if (Field == FieldEnd) {
1181      // We've run out of fields. We're done.
1182      break;
1183    }
1184
1185    // We've already initialized a member of a union. We're done.
1186    if (InitializedSomething && DeclType->isUnionType())
1187      break;
1188
1189    // If we've hit the flexible array member at the end, we're done.
1190    if (Field->getType()->isIncompleteArrayType())
1191      break;
1192
1193    if (Field->isUnnamedBitfield()) {
1194      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1195      ++Field;
1196      continue;
1197    }
1198
1199    CheckSubElementType(IList, Field->getType(), Index,
1200                        StructuredList, StructuredIndex);
1201    InitializedSomething = true;
1202
1203    if (DeclType->isUnionType()) {
1204      // Initialize the first field within the union.
1205      StructuredList->setInitializedFieldInUnion(*Field);
1206    }
1207
1208    ++Field;
1209  }
1210
1211  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1212      Index >= IList->getNumInits())
1213    return;
1214
1215  // Handle GNU flexible array initializers.
1216  if (!TopLevelObject &&
1217      (!isa<InitListExpr>(IList->getInit(Index)) ||
1218       cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
1219    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1220                  diag::err_flexible_array_init_nonempty)
1221      << IList->getInit(Index)->getSourceRange().getBegin();
1222    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1223      << *Field;
1224    hadError = true;
1225    ++Index;
1226    return;
1227  } else {
1228    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1229                 diag::ext_flexible_array_init)
1230      << IList->getInit(Index)->getSourceRange().getBegin();
1231    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1232      << *Field;
1233  }
1234
1235  if (isa<InitListExpr>(IList->getInit(Index)))
1236    CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1237                        StructuredIndex);
1238  else
1239    CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1240                          StructuredIndex);
1241}
1242
1243/// \brief Expand a field designator that refers to a member of an
1244/// anonymous struct or union into a series of field designators that
1245/// refers to the field within the appropriate subobject.
1246///
1247/// Field/FieldIndex will be updated to point to the (new)
1248/// currently-designated field.
1249static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1250                                           DesignatedInitExpr *DIE,
1251                                           unsigned DesigIdx,
1252                                           FieldDecl *Field,
1253                                        RecordDecl::field_iterator &FieldIter,
1254                                           unsigned &FieldIndex) {
1255  typedef DesignatedInitExpr::Designator Designator;
1256
1257  // Build the path from the current object to the member of the
1258  // anonymous struct/union (backwards).
1259  llvm::SmallVector<FieldDecl *, 4> Path;
1260  SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1261
1262  // Build the replacement designators.
1263  llvm::SmallVector<Designator, 4> Replacements;
1264  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1265         FI = Path.rbegin(), FIEnd = Path.rend();
1266       FI != FIEnd; ++FI) {
1267    if (FI + 1 == FIEnd)
1268      Replacements.push_back(Designator((IdentifierInfo *)0,
1269                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1270                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1271    else
1272      Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1273                                        SourceLocation()));
1274    Replacements.back().setField(*FI);
1275  }
1276
1277  // Expand the current designator into the set of replacement
1278  // designators, so we have a full subobject path down to where the
1279  // member of the anonymous struct/union is actually stored.
1280  DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1281                        &Replacements[0] + Replacements.size());
1282
1283  // Update FieldIter/FieldIndex;
1284  RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1285  FieldIter = Record->field_begin();
1286  FieldIndex = 0;
1287  for (RecordDecl::field_iterator FEnd = Record->field_end();
1288       FieldIter != FEnd; ++FieldIter) {
1289    if (FieldIter->isUnnamedBitfield())
1290        continue;
1291
1292    if (*FieldIter == Path.back())
1293      return;
1294
1295    ++FieldIndex;
1296  }
1297
1298  assert(false && "Unable to find anonymous struct/union field");
1299}
1300
1301/// @brief Check the well-formedness of a C99 designated initializer.
1302///
1303/// Determines whether the designated initializer @p DIE, which
1304/// resides at the given @p Index within the initializer list @p
1305/// IList, is well-formed for a current object of type @p DeclType
1306/// (C99 6.7.8). The actual subobject that this designator refers to
1307/// within the current subobject is returned in either
1308/// @p NextField or @p NextElementIndex (whichever is appropriate).
1309///
1310/// @param IList  The initializer list in which this designated
1311/// initializer occurs.
1312///
1313/// @param DIE The designated initializer expression.
1314///
1315/// @param DesigIdx  The index of the current designator.
1316///
1317/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
1318/// into which the designation in @p DIE should refer.
1319///
1320/// @param NextField  If non-NULL and the first designator in @p DIE is
1321/// a field, this will be set to the field declaration corresponding
1322/// to the field named by the designator.
1323///
1324/// @param NextElementIndex  If non-NULL and the first designator in @p
1325/// DIE is an array designator or GNU array-range designator, this
1326/// will be set to the last index initialized by this designator.
1327///
1328/// @param Index  Index into @p IList where the designated initializer
1329/// @p DIE occurs.
1330///
1331/// @param StructuredList  The initializer list expression that
1332/// describes all of the subobject initializers in the order they'll
1333/// actually be initialized.
1334///
1335/// @returns true if there was an error, false otherwise.
1336bool
1337InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1338                                      DesignatedInitExpr *DIE,
1339                                      unsigned DesigIdx,
1340                                      QualType &CurrentObjectType,
1341                                      RecordDecl::field_iterator *NextField,
1342                                      llvm::APSInt *NextElementIndex,
1343                                      unsigned &Index,
1344                                      InitListExpr *StructuredList,
1345                                      unsigned &StructuredIndex,
1346                                            bool FinishSubobjectInit,
1347                                            bool TopLevelObject) {
1348  if (DesigIdx == DIE->size()) {
1349    // Check the actual initialization for the designated object type.
1350    bool prevHadError = hadError;
1351
1352    // Temporarily remove the designator expression from the
1353    // initializer list that the child calls see, so that we don't try
1354    // to re-process the designator.
1355    unsigned OldIndex = Index;
1356    IList->setInit(OldIndex, DIE->getInit());
1357
1358    CheckSubElementType(IList, CurrentObjectType, Index,
1359                        StructuredList, StructuredIndex);
1360
1361    // Restore the designated initializer expression in the syntactic
1362    // form of the initializer list.
1363    if (IList->getInit(OldIndex) != DIE->getInit())
1364      DIE->setInit(IList->getInit(OldIndex));
1365    IList->setInit(OldIndex, DIE);
1366
1367    return hadError && !prevHadError;
1368  }
1369
1370  bool IsFirstDesignator = (DesigIdx == 0);
1371  assert((IsFirstDesignator || StructuredList) &&
1372         "Need a non-designated initializer list to start from");
1373
1374  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1375  // Determine the structural initializer list that corresponds to the
1376  // current subobject.
1377  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1378    : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1379                                 StructuredList, StructuredIndex,
1380                                 SourceRange(D->getStartLocation(),
1381                                             DIE->getSourceRange().getEnd()));
1382  assert(StructuredList && "Expected a structured initializer list");
1383
1384  if (D->isFieldDesignator()) {
1385    // C99 6.7.8p7:
1386    //
1387    //   If a designator has the form
1388    //
1389    //      . identifier
1390    //
1391    //   then the current object (defined below) shall have
1392    //   structure or union type and the identifier shall be the
1393    //   name of a member of that type.
1394    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1395    if (!RT) {
1396      SourceLocation Loc = D->getDotLoc();
1397      if (Loc.isInvalid())
1398        Loc = D->getFieldLoc();
1399      SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1400        << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1401      ++Index;
1402      return true;
1403    }
1404
1405    // Note: we perform a linear search of the fields here, despite
1406    // the fact that we have a faster lookup method, because we always
1407    // need to compute the field's index.
1408    FieldDecl *KnownField = D->getField();
1409    IdentifierInfo *FieldName = D->getFieldName();
1410    unsigned FieldIndex = 0;
1411    RecordDecl::field_iterator
1412      Field = RT->getDecl()->field_begin(),
1413      FieldEnd = RT->getDecl()->field_end();
1414    for (; Field != FieldEnd; ++Field) {
1415      if (Field->isUnnamedBitfield())
1416        continue;
1417
1418      if (KnownField == *Field || Field->getIdentifier() == FieldName)
1419        break;
1420
1421      ++FieldIndex;
1422    }
1423
1424    if (Field == FieldEnd) {
1425      // There was no normal field in the struct with the designated
1426      // name. Perform another lookup for this name, which may find
1427      // something that we can't designate (e.g., a member function),
1428      // may find nothing, or may find a member of an anonymous
1429      // struct/union.
1430      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1431      if (Lookup.first == Lookup.second) {
1432        // Name lookup didn't find anything.
1433        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1434          << FieldName << CurrentObjectType;
1435        ++Index;
1436        return true;
1437      } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1438                 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1439                   ->isAnonymousStructOrUnion()) {
1440        // Handle an field designator that refers to a member of an
1441        // anonymous struct or union.
1442        ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1443                                       cast<FieldDecl>(*Lookup.first),
1444                                       Field, FieldIndex);
1445        D = DIE->getDesignator(DesigIdx);
1446      } else {
1447        // Name lookup found something, but it wasn't a field.
1448        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1449          << FieldName;
1450        SemaRef.Diag((*Lookup.first)->getLocation(),
1451                      diag::note_field_designator_found);
1452        ++Index;
1453        return true;
1454      }
1455    } else if (!KnownField &&
1456               cast<RecordDecl>((*Field)->getDeclContext())
1457                 ->isAnonymousStructOrUnion()) {
1458      ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1459                                     Field, FieldIndex);
1460      D = DIE->getDesignator(DesigIdx);
1461    }
1462
1463    // All of the fields of a union are located at the same place in
1464    // the initializer list.
1465    if (RT->getDecl()->isUnion()) {
1466      FieldIndex = 0;
1467      StructuredList->setInitializedFieldInUnion(*Field);
1468    }
1469
1470    // Update the designator with the field declaration.
1471    D->setField(*Field);
1472
1473    // Make sure that our non-designated initializer list has space
1474    // for a subobject corresponding to this field.
1475    if (FieldIndex >= StructuredList->getNumInits())
1476      StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1477
1478    // This designator names a flexible array member.
1479    if (Field->getType()->isIncompleteArrayType()) {
1480      bool Invalid = false;
1481      if ((DesigIdx + 1) != DIE->size()) {
1482        // We can't designate an object within the flexible array
1483        // member (because GCC doesn't allow it).
1484        DesignatedInitExpr::Designator *NextD
1485          = DIE->getDesignator(DesigIdx + 1);
1486        SemaRef.Diag(NextD->getStartLocation(),
1487                      diag::err_designator_into_flexible_array_member)
1488          << SourceRange(NextD->getStartLocation(),
1489                         DIE->getSourceRange().getEnd());
1490        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1491          << *Field;
1492        Invalid = true;
1493      }
1494
1495      if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1496        // The initializer is not an initializer list.
1497        SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1498                      diag::err_flexible_array_init_needs_braces)
1499          << DIE->getInit()->getSourceRange();
1500        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1501          << *Field;
1502        Invalid = true;
1503      }
1504
1505      // Handle GNU flexible array initializers.
1506      if (!Invalid && !TopLevelObject &&
1507          cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1508        SemaRef.Diag(DIE->getSourceRange().getBegin(),
1509                      diag::err_flexible_array_init_nonempty)
1510          << DIE->getSourceRange().getBegin();
1511        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1512          << *Field;
1513        Invalid = true;
1514      }
1515
1516      if (Invalid) {
1517        ++Index;
1518        return true;
1519      }
1520
1521      // Initialize the array.
1522      bool prevHadError = hadError;
1523      unsigned newStructuredIndex = FieldIndex;
1524      unsigned OldIndex = Index;
1525      IList->setInit(Index, DIE->getInit());
1526      CheckSubElementType(IList, Field->getType(), Index,
1527                          StructuredList, newStructuredIndex);
1528      IList->setInit(OldIndex, DIE);
1529      if (hadError && !prevHadError) {
1530        ++Field;
1531        ++FieldIndex;
1532        if (NextField)
1533          *NextField = Field;
1534        StructuredIndex = FieldIndex;
1535        return true;
1536      }
1537    } else {
1538      // Recurse to check later designated subobjects.
1539      QualType FieldType = (*Field)->getType();
1540      unsigned newStructuredIndex = FieldIndex;
1541      if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1542                                     Index, StructuredList, newStructuredIndex,
1543                                     true, false))
1544        return true;
1545    }
1546
1547    // Find the position of the next field to be initialized in this
1548    // subobject.
1549    ++Field;
1550    ++FieldIndex;
1551
1552    // If this the first designator, our caller will continue checking
1553    // the rest of this struct/class/union subobject.
1554    if (IsFirstDesignator) {
1555      if (NextField)
1556        *NextField = Field;
1557      StructuredIndex = FieldIndex;
1558      return false;
1559    }
1560
1561    if (!FinishSubobjectInit)
1562      return false;
1563
1564    // We've already initialized something in the union; we're done.
1565    if (RT->getDecl()->isUnion())
1566      return hadError;
1567
1568    // Check the remaining fields within this class/struct/union subobject.
1569    bool prevHadError = hadError;
1570    CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1571                          StructuredList, FieldIndex);
1572    return hadError && !prevHadError;
1573  }
1574
1575  // C99 6.7.8p6:
1576  //
1577  //   If a designator has the form
1578  //
1579  //      [ constant-expression ]
1580  //
1581  //   then the current object (defined below) shall have array
1582  //   type and the expression shall be an integer constant
1583  //   expression. If the array is of unknown size, any
1584  //   nonnegative value is valid.
1585  //
1586  // Additionally, cope with the GNU extension that permits
1587  // designators of the form
1588  //
1589  //      [ constant-expression ... constant-expression ]
1590  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1591  if (!AT) {
1592    SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1593      << CurrentObjectType;
1594    ++Index;
1595    return true;
1596  }
1597
1598  Expr *IndexExpr = 0;
1599  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1600  if (D->isArrayDesignator()) {
1601    IndexExpr = DIE->getArrayIndex(*D);
1602    DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
1603    DesignatedEndIndex = DesignatedStartIndex;
1604  } else {
1605    assert(D->isArrayRangeDesignator() && "Need array-range designator");
1606
1607
1608    DesignatedStartIndex =
1609      DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1610    DesignatedEndIndex =
1611      DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
1612    IndexExpr = DIE->getArrayRangeEnd(*D);
1613
1614    if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
1615      FullyStructuredList->sawArrayRangeDesignator();
1616  }
1617
1618  if (isa<ConstantArrayType>(AT)) {
1619    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1620    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1621    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1622    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1623    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1624    if (DesignatedEndIndex >= MaxElements) {
1625      SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1626                    diag::err_array_designator_too_large)
1627        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1628        << IndexExpr->getSourceRange();
1629      ++Index;
1630      return true;
1631    }
1632  } else {
1633    // Make sure the bit-widths and signedness match.
1634    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1635      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1636    else if (DesignatedStartIndex.getBitWidth() <
1637             DesignatedEndIndex.getBitWidth())
1638      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1639    DesignatedStartIndex.setIsUnsigned(true);
1640    DesignatedEndIndex.setIsUnsigned(true);
1641  }
1642
1643  // Make sure that our non-designated initializer list has space
1644  // for a subobject corresponding to this array element.
1645  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1646    StructuredList->resizeInits(SemaRef.Context,
1647                                DesignatedEndIndex.getZExtValue() + 1);
1648
1649  // Repeatedly perform subobject initializations in the range
1650  // [DesignatedStartIndex, DesignatedEndIndex].
1651
1652  // Move to the next designator
1653  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1654  unsigned OldIndex = Index;
1655  while (DesignatedStartIndex <= DesignatedEndIndex) {
1656    // Recurse to check later designated subobjects.
1657    QualType ElementType = AT->getElementType();
1658    Index = OldIndex;
1659    if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1660                                   Index, StructuredList, ElementIndex,
1661                                   (DesignatedStartIndex == DesignatedEndIndex),
1662                                   false))
1663      return true;
1664
1665    // Move to the next index in the array that we'll be initializing.
1666    ++DesignatedStartIndex;
1667    ElementIndex = DesignatedStartIndex.getZExtValue();
1668  }
1669
1670  // If this the first designator, our caller will continue checking
1671  // the rest of this array subobject.
1672  if (IsFirstDesignator) {
1673    if (NextElementIndex)
1674      *NextElementIndex = DesignatedStartIndex;
1675    StructuredIndex = ElementIndex;
1676    return false;
1677  }
1678
1679  if (!FinishSubobjectInit)
1680    return false;
1681
1682  // Check the remaining elements within this array subobject.
1683  bool prevHadError = hadError;
1684  CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
1685                 StructuredList, ElementIndex);
1686  return hadError && !prevHadError;
1687}
1688
1689// Get the structured initializer list for a subobject of type
1690// @p CurrentObjectType.
1691InitListExpr *
1692InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1693                                            QualType CurrentObjectType,
1694                                            InitListExpr *StructuredList,
1695                                            unsigned StructuredIndex,
1696                                            SourceRange InitRange) {
1697  Expr *ExistingInit = 0;
1698  if (!StructuredList)
1699    ExistingInit = SyntacticToSemantic[IList];
1700  else if (StructuredIndex < StructuredList->getNumInits())
1701    ExistingInit = StructuredList->getInit(StructuredIndex);
1702
1703  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1704    return Result;
1705
1706  if (ExistingInit) {
1707    // We are creating an initializer list that initializes the
1708    // subobjects of the current object, but there was already an
1709    // initialization that completely initialized the current
1710    // subobject, e.g., by a compound literal:
1711    //
1712    // struct X { int a, b; };
1713    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1714    //
1715    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1716    // designated initializer re-initializes the whole
1717    // subobject [0], overwriting previous initializers.
1718    SemaRef.Diag(InitRange.getBegin(),
1719                 diag::warn_subobject_initializer_overrides)
1720      << InitRange;
1721    SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
1722                  diag::note_previous_initializer)
1723      << /*FIXME:has side effects=*/0
1724      << ExistingInit->getSourceRange();
1725  }
1726
1727  InitListExpr *Result
1728    = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1729                                         InitRange.getEnd());
1730
1731  Result->setType(CurrentObjectType);
1732
1733  // Pre-allocate storage for the structured initializer list.
1734  unsigned NumElements = 0;
1735  unsigned NumInits = 0;
1736  if (!StructuredList)
1737    NumInits = IList->getNumInits();
1738  else if (Index < IList->getNumInits()) {
1739    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1740      NumInits = SubList->getNumInits();
1741  }
1742
1743  if (const ArrayType *AType
1744      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1745    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1746      NumElements = CAType->getSize().getZExtValue();
1747      // Simple heuristic so that we don't allocate a very large
1748      // initializer with many empty entries at the end.
1749      if (NumInits && NumElements > NumInits)
1750        NumElements = 0;
1751    }
1752  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
1753    NumElements = VType->getNumElements();
1754  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
1755    RecordDecl *RDecl = RType->getDecl();
1756    if (RDecl->isUnion())
1757      NumElements = 1;
1758    else
1759      NumElements = std::distance(RDecl->field_begin(),
1760                                  RDecl->field_end());
1761  }
1762
1763  if (NumElements < NumInits)
1764    NumElements = IList->getNumInits();
1765
1766  Result->reserveInits(NumElements);
1767
1768  // Link this new initializer list into the structured initializer
1769  // lists.
1770  if (StructuredList)
1771    StructuredList->updateInit(StructuredIndex, Result);
1772  else {
1773    Result->setSyntacticForm(IList);
1774    SyntacticToSemantic[IList] = Result;
1775  }
1776
1777  return Result;
1778}
1779
1780/// Update the initializer at index @p StructuredIndex within the
1781/// structured initializer list to the value @p expr.
1782void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1783                                                  unsigned &StructuredIndex,
1784                                                  Expr *expr) {
1785  // No structured initializer list to update
1786  if (!StructuredList)
1787    return;
1788
1789  if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1790    // This initializer overwrites a previous initializer. Warn.
1791    SemaRef.Diag(expr->getSourceRange().getBegin(),
1792                  diag::warn_initializer_overrides)
1793      << expr->getSourceRange();
1794    SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
1795                  diag::note_previous_initializer)
1796      << /*FIXME:has side effects=*/0
1797      << PrevInit->getSourceRange();
1798  }
1799
1800  ++StructuredIndex;
1801}
1802
1803/// Check that the given Index expression is a valid array designator
1804/// value. This is essentailly just a wrapper around
1805/// VerifyIntegerConstantExpression that also checks for negative values
1806/// and produces a reasonable diagnostic if there is a
1807/// failure. Returns true if there was an error, false otherwise.  If
1808/// everything went okay, Value will receive the value of the constant
1809/// expression.
1810static bool
1811CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
1812  SourceLocation Loc = Index->getSourceRange().getBegin();
1813
1814  // Make sure this is an integer constant expression.
1815  if (S.VerifyIntegerConstantExpression(Index, &Value))
1816    return true;
1817
1818  if (Value.isSigned() && Value.isNegative())
1819    return S.Diag(Loc, diag::err_array_designator_negative)
1820      << Value.toString(10) << Index->getSourceRange();
1821
1822  Value.setIsUnsigned(true);
1823  return false;
1824}
1825
1826Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1827                                                        SourceLocation Loc,
1828                                                        bool GNUSyntax,
1829                                                        OwningExprResult Init) {
1830  typedef DesignatedInitExpr::Designator ASTDesignator;
1831
1832  bool Invalid = false;
1833  llvm::SmallVector<ASTDesignator, 32> Designators;
1834  llvm::SmallVector<Expr *, 32> InitExpressions;
1835
1836  // Build designators and check array designator expressions.
1837  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1838    const Designator &D = Desig.getDesignator(Idx);
1839    switch (D.getKind()) {
1840    case Designator::FieldDesignator:
1841      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1842                                          D.getFieldLoc()));
1843      break;
1844
1845    case Designator::ArrayDesignator: {
1846      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1847      llvm::APSInt IndexValue;
1848      if (!Index->isTypeDependent() &&
1849          !Index->isValueDependent() &&
1850          CheckArrayDesignatorExpr(*this, Index, IndexValue))
1851        Invalid = true;
1852      else {
1853        Designators.push_back(ASTDesignator(InitExpressions.size(),
1854                                            D.getLBracketLoc(),
1855                                            D.getRBracketLoc()));
1856        InitExpressions.push_back(Index);
1857      }
1858      break;
1859    }
1860
1861    case Designator::ArrayRangeDesignator: {
1862      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1863      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1864      llvm::APSInt StartValue;
1865      llvm::APSInt EndValue;
1866      bool StartDependent = StartIndex->isTypeDependent() ||
1867                            StartIndex->isValueDependent();
1868      bool EndDependent = EndIndex->isTypeDependent() ||
1869                          EndIndex->isValueDependent();
1870      if ((!StartDependent &&
1871           CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1872          (!EndDependent &&
1873           CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
1874        Invalid = true;
1875      else {
1876        // Make sure we're comparing values with the same bit width.
1877        if (StartDependent || EndDependent) {
1878          // Nothing to compute.
1879        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
1880          EndValue.extend(StartValue.getBitWidth());
1881        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1882          StartValue.extend(EndValue.getBitWidth());
1883
1884        if (!StartDependent && !EndDependent && EndValue < StartValue) {
1885          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1886            << StartValue.toString(10) << EndValue.toString(10)
1887            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1888          Invalid = true;
1889        } else {
1890          Designators.push_back(ASTDesignator(InitExpressions.size(),
1891                                              D.getLBracketLoc(),
1892                                              D.getEllipsisLoc(),
1893                                              D.getRBracketLoc()));
1894          InitExpressions.push_back(StartIndex);
1895          InitExpressions.push_back(EndIndex);
1896        }
1897      }
1898      break;
1899    }
1900    }
1901  }
1902
1903  if (Invalid || Init.isInvalid())
1904    return ExprError();
1905
1906  // Clear out the expressions within the designation.
1907  Desig.ClearExprs(*this);
1908
1909  DesignatedInitExpr *DIE
1910    = DesignatedInitExpr::Create(Context,
1911                                 Designators.data(), Designators.size(),
1912                                 InitExpressions.data(), InitExpressions.size(),
1913                                 Loc, GNUSyntax, Init.takeAs<Expr>());
1914  return Owned(DIE);
1915}
1916
1917bool Sema::CheckInitList(const InitializedEntity &Entity,
1918                         InitListExpr *&InitList, QualType &DeclType) {
1919  InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
1920  if (!CheckInitList.HadError())
1921    InitList = CheckInitList.getFullyStructuredList();
1922
1923  return CheckInitList.HadError();
1924}
1925
1926//===----------------------------------------------------------------------===//
1927// Initialization entity
1928//===----------------------------------------------------------------------===//
1929
1930InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1931                                     const InitializedEntity &Parent)
1932  : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1933{
1934  if (isa<ArrayType>(Parent.TL.getType())) {
1935    TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1936    return;
1937  }
1938
1939  // FIXME: should be able to get type location information for vectors, too.
1940
1941  QualType T;
1942  if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1943    T = AT->getElementType();
1944  else
1945    T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1946
1947  // FIXME: Once we've gone through the effort to create the fake
1948  // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1949  TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1950  DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1951  TL = DI->getTypeLoc();
1952}
1953
1954void InitializedEntity::InitDeclLoc() {
1955  assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1956         "InitDeclLoc cannot be used with non-declaration entities.");
1957
1958  if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1959    TL = DI->getTypeLoc();
1960    return;
1961  }
1962
1963  // FIXME: Once we've gone through the effort to create the fake
1964  // TypeSourceInfo, should we cache it in the declaration?
1965  // (If not, we "leak" it).
1966  TypeSourceInfo *DI = VariableOrMember->getASTContext()
1967                             .CreateTypeSourceInfo(VariableOrMember->getType());
1968  DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1969  TL = DI->getTypeLoc();
1970}
1971
1972InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1973                                                    CXXBaseSpecifier *Base)
1974{
1975  InitializedEntity Result;
1976  Result.Kind = EK_Base;
1977  Result.Base = Base;
1978  // FIXME: CXXBaseSpecifier should store a TypeLoc.
1979  TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1980  DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1981  Result.TL = DI->getTypeLoc();
1982  return Result;
1983}
1984
1985DeclarationName InitializedEntity::getName() const {
1986  switch (getKind()) {
1987  case EK_Variable:
1988  case EK_Parameter:
1989  case EK_Member:
1990    return VariableOrMember->getDeclName();
1991
1992  case EK_Result:
1993  case EK_Exception:
1994  case EK_Temporary:
1995  case EK_Base:
1996  case EK_ArrayOrVectorElement:
1997    return DeclarationName();
1998  }
1999
2000  // Silence GCC warning
2001  return DeclarationName();
2002}
2003
2004//===----------------------------------------------------------------------===//
2005// Initialization sequence
2006//===----------------------------------------------------------------------===//
2007
2008void InitializationSequence::Step::Destroy() {
2009  switch (Kind) {
2010  case SK_ResolveAddressOfOverloadedFunction:
2011  case SK_CastDerivedToBaseRValue:
2012  case SK_CastDerivedToBaseLValue:
2013  case SK_BindReference:
2014  case SK_BindReferenceToTemporary:
2015  case SK_UserConversion:
2016  case SK_QualificationConversionRValue:
2017  case SK_QualificationConversionLValue:
2018  case SK_ListInitialization:
2019  case SK_ConstructorInitialization:
2020  case SK_ZeroInitialization:
2021    break;
2022
2023  case SK_ConversionSequence:
2024    delete ICS;
2025  }
2026}
2027
2028void InitializationSequence::AddAddressOverloadResolutionStep(
2029                                                      FunctionDecl *Function) {
2030  Step S;
2031  S.Kind = SK_ResolveAddressOfOverloadedFunction;
2032  S.Type = Function->getType();
2033  S.Function = Function;
2034  Steps.push_back(S);
2035}
2036
2037void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2038                                                      bool IsLValue) {
2039  Step S;
2040  S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2041  S.Type = BaseType;
2042  Steps.push_back(S);
2043}
2044
2045void InitializationSequence::AddReferenceBindingStep(QualType T,
2046                                                     bool BindingTemporary) {
2047  Step S;
2048  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2049  S.Type = T;
2050  Steps.push_back(S);
2051}
2052
2053void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2054                                                   QualType T) {
2055  Step S;
2056  S.Kind = SK_UserConversion;
2057  S.Type = T;
2058  S.Function = Function;
2059  Steps.push_back(S);
2060}
2061
2062void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2063                                                            bool IsLValue) {
2064  Step S;
2065  S.Kind = IsLValue? SK_QualificationConversionLValue
2066                   : SK_QualificationConversionRValue;
2067  S.Type = Ty;
2068  Steps.push_back(S);
2069}
2070
2071void InitializationSequence::AddConversionSequenceStep(
2072                                       const ImplicitConversionSequence &ICS,
2073                                                       QualType T) {
2074  Step S;
2075  S.Kind = SK_ConversionSequence;
2076  S.Type = T;
2077  S.ICS = new ImplicitConversionSequence(ICS);
2078  Steps.push_back(S);
2079}
2080
2081void InitializationSequence::AddListInitializationStep(QualType T) {
2082  Step S;
2083  S.Kind = SK_ListInitialization;
2084  S.Type = T;
2085  Steps.push_back(S);
2086}
2087
2088void
2089InitializationSequence::AddConstructorInitializationStep(
2090                                              CXXConstructorDecl *Constructor,
2091                                                         QualType T) {
2092  Step S;
2093  S.Kind = SK_ConstructorInitialization;
2094  S.Type = T;
2095  S.Function = Constructor;
2096  Steps.push_back(S);
2097}
2098
2099void InitializationSequence::AddZeroInitializationStep(QualType T) {
2100  Step S;
2101  S.Kind = SK_ZeroInitialization;
2102  S.Type = T;
2103  Steps.push_back(S);
2104}
2105
2106void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2107                                                OverloadingResult Result) {
2108  SequenceKind = FailedSequence;
2109  this->Failure = Failure;
2110  this->FailedOverloadResult = Result;
2111}
2112
2113//===----------------------------------------------------------------------===//
2114// Attempt initialization
2115//===----------------------------------------------------------------------===//
2116
2117/// \brief Attempt list initialization (C++0x [dcl.init.list])
2118static void TryListInitialization(Sema &S,
2119                                  const InitializedEntity &Entity,
2120                                  const InitializationKind &Kind,
2121                                  InitListExpr *InitList,
2122                                  InitializationSequence &Sequence) {
2123  // FIXME: We only perform rudimentary checking of list
2124  // initializations at this point, then assume that any list
2125  // initialization of an array, aggregate, or scalar will be
2126  // well-formed. We we actually "perform" list initialization, we'll
2127  // do all of the necessary checking.  C++0x initializer lists will
2128  // force us to perform more checking here.
2129  Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2130
2131  QualType DestType = Entity.getType().getType();
2132
2133  // C++ [dcl.init]p13:
2134  //   If T is a scalar type, then a declaration of the form
2135  //
2136  //     T x = { a };
2137  //
2138  //   is equivalent to
2139  //
2140  //     T x = a;
2141  if (DestType->isScalarType()) {
2142    if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2143      Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2144      return;
2145    }
2146
2147    // Assume scalar initialization from a single value works.
2148  } else if (DestType->isAggregateType()) {
2149    // Assume aggregate initialization works.
2150  } else if (DestType->isVectorType()) {
2151    // Assume vector initialization works.
2152  } else if (DestType->isReferenceType()) {
2153    // FIXME: C++0x defines behavior for this.
2154    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2155    return;
2156  } else if (DestType->isRecordType()) {
2157    // FIXME: C++0x defines behavior for this
2158    Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2159  }
2160
2161  // Add a general "list initialization" step.
2162  Sequence.AddListInitializationStep(DestType);
2163}
2164
2165/// \brief Try a reference initialization that involves calling a conversion
2166/// function.
2167///
2168/// FIXME: look intos DRs 656, 896
2169static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2170                                             const InitializedEntity &Entity,
2171                                             const InitializationKind &Kind,
2172                                                          Expr *Initializer,
2173                                                          bool AllowRValues,
2174                                             InitializationSequence &Sequence) {
2175  QualType DestType = Entity.getType().getType();
2176  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2177  QualType T1 = cv1T1.getUnqualifiedType();
2178  QualType cv2T2 = Initializer->getType();
2179  QualType T2 = cv2T2.getUnqualifiedType();
2180
2181  bool DerivedToBase;
2182  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2183                                         T1, T2, DerivedToBase) &&
2184         "Must have incompatible references when binding via conversion");
2185  (void)DerivedToBase;
2186
2187  // Build the candidate set directly in the initialization sequence
2188  // structure, so that it will persist if we fail.
2189  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2190  CandidateSet.clear();
2191
2192  // Determine whether we are allowed to call explicit constructors or
2193  // explicit conversion operators.
2194  bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2195
2196  const RecordType *T1RecordType = 0;
2197  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2198    // The type we're converting to is a class type. Enumerate its constructors
2199    // to see if there is a suitable conversion.
2200    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2201
2202    DeclarationName ConstructorName
2203      = S.Context.DeclarationNames.getCXXConstructorName(
2204                           S.Context.getCanonicalType(T1).getUnqualifiedType());
2205    DeclContext::lookup_iterator Con, ConEnd;
2206    for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2207         Con != ConEnd; ++Con) {
2208      // Find the constructor (which may be a template).
2209      CXXConstructorDecl *Constructor = 0;
2210      FunctionTemplateDecl *ConstructorTmpl
2211        = dyn_cast<FunctionTemplateDecl>(*Con);
2212      if (ConstructorTmpl)
2213        Constructor = cast<CXXConstructorDecl>(
2214                                         ConstructorTmpl->getTemplatedDecl());
2215      else
2216        Constructor = cast<CXXConstructorDecl>(*Con);
2217
2218      if (!Constructor->isInvalidDecl() &&
2219          Constructor->isConvertingConstructor(AllowExplicit)) {
2220        if (ConstructorTmpl)
2221          S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2222                                         &Initializer, 1, CandidateSet);
2223        else
2224          S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2225      }
2226    }
2227  }
2228
2229  if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2230    // The type we're converting from is a class type, enumerate its conversion
2231    // functions.
2232    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2233
2234    // Determine the type we are converting to. If we are allowed to
2235    // convert to an rvalue, take the type that the destination type
2236    // refers to.
2237    QualType ToType = AllowRValues? cv1T1 : DestType;
2238
2239    const UnresolvedSet *Conversions
2240      = T2RecordDecl->getVisibleConversionFunctions();
2241    for (UnresolvedSet::iterator I = Conversions->begin(),
2242         E = Conversions->end();
2243         I != E; ++I) {
2244      NamedDecl *D = *I;
2245      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2246      if (isa<UsingShadowDecl>(D))
2247        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2248
2249      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2250      CXXConversionDecl *Conv;
2251      if (ConvTemplate)
2252        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2253      else
2254        Conv = cast<CXXConversionDecl>(*I);
2255
2256      // If the conversion function doesn't return a reference type,
2257      // it can't be considered for this conversion unless we're allowed to
2258      // consider rvalues.
2259      // FIXME: Do we need to make sure that we only consider conversion
2260      // candidates with reference-compatible results? That might be needed to
2261      // break recursion.
2262      if ((AllowExplicit || !Conv->isExplicit()) &&
2263          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2264        if (ConvTemplate)
2265          S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2266                                           ToType, CandidateSet);
2267        else
2268          S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2269                                   CandidateSet);
2270      }
2271    }
2272  }
2273
2274  SourceLocation DeclLoc = Initializer->getLocStart();
2275
2276  // Perform overload resolution. If it fails, return the failed result.
2277  OverloadCandidateSet::iterator Best;
2278  if (OverloadingResult Result
2279        = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2280    return Result;
2281
2282  FunctionDecl *Function = Best->Function;
2283
2284  // Compute the returned type of the conversion.
2285  if (isa<CXXConversionDecl>(Function))
2286    T2 = Function->getResultType();
2287  else
2288    T2 = cv1T1;
2289
2290  // Add the user-defined conversion step.
2291  Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2292
2293  // Determine whether we need to perform derived-to-base or
2294  // cv-qualification adjustments.
2295  bool NewDerivedToBase = false;
2296  Sema::ReferenceCompareResult NewRefRelationship
2297    = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2298                                     NewDerivedToBase);
2299  assert(NewRefRelationship != Sema::Ref_Incompatible &&
2300         "Overload resolution picked a bad conversion function");
2301  (void)NewRefRelationship;
2302  if (NewDerivedToBase)
2303    Sequence.AddDerivedToBaseCastStep(
2304                                S.Context.getQualifiedType(T1,
2305                                  T2.getNonReferenceType().getQualifiers()),
2306                                  /*isLValue=*/true);
2307
2308  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2309    Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2310
2311  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2312  return OR_Success;
2313}
2314
2315/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2316static void TryReferenceInitialization(Sema &S,
2317                                       const InitializedEntity &Entity,
2318                                       const InitializationKind &Kind,
2319                                       Expr *Initializer,
2320                                       InitializationSequence &Sequence) {
2321  Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2322
2323  QualType DestType = Entity.getType().getType();
2324  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2325  QualType T1 = cv1T1.getUnqualifiedType();
2326  QualType cv2T2 = Initializer->getType();
2327  QualType T2 = cv2T2.getUnqualifiedType();
2328  SourceLocation DeclLoc = Initializer->getLocStart();
2329
2330  // If the initializer is the address of an overloaded function, try
2331  // to resolve the overloaded function. If all goes well, T2 is the
2332  // type of the resulting function.
2333  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2334    FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2335                                                            T1,
2336                                                            false);
2337    if (!Fn) {
2338      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2339      return;
2340    }
2341
2342    Sequence.AddAddressOverloadResolutionStep(Fn);
2343    cv2T2 = Fn->getType();
2344    T2 = cv2T2.getUnqualifiedType();
2345  }
2346
2347  // FIXME: Rvalue references
2348  bool ForceRValue = false;
2349
2350  // Compute some basic properties of the types and the initializer.
2351  bool isLValueRef = DestType->isLValueReferenceType();
2352  bool isRValueRef = !isLValueRef;
2353  bool DerivedToBase = false;
2354  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2355                                    Initializer->isLvalue(S.Context);
2356  Sema::ReferenceCompareResult RefRelationship
2357    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2358
2359  // C++0x [dcl.init.ref]p5:
2360  //   A reference to type "cv1 T1" is initialized by an expression of type
2361  //   "cv2 T2" as follows:
2362  //
2363  //     - If the reference is an lvalue reference and the initializer
2364  //       expression
2365  OverloadingResult ConvOvlResult = OR_Success;
2366  if (isLValueRef) {
2367    if (InitLvalue == Expr::LV_Valid &&
2368        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2369      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
2370      //     reference-compatible with "cv2 T2," or
2371      //
2372      // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2373      // bit-field when we're determining whether the reference initialization
2374      // can occur. This property will be checked by PerformInitialization.
2375      if (DerivedToBase)
2376        Sequence.AddDerivedToBaseCastStep(
2377                         S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2378                         /*isLValue=*/true);
2379      if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2380        Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2381      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2382      return;
2383    }
2384
2385    //     - has a class type (i.e., T2 is a class type), where T1 is not
2386    //       reference-related to T2, and can be implicitly converted to an
2387    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2388    //       with "cv3 T3" (this conversion is selected by enumerating the
2389    //       applicable conversion functions (13.3.1.6) and choosing the best
2390    //       one through overload resolution (13.3)),
2391    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2392      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2393                                                       Initializer,
2394                                                       /*AllowRValues=*/false,
2395                                                       Sequence);
2396      if (ConvOvlResult == OR_Success)
2397        return;
2398    }
2399  }
2400
2401  //     - Otherwise, the reference shall be an lvalue reference to a
2402  //       non-volatile const type (i.e., cv1 shall be const), or the reference
2403  //       shall be an rvalue reference and the initializer expression shall
2404  //       be an rvalue.
2405  if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2406        (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2407    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2408      Sequence.SetOverloadFailure(
2409                        InitializationSequence::FK_ReferenceInitOverloadFailed,
2410                                  ConvOvlResult);
2411    else if (isLValueRef)
2412      Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2413        ? (RefRelationship == Sema::Ref_Related
2414             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2415             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2416        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2417    else
2418      Sequence.SetFailed(
2419                    InitializationSequence::FK_RValueReferenceBindingToLValue);
2420
2421    return;
2422  }
2423
2424  //       - If T1 and T2 are class types and
2425  if (T1->isRecordType() && T2->isRecordType()) {
2426    //       - the initializer expression is an rvalue and "cv1 T1" is
2427    //         reference-compatible with "cv2 T2", or
2428    if (InitLvalue != Expr::LV_Valid &&
2429        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2430      if (DerivedToBase)
2431        Sequence.AddDerivedToBaseCastStep(
2432                         S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2433                         /*isLValue=*/false);
2434      if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2435        Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2436      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2437      return;
2438    }
2439
2440    //       - T1 is not reference-related to T2 and the initializer expression
2441    //         can be implicitly converted to an rvalue of type "cv3 T3" (this
2442    //         conversion is selected by enumerating the applicable conversion
2443    //         functions (13.3.1.6) and choosing the best one through overload
2444    //         resolution (13.3)),
2445    if (RefRelationship == Sema::Ref_Incompatible) {
2446      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2447                                                       Kind, Initializer,
2448                                                       /*AllowRValues=*/true,
2449                                                       Sequence);
2450      if (ConvOvlResult)
2451        Sequence.SetOverloadFailure(
2452                      InitializationSequence::FK_ReferenceInitOverloadFailed,
2453                                    ConvOvlResult);
2454
2455      return;
2456    }
2457
2458    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2459    return;
2460  }
2461
2462  //      - If the initializer expression is an rvalue, with T2 an array type,
2463  //        and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2464  //        is bound to the object represented by the rvalue (see 3.10).
2465  // FIXME: How can an array type be reference-compatible with anything?
2466  // Don't we mean the element types of T1 and T2?
2467
2468  //      - Otherwise, a temporary of type “cv1 T1” is created and initialized
2469  //        from the initializer expression using the rules for a non-reference
2470  //        copy initialization (8.5). The reference is then bound to the
2471  //        temporary. [...]
2472  // Determine whether we are allowed to call explicit constructors or
2473  // explicit conversion operators.
2474  bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2475  ImplicitConversionSequence ICS
2476    = S.TryImplicitConversion(Initializer, cv1T1,
2477                              /*SuppressUserConversions=*/false, AllowExplicit,
2478                              /*ForceRValue=*/false,
2479                              /*FIXME:InOverloadResolution=*/false,
2480                              /*UserCast=*/Kind.isExplicitCast());
2481
2482  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2483    // FIXME: Use the conversion function set stored in ICS to turn
2484    // this into an overloading ambiguity diagnostic. However, we need
2485    // to keep that set as an OverloadCandidateSet rather than as some
2486    // other kind of set.
2487    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
2488    return;
2489  }
2490
2491  //        [...] If T1 is reference-related to T2, cv1 must be the
2492  //        same cv-qualification as, or greater cv-qualification
2493  //        than, cv2; otherwise, the program is ill-formed.
2494  if (RefRelationship == Sema::Ref_Related &&
2495      !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2496    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2497    return;
2498  }
2499
2500  // Perform the actual conversion.
2501  Sequence.AddConversionSequenceStep(ICS, cv1T1);
2502  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2503  return;
2504}
2505
2506/// \brief Attempt character array initialization from a string literal
2507/// (C++ [dcl.init.string], C99 6.7.8).
2508static void TryStringLiteralInitialization(Sema &S,
2509                                           const InitializedEntity &Entity,
2510                                           const InitializationKind &Kind,
2511                                           Expr *Initializer,
2512                                       InitializationSequence &Sequence) {
2513  // FIXME: Implement!
2514}
2515
2516/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2517/// enumerates the constructors of the initialized entity and performs overload
2518/// resolution to select the best.
2519static void TryConstructorInitialization(Sema &S,
2520                                         const InitializedEntity &Entity,
2521                                         const InitializationKind &Kind,
2522                                         Expr **Args, unsigned NumArgs,
2523                                         QualType DestType,
2524                                         InitializationSequence &Sequence) {
2525  Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
2526
2527  // Build the candidate set directly in the initialization sequence
2528  // structure, so that it will persist if we fail.
2529  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2530  CandidateSet.clear();
2531
2532  // Determine whether we are allowed to call explicit constructors or
2533  // explicit conversion operators.
2534  bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2535                        Kind.getKind() == InitializationKind::IK_Value ||
2536                        Kind.getKind() == InitializationKind::IK_Default);
2537
2538  // The type we're converting to is a class type. Enumerate its constructors
2539  // to see if one is suitable.
2540  const RecordType *DestRecordType = DestType->getAs<RecordType>();
2541  assert(DestRecordType && "Constructor initialization requires record type");
2542  CXXRecordDecl *DestRecordDecl
2543    = cast<CXXRecordDecl>(DestRecordType->getDecl());
2544
2545  DeclarationName ConstructorName
2546    = S.Context.DeclarationNames.getCXXConstructorName(
2547                     S.Context.getCanonicalType(DestType).getUnqualifiedType());
2548  DeclContext::lookup_iterator Con, ConEnd;
2549  for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2550       Con != ConEnd; ++Con) {
2551    // Find the constructor (which may be a template).
2552    CXXConstructorDecl *Constructor = 0;
2553    FunctionTemplateDecl *ConstructorTmpl
2554      = dyn_cast<FunctionTemplateDecl>(*Con);
2555    if (ConstructorTmpl)
2556      Constructor = cast<CXXConstructorDecl>(
2557                                           ConstructorTmpl->getTemplatedDecl());
2558    else
2559      Constructor = cast<CXXConstructorDecl>(*Con);
2560
2561    if (!Constructor->isInvalidDecl() &&
2562        (AllowExplicit || !Constructor->isExplicit())) {
2563      if (ConstructorTmpl)
2564        S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2565                                       Args, NumArgs, CandidateSet);
2566      else
2567        S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2568    }
2569  }
2570
2571  SourceLocation DeclLoc = Kind.getLocation();
2572
2573  // Perform overload resolution. If it fails, return the failed result.
2574  OverloadCandidateSet::iterator Best;
2575  if (OverloadingResult Result
2576        = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2577    Sequence.SetOverloadFailure(
2578                          InitializationSequence::FK_ConstructorOverloadFailed,
2579                                Result);
2580    return;
2581  }
2582
2583  // Add the constructor initialization step. Any cv-qualification conversion is
2584  // subsumed by the initialization.
2585  Sequence.AddConstructorInitializationStep(
2586                                      cast<CXXConstructorDecl>(Best->Function),
2587                                            DestType);
2588}
2589
2590/// \brief Attempt value initialization (C++ [dcl.init]p7).
2591static void TryValueInitialization(Sema &S,
2592                                   const InitializedEntity &Entity,
2593                                   const InitializationKind &Kind,
2594                                   InitializationSequence &Sequence) {
2595  // C++ [dcl.init]p5:
2596  //
2597  //   To value-initialize an object of type T means:
2598  QualType T = Entity.getType().getType();
2599
2600  //     -- if T is an array type, then each element is value-initialized;
2601  while (const ArrayType *AT = S.Context.getAsArrayType(T))
2602    T = AT->getElementType();
2603
2604  if (const RecordType *RT = T->getAs<RecordType>()) {
2605    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2606      // -- if T is a class type (clause 9) with a user-declared
2607      //    constructor (12.1), then the default constructor for T is
2608      //    called (and the initialization is ill-formed if T has no
2609      //    accessible default constructor);
2610      //
2611      // FIXME: we really want to refer to a single subobject of the array,
2612      // but Entity doesn't have a way to capture that (yet).
2613      if (ClassDecl->hasUserDeclaredConstructor())
2614        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2615
2616      // FIXME: non-union class type w/ non-trivial default constructor gets
2617      // zero-initialized, then constructor gets called.
2618    }
2619  }
2620
2621  Sequence.AddZeroInitializationStep(Entity.getType().getType());
2622  Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2623}
2624
2625/// \brief Attempt default initialization (C++ [dcl.init]p6).
2626static void TryDefaultInitialization(Sema &S,
2627                                     const InitializedEntity &Entity,
2628                                     const InitializationKind &Kind,
2629                                     InitializationSequence &Sequence) {
2630  assert(Kind.getKind() == InitializationKind::IK_Default);
2631
2632  // C++ [dcl.init]p6:
2633  //   To default-initialize an object of type T means:
2634  //     - if T is an array type, each element is default-initialized;
2635  QualType DestType = Entity.getType().getType();
2636  while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2637    DestType = Array->getElementType();
2638
2639  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
2640  //       constructor for T is called (and the initialization is ill-formed if
2641  //       T has no accessible default constructor);
2642  if (DestType->isRecordType()) {
2643    // FIXME: If a program calls for the default initialization of an object of
2644    // a const-qualified type T, T shall be a class type with a user-provided
2645    // default constructor.
2646    return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2647                                        Sequence);
2648  }
2649
2650  //     - otherwise, no initialization is performed.
2651  Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2652
2653  //   If a program calls for the default initialization of an object of
2654  //   a const-qualified type T, T shall be a class type with a user-provided
2655  //   default constructor.
2656  if (DestType.isConstQualified())
2657    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2658}
2659
2660/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2661/// which enumerates all conversion functions and performs overload resolution
2662/// to select the best.
2663static void TryUserDefinedConversion(Sema &S,
2664                                     const InitializedEntity &Entity,
2665                                     const InitializationKind &Kind,
2666                                     Expr *Initializer,
2667                                     InitializationSequence &Sequence) {
2668  Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2669
2670  QualType DestType = Entity.getType().getType();
2671  assert(!DestType->isReferenceType() && "References are handled elsewhere");
2672  QualType SourceType = Initializer->getType();
2673  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2674         "Must have a class type to perform a user-defined conversion");
2675
2676  // Build the candidate set directly in the initialization sequence
2677  // structure, so that it will persist if we fail.
2678  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2679  CandidateSet.clear();
2680
2681  // Determine whether we are allowed to call explicit constructors or
2682  // explicit conversion operators.
2683  bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2684
2685  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2686    // The type we're converting to is a class type. Enumerate its constructors
2687    // to see if there is a suitable conversion.
2688    CXXRecordDecl *DestRecordDecl
2689      = cast<CXXRecordDecl>(DestRecordType->getDecl());
2690
2691    DeclarationName ConstructorName
2692      = S.Context.DeclarationNames.getCXXConstructorName(
2693                     S.Context.getCanonicalType(DestType).getUnqualifiedType());
2694    DeclContext::lookup_iterator Con, ConEnd;
2695    for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2696         Con != ConEnd; ++Con) {
2697      // Find the constructor (which may be a template).
2698      CXXConstructorDecl *Constructor = 0;
2699      FunctionTemplateDecl *ConstructorTmpl
2700        = dyn_cast<FunctionTemplateDecl>(*Con);
2701      if (ConstructorTmpl)
2702        Constructor = cast<CXXConstructorDecl>(
2703                                           ConstructorTmpl->getTemplatedDecl());
2704      else
2705        Constructor = cast<CXXConstructorDecl>(*Con);
2706
2707      if (!Constructor->isInvalidDecl() &&
2708          Constructor->isConvertingConstructor(AllowExplicit)) {
2709        if (ConstructorTmpl)
2710          S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2711                                         &Initializer, 1, CandidateSet);
2712        else
2713          S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2714      }
2715    }
2716  }
2717
2718  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2719    // The type we're converting from is a class type, enumerate its conversion
2720    // functions.
2721    CXXRecordDecl *SourceRecordDecl
2722      = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2723
2724    const UnresolvedSet *Conversions
2725      = SourceRecordDecl->getVisibleConversionFunctions();
2726    for (UnresolvedSet::iterator I = Conversions->begin(),
2727         E = Conversions->end();
2728         I != E; ++I) {
2729      NamedDecl *D = *I;
2730      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2731      if (isa<UsingShadowDecl>(D))
2732        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2733
2734      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2735      CXXConversionDecl *Conv;
2736      if (ConvTemplate)
2737        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2738      else
2739        Conv = cast<CXXConversionDecl>(*I);
2740
2741      if (AllowExplicit || !Conv->isExplicit()) {
2742        if (ConvTemplate)
2743          S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2744                                           DestType, CandidateSet);
2745        else
2746          S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2747                                   CandidateSet);
2748      }
2749    }
2750  }
2751
2752  SourceLocation DeclLoc = Initializer->getLocStart();
2753
2754  // Perform overload resolution. If it fails, return the failed result.
2755  OverloadCandidateSet::iterator Best;
2756  if (OverloadingResult Result
2757        = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2758    Sequence.SetOverloadFailure(
2759                        InitializationSequence::FK_UserConversionOverloadFailed,
2760                                Result);
2761    return;
2762  }
2763
2764  FunctionDecl *Function = Best->Function;
2765
2766  if (isa<CXXConstructorDecl>(Function)) {
2767    // Add the user-defined conversion step. Any cv-qualification conversion is
2768    // subsumed by the initialization.
2769    Sequence.AddUserConversionStep(Function, DestType);
2770    return;
2771  }
2772
2773  // Add the user-defined conversion step that calls the conversion function.
2774  QualType ConvType = Function->getResultType().getNonReferenceType();
2775  Sequence.AddUserConversionStep(Function, ConvType);
2776
2777  // If the conversion following the call to the conversion function is
2778  // interesting, add it as a separate step.
2779  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2780      Best->FinalConversion.Third) {
2781    ImplicitConversionSequence ICS;
2782    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2783    ICS.Standard = Best->FinalConversion;
2784    Sequence.AddConversionSequenceStep(ICS, DestType);
2785  }
2786}
2787
2788/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2789/// non-class type to another.
2790static void TryImplicitConversion(Sema &S,
2791                                  const InitializedEntity &Entity,
2792                                  const InitializationKind &Kind,
2793                                  Expr *Initializer,
2794                                  InitializationSequence &Sequence) {
2795  ImplicitConversionSequence ICS
2796    = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2797                              /*SuppressUserConversions=*/true,
2798                              /*AllowExplicit=*/false,
2799                              /*ForceRValue=*/false,
2800                              /*FIXME:InOverloadResolution=*/false,
2801                              /*UserCast=*/Kind.isExplicitCast());
2802
2803  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2804    Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2805    return;
2806  }
2807
2808  Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2809}
2810
2811InitializationSequence::InitializationSequence(Sema &S,
2812                                               const InitializedEntity &Entity,
2813                                               const InitializationKind &Kind,
2814                                               Expr **Args,
2815                                               unsigned NumArgs) {
2816  ASTContext &Context = S.Context;
2817
2818  // C++0x [dcl.init]p16:
2819  //   The semantics of initializers are as follows. The destination type is
2820  //   the type of the object or reference being initialized and the source
2821  //   type is the type of the initializer expression. The source type is not
2822  //   defined when the initializer is a braced-init-list or when it is a
2823  //   parenthesized list of expressions.
2824  QualType DestType = Entity.getType().getType();
2825
2826  if (DestType->isDependentType() ||
2827      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2828    SequenceKind = DependentSequence;
2829    return;
2830  }
2831
2832  QualType SourceType;
2833  Expr *Initializer = 0;
2834  if (NumArgs == 1) {
2835    Initializer = Args[0];
2836    if (!isa<InitListExpr>(Initializer))
2837      SourceType = Initializer->getType();
2838  }
2839
2840  //     - If the initializer is a braced-init-list, the object is
2841  //       list-initialized (8.5.4).
2842  if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2843    TryListInitialization(S, Entity, Kind, InitList, *this);
2844    return;
2845  }
2846
2847  //     - If the destination type is a reference type, see 8.5.3.
2848  if (DestType->isReferenceType()) {
2849    // C++0x [dcl.init.ref]p1:
2850    //   A variable declared to be a T& or T&&, that is, "reference to type T"
2851    //   (8.3.2), shall be initialized by an object, or function, of type T or
2852    //   by an object that can be converted into a T.
2853    // (Therefore, multiple arguments are not permitted.)
2854    if (NumArgs != 1)
2855      SetFailed(FK_TooManyInitsForReference);
2856    else
2857      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2858    return;
2859  }
2860
2861  //     - If the destination type is an array of characters, an array of
2862  //       char16_t, an array of char32_t, or an array of wchar_t, and the
2863  //       initializer is a string literal, see 8.5.2.
2864  if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2865    TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2866    return;
2867  }
2868
2869  //     - If the initializer is (), the object is value-initialized.
2870  if (Kind.getKind() == InitializationKind::IK_Value ||
2871      (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
2872    TryValueInitialization(S, Entity, Kind, *this);
2873    return;
2874  }
2875
2876  // Handle default initialization.
2877  if (Kind.getKind() == InitializationKind::IK_Default){
2878    TryDefaultInitialization(S, Entity, Kind, *this);
2879    return;
2880  }
2881
2882  //     - Otherwise, if the destination type is an array, the program is
2883  //       ill-formed.
2884  if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2885    if (AT->getElementType()->isAnyCharacterType())
2886      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2887    else
2888      SetFailed(FK_ArrayNeedsInitList);
2889
2890    return;
2891  }
2892
2893  //     - If the destination type is a (possibly cv-qualified) class type:
2894  if (DestType->isRecordType()) {
2895    //     - If the initialization is direct-initialization, or if it is
2896    //       copy-initialization where the cv-unqualified version of the
2897    //       source type is the same class as, or a derived class of, the
2898    //       class of the destination, constructors are considered. [...]
2899    if (Kind.getKind() == InitializationKind::IK_Direct ||
2900        (Kind.getKind() == InitializationKind::IK_Copy &&
2901         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2902          S.IsDerivedFrom(SourceType, DestType))))
2903      TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2904                                   Entity.getType().getType(), *this);
2905    //     - Otherwise (i.e., for the remaining copy-initialization cases),
2906    //       user-defined conversion sequences that can convert from the source
2907    //       type to the destination type or (when a conversion function is
2908    //       used) to a derived class thereof are enumerated as described in
2909    //       13.3.1.4, and the best one is chosen through overload resolution
2910    //       (13.3).
2911    else
2912      TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2913    return;
2914  }
2915
2916  if (NumArgs > 1) {
2917    SetFailed(FK_TooManyInitsForScalar);
2918    return;
2919  }
2920  assert(NumArgs == 1 && "Zero-argument case handled above");
2921
2922  //    - Otherwise, if the source type is a (possibly cv-qualified) class
2923  //      type, conversion functions are considered.
2924  if (!SourceType.isNull() && SourceType->isRecordType()) {
2925    TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2926    return;
2927  }
2928
2929  //    - Otherwise, the initial value of the object being initialized is the
2930  //      (possibly converted) value of the initializer expression. Standard
2931  //      conversions (Clause 4) will be used, if necessary, to convert the
2932  //      initializer expression to the cv-unqualified version of the
2933  //      destination type; no user-defined conversions are considered.
2934  setSequenceKind(StandardConversion);
2935  TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2936}
2937
2938InitializationSequence::~InitializationSequence() {
2939  for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2940                                          StepEnd = Steps.end();
2941       Step != StepEnd; ++Step)
2942    Step->Destroy();
2943}
2944
2945//===----------------------------------------------------------------------===//
2946// Perform initialization
2947//===----------------------------------------------------------------------===//
2948
2949Action::OwningExprResult
2950InitializationSequence::Perform(Sema &S,
2951                                const InitializedEntity &Entity,
2952                                const InitializationKind &Kind,
2953                                Action::MultiExprArg Args,
2954                                QualType *ResultType) {
2955  if (SequenceKind == FailedSequence) {
2956    unsigned NumArgs = Args.size();
2957    Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
2958    return S.ExprError();
2959  }
2960
2961  if (SequenceKind == DependentSequence) {
2962    // If the declaration is a non-dependent, incomplete array type
2963    // that has an initializer, then its type will be completed once
2964    // the initializer is instantiated.
2965    if (ResultType && !Entity.getType().getType()->isDependentType() &&
2966        Args.size() == 1) {
2967      QualType DeclType = Entity.getType().getType();
2968      if (const IncompleteArrayType *ArrayT
2969                           = S.Context.getAsIncompleteArrayType(DeclType)) {
2970        // FIXME: We don't currently have the ability to accurately
2971        // compute the length of an initializer list without
2972        // performing full type-checking of the initializer list
2973        // (since we have to determine where braces are implicitly
2974        // introduced and such).  So, we fall back to making the array
2975        // type a dependently-sized array type with no specified
2976        // bound.
2977        if (isa<InitListExpr>((Expr *)Args.get()[0])) {
2978          SourceRange Brackets;
2979          // Scavange the location of the brackets from the entity, if we can.
2980          if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
2981            IncompleteArrayTypeLoc ArrayLoc
2982              = cast<IncompleteArrayTypeLoc>(Entity.getType());
2983            Brackets = ArrayLoc.getBracketsRange();
2984          }
2985
2986          *ResultType
2987            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
2988                                                   /*NumElts=*/0,
2989                                                   ArrayT->getSizeModifier(),
2990                                       ArrayT->getIndexTypeCVRQualifiers(),
2991                                                   Brackets);
2992        }
2993
2994      }
2995    }
2996
2997    if (Kind.getKind() == InitializationKind::IK_Copy)
2998      return Sema::OwningExprResult(S, Args.release()[0]);
2999
3000    unsigned NumArgs = Args.size();
3001    return S.Owned(new (S.Context) ParenListExpr(S.Context,
3002                                                 SourceLocation(),
3003                                                 (Expr **)Args.release(),
3004                                                 NumArgs,
3005                                                 SourceLocation()));
3006  }
3007
3008  if (SequenceKind == NoInitialization)
3009    return S.Owned((Expr *)0);
3010
3011  QualType DestType = Entity.getType().getType().getNonReferenceType();
3012  if (ResultType)
3013    *ResultType = Entity.getType().getType();
3014
3015  Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3016
3017  assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3018
3019  // For initialization steps that start with a single initializer,
3020  // grab the only argument out the Args and place it into the "current"
3021  // initializer.
3022  switch (Steps.front().Kind) {
3023    case SK_ResolveAddressOfOverloadedFunction:
3024    case SK_CastDerivedToBaseRValue:
3025    case SK_CastDerivedToBaseLValue:
3026    case SK_BindReference:
3027    case SK_BindReferenceToTemporary:
3028    case SK_UserConversion:
3029    case SK_QualificationConversionLValue:
3030    case SK_QualificationConversionRValue:
3031    case SK_ConversionSequence:
3032    case SK_ListInitialization:
3033      assert(Args.size() == 1);
3034      CurInit = Sema::OwningExprResult(S,
3035                                       ((Expr **)(Args.get()))[0]->Retain());
3036      if (CurInit.isInvalid())
3037        return S.ExprError();
3038      break;
3039
3040    case SK_ConstructorInitialization:
3041    case SK_ZeroInitialization:
3042      break;
3043  }
3044
3045  // Walk through the computed steps for the initialization sequence,
3046  // performing the specified conversions along the way.
3047  for (step_iterator Step = step_begin(), StepEnd = step_end();
3048       Step != StepEnd; ++Step) {
3049    if (CurInit.isInvalid())
3050      return S.ExprError();
3051
3052    Expr *CurInitExpr = (Expr *)CurInit.get();
3053    QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
3054
3055    switch (Step->Kind) {
3056    case SK_ResolveAddressOfOverloadedFunction:
3057      // Overload resolution determined which function invoke; update the
3058      // initializer to reflect that choice.
3059      CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3060      break;
3061
3062    case SK_CastDerivedToBaseRValue:
3063    case SK_CastDerivedToBaseLValue: {
3064      // We have a derived-to-base cast that produces either an rvalue or an
3065      // lvalue. Perform that cast.
3066
3067      // Casts to inaccessible base classes are allowed with C-style casts.
3068      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3069      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3070                                         CurInitExpr->getLocStart(),
3071                                         CurInitExpr->getSourceRange(),
3072                                         IgnoreBaseAccess))
3073        return S.ExprError();
3074
3075      CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3076                                                    CastExpr::CK_DerivedToBase,
3077                                                      (Expr*)CurInit.release(),
3078                                     Step->Kind == SK_CastDerivedToBaseLValue));
3079      break;
3080    }
3081
3082    case SK_BindReference:
3083      if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3084        // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3085        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3086          << Entity.getType().getType().isVolatileQualified()
3087          << BitField->getDeclName()
3088          << CurInitExpr->getSourceRange();
3089        S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3090        return S.ExprError();
3091      }
3092
3093      // Reference binding does not have any corresponding ASTs.
3094
3095      // Check exception specifications
3096      if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3097        return S.ExprError();
3098      break;
3099
3100    case SK_BindReferenceToTemporary:
3101      // Check exception specifications
3102      if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3103        return S.ExprError();
3104
3105      // FIXME: At present, we have no AST to describe when we need to make a
3106      // temporary to bind a reference to. We should.
3107      break;
3108
3109    case SK_UserConversion: {
3110      // We have a user-defined conversion that invokes either a constructor
3111      // or a conversion function.
3112      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
3113      if (CXXConstructorDecl *Constructor
3114                              = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3115        // Build a call to the selected constructor.
3116        ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3117        SourceLocation Loc = CurInitExpr->getLocStart();
3118        CurInit.release(); // Ownership transferred into MultiExprArg, below.
3119
3120        // Determine the arguments required to actually perform the constructor
3121        // call.
3122        if (S.CompleteConstructorCall(Constructor,
3123                                      Sema::MultiExprArg(S,
3124                                                         (void **)&CurInitExpr,
3125                                                         1),
3126                                      Loc, ConstructorArgs))
3127          return S.ExprError();
3128
3129        // Build the an expression that constructs a temporary.
3130        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3131                                          move_arg(ConstructorArgs));
3132        if (CurInit.isInvalid())
3133          return S.ExprError();
3134
3135        CastKind = CastExpr::CK_ConstructorConversion;
3136      } else {
3137        // Build a call to the conversion function.
3138        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
3139
3140        // FIXME: Should we move this initialization into a separate
3141        // derived-to-base conversion? I believe the answer is "no", because
3142        // we don't want to turn off access control here for c-style casts.
3143        if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3144          return S.ExprError();
3145
3146        // Do a little dance to make sure that CurInit has the proper
3147        // pointer.
3148        CurInit.release();
3149
3150        // Build the actual call to the conversion function.
3151        CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3152        if (CurInit.isInvalid() || !CurInit.get())
3153          return S.ExprError();
3154
3155        CastKind = CastExpr::CK_UserDefinedConversion;
3156      }
3157
3158      CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3159      CurInitExpr = CurInit.takeAs<Expr>();
3160      CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3161                                                         CastKind,
3162                                                         CurInitExpr,
3163                                                         false));
3164      break;
3165    }
3166
3167    case SK_QualificationConversionLValue:
3168    case SK_QualificationConversionRValue:
3169      // Perform a qualification conversion; these can never go wrong.
3170      S.ImpCastExprToType(CurInitExpr, Step->Type,
3171                          CastExpr::CK_NoOp,
3172                          Step->Kind == SK_QualificationConversionLValue);
3173      CurInit.release();
3174      CurInit = S.Owned(CurInitExpr);
3175      break;
3176
3177    case SK_ConversionSequence:
3178        if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
3179                                      false, false, *Step->ICS))
3180        return S.ExprError();
3181
3182      CurInit.release();
3183      CurInit = S.Owned(CurInitExpr);
3184      break;
3185
3186    case SK_ListInitialization: {
3187      InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3188      QualType Ty = Step->Type;
3189      if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
3190        return S.ExprError();
3191
3192      CurInit.release();
3193      CurInit = S.Owned(InitList);
3194      break;
3195    }
3196
3197    case SK_ConstructorInitialization: {
3198      CXXConstructorDecl *Constructor
3199        = cast<CXXConstructorDecl>(Step->Function);
3200
3201      // Build a call to the selected constructor.
3202      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3203      SourceLocation Loc = Kind.getLocation();
3204
3205      // Determine the arguments required to actually perform the constructor
3206      // call.
3207      if (S.CompleteConstructorCall(Constructor, move(Args),
3208                                    Loc, ConstructorArgs))
3209        return S.ExprError();
3210
3211      // Build the an expression that constructs a temporary.
3212      CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3213                                        move_arg(ConstructorArgs));
3214      if (CurInit.isInvalid())
3215        return S.ExprError();
3216
3217      break;
3218    }
3219
3220    case SK_ZeroInitialization: {
3221      if (Kind.getKind() == InitializationKind::IK_Value &&
3222          S.getLangOptions().CPlusPlus &&
3223          !Kind.isImplicitValueInit())
3224        CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3225                                                   Kind.getRange().getBegin(),
3226                                                    Kind.getRange().getEnd()));
3227      else
3228        CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
3229      break;
3230    }
3231    }
3232  }
3233
3234  return move(CurInit);
3235}
3236
3237//===----------------------------------------------------------------------===//
3238// Diagnose initialization failures
3239//===----------------------------------------------------------------------===//
3240bool InitializationSequence::Diagnose(Sema &S,
3241                                      const InitializedEntity &Entity,
3242                                      const InitializationKind &Kind,
3243                                      Expr **Args, unsigned NumArgs) {
3244  if (SequenceKind != FailedSequence)
3245    return false;
3246
3247  QualType DestType = Entity.getType().getType();
3248  switch (Failure) {
3249  case FK_TooManyInitsForReference:
3250    S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3251      << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3252    break;
3253
3254  case FK_ArrayNeedsInitList:
3255  case FK_ArrayNeedsInitListOrStringLiteral:
3256    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3257      << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3258    break;
3259
3260  case FK_AddressOfOverloadFailed:
3261    S.ResolveAddressOfOverloadedFunction(Args[0],
3262                                         DestType.getNonReferenceType(),
3263                                         true);
3264    break;
3265
3266  case FK_ReferenceInitOverloadFailed:
3267  case FK_UserConversionOverloadFailed:
3268    switch (FailedOverloadResult) {
3269    case OR_Ambiguous:
3270      S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3271        << Args[0]->getType() << DestType.getNonReferenceType()
3272        << Args[0]->getSourceRange();
3273      S.PrintOverloadCandidates(FailedCandidateSet, true);
3274      break;
3275
3276    case OR_No_Viable_Function:
3277      S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3278        << Args[0]->getType() << DestType.getNonReferenceType()
3279        << Args[0]->getSourceRange();
3280      S.PrintOverloadCandidates(FailedCandidateSet, false);
3281      break;
3282
3283    case OR_Deleted: {
3284      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3285        << Args[0]->getType() << DestType.getNonReferenceType()
3286        << Args[0]->getSourceRange();
3287      OverloadCandidateSet::iterator Best;
3288      OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3289                                                   Kind.getLocation(),
3290                                                   Best);
3291      if (Ovl == OR_Deleted) {
3292        S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3293          << Best->Function->isDeleted();
3294      } else {
3295        llvm_unreachable("Inconsistent overload resolution?");
3296      }
3297      break;
3298    }
3299
3300    case OR_Success:
3301      llvm_unreachable("Conversion did not fail!");
3302      break;
3303    }
3304    break;
3305
3306  case FK_NonConstLValueReferenceBindingToTemporary:
3307  case FK_NonConstLValueReferenceBindingToUnrelated:
3308    S.Diag(Kind.getLocation(),
3309           Failure == FK_NonConstLValueReferenceBindingToTemporary
3310             ? diag::err_lvalue_reference_bind_to_temporary
3311             : diag::err_lvalue_reference_bind_to_unrelated)
3312      << DestType.getNonReferenceType()
3313      << Args[0]->getType()
3314      << Args[0]->getSourceRange();
3315    break;
3316
3317  case FK_RValueReferenceBindingToLValue:
3318    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3319      << Args[0]->getSourceRange();
3320    break;
3321
3322  case FK_ReferenceInitDropsQualifiers:
3323    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3324      << DestType.getNonReferenceType()
3325      << Args[0]->getType()
3326      << Args[0]->getSourceRange();
3327    break;
3328
3329  case FK_ReferenceInitFailed:
3330    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3331      << DestType.getNonReferenceType()
3332      << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3333      << Args[0]->getType()
3334      << Args[0]->getSourceRange();
3335    break;
3336
3337  case FK_ConversionFailed:
3338    S.Diag(Kind.getLocation(), diag::err_cannot_initialize_decl_noname)
3339      << DestType
3340      << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3341      << Args[0]->getType()
3342      << Args[0]->getSourceRange();
3343    break;
3344
3345  case FK_TooManyInitsForScalar: {
3346    SourceRange R;
3347
3348    if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3349      R = SourceRange(InitList->getInit(1)->getLocStart(),
3350                      InitList->getLocEnd());
3351    else
3352      R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3353
3354    S.Diag(Kind.getLocation(), diag::err_excess_initializers)
3355      << /*scalar=*/2 << R;
3356    break;
3357  }
3358
3359  case FK_ReferenceBindingToInitList:
3360    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3361      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3362    break;
3363
3364  case FK_InitListBadDestinationType:
3365    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3366      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3367    break;
3368
3369  case FK_ConstructorOverloadFailed: {
3370    SourceRange ArgsRange;
3371    if (NumArgs)
3372      ArgsRange = SourceRange(Args[0]->getLocStart(),
3373                              Args[NumArgs - 1]->getLocEnd());
3374
3375    // FIXME: Using "DestType" for the entity we're printing is probably
3376    // bad.
3377    switch (FailedOverloadResult) {
3378      case OR_Ambiguous:
3379        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3380          << DestType << ArgsRange;
3381        S.PrintOverloadCandidates(FailedCandidateSet, true);
3382        break;
3383
3384      case OR_No_Viable_Function:
3385        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3386          << DestType << ArgsRange;
3387        S.PrintOverloadCandidates(FailedCandidateSet, false);
3388        break;
3389
3390      case OR_Deleted: {
3391        S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3392          << true << DestType << ArgsRange;
3393        OverloadCandidateSet::iterator Best;
3394        OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3395                                                     Kind.getLocation(),
3396                                                     Best);
3397        if (Ovl == OR_Deleted) {
3398          S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3399            << Best->Function->isDeleted();
3400        } else {
3401          llvm_unreachable("Inconsistent overload resolution?");
3402        }
3403        break;
3404      }
3405
3406      case OR_Success:
3407        llvm_unreachable("Conversion did not fail!");
3408        break;
3409    }
3410    break;
3411  }
3412
3413  case FK_DefaultInitOfConst:
3414    S.Diag(Kind.getLocation(), diag::err_default_init_const)
3415      << DestType;
3416    break;
3417  }
3418
3419  return true;
3420}
3421