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