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