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