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