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