SemaInit.cpp revision 3a45c0e61dfc19f27b8ebcb15dd70159a36f1f9a
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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Designator.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/SemaInternal.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/TypeLoc.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include <map>
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
35static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36                          ASTContext &Context) {
37  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38    return 0;
39
40  // See if this is a string literal or @encode.
41  Init = Init->IgnoreParens();
42
43  // Handle @encode, which is a narrow string.
44  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45    return Init;
46
47  // Otherwise we can only handle string literals.
48  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
49  if (SL == 0) return 0;
50
51  QualType ElemTy = Context.getCanonicalType(AT->getElementType());
52
53  switch (SL->getKind()) {
54  case StringLiteral::Ascii:
55  case StringLiteral::UTF8:
56    // char array can be initialized with a narrow string.
57    // Only allow char x[] = "foo";  not char x[] = L"foo";
58    return ElemTy->isCharType() ? Init : 0;
59  case StringLiteral::UTF16:
60    return ElemTy->isChar16Type() ? Init : 0;
61  case StringLiteral::UTF32:
62    return ElemTy->isChar32Type() ? Init : 0;
63  case StringLiteral::Wide:
64    // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65    // correction from DR343): "An array with element type compatible with a
66    // qualified or unqualified version of wchar_t may be initialized by a wide
67    // string literal, optionally enclosed in braces."
68    if (Context.typesAreCompatible(Context.getWCharType(),
69                                   ElemTy.getUnqualifiedType()))
70      return Init;
71
72    return 0;
73  }
74
75  llvm_unreachable("missed a StringLiteral kind?");
76}
77
78static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79  const ArrayType *arrayType = Context.getAsArrayType(declType);
80  if (!arrayType) return 0;
81
82  return IsStringInit(init, arrayType, Context);
83}
84
85static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86                            Sema &S) {
87  // Get the length of the string as parsed.
88  uint64_t StrLength =
89    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
91
92  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
93    // C99 6.7.8p14. We have an array of character type with unknown size
94    // being initialized to a string literal.
95    llvm::APSInt ConstVal(32);
96    ConstVal = StrLength;
97    // Return a new array type (C99 6.7.8p22).
98    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99                                           ConstVal,
100                                           ArrayType::Normal, 0);
101    return;
102  }
103
104  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
105
106  // We have an array of character type with known size.  However,
107  // the size may be smaller or larger than the string we are initializing.
108  // FIXME: Avoid truncation for 64-bit length strings.
109  if (S.getLangOptions().CPlusPlus) {
110    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111      // For Pascal strings it's OK to strip off the terminating null character,
112      // so the example below is valid:
113      //
114      // unsigned char a[2] = "\pa";
115      if (SL->isPascal())
116        StrLength--;
117    }
118
119    // [dcl.init.string]p2
120    if (StrLength > CAT->getSize().getZExtValue())
121      S.Diag(Str->getSourceRange().getBegin(),
122             diag::err_initializer_string_for_char_array_too_long)
123        << Str->getSourceRange();
124  } else {
125    // C99 6.7.8p14.
126    if (StrLength-1 > CAT->getSize().getZExtValue())
127      S.Diag(Str->getSourceRange().getBegin(),
128             diag::warn_initializer_string_for_char_array_too_long)
129        << Str->getSourceRange();
130  }
131
132  // Set the type to the actual size that we are initializing.  If we have
133  // something like:
134  //   char x[1] = "foo";
135  // then this will set the string literal's type to char[1].
136  Str->setType(DeclT);
137}
138
139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
157/// arguments, which contains the current "structured" (semantic)
158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
170namespace {
171class InitListChecker {
172  Sema &SemaRef;
173  bool hadError;
174  bool VerifyOnly; // no diagnostics, no structure building
175  bool AllowBraceElision;
176  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177  InitListExpr *FullyStructuredList;
178
179  void CheckImplicitInitList(const InitializedEntity &Entity,
180                             InitListExpr *ParentIList, QualType T,
181                             unsigned &Index, InitListExpr *StructuredList,
182                             unsigned &StructuredIndex);
183  void CheckExplicitInitList(const InitializedEntity &Entity,
184                             InitListExpr *IList, QualType &T,
185                             unsigned &Index, InitListExpr *StructuredList,
186                             unsigned &StructuredIndex,
187                             bool TopLevelObject = false);
188  void CheckListElementTypes(const InitializedEntity &Entity,
189                             InitListExpr *IList, QualType &DeclType,
190                             bool SubobjectIsDesignatorContext,
191                             unsigned &Index,
192                             InitListExpr *StructuredList,
193                             unsigned &StructuredIndex,
194                             bool TopLevelObject = false);
195  void CheckSubElementType(const InitializedEntity &Entity,
196                           InitListExpr *IList, QualType ElemType,
197                           unsigned &Index,
198                           InitListExpr *StructuredList,
199                           unsigned &StructuredIndex);
200  void CheckComplexType(const InitializedEntity &Entity,
201                        InitListExpr *IList, QualType DeclType,
202                        unsigned &Index,
203                        InitListExpr *StructuredList,
204                        unsigned &StructuredIndex);
205  void CheckScalarType(const InitializedEntity &Entity,
206                       InitListExpr *IList, QualType DeclType,
207                       unsigned &Index,
208                       InitListExpr *StructuredList,
209                       unsigned &StructuredIndex);
210  void CheckReferenceType(const InitializedEntity &Entity,
211                          InitListExpr *IList, QualType DeclType,
212                          unsigned &Index,
213                          InitListExpr *StructuredList,
214                          unsigned &StructuredIndex);
215  void CheckVectorType(const InitializedEntity &Entity,
216                       InitListExpr *IList, QualType DeclType, unsigned &Index,
217                       InitListExpr *StructuredList,
218                       unsigned &StructuredIndex);
219  void CheckStructUnionTypes(const InitializedEntity &Entity,
220                             InitListExpr *IList, QualType DeclType,
221                             RecordDecl::field_iterator Field,
222                             bool SubobjectIsDesignatorContext, unsigned &Index,
223                             InitListExpr *StructuredList,
224                             unsigned &StructuredIndex,
225                             bool TopLevelObject = false);
226  void CheckArrayType(const InitializedEntity &Entity,
227                      InitListExpr *IList, QualType &DeclType,
228                      llvm::APSInt elementIndex,
229                      bool SubobjectIsDesignatorContext, unsigned &Index,
230                      InitListExpr *StructuredList,
231                      unsigned &StructuredIndex);
232  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
233                                  InitListExpr *IList, DesignatedInitExpr *DIE,
234                                  unsigned DesigIdx,
235                                  QualType &CurrentObjectType,
236                                  RecordDecl::field_iterator *NextField,
237                                  llvm::APSInt *NextElementIndex,
238                                  unsigned &Index,
239                                  InitListExpr *StructuredList,
240                                  unsigned &StructuredIndex,
241                                  bool FinishSubobjectInit,
242                                  bool TopLevelObject);
243  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244                                           QualType CurrentObjectType,
245                                           InitListExpr *StructuredList,
246                                           unsigned StructuredIndex,
247                                           SourceRange InitRange);
248  void UpdateStructuredListElement(InitListExpr *StructuredList,
249                                   unsigned &StructuredIndex,
250                                   Expr *expr);
251  int numArrayElements(QualType DeclType);
252  int numStructUnionElements(QualType DeclType);
253
254  void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255                               const InitializedEntity &ParentEntity,
256                               InitListExpr *ILE, bool &RequiresSecondPass);
257  void FillInValueInitializations(const InitializedEntity &Entity,
258                                  InitListExpr *ILE, bool &RequiresSecondPass);
259  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260                              Expr *InitExpr, FieldDecl *Field,
261                              bool TopLevelObject);
262  void CheckValueInitializable(const InitializedEntity &Entity);
263
264public:
265  InitListChecker(Sema &S, const InitializedEntity &Entity,
266                  InitListExpr *IL, QualType &T, bool VerifyOnly,
267                  bool AllowBraceElision);
268  bool HadError() { return hadError; }
269
270  // @brief Retrieves the fully-structured initializer list used for
271  // semantic analysis and code generation.
272  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
274} // end anonymous namespace
275
276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277  assert(VerifyOnly &&
278         "CheckValueInitializable is only inteded for verification mode.");
279
280  SourceLocation Loc;
281  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282                                                            true);
283  InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284  if (InitSeq.Failed())
285    hadError = true;
286}
287
288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289                                        const InitializedEntity &ParentEntity,
290                                              InitListExpr *ILE,
291                                              bool &RequiresSecondPass) {
292  SourceLocation Loc = ILE->getSourceRange().getBegin();
293  unsigned NumInits = ILE->getNumInits();
294  InitializedEntity MemberEntity
295    = InitializedEntity::InitializeMember(Field, &ParentEntity);
296  if (Init >= NumInits || !ILE->getInit(Init)) {
297    // FIXME: We probably don't need to handle references
298    // specially here, since value-initialization of references is
299    // handled in InitializationSequence.
300    if (Field->getType()->isReferenceType()) {
301      // C++ [dcl.init.aggr]p9:
302      //   If an incomplete or empty initializer-list leaves a
303      //   member of reference type uninitialized, the program is
304      //   ill-formed.
305      SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306        << Field->getType()
307        << ILE->getSyntacticForm()->getSourceRange();
308      SemaRef.Diag(Field->getLocation(),
309                   diag::note_uninit_reference_member);
310      hadError = true;
311      return;
312    }
313
314    InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315                                                              true);
316    InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317    if (!InitSeq) {
318      InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319      hadError = true;
320      return;
321    }
322
323    ExprResult MemberInit
324      = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
325    if (MemberInit.isInvalid()) {
326      hadError = true;
327      return;
328    }
329
330    if (hadError) {
331      // Do nothing
332    } else if (Init < NumInits) {
333      ILE->setInit(Init, MemberInit.takeAs<Expr>());
334    } else if (InitSeq.isConstructorInitialization()) {
335      // Value-initialization requires a constructor call, so
336      // extend the initializer list to include the constructor
337      // call and make a note that we'll need to take another pass
338      // through the initializer list.
339      ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
340      RequiresSecondPass = true;
341    }
342  } else if (InitListExpr *InnerILE
343               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
344    FillInValueInitializations(MemberEntity, InnerILE,
345                               RequiresSecondPass);
346}
347
348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
351void
352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353                                            InitListExpr *ILE,
354                                            bool &RequiresSecondPass) {
355  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
356         "Should not have void type");
357  SourceLocation Loc = ILE->getSourceRange().getBegin();
358  if (ILE->getSyntacticForm())
359    Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
360
361  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
362    if (RType->getDecl()->isUnion() &&
363        ILE->getInitializedFieldInUnion())
364      FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365                              Entity, ILE, RequiresSecondPass);
366    else {
367      unsigned Init = 0;
368      for (RecordDecl::field_iterator
369             Field = RType->getDecl()->field_begin(),
370             FieldEnd = RType->getDecl()->field_end();
371           Field != FieldEnd; ++Field) {
372        if (Field->isUnnamedBitfield())
373          continue;
374
375        if (hadError)
376          return;
377
378        FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379        if (hadError)
380          return;
381
382        ++Init;
383
384        // Only look at the first initialization of a union.
385        if (RType->getDecl()->isUnion())
386          break;
387      }
388    }
389
390    return;
391  }
392
393  QualType ElementType;
394
395  InitializedEntity ElementEntity = Entity;
396  unsigned NumInits = ILE->getNumInits();
397  unsigned NumElements = NumInits;
398  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
399    ElementType = AType->getElementType();
400    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401      NumElements = CAType->getSize().getZExtValue();
402    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
403                                                         0, Entity);
404  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
405    ElementType = VType->getElementType();
406    NumElements = VType->getNumElements();
407    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
408                                                         0, Entity);
409  } else
410    ElementType = ILE->getType();
411
412
413  for (unsigned Init = 0; Init != NumElements; ++Init) {
414    if (hadError)
415      return;
416
417    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418        ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
419      ElementEntity.setElementIndex(Init);
420
421    Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422    if (!InitExpr && !ILE->hasArrayFiller()) {
423      InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424                                                                true);
425      InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426      if (!InitSeq) {
427        InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
428        hadError = true;
429        return;
430      }
431
432      ExprResult ElementInit
433        = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
434      if (ElementInit.isInvalid()) {
435        hadError = true;
436        return;
437      }
438
439      if (hadError) {
440        // Do nothing
441      } else if (Init < NumInits) {
442        // For arrays, just set the expression used for value-initialization
443        // of the "holes" in the array.
444        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445          ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446        else
447          ILE->setInit(Init, ElementInit.takeAs<Expr>());
448      } else {
449        // For arrays, just set the expression used for value-initialization
450        // of the rest of elements and exit.
451        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452          ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453          return;
454        }
455
456        if (InitSeq.isConstructorInitialization()) {
457          // Value-initialization requires a constructor call, so
458          // extend the initializer list to include the constructor
459          // call and make a note that we'll need to take another pass
460          // through the initializer list.
461          ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462          RequiresSecondPass = true;
463        }
464      }
465    } else if (InitListExpr *InnerILE
466                 = dyn_cast_or_null<InitListExpr>(InitExpr))
467      FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
468  }
469}
470
471
472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
473                                 InitListExpr *IL, QualType &T,
474                                 bool VerifyOnly, bool AllowBraceElision)
475  : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
476  hadError = false;
477
478  unsigned newIndex = 0;
479  unsigned newStructuredIndex = 0;
480  FullyStructuredList
481    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
482  CheckExplicitInitList(Entity, IL, T, newIndex,
483                        FullyStructuredList, newStructuredIndex,
484                        /*TopLevelObject=*/true);
485
486  if (!hadError && !VerifyOnly) {
487    bool RequiresSecondPass = false;
488    FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
489    if (RequiresSecondPass && !hadError)
490      FillInValueInitializations(Entity, FullyStructuredList,
491                                 RequiresSecondPass);
492  }
493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
496  // FIXME: use a proper constant
497  int maxElements = 0x7FFFFFFF;
498  if (const ConstantArrayType *CAT =
499        SemaRef.Context.getAsConstantArrayType(DeclType)) {
500    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501  }
502  return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
506  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
507  int InitializableMembers = 0;
508  for (RecordDecl::field_iterator
509         Field = structDecl->field_begin(),
510         FieldEnd = structDecl->field_end();
511       Field != FieldEnd; ++Field) {
512    if (!Field->isUnnamedBitfield())
513      ++InitializableMembers;
514  }
515  if (structDecl->isUnion())
516    return std::min(InitializableMembers, 1);
517  return InitializableMembers - structDecl->hasFlexibleArrayMember();
518}
519
520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
521                                            InitListExpr *ParentIList,
522                                            QualType T, unsigned &Index,
523                                            InitListExpr *StructuredList,
524                                            unsigned &StructuredIndex) {
525  int maxElements = 0;
526
527  if (T->isArrayType())
528    maxElements = numArrayElements(T);
529  else if (T->isRecordType())
530    maxElements = numStructUnionElements(T);
531  else if (T->isVectorType())
532    maxElements = T->getAs<VectorType>()->getNumElements();
533  else
534    llvm_unreachable("CheckImplicitInitList(): Illegal type");
535
536  if (maxElements == 0) {
537    if (!VerifyOnly)
538      SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539                   diag::err_implicit_empty_initializer);
540    ++Index;
541    hadError = true;
542    return;
543  }
544
545  // Build a structured initializer list corresponding to this subobject.
546  InitListExpr *StructuredSubobjectInitList
547    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548                                 StructuredIndex,
549          SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550                      ParentIList->getSourceRange().getEnd()));
551  unsigned StructuredSubobjectInitIndex = 0;
552
553  // Check the element types and build the structural subobject.
554  unsigned StartIndex = Index;
555  CheckListElementTypes(Entity, ParentIList, T,
556                        /*SubobjectIsDesignatorContext=*/false, Index,
557                        StructuredSubobjectInitList,
558                        StructuredSubobjectInitIndex);
559
560  if (VerifyOnly) {
561    if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562      hadError = true;
563  } else {
564    StructuredSubobjectInitList->setType(T);
565
566    unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
567    // Update the structured sub-object initializer so that it's ending
568    // range corresponds with the end of the last initializer it used.
569    if (EndIndex < ParentIList->getNumInits()) {
570      SourceLocation EndLoc
571        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573    }
574
575    // Complain about missing braces.
576    if (T->isArrayType() || T->isRecordType()) {
577      SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
578                    AllowBraceElision ? diag::warn_missing_braces :
579                                        diag::err_missing_braces)
580        << StructuredSubobjectInitList->getSourceRange()
581        << FixItHint::CreateInsertion(
582              StructuredSubobjectInitList->getLocStart(), "{")
583        << FixItHint::CreateInsertion(
584              SemaRef.PP.getLocForEndOfToken(
585                                      StructuredSubobjectInitList->getLocEnd()),
586              "}");
587      if (!AllowBraceElision)
588        hadError = true;
589    }
590  }
591}
592
593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
594                                            InitListExpr *IList, QualType &T,
595                                            unsigned &Index,
596                                            InitListExpr *StructuredList,
597                                            unsigned &StructuredIndex,
598                                            bool TopLevelObject) {
599  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
600  if (!VerifyOnly) {
601    SyntacticToSemantic[IList] = StructuredList;
602    StructuredList->setSyntacticForm(IList);
603  }
604  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
605                        Index, StructuredList, StructuredIndex, TopLevelObject);
606  if (!VerifyOnly) {
607    QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608    IList->setType(ExprTy);
609    StructuredList->setType(ExprTy);
610  }
611  if (hadError)
612    return;
613
614  if (Index < IList->getNumInits()) {
615    // We have leftover initializers
616    if (VerifyOnly) {
617      if (SemaRef.getLangOptions().CPlusPlus ||
618          (SemaRef.getLangOptions().OpenCL &&
619           IList->getType()->isVectorType())) {
620        hadError = true;
621      }
622      return;
623    }
624
625    if (StructuredIndex == 1 &&
626        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
627      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
628      if (SemaRef.getLangOptions().CPlusPlus) {
629        DK = diag::err_excess_initializers_in_char_array_initializer;
630        hadError = true;
631      }
632      // Special-case
633      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
634        << IList->getInit(Index)->getSourceRange();
635    } else if (!T->isIncompleteType()) {
636      // Don't complain for incomplete types, since we'll get an error
637      // elsewhere
638      QualType CurrentObjectType = StructuredList->getType();
639      int initKind =
640        CurrentObjectType->isArrayType()? 0 :
641        CurrentObjectType->isVectorType()? 1 :
642        CurrentObjectType->isScalarType()? 2 :
643        CurrentObjectType->isUnionType()? 3 :
644        4;
645
646      unsigned DK = diag::warn_excess_initializers;
647      if (SemaRef.getLangOptions().CPlusPlus) {
648        DK = diag::err_excess_initializers;
649        hadError = true;
650      }
651      if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652        DK = diag::err_excess_initializers;
653        hadError = true;
654      }
655
656      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
657        << initKind << IList->getInit(Index)->getSourceRange();
658    }
659  }
660
661  if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662      !TopLevelObject)
663    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
664      << IList->getSourceRange()
665      << FixItHint::CreateRemoval(IList->getLocStart())
666      << FixItHint::CreateRemoval(IList->getLocEnd());
667}
668
669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
670                                            InitListExpr *IList,
671                                            QualType &DeclType,
672                                            bool SubobjectIsDesignatorContext,
673                                            unsigned &Index,
674                                            InitListExpr *StructuredList,
675                                            unsigned &StructuredIndex,
676                                            bool TopLevelObject) {
677  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678    // Explicitly braced initializer for complex type can be real+imaginary
679    // parts.
680    CheckComplexType(Entity, IList, DeclType, Index,
681                     StructuredList, StructuredIndex);
682  } else if (DeclType->isScalarType()) {
683    CheckScalarType(Entity, IList, DeclType, Index,
684                    StructuredList, StructuredIndex);
685  } else if (DeclType->isVectorType()) {
686    CheckVectorType(Entity, IList, DeclType, Index,
687                    StructuredList, StructuredIndex);
688  } else if (DeclType->isAggregateType()) {
689    if (DeclType->isRecordType()) {
690      RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
691      CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
692                            SubobjectIsDesignatorContext, Index,
693                            StructuredList, StructuredIndex,
694                            TopLevelObject);
695    } else if (DeclType->isArrayType()) {
696      llvm::APSInt Zero(
697                      SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
698                      false);
699      CheckArrayType(Entity, IList, DeclType, Zero,
700                     SubobjectIsDesignatorContext, Index,
701                     StructuredList, StructuredIndex);
702    } else
703      llvm_unreachable("Aggregate that isn't a structure or array?!");
704  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705    // This type is invalid, issue a diagnostic.
706    ++Index;
707    if (!VerifyOnly)
708      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709        << DeclType;
710    hadError = true;
711  } else if (DeclType->isRecordType()) {
712    // C++ [dcl.init]p14:
713    //   [...] If the class is an aggregate (8.5.1), and the initializer
714    //   is a brace-enclosed list, see 8.5.1.
715    //
716    // Note: 8.5.1 is handled below; here, we diagnose the case where
717    // we have an initializer list and a destination type that is not
718    // an aggregate.
719    // FIXME: In C++0x, this is yet another form of initialization.
720    if (!VerifyOnly)
721      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722        << DeclType << IList->getSourceRange();
723    hadError = true;
724  } else if (DeclType->isReferenceType()) {
725    CheckReferenceType(Entity, IList, DeclType, Index,
726                       StructuredList, StructuredIndex);
727  } else if (DeclType->isObjCObjectType()) {
728    if (!VerifyOnly)
729      SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730        << DeclType;
731    hadError = true;
732  } else {
733    if (!VerifyOnly)
734      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735        << DeclType;
736    hadError = true;
737  }
738}
739
740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
741                                          InitListExpr *IList,
742                                          QualType ElemType,
743                                          unsigned &Index,
744                                          InitListExpr *StructuredList,
745                                          unsigned &StructuredIndex) {
746  Expr *expr = IList->getInit(Index);
747  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748    unsigned newIndex = 0;
749    unsigned newStructuredIndex = 0;
750    InitListExpr *newStructuredList
751      = getStructuredSubobjectInit(IList, Index, ElemType,
752                                   StructuredList, StructuredIndex,
753                                   SubInitList->getSourceRange());
754    CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
755                          newStructuredList, newStructuredIndex);
756    ++StructuredIndex;
757    ++Index;
758    return;
759  } else if (ElemType->isScalarType()) {
760    return CheckScalarType(Entity, IList, ElemType, Index,
761                           StructuredList, StructuredIndex);
762  } else if (ElemType->isReferenceType()) {
763    return CheckReferenceType(Entity, IList, ElemType, Index,
764                              StructuredList, StructuredIndex);
765  }
766
767  if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768    // arrayType can be incomplete if we're initializing a flexible
769    // array member.  There's nothing we can do with the completed
770    // type here, though.
771
772    if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
773      if (!VerifyOnly) {
774        CheckStringInit(Str, ElemType, arrayType, SemaRef);
775        UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776      }
777      ++Index;
778      return;
779    }
780
781    // Fall through for subaggregate initialization.
782
783  } else if (SemaRef.getLangOptions().CPlusPlus) {
784    // C++ [dcl.init.aggr]p12:
785    //   All implicit type conversions (clause 4) are considered when
786    //   initializing the aggregate member with an initializer from
787    //   an initializer-list. If the initializer can initialize a
788    //   member, the member is initialized. [...]
789
790    // FIXME: Better EqualLoc?
791    InitializationKind Kind =
792      InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793    InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795    if (Seq) {
796      if (!VerifyOnly) {
797        ExprResult Result =
798          Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799        if (Result.isInvalid())
800          hadError = true;
801
802        UpdateStructuredListElement(StructuredList, StructuredIndex,
803                                    Result.takeAs<Expr>());
804      }
805      ++Index;
806      return;
807    }
808
809    // Fall through for subaggregate initialization
810  } else {
811    // C99 6.7.8p13:
812    //
813    //   The initializer for a structure or union object that has
814    //   automatic storage duration shall be either an initializer
815    //   list as described below, or a single expression that has
816    //   compatible structure or union type. In the latter case, the
817    //   initial value of the object, including unnamed members, is
818    //   that of the expression.
819    ExprResult ExprRes = SemaRef.Owned(expr);
820    if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
821        SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822                                                 !VerifyOnly)
823          == Sema::Compatible) {
824      if (ExprRes.isInvalid())
825        hadError = true;
826      else {
827        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828	      if (ExprRes.isInvalid())
829	        hadError = true;
830      }
831      UpdateStructuredListElement(StructuredList, StructuredIndex,
832                                  ExprRes.takeAs<Expr>());
833      ++Index;
834      return;
835    }
836    ExprRes.release();
837    // Fall through for subaggregate initialization
838  }
839
840  // C++ [dcl.init.aggr]p12:
841  //
842  //   [...] Otherwise, if the member is itself a non-empty
843  //   subaggregate, brace elision is assumed and the initializer is
844  //   considered for the initialization of the first member of
845  //   the subaggregate.
846  if (!SemaRef.getLangOptions().OpenCL &&
847      (ElemType->isAggregateType() || ElemType->isVectorType())) {
848    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849                          StructuredIndex);
850    ++StructuredIndex;
851  } else {
852    if (!VerifyOnly) {
853      // We cannot initialize this element, so let
854      // PerformCopyInitialization produce the appropriate diagnostic.
855      SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856                                        SemaRef.Owned(expr),
857                                        /*TopLevelOfInitList=*/true);
858    }
859    hadError = true;
860    ++Index;
861    ++StructuredIndex;
862  }
863}
864
865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866                                       InitListExpr *IList, QualType DeclType,
867                                       unsigned &Index,
868                                       InitListExpr *StructuredList,
869                                       unsigned &StructuredIndex) {
870  assert(Index == 0 && "Index in explicit init list must be zero");
871
872  // As an extension, clang supports complex initializers, which initialize
873  // a complex number component-wise.  When an explicit initializer list for
874  // a complex number contains two two initializers, this extension kicks in:
875  // it exepcts the initializer list to contain two elements convertible to
876  // the element type of the complex type. The first element initializes
877  // the real part, and the second element intitializes the imaginary part.
878
879  if (IList->getNumInits() != 2)
880    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881                           StructuredIndex);
882
883  // This is an extension in C.  (The builtin _Complex type does not exist
884  // in the C++ standard.)
885  if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
886    SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887      << IList->getSourceRange();
888
889  // Initialize the complex number.
890  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891  InitializedEntity ElementEntity =
892    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894  for (unsigned i = 0; i < 2; ++i) {
895    ElementEntity.setElementIndex(Index);
896    CheckSubElementType(ElementEntity, IList, elementType, Index,
897                        StructuredList, StructuredIndex);
898  }
899}
900
901
902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
903                                      InitListExpr *IList, QualType DeclType,
904                                      unsigned &Index,
905                                      InitListExpr *StructuredList,
906                                      unsigned &StructuredIndex) {
907  if (Index >= IList->getNumInits()) {
908    if (!VerifyOnly)
909      SemaRef.Diag(IList->getLocStart(),
910                   SemaRef.getLangOptions().CPlusPlus0x ?
911                     diag::warn_cxx98_compat_empty_scalar_initializer :
912                     diag::err_empty_scalar_initializer)
913        << IList->getSourceRange();
914    hadError = !SemaRef.getLangOptions().CPlusPlus0x;
915    ++Index;
916    ++StructuredIndex;
917    return;
918  }
919
920  Expr *expr = IList->getInit(Index);
921  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
922    if (!VerifyOnly)
923      SemaRef.Diag(SubIList->getLocStart(),
924                   diag::warn_many_braces_around_scalar_init)
925        << SubIList->getSourceRange();
926
927    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928                    StructuredIndex);
929    return;
930  } else if (isa<DesignatedInitExpr>(expr)) {
931    if (!VerifyOnly)
932      SemaRef.Diag(expr->getSourceRange().getBegin(),
933                   diag::err_designator_for_scalar_init)
934        << DeclType << expr->getSourceRange();
935    hadError = true;
936    ++Index;
937    ++StructuredIndex;
938    return;
939  }
940
941  if (VerifyOnly) {
942    if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943      hadError = true;
944    ++Index;
945    return;
946  }
947
948  ExprResult Result =
949    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
950                                      SemaRef.Owned(expr),
951                                      /*TopLevelOfInitList=*/true);
952
953  Expr *ResultExpr = 0;
954
955  if (Result.isInvalid())
956    hadError = true; // types weren't compatible.
957  else {
958    ResultExpr = Result.takeAs<Expr>();
959
960    if (ResultExpr != expr) {
961      // The type was promoted, update initializer list.
962      IList->setInit(Index, ResultExpr);
963    }
964  }
965  if (hadError)
966    ++StructuredIndex;
967  else
968    UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969  ++Index;
970}
971
972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973                                         InitListExpr *IList, QualType DeclType,
974                                         unsigned &Index,
975                                         InitListExpr *StructuredList,
976                                         unsigned &StructuredIndex) {
977  if (Index >= IList->getNumInits()) {
978    // FIXME: It would be wonderful if we could point at the actual member. In
979    // general, it would be useful to pass location information down the stack,
980    // so that we know the location (or decl) of the "current object" being
981    // initialized.
982    if (!VerifyOnly)
983      SemaRef.Diag(IList->getLocStart(),
984                    diag::err_init_reference_member_uninitialized)
985        << DeclType
986        << IList->getSourceRange();
987    hadError = true;
988    ++Index;
989    ++StructuredIndex;
990    return;
991  }
992
993  Expr *expr = IList->getInit(Index);
994  if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
995    if (!VerifyOnly)
996      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997        << DeclType << IList->getSourceRange();
998    hadError = true;
999    ++Index;
1000    ++StructuredIndex;
1001    return;
1002  }
1003
1004  if (VerifyOnly) {
1005    if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006      hadError = true;
1007    ++Index;
1008    return;
1009  }
1010
1011  ExprResult Result =
1012    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013                                      SemaRef.Owned(expr),
1014                                      /*TopLevelOfInitList=*/true);
1015
1016  if (Result.isInvalid())
1017    hadError = true;
1018
1019  expr = Result.takeAs<Expr>();
1020  IList->setInit(Index, expr);
1021
1022  if (hadError)
1023    ++StructuredIndex;
1024  else
1025    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026  ++Index;
1027}
1028
1029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1030                                      InitListExpr *IList, QualType DeclType,
1031                                      unsigned &Index,
1032                                      InitListExpr *StructuredList,
1033                                      unsigned &StructuredIndex) {
1034  const VectorType *VT = DeclType->getAs<VectorType>();
1035  unsigned maxElements = VT->getNumElements();
1036  unsigned numEltsInit = 0;
1037  QualType elementType = VT->getElementType();
1038
1039  if (Index >= IList->getNumInits()) {
1040    // Make sure the element type can be value-initialized.
1041    if (VerifyOnly)
1042      CheckValueInitializable(
1043          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044    return;
1045  }
1046
1047  if (!SemaRef.getLangOptions().OpenCL) {
1048    // If the initializing element is a vector, try to copy-initialize
1049    // instead of breaking it apart (which is doomed to failure anyway).
1050    Expr *Init = IList->getInit(Index);
1051    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1052      if (VerifyOnly) {
1053        if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054          hadError = true;
1055        ++Index;
1056        return;
1057      }
1058
1059      ExprResult Result =
1060        SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1061                                          SemaRef.Owned(Init),
1062                                          /*TopLevelOfInitList=*/true);
1063
1064      Expr *ResultExpr = 0;
1065      if (Result.isInvalid())
1066        hadError = true; // types weren't compatible.
1067      else {
1068        ResultExpr = Result.takeAs<Expr>();
1069
1070        if (ResultExpr != Init) {
1071          // The type was promoted, update initializer list.
1072          IList->setInit(Index, ResultExpr);
1073        }
1074      }
1075      if (hadError)
1076        ++StructuredIndex;
1077      else
1078        UpdateStructuredListElement(StructuredList, StructuredIndex,
1079                                    ResultExpr);
1080      ++Index;
1081      return;
1082    }
1083
1084    InitializedEntity ElementEntity =
1085      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1086
1087    for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088      // Don't attempt to go past the end of the init list
1089      if (Index >= IList->getNumInits()) {
1090        if (VerifyOnly)
1091          CheckValueInitializable(ElementEntity);
1092        break;
1093      }
1094
1095      ElementEntity.setElementIndex(Index);
1096      CheckSubElementType(ElementEntity, IList, elementType, Index,
1097                          StructuredList, StructuredIndex);
1098    }
1099    return;
1100  }
1101
1102  InitializedEntity ElementEntity =
1103    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1104
1105  // OpenCL initializers allows vectors to be constructed from vectors.
1106  for (unsigned i = 0; i < maxElements; ++i) {
1107    // Don't attempt to go past the end of the init list
1108    if (Index >= IList->getNumInits())
1109      break;
1110
1111    ElementEntity.setElementIndex(Index);
1112
1113    QualType IType = IList->getInit(Index)->getType();
1114    if (!IType->isVectorType()) {
1115      CheckSubElementType(ElementEntity, IList, elementType, Index,
1116                          StructuredList, StructuredIndex);
1117      ++numEltsInit;
1118    } else {
1119      QualType VecType;
1120      const VectorType *IVT = IType->getAs<VectorType>();
1121      unsigned numIElts = IVT->getNumElements();
1122
1123      if (IType->isExtVectorType())
1124        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125      else
1126        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1127                                                IVT->getVectorKind());
1128      CheckSubElementType(ElementEntity, IList, VecType, Index,
1129                          StructuredList, StructuredIndex);
1130      numEltsInit += numIElts;
1131    }
1132  }
1133
1134  // OpenCL requires all elements to be initialized.
1135  if (numEltsInit != maxElements) {
1136    if (!VerifyOnly)
1137      SemaRef.Diag(IList->getSourceRange().getBegin(),
1138                   diag::err_vector_incorrect_num_initializers)
1139        << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140    hadError = true;
1141  }
1142}
1143
1144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1145                                     InitListExpr *IList, QualType &DeclType,
1146                                     llvm::APSInt elementIndex,
1147                                     bool SubobjectIsDesignatorContext,
1148                                     unsigned &Index,
1149                                     InitListExpr *StructuredList,
1150                                     unsigned &StructuredIndex) {
1151  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
1153  // Check for the special-case of initializing an array with a string.
1154  if (Index < IList->getNumInits()) {
1155    if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1156                                 SemaRef.Context)) {
1157      // We place the string literal directly into the resulting
1158      // initializer list. This is the only place where the structure
1159      // of the structured initializer list doesn't match exactly,
1160      // because doing so would involve allocating one character
1161      // constant for each string.
1162      if (!VerifyOnly) {
1163        CheckStringInit(Str, DeclType, arrayType, SemaRef);
1164        UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166      }
1167      ++Index;
1168      return;
1169    }
1170  }
1171  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1172    // Check for VLAs; in standard C it would be possible to check this
1173    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174    // them in all sorts of strange places).
1175    if (!VerifyOnly)
1176      SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177                    diag::err_variable_object_no_init)
1178        << VAT->getSizeExpr()->getSourceRange();
1179    hadError = true;
1180    ++Index;
1181    ++StructuredIndex;
1182    return;
1183  }
1184
1185  // We might know the maximum number of elements in advance.
1186  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187                           elementIndex.isUnsigned());
1188  bool maxElementsKnown = false;
1189  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1190    maxElements = CAT->getSize();
1191    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1192    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1193    maxElementsKnown = true;
1194  }
1195
1196  QualType elementType = arrayType->getElementType();
1197  while (Index < IList->getNumInits()) {
1198    Expr *Init = IList->getInit(Index);
1199    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1200      // If we're not the subobject that matches up with the '{' for
1201      // the designator, we shouldn't be handling the
1202      // designator. Return immediately.
1203      if (!SubobjectIsDesignatorContext)
1204        return;
1205
1206      // Handle this designated initializer. elementIndex will be
1207      // updated to be the next array element we'll initialize.
1208      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1209                                     DeclType, 0, &elementIndex, Index,
1210                                     StructuredList, StructuredIndex, true,
1211                                     false)) {
1212        hadError = true;
1213        continue;
1214      }
1215
1216      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1217        maxElements = maxElements.extend(elementIndex.getBitWidth());
1218      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1219        elementIndex = elementIndex.extend(maxElements.getBitWidth());
1220      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1221
1222      // If the array is of incomplete type, keep track of the number of
1223      // elements in the initializer.
1224      if (!maxElementsKnown && elementIndex > maxElements)
1225        maxElements = elementIndex;
1226
1227      continue;
1228    }
1229
1230    // If we know the maximum number of elements, and we've already
1231    // hit it, stop consuming elements in the initializer list.
1232    if (maxElementsKnown && elementIndex == maxElements)
1233      break;
1234
1235    InitializedEntity ElementEntity =
1236      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1237                                           Entity);
1238    // Check this element.
1239    CheckSubElementType(ElementEntity, IList, elementType, Index,
1240                        StructuredList, StructuredIndex);
1241    ++elementIndex;
1242
1243    // If the array is of incomplete type, keep track of the number of
1244    // elements in the initializer.
1245    if (!maxElementsKnown && elementIndex > maxElements)
1246      maxElements = elementIndex;
1247  }
1248  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1249    // If this is an incomplete array type, the actual type needs to
1250    // be calculated here.
1251    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1252    if (maxElements == Zero) {
1253      // Sizing an array implicitly to zero is not allowed by ISO C,
1254      // but is supported by GNU.
1255      SemaRef.Diag(IList->getLocStart(),
1256                    diag::ext_typecheck_zero_array_size);
1257    }
1258
1259    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1260                                                     ArrayType::Normal, 0);
1261  }
1262  if (!hadError && VerifyOnly) {
1263    // Check if there are any members of the array that get value-initialized.
1264    // If so, check if doing that is possible.
1265    // FIXME: This needs to detect holes left by designated initializers too.
1266    if (maxElementsKnown && elementIndex < maxElements)
1267      CheckValueInitializable(InitializedEntity::InitializeElement(
1268                                                  SemaRef.Context, 0, Entity));
1269  }
1270}
1271
1272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273                                             Expr *InitExpr,
1274                                             FieldDecl *Field,
1275                                             bool TopLevelObject) {
1276  // Handle GNU flexible array initializers.
1277  unsigned FlexArrayDiag;
1278  if (isa<InitListExpr>(InitExpr) &&
1279      cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280    // Empty flexible array init always allowed as an extension
1281    FlexArrayDiag = diag::ext_flexible_array_init;
1282  } else if (SemaRef.getLangOptions().CPlusPlus) {
1283    // Disallow flexible array init in C++; it is not required for gcc
1284    // compatibility, and it needs work to IRGen correctly in general.
1285    FlexArrayDiag = diag::err_flexible_array_init;
1286  } else if (!TopLevelObject) {
1287    // Disallow flexible array init on non-top-level object
1288    FlexArrayDiag = diag::err_flexible_array_init;
1289  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290    // Disallow flexible array init on anything which is not a variable.
1291    FlexArrayDiag = diag::err_flexible_array_init;
1292  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293    // Disallow flexible array init on local variables.
1294    FlexArrayDiag = diag::err_flexible_array_init;
1295  } else {
1296    // Allow other cases.
1297    FlexArrayDiag = diag::ext_flexible_array_init;
1298  }
1299
1300  if (!VerifyOnly) {
1301    SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302                 FlexArrayDiag)
1303      << InitExpr->getSourceRange().getBegin();
1304    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305      << Field;
1306  }
1307
1308  return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
1311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1312                                            InitListExpr *IList,
1313                                            QualType DeclType,
1314                                            RecordDecl::field_iterator Field,
1315                                            bool SubobjectIsDesignatorContext,
1316                                            unsigned &Index,
1317                                            InitListExpr *StructuredList,
1318                                            unsigned &StructuredIndex,
1319                                            bool TopLevelObject) {
1320  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1321
1322  // If the record is invalid, some of it's members are invalid. To avoid
1323  // confusion, we forgo checking the intializer for the entire record.
1324  if (structDecl->isInvalidDecl()) {
1325    hadError = true;
1326    return;
1327  }
1328
1329  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1330    // Value-initialize the first named member of the union.
1331    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333         Field != FieldEnd; ++Field) {
1334      if (Field->getDeclName()) {
1335        if (VerifyOnly)
1336          CheckValueInitializable(
1337              InitializedEntity::InitializeMember(*Field, &Entity));
1338        else
1339          StructuredList->setInitializedFieldInUnion(*Field);
1340        break;
1341      }
1342    }
1343    return;
1344  }
1345
1346  // If structDecl is a forward declaration, this loop won't do
1347  // anything except look at designated initializers; That's okay,
1348  // because an error should get printed out elsewhere. It might be
1349  // worthwhile to skip over the rest of the initializer, though.
1350  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1351  RecordDecl::field_iterator FieldEnd = RD->field_end();
1352  bool InitializedSomething = false;
1353  bool CheckForMissingFields = true;
1354  while (Index < IList->getNumInits()) {
1355    Expr *Init = IList->getInit(Index);
1356
1357    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1358      // If we're not the subobject that matches up with the '{' for
1359      // the designator, we shouldn't be handling the
1360      // designator. Return immediately.
1361      if (!SubobjectIsDesignatorContext)
1362        return;
1363
1364      // Handle this designated initializer. Field will be updated to
1365      // the next field that we'll be initializing.
1366      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1367                                     DeclType, &Field, 0, Index,
1368                                     StructuredList, StructuredIndex,
1369                                     true, TopLevelObject))
1370        hadError = true;
1371
1372      InitializedSomething = true;
1373
1374      // Disable check for missing fields when designators are used.
1375      // This matches gcc behaviour.
1376      CheckForMissingFields = false;
1377      continue;
1378    }
1379
1380    if (Field == FieldEnd) {
1381      // We've run out of fields. We're done.
1382      break;
1383    }
1384
1385    // We've already initialized a member of a union. We're done.
1386    if (InitializedSomething && DeclType->isUnionType())
1387      break;
1388
1389    // If we've hit the flexible array member at the end, we're done.
1390    if (Field->getType()->isIncompleteArrayType())
1391      break;
1392
1393    if (Field->isUnnamedBitfield()) {
1394      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1395      ++Field;
1396      continue;
1397    }
1398
1399    // Make sure we can use this declaration.
1400    bool InvalidUse;
1401    if (VerifyOnly)
1402      InvalidUse = !SemaRef.CanUseDecl(*Field);
1403    else
1404      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405                                          IList->getInit(Index)->getLocStart());
1406    if (InvalidUse) {
1407      ++Index;
1408      ++Field;
1409      hadError = true;
1410      continue;
1411    }
1412
1413    InitializedEntity MemberEntity =
1414      InitializedEntity::InitializeMember(*Field, &Entity);
1415    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416                        StructuredList, StructuredIndex);
1417    InitializedSomething = true;
1418
1419    if (DeclType->isUnionType() && !VerifyOnly) {
1420      // Initialize the first field within the union.
1421      StructuredList->setInitializedFieldInUnion(*Field);
1422    }
1423
1424    ++Field;
1425  }
1426
1427  // Emit warnings for missing struct field initializers.
1428  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429      Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430      !DeclType->isUnionType()) {
1431    // It is possible we have one or more unnamed bitfields remaining.
1432    // Find first (if any) named field and emit warning.
1433    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434         it != end; ++it) {
1435      if (!it->isUnnamedBitfield()) {
1436        SemaRef.Diag(IList->getSourceRange().getEnd(),
1437                     diag::warn_missing_field_initializers) << it->getName();
1438        break;
1439      }
1440    }
1441  }
1442
1443  // Check that any remaining fields can be value-initialized.
1444  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445      !Field->getType()->isIncompleteArrayType()) {
1446    // FIXME: Should check for holes left by designated initializers too.
1447    for (; Field != FieldEnd && !hadError; ++Field) {
1448      if (!Field->isUnnamedBitfield())
1449        CheckValueInitializable(
1450            InitializedEntity::InitializeMember(*Field, &Entity));
1451    }
1452  }
1453
1454  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1455      Index >= IList->getNumInits())
1456    return;
1457
1458  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459                             TopLevelObject)) {
1460    hadError = true;
1461    ++Index;
1462    return;
1463  }
1464
1465  InitializedEntity MemberEntity =
1466    InitializedEntity::InitializeMember(*Field, &Entity);
1467
1468  if (isa<InitListExpr>(IList->getInit(Index)))
1469    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1470                        StructuredList, StructuredIndex);
1471  else
1472    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1473                          StructuredList, StructuredIndex);
1474}
1475
1476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
1480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1481                                           DesignatedInitExpr *DIE,
1482                                           unsigned DesigIdx,
1483                                           IndirectFieldDecl *IndirectField) {
1484  typedef DesignatedInitExpr::Designator Designator;
1485
1486  // Build the replacement designators.
1487  SmallVector<Designator, 4> Replacements;
1488  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489       PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490    if (PI + 1 == PE)
1491      Replacements.push_back(Designator((IdentifierInfo *)0,
1492                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1493                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494    else
1495      Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496                                        SourceLocation()));
1497    assert(isa<FieldDecl>(*PI));
1498    Replacements.back().setField(cast<FieldDecl>(*PI));
1499  }
1500
1501  // Expand the current designator into the set of replacement
1502  // designators, so we have a full subobject path down to where the
1503  // member of the anonymous struct/union is actually stored.
1504  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1505                        &Replacements[0] + Replacements.size());
1506}
1507
1508/// \brief Given an implicit anonymous field, search the IndirectField that
1509///  corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511                                                 IdentifierInfo *FieldName) {
1512  assert(AnonField->isAnonymousStructOrUnion());
1513  Decl *NextDecl = AnonField->getNextDeclInContext();
1514  while (IndirectFieldDecl *IF =
1515          dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1516    if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1517      return IF;
1518    NextDecl = NextDecl->getNextDeclInContext();
1519  }
1520  return 0;
1521}
1522
1523static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1524                                                   DesignatedInitExpr *DIE) {
1525  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1526  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1527  for (unsigned I = 0; I < NumIndexExprs; ++I)
1528    IndexExprs[I] = DIE->getSubExpr(I + 1);
1529  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1530                                    DIE->size(), IndexExprs.data(),
1531                                    NumIndexExprs, DIE->getEqualOrColonLoc(),
1532                                    DIE->usesGNUSyntax(), DIE->getInit());
1533}
1534
1535namespace {
1536
1537// Callback to only accept typo corrections that are for field members of
1538// the given struct or union.
1539class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1540 public:
1541  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1542      : Record(RD) {}
1543
1544  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1545    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1546    return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1547  }
1548
1549 private:
1550  RecordDecl *Record;
1551};
1552
1553}
1554
1555/// @brief Check the well-formedness of a C99 designated initializer.
1556///
1557/// Determines whether the designated initializer @p DIE, which
1558/// resides at the given @p Index within the initializer list @p
1559/// IList, is well-formed for a current object of type @p DeclType
1560/// (C99 6.7.8). The actual subobject that this designator refers to
1561/// within the current subobject is returned in either
1562/// @p NextField or @p NextElementIndex (whichever is appropriate).
1563///
1564/// @param IList  The initializer list in which this designated
1565/// initializer occurs.
1566///
1567/// @param DIE The designated initializer expression.
1568///
1569/// @param DesigIdx  The index of the current designator.
1570///
1571/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
1572/// into which the designation in @p DIE should refer.
1573///
1574/// @param NextField  If non-NULL and the first designator in @p DIE is
1575/// a field, this will be set to the field declaration corresponding
1576/// to the field named by the designator.
1577///
1578/// @param NextElementIndex  If non-NULL and the first designator in @p
1579/// DIE is an array designator or GNU array-range designator, this
1580/// will be set to the last index initialized by this designator.
1581///
1582/// @param Index  Index into @p IList where the designated initializer
1583/// @p DIE occurs.
1584///
1585/// @param StructuredList  The initializer list expression that
1586/// describes all of the subobject initializers in the order they'll
1587/// actually be initialized.
1588///
1589/// @returns true if there was an error, false otherwise.
1590bool
1591InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1592                                            InitListExpr *IList,
1593                                            DesignatedInitExpr *DIE,
1594                                            unsigned DesigIdx,
1595                                            QualType &CurrentObjectType,
1596                                          RecordDecl::field_iterator *NextField,
1597                                            llvm::APSInt *NextElementIndex,
1598                                            unsigned &Index,
1599                                            InitListExpr *StructuredList,
1600                                            unsigned &StructuredIndex,
1601                                            bool FinishSubobjectInit,
1602                                            bool TopLevelObject) {
1603  if (DesigIdx == DIE->size()) {
1604    // Check the actual initialization for the designated object type.
1605    bool prevHadError = hadError;
1606
1607    // Temporarily remove the designator expression from the
1608    // initializer list that the child calls see, so that we don't try
1609    // to re-process the designator.
1610    unsigned OldIndex = Index;
1611    IList->setInit(OldIndex, DIE->getInit());
1612
1613    CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1614                        StructuredList, StructuredIndex);
1615
1616    // Restore the designated initializer expression in the syntactic
1617    // form of the initializer list.
1618    if (IList->getInit(OldIndex) != DIE->getInit())
1619      DIE->setInit(IList->getInit(OldIndex));
1620    IList->setInit(OldIndex, DIE);
1621
1622    return hadError && !prevHadError;
1623  }
1624
1625  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1626  bool IsFirstDesignator = (DesigIdx == 0);
1627  if (!VerifyOnly) {
1628    assert((IsFirstDesignator || StructuredList) &&
1629           "Need a non-designated initializer list to start from");
1630
1631    // Determine the structural initializer list that corresponds to the
1632    // current subobject.
1633    StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1634      : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1635                                   StructuredList, StructuredIndex,
1636                                   SourceRange(D->getStartLocation(),
1637                                               DIE->getSourceRange().getEnd()));
1638    assert(StructuredList && "Expected a structured initializer list");
1639  }
1640
1641  if (D->isFieldDesignator()) {
1642    // C99 6.7.8p7:
1643    //
1644    //   If a designator has the form
1645    //
1646    //      . identifier
1647    //
1648    //   then the current object (defined below) shall have
1649    //   structure or union type and the identifier shall be the
1650    //   name of a member of that type.
1651    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1652    if (!RT) {
1653      SourceLocation Loc = D->getDotLoc();
1654      if (Loc.isInvalid())
1655        Loc = D->getFieldLoc();
1656      if (!VerifyOnly)
1657        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1658          << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1659      ++Index;
1660      return true;
1661    }
1662
1663    // Note: we perform a linear search of the fields here, despite
1664    // the fact that we have a faster lookup method, because we always
1665    // need to compute the field's index.
1666    FieldDecl *KnownField = D->getField();
1667    IdentifierInfo *FieldName = D->getFieldName();
1668    unsigned FieldIndex = 0;
1669    RecordDecl::field_iterator
1670      Field = RT->getDecl()->field_begin(),
1671      FieldEnd = RT->getDecl()->field_end();
1672    for (; Field != FieldEnd; ++Field) {
1673      if (Field->isUnnamedBitfield())
1674        continue;
1675
1676      // If we find a field representing an anonymous field, look in the
1677      // IndirectFieldDecl that follow for the designated initializer.
1678      if (!KnownField && Field->isAnonymousStructOrUnion()) {
1679        if (IndirectFieldDecl *IF =
1680            FindIndirectFieldDesignator(*Field, FieldName)) {
1681          // In verify mode, don't modify the original.
1682          if (VerifyOnly)
1683            DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1684          ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1685          D = DIE->getDesignator(DesigIdx);
1686          break;
1687        }
1688      }
1689      if (KnownField && KnownField == *Field)
1690        break;
1691      if (FieldName && FieldName == Field->getIdentifier())
1692        break;
1693
1694      ++FieldIndex;
1695    }
1696
1697    if (Field == FieldEnd) {
1698      if (VerifyOnly) {
1699        ++Index;
1700        return true; // No typo correction when just trying this out.
1701      }
1702
1703      // There was no normal field in the struct with the designated
1704      // name. Perform another lookup for this name, which may find
1705      // something that we can't designate (e.g., a member function),
1706      // may find nothing, or may find a member of an anonymous
1707      // struct/union.
1708      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1709      FieldDecl *ReplacementField = 0;
1710      if (Lookup.first == Lookup.second) {
1711        // Name lookup didn't find anything. Determine whether this
1712        // was a typo for another field name.
1713        FieldInitializerValidatorCCC Validator(RT->getDecl());
1714        TypoCorrection Corrected = SemaRef.CorrectTypo(
1715            DeclarationNameInfo(FieldName, D->getFieldLoc()),
1716            Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
1717            RT->getDecl());
1718        if (Corrected) {
1719          std::string CorrectedStr(
1720              Corrected.getAsString(SemaRef.getLangOptions()));
1721          std::string CorrectedQuotedStr(
1722              Corrected.getQuoted(SemaRef.getLangOptions()));
1723          ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1724          SemaRef.Diag(D->getFieldLoc(),
1725                       diag::err_field_designator_unknown_suggest)
1726            << FieldName << CurrentObjectType << CorrectedQuotedStr
1727            << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1728          SemaRef.Diag(ReplacementField->getLocation(),
1729                       diag::note_previous_decl) << CorrectedQuotedStr;
1730          hadError = true;
1731        } else {
1732          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1733            << FieldName << CurrentObjectType;
1734          ++Index;
1735          return true;
1736        }
1737      }
1738
1739      if (!ReplacementField) {
1740        // Name lookup found something, but it wasn't a field.
1741        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1742          << FieldName;
1743        SemaRef.Diag((*Lookup.first)->getLocation(),
1744                      diag::note_field_designator_found);
1745        ++Index;
1746        return true;
1747      }
1748
1749      if (!KnownField) {
1750        // The replacement field comes from typo correction; find it
1751        // in the list of fields.
1752        FieldIndex = 0;
1753        Field = RT->getDecl()->field_begin();
1754        for (; Field != FieldEnd; ++Field) {
1755          if (Field->isUnnamedBitfield())
1756            continue;
1757
1758          if (ReplacementField == *Field ||
1759              Field->getIdentifier() == ReplacementField->getIdentifier())
1760            break;
1761
1762          ++FieldIndex;
1763        }
1764      }
1765    }
1766
1767    // All of the fields of a union are located at the same place in
1768    // the initializer list.
1769    if (RT->getDecl()->isUnion()) {
1770      FieldIndex = 0;
1771      if (!VerifyOnly)
1772        StructuredList->setInitializedFieldInUnion(*Field);
1773    }
1774
1775    // Make sure we can use this declaration.
1776    bool InvalidUse;
1777    if (VerifyOnly)
1778      InvalidUse = !SemaRef.CanUseDecl(*Field);
1779    else
1780      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1781    if (InvalidUse) {
1782      ++Index;
1783      return true;
1784    }
1785
1786    if (!VerifyOnly) {
1787      // Update the designator with the field declaration.
1788      D->setField(*Field);
1789
1790      // Make sure that our non-designated initializer list has space
1791      // for a subobject corresponding to this field.
1792      if (FieldIndex >= StructuredList->getNumInits())
1793        StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1794    }
1795
1796    // This designator names a flexible array member.
1797    if (Field->getType()->isIncompleteArrayType()) {
1798      bool Invalid = false;
1799      if ((DesigIdx + 1) != DIE->size()) {
1800        // We can't designate an object within the flexible array
1801        // member (because GCC doesn't allow it).
1802        if (!VerifyOnly) {
1803          DesignatedInitExpr::Designator *NextD
1804            = DIE->getDesignator(DesigIdx + 1);
1805          SemaRef.Diag(NextD->getStartLocation(),
1806                        diag::err_designator_into_flexible_array_member)
1807            << SourceRange(NextD->getStartLocation(),
1808                           DIE->getSourceRange().getEnd());
1809          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1810            << *Field;
1811        }
1812        Invalid = true;
1813      }
1814
1815      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1816          !isa<StringLiteral>(DIE->getInit())) {
1817        // The initializer is not an initializer list.
1818        if (!VerifyOnly) {
1819          SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1820                        diag::err_flexible_array_init_needs_braces)
1821            << DIE->getInit()->getSourceRange();
1822          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1823            << *Field;
1824        }
1825        Invalid = true;
1826      }
1827
1828      // Check GNU flexible array initializer.
1829      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1830                                             TopLevelObject))
1831        Invalid = true;
1832
1833      if (Invalid) {
1834        ++Index;
1835        return true;
1836      }
1837
1838      // Initialize the array.
1839      bool prevHadError = hadError;
1840      unsigned newStructuredIndex = FieldIndex;
1841      unsigned OldIndex = Index;
1842      IList->setInit(Index, DIE->getInit());
1843
1844      InitializedEntity MemberEntity =
1845        InitializedEntity::InitializeMember(*Field, &Entity);
1846      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1847                          StructuredList, newStructuredIndex);
1848
1849      IList->setInit(OldIndex, DIE);
1850      if (hadError && !prevHadError) {
1851        ++Field;
1852        ++FieldIndex;
1853        if (NextField)
1854          *NextField = Field;
1855        StructuredIndex = FieldIndex;
1856        return true;
1857      }
1858    } else {
1859      // Recurse to check later designated subobjects.
1860      QualType FieldType = (*Field)->getType();
1861      unsigned newStructuredIndex = FieldIndex;
1862
1863      InitializedEntity MemberEntity =
1864        InitializedEntity::InitializeMember(*Field, &Entity);
1865      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1866                                     FieldType, 0, 0, Index,
1867                                     StructuredList, newStructuredIndex,
1868                                     true, false))
1869        return true;
1870    }
1871
1872    // Find the position of the next field to be initialized in this
1873    // subobject.
1874    ++Field;
1875    ++FieldIndex;
1876
1877    // If this the first designator, our caller will continue checking
1878    // the rest of this struct/class/union subobject.
1879    if (IsFirstDesignator) {
1880      if (NextField)
1881        *NextField = Field;
1882      StructuredIndex = FieldIndex;
1883      return false;
1884    }
1885
1886    if (!FinishSubobjectInit)
1887      return false;
1888
1889    // We've already initialized something in the union; we're done.
1890    if (RT->getDecl()->isUnion())
1891      return hadError;
1892
1893    // Check the remaining fields within this class/struct/union subobject.
1894    bool prevHadError = hadError;
1895
1896    CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1897                          StructuredList, FieldIndex);
1898    return hadError && !prevHadError;
1899  }
1900
1901  // C99 6.7.8p6:
1902  //
1903  //   If a designator has the form
1904  //
1905  //      [ constant-expression ]
1906  //
1907  //   then the current object (defined below) shall have array
1908  //   type and the expression shall be an integer constant
1909  //   expression. If the array is of unknown size, any
1910  //   nonnegative value is valid.
1911  //
1912  // Additionally, cope with the GNU extension that permits
1913  // designators of the form
1914  //
1915  //      [ constant-expression ... constant-expression ]
1916  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1917  if (!AT) {
1918    if (!VerifyOnly)
1919      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1920        << CurrentObjectType;
1921    ++Index;
1922    return true;
1923  }
1924
1925  Expr *IndexExpr = 0;
1926  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1927  if (D->isArrayDesignator()) {
1928    IndexExpr = DIE->getArrayIndex(*D);
1929    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
1930    DesignatedEndIndex = DesignatedStartIndex;
1931  } else {
1932    assert(D->isArrayRangeDesignator() && "Need array-range designator");
1933
1934    DesignatedStartIndex =
1935      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
1936    DesignatedEndIndex =
1937      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
1938    IndexExpr = DIE->getArrayRangeEnd(*D);
1939
1940    // Codegen can't handle evaluating array range designators that have side
1941    // effects, because we replicate the AST value for each initialized element.
1942    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1943    // elements with something that has a side effect, so codegen can emit an
1944    // "error unsupported" error instead of miscompiling the app.
1945    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1946        DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
1947      FullyStructuredList->sawArrayRangeDesignator();
1948  }
1949
1950  if (isa<ConstantArrayType>(AT)) {
1951    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1952    DesignatedStartIndex
1953      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1954    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1955    DesignatedEndIndex
1956      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1957    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1958    if (DesignatedEndIndex >= MaxElements) {
1959      if (!VerifyOnly)
1960        SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1961                      diag::err_array_designator_too_large)
1962          << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1963          << IndexExpr->getSourceRange();
1964      ++Index;
1965      return true;
1966    }
1967  } else {
1968    // Make sure the bit-widths and signedness match.
1969    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1970      DesignatedEndIndex
1971        = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1972    else if (DesignatedStartIndex.getBitWidth() <
1973             DesignatedEndIndex.getBitWidth())
1974      DesignatedStartIndex
1975        = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1976    DesignatedStartIndex.setIsUnsigned(true);
1977    DesignatedEndIndex.setIsUnsigned(true);
1978  }
1979
1980  // Make sure that our non-designated initializer list has space
1981  // for a subobject corresponding to this array element.
1982  if (!VerifyOnly &&
1983      DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1984    StructuredList->resizeInits(SemaRef.Context,
1985                                DesignatedEndIndex.getZExtValue() + 1);
1986
1987  // Repeatedly perform subobject initializations in the range
1988  // [DesignatedStartIndex, DesignatedEndIndex].
1989
1990  // Move to the next designator
1991  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1992  unsigned OldIndex = Index;
1993
1994  InitializedEntity ElementEntity =
1995    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1996
1997  while (DesignatedStartIndex <= DesignatedEndIndex) {
1998    // Recurse to check later designated subobjects.
1999    QualType ElementType = AT->getElementType();
2000    Index = OldIndex;
2001
2002    ElementEntity.setElementIndex(ElementIndex);
2003    if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2004                                   ElementType, 0, 0, Index,
2005                                   StructuredList, ElementIndex,
2006                                   (DesignatedStartIndex == DesignatedEndIndex),
2007                                   false))
2008      return true;
2009
2010    // Move to the next index in the array that we'll be initializing.
2011    ++DesignatedStartIndex;
2012    ElementIndex = DesignatedStartIndex.getZExtValue();
2013  }
2014
2015  // If this the first designator, our caller will continue checking
2016  // the rest of this array subobject.
2017  if (IsFirstDesignator) {
2018    if (NextElementIndex)
2019      *NextElementIndex = DesignatedStartIndex;
2020    StructuredIndex = ElementIndex;
2021    return false;
2022  }
2023
2024  if (!FinishSubobjectInit)
2025    return false;
2026
2027  // Check the remaining elements within this array subobject.
2028  bool prevHadError = hadError;
2029  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2030                 /*SubobjectIsDesignatorContext=*/false, Index,
2031                 StructuredList, ElementIndex);
2032  return hadError && !prevHadError;
2033}
2034
2035// Get the structured initializer list for a subobject of type
2036// @p CurrentObjectType.
2037InitListExpr *
2038InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2039                                            QualType CurrentObjectType,
2040                                            InitListExpr *StructuredList,
2041                                            unsigned StructuredIndex,
2042                                            SourceRange InitRange) {
2043  if (VerifyOnly)
2044    return 0; // No structured list in verification-only mode.
2045  Expr *ExistingInit = 0;
2046  if (!StructuredList)
2047    ExistingInit = SyntacticToSemantic[IList];
2048  else if (StructuredIndex < StructuredList->getNumInits())
2049    ExistingInit = StructuredList->getInit(StructuredIndex);
2050
2051  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2052    return Result;
2053
2054  if (ExistingInit) {
2055    // We are creating an initializer list that initializes the
2056    // subobjects of the current object, but there was already an
2057    // initialization that completely initialized the current
2058    // subobject, e.g., by a compound literal:
2059    //
2060    // struct X { int a, b; };
2061    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2062    //
2063    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2064    // designated initializer re-initializes the whole
2065    // subobject [0], overwriting previous initializers.
2066    SemaRef.Diag(InitRange.getBegin(),
2067                 diag::warn_subobject_initializer_overrides)
2068      << InitRange;
2069    SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
2070                  diag::note_previous_initializer)
2071      << /*FIXME:has side effects=*/0
2072      << ExistingInit->getSourceRange();
2073  }
2074
2075  InitListExpr *Result
2076    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2077                                         InitRange.getBegin(), 0, 0,
2078                                         InitRange.getEnd());
2079
2080  Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
2081
2082  // Pre-allocate storage for the structured initializer list.
2083  unsigned NumElements = 0;
2084  unsigned NumInits = 0;
2085  bool GotNumInits = false;
2086  if (!StructuredList) {
2087    NumInits = IList->getNumInits();
2088    GotNumInits = true;
2089  } else if (Index < IList->getNumInits()) {
2090    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2091      NumInits = SubList->getNumInits();
2092      GotNumInits = true;
2093    }
2094  }
2095
2096  if (const ArrayType *AType
2097      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2098    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2099      NumElements = CAType->getSize().getZExtValue();
2100      // Simple heuristic so that we don't allocate a very large
2101      // initializer with many empty entries at the end.
2102      if (GotNumInits && NumElements > NumInits)
2103        NumElements = 0;
2104    }
2105  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2106    NumElements = VType->getNumElements();
2107  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2108    RecordDecl *RDecl = RType->getDecl();
2109    if (RDecl->isUnion())
2110      NumElements = 1;
2111    else
2112      NumElements = std::distance(RDecl->field_begin(),
2113                                  RDecl->field_end());
2114  }
2115
2116  Result->reserveInits(SemaRef.Context, NumElements);
2117
2118  // Link this new initializer list into the structured initializer
2119  // lists.
2120  if (StructuredList)
2121    StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2122  else {
2123    Result->setSyntacticForm(IList);
2124    SyntacticToSemantic[IList] = Result;
2125  }
2126
2127  return Result;
2128}
2129
2130/// Update the initializer at index @p StructuredIndex within the
2131/// structured initializer list to the value @p expr.
2132void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2133                                                  unsigned &StructuredIndex,
2134                                                  Expr *expr) {
2135  // No structured initializer list to update
2136  if (!StructuredList)
2137    return;
2138
2139  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2140                                                  StructuredIndex, expr)) {
2141    // This initializer overwrites a previous initializer. Warn.
2142    SemaRef.Diag(expr->getSourceRange().getBegin(),
2143                  diag::warn_initializer_overrides)
2144      << expr->getSourceRange();
2145    SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
2146                  diag::note_previous_initializer)
2147      << /*FIXME:has side effects=*/0
2148      << PrevInit->getSourceRange();
2149  }
2150
2151  ++StructuredIndex;
2152}
2153
2154/// Check that the given Index expression is a valid array designator
2155/// value. This is essentially just a wrapper around
2156/// VerifyIntegerConstantExpression that also checks for negative values
2157/// and produces a reasonable diagnostic if there is a
2158/// failure. Returns the index expression, possibly with an implicit cast
2159/// added, on success.  If everything went okay, Value will receive the
2160/// value of the constant expression.
2161static ExprResult
2162CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2163  SourceLocation Loc = Index->getSourceRange().getBegin();
2164
2165  // Make sure this is an integer constant expression.
2166  ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2167  if (Result.isInvalid())
2168    return Result;
2169
2170  if (Value.isSigned() && Value.isNegative())
2171    return S.Diag(Loc, diag::err_array_designator_negative)
2172      << Value.toString(10) << Index->getSourceRange();
2173
2174  Value.setIsUnsigned(true);
2175  return Result;
2176}
2177
2178ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2179                                            SourceLocation Loc,
2180                                            bool GNUSyntax,
2181                                            ExprResult Init) {
2182  typedef DesignatedInitExpr::Designator ASTDesignator;
2183
2184  bool Invalid = false;
2185  SmallVector<ASTDesignator, 32> Designators;
2186  SmallVector<Expr *, 32> InitExpressions;
2187
2188  // Build designators and check array designator expressions.
2189  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2190    const Designator &D = Desig.getDesignator(Idx);
2191    switch (D.getKind()) {
2192    case Designator::FieldDesignator:
2193      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2194                                          D.getFieldLoc()));
2195      break;
2196
2197    case Designator::ArrayDesignator: {
2198      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2199      llvm::APSInt IndexValue;
2200      if (!Index->isTypeDependent() && !Index->isValueDependent())
2201        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2202      if (!Index)
2203        Invalid = true;
2204      else {
2205        Designators.push_back(ASTDesignator(InitExpressions.size(),
2206                                            D.getLBracketLoc(),
2207                                            D.getRBracketLoc()));
2208        InitExpressions.push_back(Index);
2209      }
2210      break;
2211    }
2212
2213    case Designator::ArrayRangeDesignator: {
2214      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2215      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2216      llvm::APSInt StartValue;
2217      llvm::APSInt EndValue;
2218      bool StartDependent = StartIndex->isTypeDependent() ||
2219                            StartIndex->isValueDependent();
2220      bool EndDependent = EndIndex->isTypeDependent() ||
2221                          EndIndex->isValueDependent();
2222      if (!StartDependent)
2223        StartIndex =
2224            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2225      if (!EndDependent)
2226        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2227
2228      if (!StartIndex || !EndIndex)
2229        Invalid = true;
2230      else {
2231        // Make sure we're comparing values with the same bit width.
2232        if (StartDependent || EndDependent) {
2233          // Nothing to compute.
2234        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2235          EndValue = EndValue.extend(StartValue.getBitWidth());
2236        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2237          StartValue = StartValue.extend(EndValue.getBitWidth());
2238
2239        if (!StartDependent && !EndDependent && EndValue < StartValue) {
2240          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2241            << StartValue.toString(10) << EndValue.toString(10)
2242            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2243          Invalid = true;
2244        } else {
2245          Designators.push_back(ASTDesignator(InitExpressions.size(),
2246                                              D.getLBracketLoc(),
2247                                              D.getEllipsisLoc(),
2248                                              D.getRBracketLoc()));
2249          InitExpressions.push_back(StartIndex);
2250          InitExpressions.push_back(EndIndex);
2251        }
2252      }
2253      break;
2254    }
2255    }
2256  }
2257
2258  if (Invalid || Init.isInvalid())
2259    return ExprError();
2260
2261  // Clear out the expressions within the designation.
2262  Desig.ClearExprs(*this);
2263
2264  DesignatedInitExpr *DIE
2265    = DesignatedInitExpr::Create(Context,
2266                                 Designators.data(), Designators.size(),
2267                                 InitExpressions.data(), InitExpressions.size(),
2268                                 Loc, GNUSyntax, Init.takeAs<Expr>());
2269
2270  if (!getLangOptions().C99)
2271    Diag(DIE->getLocStart(), diag::ext_designated_init)
2272      << DIE->getSourceRange();
2273
2274  return Owned(DIE);
2275}
2276
2277//===----------------------------------------------------------------------===//
2278// Initialization entity
2279//===----------------------------------------------------------------------===//
2280
2281InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2282                                     const InitializedEntity &Parent)
2283  : Parent(&Parent), Index(Index)
2284{
2285  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2286    Kind = EK_ArrayElement;
2287    Type = AT->getElementType();
2288  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2289    Kind = EK_VectorElement;
2290    Type = VT->getElementType();
2291  } else {
2292    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2293    assert(CT && "Unexpected type");
2294    Kind = EK_ComplexElement;
2295    Type = CT->getElementType();
2296  }
2297}
2298
2299InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2300                                                    CXXBaseSpecifier *Base,
2301                                                    bool IsInheritedVirtualBase)
2302{
2303  InitializedEntity Result;
2304  Result.Kind = EK_Base;
2305  Result.Base = reinterpret_cast<uintptr_t>(Base);
2306  if (IsInheritedVirtualBase)
2307    Result.Base |= 0x01;
2308
2309  Result.Type = Base->getType();
2310  return Result;
2311}
2312
2313DeclarationName InitializedEntity::getName() const {
2314  switch (getKind()) {
2315  case EK_Parameter: {
2316    ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2317    return (D ? D->getDeclName() : DeclarationName());
2318  }
2319
2320  case EK_Variable:
2321  case EK_Member:
2322    return VariableOrMember->getDeclName();
2323
2324  case EK_Result:
2325  case EK_Exception:
2326  case EK_New:
2327  case EK_Temporary:
2328  case EK_Base:
2329  case EK_Delegating:
2330  case EK_ArrayElement:
2331  case EK_VectorElement:
2332  case EK_ComplexElement:
2333  case EK_BlockElement:
2334    return DeclarationName();
2335  }
2336
2337  llvm_unreachable("Invalid EntityKind!");
2338}
2339
2340DeclaratorDecl *InitializedEntity::getDecl() const {
2341  switch (getKind()) {
2342  case EK_Variable:
2343  case EK_Member:
2344    return VariableOrMember;
2345
2346  case EK_Parameter:
2347    return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2348
2349  case EK_Result:
2350  case EK_Exception:
2351  case EK_New:
2352  case EK_Temporary:
2353  case EK_Base:
2354  case EK_Delegating:
2355  case EK_ArrayElement:
2356  case EK_VectorElement:
2357  case EK_ComplexElement:
2358  case EK_BlockElement:
2359    return 0;
2360  }
2361
2362  llvm_unreachable("Invalid EntityKind!");
2363}
2364
2365bool InitializedEntity::allowsNRVO() const {
2366  switch (getKind()) {
2367  case EK_Result:
2368  case EK_Exception:
2369    return LocAndNRVO.NRVO;
2370
2371  case EK_Variable:
2372  case EK_Parameter:
2373  case EK_Member:
2374  case EK_New:
2375  case EK_Temporary:
2376  case EK_Base:
2377  case EK_Delegating:
2378  case EK_ArrayElement:
2379  case EK_VectorElement:
2380  case EK_ComplexElement:
2381  case EK_BlockElement:
2382    break;
2383  }
2384
2385  return false;
2386}
2387
2388//===----------------------------------------------------------------------===//
2389// Initialization sequence
2390//===----------------------------------------------------------------------===//
2391
2392void InitializationSequence::Step::Destroy() {
2393  switch (Kind) {
2394  case SK_ResolveAddressOfOverloadedFunction:
2395  case SK_CastDerivedToBaseRValue:
2396  case SK_CastDerivedToBaseXValue:
2397  case SK_CastDerivedToBaseLValue:
2398  case SK_BindReference:
2399  case SK_BindReferenceToTemporary:
2400  case SK_ExtraneousCopyToTemporary:
2401  case SK_UserConversion:
2402  case SK_QualificationConversionRValue:
2403  case SK_QualificationConversionXValue:
2404  case SK_QualificationConversionLValue:
2405  case SK_ListInitialization:
2406  case SK_ListConstructorCall:
2407  case SK_UnwrapInitList:
2408  case SK_RewrapInitList:
2409  case SK_ConstructorInitialization:
2410  case SK_ZeroInitialization:
2411  case SK_CAssignment:
2412  case SK_StringInit:
2413  case SK_ObjCObjectConversion:
2414  case SK_ArrayInit:
2415  case SK_PassByIndirectCopyRestore:
2416  case SK_PassByIndirectRestore:
2417  case SK_ProduceObjCObject:
2418  case SK_StdInitializerList:
2419    break;
2420
2421  case SK_ConversionSequence:
2422    delete ICS;
2423  }
2424}
2425
2426bool InitializationSequence::isDirectReferenceBinding() const {
2427  return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2428}
2429
2430bool InitializationSequence::isAmbiguous() const {
2431  if (!Failed())
2432    return false;
2433
2434  switch (getFailureKind()) {
2435  case FK_TooManyInitsForReference:
2436  case FK_ArrayNeedsInitList:
2437  case FK_ArrayNeedsInitListOrStringLiteral:
2438  case FK_AddressOfOverloadFailed: // FIXME: Could do better
2439  case FK_NonConstLValueReferenceBindingToTemporary:
2440  case FK_NonConstLValueReferenceBindingToUnrelated:
2441  case FK_RValueReferenceBindingToLValue:
2442  case FK_ReferenceInitDropsQualifiers:
2443  case FK_ReferenceInitFailed:
2444  case FK_ConversionFailed:
2445  case FK_ConversionFromPropertyFailed:
2446  case FK_TooManyInitsForScalar:
2447  case FK_ReferenceBindingToInitList:
2448  case FK_InitListBadDestinationType:
2449  case FK_DefaultInitOfConst:
2450  case FK_Incomplete:
2451  case FK_ArrayTypeMismatch:
2452  case FK_NonConstantArrayInit:
2453  case FK_ListInitializationFailed:
2454  case FK_VariableLengthArrayHasInitializer:
2455  case FK_PlaceholderType:
2456  case FK_InitListElementCopyFailure:
2457    return false;
2458
2459  case FK_ReferenceInitOverloadFailed:
2460  case FK_UserConversionOverloadFailed:
2461  case FK_ConstructorOverloadFailed:
2462  case FK_ListConstructorOverloadFailed:
2463    return FailedOverloadResult == OR_Ambiguous;
2464  }
2465
2466  llvm_unreachable("Invalid EntityKind!");
2467}
2468
2469bool InitializationSequence::isConstructorInitialization() const {
2470  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2471}
2472
2473void
2474InitializationSequence
2475::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2476                                   DeclAccessPair Found,
2477                                   bool HadMultipleCandidates) {
2478  Step S;
2479  S.Kind = SK_ResolveAddressOfOverloadedFunction;
2480  S.Type = Function->getType();
2481  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2482  S.Function.Function = Function;
2483  S.Function.FoundDecl = Found;
2484  Steps.push_back(S);
2485}
2486
2487void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2488                                                      ExprValueKind VK) {
2489  Step S;
2490  switch (VK) {
2491  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2492  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2493  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2494  }
2495  S.Type = BaseType;
2496  Steps.push_back(S);
2497}
2498
2499void InitializationSequence::AddReferenceBindingStep(QualType T,
2500                                                     bool BindingTemporary) {
2501  Step S;
2502  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2503  S.Type = T;
2504  Steps.push_back(S);
2505}
2506
2507void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2508  Step S;
2509  S.Kind = SK_ExtraneousCopyToTemporary;
2510  S.Type = T;
2511  Steps.push_back(S);
2512}
2513
2514void
2515InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2516                                              DeclAccessPair FoundDecl,
2517                                              QualType T,
2518                                              bool HadMultipleCandidates) {
2519  Step S;
2520  S.Kind = SK_UserConversion;
2521  S.Type = T;
2522  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2523  S.Function.Function = Function;
2524  S.Function.FoundDecl = FoundDecl;
2525  Steps.push_back(S);
2526}
2527
2528void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2529                                                            ExprValueKind VK) {
2530  Step S;
2531  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2532  switch (VK) {
2533  case VK_RValue:
2534    S.Kind = SK_QualificationConversionRValue;
2535    break;
2536  case VK_XValue:
2537    S.Kind = SK_QualificationConversionXValue;
2538    break;
2539  case VK_LValue:
2540    S.Kind = SK_QualificationConversionLValue;
2541    break;
2542  }
2543  S.Type = Ty;
2544  Steps.push_back(S);
2545}
2546
2547void InitializationSequence::AddConversionSequenceStep(
2548                                       const ImplicitConversionSequence &ICS,
2549                                                       QualType T) {
2550  Step S;
2551  S.Kind = SK_ConversionSequence;
2552  S.Type = T;
2553  S.ICS = new ImplicitConversionSequence(ICS);
2554  Steps.push_back(S);
2555}
2556
2557void InitializationSequence::AddListInitializationStep(QualType T) {
2558  Step S;
2559  S.Kind = SK_ListInitialization;
2560  S.Type = T;
2561  Steps.push_back(S);
2562}
2563
2564void
2565InitializationSequence
2566::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2567                                   AccessSpecifier Access,
2568                                   QualType T,
2569                                   bool HadMultipleCandidates,
2570                                   bool FromInitList, bool AsInitList) {
2571  Step S;
2572  S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2573                                       : SK_ConstructorInitialization;
2574  S.Type = T;
2575  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2576  S.Function.Function = Constructor;
2577  S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2578  Steps.push_back(S);
2579}
2580
2581void InitializationSequence::AddZeroInitializationStep(QualType T) {
2582  Step S;
2583  S.Kind = SK_ZeroInitialization;
2584  S.Type = T;
2585  Steps.push_back(S);
2586}
2587
2588void InitializationSequence::AddCAssignmentStep(QualType T) {
2589  Step S;
2590  S.Kind = SK_CAssignment;
2591  S.Type = T;
2592  Steps.push_back(S);
2593}
2594
2595void InitializationSequence::AddStringInitStep(QualType T) {
2596  Step S;
2597  S.Kind = SK_StringInit;
2598  S.Type = T;
2599  Steps.push_back(S);
2600}
2601
2602void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2603  Step S;
2604  S.Kind = SK_ObjCObjectConversion;
2605  S.Type = T;
2606  Steps.push_back(S);
2607}
2608
2609void InitializationSequence::AddArrayInitStep(QualType T) {
2610  Step S;
2611  S.Kind = SK_ArrayInit;
2612  S.Type = T;
2613  Steps.push_back(S);
2614}
2615
2616void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2617                                                              bool shouldCopy) {
2618  Step s;
2619  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2620                       : SK_PassByIndirectRestore);
2621  s.Type = type;
2622  Steps.push_back(s);
2623}
2624
2625void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2626  Step S;
2627  S.Kind = SK_ProduceObjCObject;
2628  S.Type = T;
2629  Steps.push_back(S);
2630}
2631
2632void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2633  Step S;
2634  S.Kind = SK_StdInitializerList;
2635  S.Type = T;
2636  Steps.push_back(S);
2637}
2638
2639void InitializationSequence::RewrapReferenceInitList(QualType T,
2640                                                     InitListExpr *Syntactic) {
2641  assert(Syntactic->getNumInits() == 1 &&
2642         "Can only rewrap trivial init lists.");
2643  Step S;
2644  S.Kind = SK_UnwrapInitList;
2645  S.Type = Syntactic->getInit(0)->getType();
2646  Steps.insert(Steps.begin(), S);
2647
2648  S.Kind = SK_RewrapInitList;
2649  S.Type = T;
2650  S.WrappingSyntacticList = Syntactic;
2651  Steps.push_back(S);
2652}
2653
2654void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2655                                                OverloadingResult Result) {
2656  setSequenceKind(FailedSequence);
2657  this->Failure = Failure;
2658  this->FailedOverloadResult = Result;
2659}
2660
2661//===----------------------------------------------------------------------===//
2662// Attempt initialization
2663//===----------------------------------------------------------------------===//
2664
2665static void MaybeProduceObjCObject(Sema &S,
2666                                   InitializationSequence &Sequence,
2667                                   const InitializedEntity &Entity) {
2668  if (!S.getLangOptions().ObjCAutoRefCount) return;
2669
2670  /// When initializing a parameter, produce the value if it's marked
2671  /// __attribute__((ns_consumed)).
2672  if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2673    if (!Entity.isParameterConsumed())
2674      return;
2675
2676    assert(Entity.getType()->isObjCRetainableType() &&
2677           "consuming an object of unretainable type?");
2678    Sequence.AddProduceObjCObjectStep(Entity.getType());
2679
2680  /// When initializing a return value, if the return type is a
2681  /// retainable type, then returns need to immediately retain the
2682  /// object.  If an autorelease is required, it will be done at the
2683  /// last instant.
2684  } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2685    if (!Entity.getType()->isObjCRetainableType())
2686      return;
2687
2688    Sequence.AddProduceObjCObjectStep(Entity.getType());
2689  }
2690}
2691
2692/// \brief When initializing from init list via constructor, deal with the
2693/// empty init list and std::initializer_list special cases.
2694///
2695/// \return True if this was a special case, false otherwise.
2696static bool TryListConstructionSpecialCases(Sema &S,
2697                                            InitListExpr *List,
2698                                            CXXRecordDecl *DestRecordDecl,
2699                                            QualType DestType,
2700                                            InitializationSequence &Sequence) {
2701  // C++11 [dcl.init.list]p3:
2702  //   List-initialization of an object of type T is defined as follows:
2703  //   - If the initializer list has no elements and T is a class type with
2704  //     a default constructor, the object is value-initialized.
2705  if (List->getNumInits() == 0) {
2706    if (CXXConstructorDecl *DefaultConstructor =
2707            S.LookupDefaultConstructor(DestRecordDecl)) {
2708      if (DefaultConstructor->isDeleted() ||
2709          S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2710        // Fake an overload resolution failure.
2711        OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2712        DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2713                                              DefaultConstructor->getAccess());
2714        if (FunctionTemplateDecl *ConstructorTmpl =
2715                dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2716          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2717                                         /*ExplicitArgs*/ 0,
2718                                         0, 0, CandidateSet,
2719                                         /*SuppressUserConversions*/ false);
2720        else
2721          S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2722                                 0, 0, CandidateSet,
2723                                 /*SuppressUserConversions*/ false);
2724        Sequence.SetOverloadFailure(
2725                       InitializationSequence::FK_ListConstructorOverloadFailed,
2726                       OR_Deleted);
2727      } else
2728        Sequence.AddConstructorInitializationStep(DefaultConstructor,
2729                                                DefaultConstructor->getAccess(),
2730                                                  DestType,
2731                                                  /*MultipleCandidates=*/false,
2732                                                  /*FromInitList=*/true,
2733                                                  /*AsInitList=*/false);
2734      return true;
2735    }
2736  }
2737
2738  //   - Otherwise, if T is a specialization of std::initializer_list, [...]
2739  QualType E;
2740  if (S.isStdInitializerList(DestType, &E)) {
2741    // Check that each individual element can be copy-constructed. But since we
2742    // have no place to store further information, we'll recalculate everything
2743    // later.
2744    InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2745        S.Context.getConstantArrayType(E,
2746            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2747                        List->getNumInits()),
2748            ArrayType::Normal, 0));
2749    InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2750        0, HiddenArray);
2751    for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2752      Element.setElementIndex(i);
2753      if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2754        Sequence.SetFailed(
2755            InitializationSequence::FK_InitListElementCopyFailure);
2756        return true;
2757      }
2758    }
2759    Sequence.AddStdInitializerListConstructionStep(DestType);
2760    return true;
2761  }
2762
2763  // Not a special case.
2764  return false;
2765}
2766
2767static OverloadingResult
2768ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2769                           Expr **Args, unsigned NumArgs,
2770                           OverloadCandidateSet &CandidateSet,
2771                           DeclContext::lookup_iterator Con,
2772                           DeclContext::lookup_iterator ConEnd,
2773                           OverloadCandidateSet::iterator &Best,
2774                           bool CopyInitializing, bool AllowExplicit,
2775                           bool OnlyListConstructors) {
2776  CandidateSet.clear();
2777
2778  for (; Con != ConEnd; ++Con) {
2779    NamedDecl *D = *Con;
2780    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2781    bool SuppressUserConversions = false;
2782
2783    // Find the constructor (which may be a template).
2784    CXXConstructorDecl *Constructor = 0;
2785    FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2786    if (ConstructorTmpl)
2787      Constructor = cast<CXXConstructorDecl>(
2788                                           ConstructorTmpl->getTemplatedDecl());
2789    else {
2790      Constructor = cast<CXXConstructorDecl>(D);
2791
2792      // If we're performing copy initialization using a copy constructor, we
2793      // suppress user-defined conversions on the arguments.
2794      // FIXME: Move constructors?
2795      if (CopyInitializing && Constructor->isCopyConstructor())
2796        SuppressUserConversions = true;
2797    }
2798
2799    if (!Constructor->isInvalidDecl() &&
2800        (AllowExplicit || !Constructor->isExplicit()) &&
2801        (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
2802      if (ConstructorTmpl)
2803        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2804                                       /*ExplicitArgs*/ 0,
2805                                       Args, NumArgs, CandidateSet,
2806                                       SuppressUserConversions);
2807      else
2808        S.AddOverloadCandidate(Constructor, FoundDecl,
2809                               Args, NumArgs, CandidateSet,
2810                               SuppressUserConversions);
2811    }
2812  }
2813
2814  // Perform overload resolution and return the result.
2815  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2816}
2817
2818/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2819/// enumerates the constructors of the initialized entity and performs overload
2820/// resolution to select the best.
2821/// If InitListSyntax is true, this is list-initialization of a non-aggregate
2822/// class type.
2823static void TryConstructorInitialization(Sema &S,
2824                                         const InitializedEntity &Entity,
2825                                         const InitializationKind &Kind,
2826                                         Expr **Args, unsigned NumArgs,
2827                                         QualType DestType,
2828                                         InitializationSequence &Sequence,
2829                                         bool InitListSyntax = false) {
2830  assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2831         "InitListSyntax must come with a single initializer list argument.");
2832
2833  // Check constructor arguments for self reference.
2834  if (DeclaratorDecl *DD = Entity.getDecl())
2835    // Parameters arguments are occassionially constructed with itself,
2836    // for instance, in recursive functions.  Skip them.
2837    if (!isa<ParmVarDecl>(DD))
2838      for (unsigned i = 0; i < NumArgs; ++i)
2839        S.CheckSelfReference(DD, Args[i]);
2840
2841  // The type we're constructing needs to be complete.
2842  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2843    Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2844    return;
2845  }
2846
2847  const RecordType *DestRecordType = DestType->getAs<RecordType>();
2848  assert(DestRecordType && "Constructor initialization requires record type");
2849  CXXRecordDecl *DestRecordDecl
2850    = cast<CXXRecordDecl>(DestRecordType->getDecl());
2851
2852  if (InitListSyntax &&
2853      TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2854                                      DestRecordDecl, DestType, Sequence))
2855    return;
2856
2857  // Build the candidate set directly in the initialization sequence
2858  // structure, so that it will persist if we fail.
2859  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2860
2861  // Determine whether we are allowed to call explicit constructors or
2862  // explicit conversion operators.
2863  bool AllowExplicit = Kind.AllowExplicit();
2864  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
2865
2866  //   - Otherwise, if T is a class type, constructors are considered. The
2867  //     applicable constructors are enumerated, and the best one is chosen
2868  //     through overload resolution.
2869  DeclContext::lookup_iterator ConStart, ConEnd;
2870  llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
2871
2872  OverloadingResult Result = OR_No_Viable_Function;
2873  OverloadCandidateSet::iterator Best;
2874  bool AsInitializerList = false;
2875
2876  // C++11 [over.match.list]p1:
2877  //   When objects of non-aggregate type T are list-initialized, overload
2878  //   resolution selects the constructor in two phases:
2879  //   - Initially, the candidate functions are the initializer-list
2880  //     constructors of the class T and the argument list consists of the
2881  //     initializer list as a single argument.
2882  if (InitListSyntax) {
2883    AsInitializerList = true;
2884    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2885                                        CandidateSet, ConStart, ConEnd, Best,
2886                                        CopyInitialization, AllowExplicit,
2887                                        /*OnlyListConstructor=*/true);
2888
2889    // Time to unwrap the init list.
2890    InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2891    Args = ILE->getInits();
2892    NumArgs = ILE->getNumInits();
2893  }
2894
2895  // C++11 [over.match.list]p1:
2896  //   - If no viable initializer-list constructor is found, overload resolution
2897  //     is performed again, where the candidate functions are all the
2898  //     constructors of the class T nad the argument list consists of the
2899  //     elements of the initializer list.
2900  if (Result == OR_No_Viable_Function) {
2901    AsInitializerList = false;
2902    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2903                                        CandidateSet, ConStart, ConEnd, Best,
2904                                        CopyInitialization, AllowExplicit,
2905                                        /*OnlyListConstructors=*/false);
2906  }
2907  if (Result) {
2908    Sequence.SetOverloadFailure(InitListSyntax ?
2909                      InitializationSequence::FK_ListConstructorOverloadFailed :
2910                      InitializationSequence::FK_ConstructorOverloadFailed,
2911                                Result);
2912    return;
2913  }
2914
2915  // C++0x [dcl.init]p6:
2916  //   If a program calls for the default initialization of an object
2917  //   of a const-qualified type T, T shall be a class type with a
2918  //   user-provided default constructor.
2919  if (Kind.getKind() == InitializationKind::IK_Default &&
2920      Entity.getType().isConstQualified() &&
2921      cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2922    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2923    return;
2924  }
2925
2926  // Add the constructor initialization step. Any cv-qualification conversion is
2927  // subsumed by the initialization.
2928  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2929  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2930  Sequence.AddConstructorInitializationStep(CtorDecl,
2931                                            Best->FoundDecl.getAccess(),
2932                                            DestType, HadMultipleCandidates,
2933                                            InitListSyntax, AsInitializerList);
2934}
2935
2936static bool
2937ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2938                                             Expr *Initializer,
2939                                             QualType &SourceType,
2940                                             QualType &UnqualifiedSourceType,
2941                                             QualType UnqualifiedTargetType,
2942                                             InitializationSequence &Sequence) {
2943  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2944        S.Context.OverloadTy) {
2945    DeclAccessPair Found;
2946    bool HadMultipleCandidates = false;
2947    if (FunctionDecl *Fn
2948        = S.ResolveAddressOfOverloadedFunction(Initializer,
2949                                               UnqualifiedTargetType,
2950                                               false, Found,
2951                                               &HadMultipleCandidates)) {
2952      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2953                                                HadMultipleCandidates);
2954      SourceType = Fn->getType();
2955      UnqualifiedSourceType = SourceType.getUnqualifiedType();
2956    } else if (!UnqualifiedTargetType->isRecordType()) {
2957      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2958      return true;
2959    }
2960  }
2961  return false;
2962}
2963
2964static void TryReferenceInitializationCore(Sema &S,
2965                                           const InitializedEntity &Entity,
2966                                           const InitializationKind &Kind,
2967                                           Expr *Initializer,
2968                                           QualType cv1T1, QualType T1,
2969                                           Qualifiers T1Quals,
2970                                           QualType cv2T2, QualType T2,
2971                                           Qualifiers T2Quals,
2972                                           InitializationSequence &Sequence);
2973
2974static void TryListInitialization(Sema &S,
2975                                  const InitializedEntity &Entity,
2976                                  const InitializationKind &Kind,
2977                                  InitListExpr *InitList,
2978                                  InitializationSequence &Sequence);
2979
2980/// \brief Attempt list initialization of a reference.
2981static void TryReferenceListInitialization(Sema &S,
2982                                           const InitializedEntity &Entity,
2983                                           const InitializationKind &Kind,
2984                                           InitListExpr *InitList,
2985                                           InitializationSequence &Sequence)
2986{
2987  // First, catch C++03 where this isn't possible.
2988  if (!S.getLangOptions().CPlusPlus0x) {
2989    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2990    return;
2991  }
2992
2993  QualType DestType = Entity.getType();
2994  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2995  Qualifiers T1Quals;
2996  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2997
2998  // Reference initialization via an initializer list works thus:
2999  // If the initializer list consists of a single element that is
3000  // reference-related to the referenced type, bind directly to that element
3001  // (possibly creating temporaries).
3002  // Otherwise, initialize a temporary with the initializer list and
3003  // bind to that.
3004  if (InitList->getNumInits() == 1) {
3005    Expr *Initializer = InitList->getInit(0);
3006    QualType cv2T2 = Initializer->getType();
3007    Qualifiers T2Quals;
3008    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3009
3010    // If this fails, creating a temporary wouldn't work either.
3011    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3012                                                     T1, Sequence))
3013      return;
3014
3015    SourceLocation DeclLoc = Initializer->getLocStart();
3016    bool dummy1, dummy2, dummy3;
3017    Sema::ReferenceCompareResult RefRelationship
3018      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3019                                       dummy2, dummy3);
3020    if (RefRelationship >= Sema::Ref_Related) {
3021      // Try to bind the reference here.
3022      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3023                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
3024      if (Sequence)
3025        Sequence.RewrapReferenceInitList(cv1T1, InitList);
3026      return;
3027    }
3028  }
3029
3030  // Not reference-related. Create a temporary and bind to that.
3031  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3032
3033  TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3034  if (Sequence) {
3035    if (DestType->isRValueReferenceType() ||
3036        (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3037      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3038    else
3039      Sequence.SetFailed(
3040          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3041  }
3042}
3043
3044/// \brief Attempt list initialization (C++0x [dcl.init.list])
3045static void TryListInitialization(Sema &S,
3046                                  const InitializedEntity &Entity,
3047                                  const InitializationKind &Kind,
3048                                  InitListExpr *InitList,
3049                                  InitializationSequence &Sequence) {
3050  QualType DestType = Entity.getType();
3051
3052  // C++ doesn't allow scalar initialization with more than one argument.
3053  // But C99 complex numbers are scalars and it makes sense there.
3054  if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3055      !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3056    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3057    return;
3058  }
3059  if (DestType->isReferenceType()) {
3060    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3061    return;
3062  }
3063  if (DestType->isRecordType() && !DestType->isAggregateType()) {
3064    if (S.getLangOptions().CPlusPlus0x) {
3065      Expr *Arg = InitList;
3066      // A direct-initializer is not list-syntax, i.e. there's no special
3067      // treatment of "A a({1, 2});".
3068      TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3069                    Sequence, Kind.getKind() != InitializationKind::IK_Direct);
3070    } else
3071      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3072    return;
3073  }
3074
3075  InitListChecker CheckInitList(S, Entity, InitList,
3076          DestType, /*VerifyOnly=*/true,
3077          Kind.getKind() != InitializationKind::IK_DirectList ||
3078            !S.getLangOptions().CPlusPlus0x);
3079  if (CheckInitList.HadError()) {
3080    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3081    return;
3082  }
3083
3084  // Add the list initialization step with the built init list.
3085  Sequence.AddListInitializationStep(DestType);
3086}
3087
3088/// \brief Try a reference initialization that involves calling a conversion
3089/// function.
3090static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3091                                             const InitializedEntity &Entity,
3092                                             const InitializationKind &Kind,
3093                                                          Expr *Initializer,
3094                                                          bool AllowRValues,
3095                                             InitializationSequence &Sequence) {
3096  QualType DestType = Entity.getType();
3097  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3098  QualType T1 = cv1T1.getUnqualifiedType();
3099  QualType cv2T2 = Initializer->getType();
3100  QualType T2 = cv2T2.getUnqualifiedType();
3101
3102  bool DerivedToBase;
3103  bool ObjCConversion;
3104  bool ObjCLifetimeConversion;
3105  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3106                                         T1, T2, DerivedToBase,
3107                                         ObjCConversion,
3108                                         ObjCLifetimeConversion) &&
3109         "Must have incompatible references when binding via conversion");
3110  (void)DerivedToBase;
3111  (void)ObjCConversion;
3112  (void)ObjCLifetimeConversion;
3113
3114  // Build the candidate set directly in the initialization sequence
3115  // structure, so that it will persist if we fail.
3116  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3117  CandidateSet.clear();
3118
3119  // Determine whether we are allowed to call explicit constructors or
3120  // explicit conversion operators.
3121  bool AllowExplicit = Kind.AllowExplicit();
3122
3123  const RecordType *T1RecordType = 0;
3124  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3125      !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3126    // The type we're converting to is a class type. Enumerate its constructors
3127    // to see if there is a suitable conversion.
3128    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3129
3130    DeclContext::lookup_iterator Con, ConEnd;
3131    for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
3132         Con != ConEnd; ++Con) {
3133      NamedDecl *D = *Con;
3134      DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3135
3136      // Find the constructor (which may be a template).
3137      CXXConstructorDecl *Constructor = 0;
3138      FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3139      if (ConstructorTmpl)
3140        Constructor = cast<CXXConstructorDecl>(
3141                                         ConstructorTmpl->getTemplatedDecl());
3142      else
3143        Constructor = cast<CXXConstructorDecl>(D);
3144
3145      if (!Constructor->isInvalidDecl() &&
3146          Constructor->isConvertingConstructor(AllowExplicit)) {
3147        if (ConstructorTmpl)
3148          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3149                                         /*ExplicitArgs*/ 0,
3150                                         &Initializer, 1, CandidateSet,
3151                                         /*SuppressUserConversions=*/true);
3152        else
3153          S.AddOverloadCandidate(Constructor, FoundDecl,
3154                                 &Initializer, 1, CandidateSet,
3155                                 /*SuppressUserConversions=*/true);
3156      }
3157    }
3158  }
3159  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3160    return OR_No_Viable_Function;
3161
3162  const RecordType *T2RecordType = 0;
3163  if ((T2RecordType = T2->getAs<RecordType>()) &&
3164      !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3165    // The type we're converting from is a class type, enumerate its conversion
3166    // functions.
3167    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3168
3169    const UnresolvedSetImpl *Conversions
3170      = T2RecordDecl->getVisibleConversionFunctions();
3171    for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3172           E = Conversions->end(); I != E; ++I) {
3173      NamedDecl *D = *I;
3174      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3175      if (isa<UsingShadowDecl>(D))
3176        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3177
3178      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3179      CXXConversionDecl *Conv;
3180      if (ConvTemplate)
3181        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3182      else
3183        Conv = cast<CXXConversionDecl>(D);
3184
3185      // If the conversion function doesn't return a reference type,
3186      // it can't be considered for this conversion unless we're allowed to
3187      // consider rvalues.
3188      // FIXME: Do we need to make sure that we only consider conversion
3189      // candidates with reference-compatible results? That might be needed to
3190      // break recursion.
3191      if ((AllowExplicit || !Conv->isExplicit()) &&
3192          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3193        if (ConvTemplate)
3194          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3195                                           ActingDC, Initializer,
3196                                           DestType, CandidateSet);
3197        else
3198          S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3199                                   Initializer, DestType, CandidateSet);
3200      }
3201    }
3202  }
3203  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3204    return OR_No_Viable_Function;
3205
3206  SourceLocation DeclLoc = Initializer->getLocStart();
3207
3208  // Perform overload resolution. If it fails, return the failed result.
3209  OverloadCandidateSet::iterator Best;
3210  if (OverloadingResult Result
3211        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3212    return Result;
3213
3214  FunctionDecl *Function = Best->Function;
3215
3216  // This is the overload that will actually be used for the initialization, so
3217  // mark it as used.
3218  S.MarkFunctionReferenced(DeclLoc, Function);
3219
3220  // Compute the returned type of the conversion.
3221  if (isa<CXXConversionDecl>(Function))
3222    T2 = Function->getResultType();
3223  else
3224    T2 = cv1T1;
3225
3226  // Add the user-defined conversion step.
3227  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3228  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3229                                 T2.getNonLValueExprType(S.Context),
3230                                 HadMultipleCandidates);
3231
3232  // Determine whether we need to perform derived-to-base or
3233  // cv-qualification adjustments.
3234  ExprValueKind VK = VK_RValue;
3235  if (T2->isLValueReferenceType())
3236    VK = VK_LValue;
3237  else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3238    VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3239
3240  bool NewDerivedToBase = false;
3241  bool NewObjCConversion = false;
3242  bool NewObjCLifetimeConversion = false;
3243  Sema::ReferenceCompareResult NewRefRelationship
3244    = S.CompareReferenceRelationship(DeclLoc, T1,
3245                                     T2.getNonLValueExprType(S.Context),
3246                                     NewDerivedToBase, NewObjCConversion,
3247                                     NewObjCLifetimeConversion);
3248  if (NewRefRelationship == Sema::Ref_Incompatible) {
3249    // If the type we've converted to is not reference-related to the
3250    // type we're looking for, then there is another conversion step
3251    // we need to perform to produce a temporary of the right type
3252    // that we'll be binding to.
3253    ImplicitConversionSequence ICS;
3254    ICS.setStandard();
3255    ICS.Standard = Best->FinalConversion;
3256    T2 = ICS.Standard.getToType(2);
3257    Sequence.AddConversionSequenceStep(ICS, T2);
3258  } else if (NewDerivedToBase)
3259    Sequence.AddDerivedToBaseCastStep(
3260                                S.Context.getQualifiedType(T1,
3261                                  T2.getNonReferenceType().getQualifiers()),
3262                                      VK);
3263  else if (NewObjCConversion)
3264    Sequence.AddObjCObjectConversionStep(
3265                                S.Context.getQualifiedType(T1,
3266                                  T2.getNonReferenceType().getQualifiers()));
3267
3268  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3269    Sequence.AddQualificationConversionStep(cv1T1, VK);
3270
3271  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3272  return OR_Success;
3273}
3274
3275static void CheckCXX98CompatAccessibleCopy(Sema &S,
3276                                           const InitializedEntity &Entity,
3277                                           Expr *CurInitExpr);
3278
3279/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3280static void TryReferenceInitialization(Sema &S,
3281                                       const InitializedEntity &Entity,
3282                                       const InitializationKind &Kind,
3283                                       Expr *Initializer,
3284                                       InitializationSequence &Sequence) {
3285  QualType DestType = Entity.getType();
3286  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3287  Qualifiers T1Quals;
3288  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3289  QualType cv2T2 = Initializer->getType();
3290  Qualifiers T2Quals;
3291  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3292
3293  // If the initializer is the address of an overloaded function, try
3294  // to resolve the overloaded function. If all goes well, T2 is the
3295  // type of the resulting function.
3296  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3297                                                   T1, Sequence))
3298    return;
3299
3300  // Delegate everything else to a subfunction.
3301  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3302                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
3303}
3304
3305/// \brief Reference initialization without resolving overloaded functions.
3306static void TryReferenceInitializationCore(Sema &S,
3307                                           const InitializedEntity &Entity,
3308                                           const InitializationKind &Kind,
3309                                           Expr *Initializer,
3310                                           QualType cv1T1, QualType T1,
3311                                           Qualifiers T1Quals,
3312                                           QualType cv2T2, QualType T2,
3313                                           Qualifiers T2Quals,
3314                                           InitializationSequence &Sequence) {
3315  QualType DestType = Entity.getType();
3316  SourceLocation DeclLoc = Initializer->getLocStart();
3317  // Compute some basic properties of the types and the initializer.
3318  bool isLValueRef = DestType->isLValueReferenceType();
3319  bool isRValueRef = !isLValueRef;
3320  bool DerivedToBase = false;
3321  bool ObjCConversion = false;
3322  bool ObjCLifetimeConversion = false;
3323  Expr::Classification InitCategory = Initializer->Classify(S.Context);
3324  Sema::ReferenceCompareResult RefRelationship
3325    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3326                                     ObjCConversion, ObjCLifetimeConversion);
3327
3328  // C++0x [dcl.init.ref]p5:
3329  //   A reference to type "cv1 T1" is initialized by an expression of type
3330  //   "cv2 T2" as follows:
3331  //
3332  //     - If the reference is an lvalue reference and the initializer
3333  //       expression
3334  // Note the analogous bullet points for rvlaue refs to functions. Because
3335  // there are no function rvalues in C++, rvalue refs to functions are treated
3336  // like lvalue refs.
3337  OverloadingResult ConvOvlResult = OR_Success;
3338  bool T1Function = T1->isFunctionType();
3339  if (isLValueRef || T1Function) {
3340    if (InitCategory.isLValue() &&
3341        (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3342         (Kind.isCStyleOrFunctionalCast() &&
3343          RefRelationship == Sema::Ref_Related))) {
3344      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3345      //     reference-compatible with "cv2 T2," or
3346      //
3347      // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3348      // bit-field when we're determining whether the reference initialization
3349      // can occur. However, we do pay attention to whether it is a bit-field
3350      // to decide whether we're actually binding to a temporary created from
3351      // the bit-field.
3352      if (DerivedToBase)
3353        Sequence.AddDerivedToBaseCastStep(
3354                         S.Context.getQualifiedType(T1, T2Quals),
3355                         VK_LValue);
3356      else if (ObjCConversion)
3357        Sequence.AddObjCObjectConversionStep(
3358                                     S.Context.getQualifiedType(T1, T2Quals));
3359
3360      if (T1Quals != T2Quals)
3361        Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
3362      bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
3363        (Initializer->getBitField() || Initializer->refersToVectorElement());
3364      Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
3365      return;
3366    }
3367
3368    //     - has a class type (i.e., T2 is a class type), where T1 is not
3369    //       reference-related to T2, and can be implicitly converted to an
3370    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3371    //       with "cv3 T3" (this conversion is selected by enumerating the
3372    //       applicable conversion functions (13.3.1.6) and choosing the best
3373    //       one through overload resolution (13.3)),
3374    // If we have an rvalue ref to function type here, the rhs must be
3375    // an rvalue.
3376    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3377        (isLValueRef || InitCategory.isRValue())) {
3378      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3379                                                       Initializer,
3380                                                   /*AllowRValues=*/isRValueRef,
3381                                                       Sequence);
3382      if (ConvOvlResult == OR_Success)
3383        return;
3384      if (ConvOvlResult != OR_No_Viable_Function) {
3385        Sequence.SetOverloadFailure(
3386                      InitializationSequence::FK_ReferenceInitOverloadFailed,
3387                                    ConvOvlResult);
3388      }
3389    }
3390  }
3391
3392  //     - Otherwise, the reference shall be an lvalue reference to a
3393  //       non-volatile const type (i.e., cv1 shall be const), or the reference
3394  //       shall be an rvalue reference.
3395  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3396    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3397      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3398    else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3399      Sequence.SetOverloadFailure(
3400                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3401                                  ConvOvlResult);
3402    else
3403      Sequence.SetFailed(InitCategory.isLValue()
3404        ? (RefRelationship == Sema::Ref_Related
3405             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3406             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3407        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3408
3409    return;
3410  }
3411
3412  //    - If the initializer expression
3413  //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3414  //        "cv1 T1" is reference-compatible with "cv2 T2"
3415  // Note: functions are handled below.
3416  if (!T1Function &&
3417      (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3418       (Kind.isCStyleOrFunctionalCast() &&
3419        RefRelationship == Sema::Ref_Related)) &&
3420      (InitCategory.isXValue() ||
3421       (InitCategory.isPRValue() && T2->isRecordType()) ||
3422       (InitCategory.isPRValue() && T2->isArrayType()))) {
3423    ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3424    if (InitCategory.isPRValue() && T2->isRecordType()) {
3425      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3426      // compiler the freedom to perform a copy here or bind to the
3427      // object, while C++0x requires that we bind directly to the
3428      // object. Hence, we always bind to the object without making an
3429      // extra copy. However, in C++03 requires that we check for the
3430      // presence of a suitable copy constructor:
3431      //
3432      //   The constructor that would be used to make the copy shall
3433      //   be callable whether or not the copy is actually done.
3434      if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
3435        Sequence.AddExtraneousCopyToTemporary(cv2T2);
3436      else if (S.getLangOptions().CPlusPlus0x)
3437        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3438    }
3439
3440    if (DerivedToBase)
3441      Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3442                                        ValueKind);
3443    else if (ObjCConversion)
3444      Sequence.AddObjCObjectConversionStep(
3445                                       S.Context.getQualifiedType(T1, T2Quals));
3446
3447    if (T1Quals != T2Quals)
3448      Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
3449    Sequence.AddReferenceBindingStep(cv1T1,
3450                                 /*bindingTemporary=*/InitCategory.isPRValue());
3451    return;
3452  }
3453
3454  //       - has a class type (i.e., T2 is a class type), where T1 is not
3455  //         reference-related to T2, and can be implicitly converted to an
3456  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3457  //         where "cv1 T1" is reference-compatible with "cv3 T3",
3458  if (T2->isRecordType()) {
3459    if (RefRelationship == Sema::Ref_Incompatible) {
3460      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3461                                                       Kind, Initializer,
3462                                                       /*AllowRValues=*/true,
3463                                                       Sequence);
3464      if (ConvOvlResult)
3465        Sequence.SetOverloadFailure(
3466                      InitializationSequence::FK_ReferenceInitOverloadFailed,
3467                                    ConvOvlResult);
3468
3469      return;
3470    }
3471
3472    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3473    return;
3474  }
3475
3476  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3477  //        from the initializer expression using the rules for a non-reference
3478  //        copy initialization (8.5). The reference is then bound to the
3479  //        temporary. [...]
3480
3481  // Determine whether we are allowed to call explicit constructors or
3482  // explicit conversion operators.
3483  bool AllowExplicit = Kind.AllowExplicit();
3484
3485  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3486
3487  ImplicitConversionSequence ICS
3488    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3489                              /*SuppressUserConversions*/ false,
3490                              AllowExplicit,
3491                              /*FIXME:InOverloadResolution=*/false,
3492                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3493                              /*AllowObjCWritebackConversion=*/false);
3494
3495  if (ICS.isBad()) {
3496    // FIXME: Use the conversion function set stored in ICS to turn
3497    // this into an overloading ambiguity diagnostic. However, we need
3498    // to keep that set as an OverloadCandidateSet rather than as some
3499    // other kind of set.
3500    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3501      Sequence.SetOverloadFailure(
3502                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3503                                  ConvOvlResult);
3504    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3505      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3506    else
3507      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3508    return;
3509  } else {
3510    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3511  }
3512
3513  //        [...] If T1 is reference-related to T2, cv1 must be the
3514  //        same cv-qualification as, or greater cv-qualification
3515  //        than, cv2; otherwise, the program is ill-formed.
3516  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3517  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3518  if (RefRelationship == Sema::Ref_Related &&
3519      (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3520    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3521    return;
3522  }
3523
3524  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3525  //   reference, the initializer expression shall not be an lvalue.
3526  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3527      InitCategory.isLValue()) {
3528    Sequence.SetFailed(
3529                    InitializationSequence::FK_RValueReferenceBindingToLValue);
3530    return;
3531  }
3532
3533  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3534  return;
3535}
3536
3537/// \brief Attempt character array initialization from a string literal
3538/// (C++ [dcl.init.string], C99 6.7.8).
3539static void TryStringLiteralInitialization(Sema &S,
3540                                           const InitializedEntity &Entity,
3541                                           const InitializationKind &Kind,
3542                                           Expr *Initializer,
3543                                       InitializationSequence &Sequence) {
3544  Sequence.AddStringInitStep(Entity.getType());
3545}
3546
3547/// \brief Attempt value initialization (C++ [dcl.init]p7).
3548static void TryValueInitialization(Sema &S,
3549                                   const InitializedEntity &Entity,
3550                                   const InitializationKind &Kind,
3551                                   InitializationSequence &Sequence) {
3552  // C++ [dcl.init]p5:
3553  //
3554  //   To value-initialize an object of type T means:
3555  QualType T = Entity.getType();
3556
3557  //     -- if T is an array type, then each element is value-initialized;
3558  while (const ArrayType *AT = S.Context.getAsArrayType(T))
3559    T = AT->getElementType();
3560
3561  if (const RecordType *RT = T->getAs<RecordType>()) {
3562    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3563      // -- if T is a class type (clause 9) with a user-declared
3564      //    constructor (12.1), then the default constructor for T is
3565      //    called (and the initialization is ill-formed if T has no
3566      //    accessible default constructor);
3567      //
3568      // FIXME: we really want to refer to a single subobject of the array,
3569      // but Entity doesn't have a way to capture that (yet).
3570      if (ClassDecl->hasUserDeclaredConstructor())
3571        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3572
3573      // -- if T is a (possibly cv-qualified) non-union class type
3574      //    without a user-provided constructor, then the object is
3575      //    zero-initialized and, if T's implicitly-declared default
3576      //    constructor is non-trivial, that constructor is called.
3577      if ((ClassDecl->getTagKind() == TTK_Class ||
3578           ClassDecl->getTagKind() == TTK_Struct)) {
3579        Sequence.AddZeroInitializationStep(Entity.getType());
3580        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3581      }
3582    }
3583  }
3584
3585  Sequence.AddZeroInitializationStep(Entity.getType());
3586}
3587
3588/// \brief Attempt default initialization (C++ [dcl.init]p6).
3589static void TryDefaultInitialization(Sema &S,
3590                                     const InitializedEntity &Entity,
3591                                     const InitializationKind &Kind,
3592                                     InitializationSequence &Sequence) {
3593  assert(Kind.getKind() == InitializationKind::IK_Default);
3594
3595  // C++ [dcl.init]p6:
3596  //   To default-initialize an object of type T means:
3597  //     - if T is an array type, each element is default-initialized;
3598  QualType DestType = S.Context.getBaseElementType(Entity.getType());
3599
3600  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
3601  //       constructor for T is called (and the initialization is ill-formed if
3602  //       T has no accessible default constructor);
3603  if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
3604    TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3605    return;
3606  }
3607
3608  //     - otherwise, no initialization is performed.
3609
3610  //   If a program calls for the default initialization of an object of
3611  //   a const-qualified type T, T shall be a class type with a user-provided
3612  //   default constructor.
3613  if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
3614    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3615    return;
3616  }
3617
3618  // If the destination type has a lifetime property, zero-initialize it.
3619  if (DestType.getQualifiers().hasObjCLifetime()) {
3620    Sequence.AddZeroInitializationStep(Entity.getType());
3621    return;
3622  }
3623}
3624
3625/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3626/// which enumerates all conversion functions and performs overload resolution
3627/// to select the best.
3628static void TryUserDefinedConversion(Sema &S,
3629                                     const InitializedEntity &Entity,
3630                                     const InitializationKind &Kind,
3631                                     Expr *Initializer,
3632                                     InitializationSequence &Sequence) {
3633  QualType DestType = Entity.getType();
3634  assert(!DestType->isReferenceType() && "References are handled elsewhere");
3635  QualType SourceType = Initializer->getType();
3636  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3637         "Must have a class type to perform a user-defined conversion");
3638
3639  // Build the candidate set directly in the initialization sequence
3640  // structure, so that it will persist if we fail.
3641  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3642  CandidateSet.clear();
3643
3644  // Determine whether we are allowed to call explicit constructors or
3645  // explicit conversion operators.
3646  bool AllowExplicit = Kind.AllowExplicit();
3647
3648  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3649    // The type we're converting to is a class type. Enumerate its constructors
3650    // to see if there is a suitable conversion.
3651    CXXRecordDecl *DestRecordDecl
3652      = cast<CXXRecordDecl>(DestRecordType->getDecl());
3653
3654    // Try to complete the type we're converting to.
3655    if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3656      DeclContext::lookup_iterator Con, ConEnd;
3657      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3658           Con != ConEnd; ++Con) {
3659        NamedDecl *D = *Con;
3660        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3661
3662        // Find the constructor (which may be a template).
3663        CXXConstructorDecl *Constructor = 0;
3664        FunctionTemplateDecl *ConstructorTmpl
3665          = dyn_cast<FunctionTemplateDecl>(D);
3666        if (ConstructorTmpl)
3667          Constructor = cast<CXXConstructorDecl>(
3668                                           ConstructorTmpl->getTemplatedDecl());
3669        else
3670          Constructor = cast<CXXConstructorDecl>(D);
3671
3672        if (!Constructor->isInvalidDecl() &&
3673            Constructor->isConvertingConstructor(AllowExplicit)) {
3674          if (ConstructorTmpl)
3675            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3676                                           /*ExplicitArgs*/ 0,
3677                                           &Initializer, 1, CandidateSet,
3678                                           /*SuppressUserConversions=*/true);
3679          else
3680            S.AddOverloadCandidate(Constructor, FoundDecl,
3681                                   &Initializer, 1, CandidateSet,
3682                                   /*SuppressUserConversions=*/true);
3683        }
3684      }
3685    }
3686  }
3687
3688  SourceLocation DeclLoc = Initializer->getLocStart();
3689
3690  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3691    // The type we're converting from is a class type, enumerate its conversion
3692    // functions.
3693
3694    // We can only enumerate the conversion functions for a complete type; if
3695    // the type isn't complete, simply skip this step.
3696    if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3697      CXXRecordDecl *SourceRecordDecl
3698        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3699
3700      const UnresolvedSetImpl *Conversions
3701        = SourceRecordDecl->getVisibleConversionFunctions();
3702      for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3703           E = Conversions->end();
3704           I != E; ++I) {
3705        NamedDecl *D = *I;
3706        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3707        if (isa<UsingShadowDecl>(D))
3708          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3709
3710        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3711        CXXConversionDecl *Conv;
3712        if (ConvTemplate)
3713          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3714        else
3715          Conv = cast<CXXConversionDecl>(D);
3716
3717        if (AllowExplicit || !Conv->isExplicit()) {
3718          if (ConvTemplate)
3719            S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3720                                             ActingDC, Initializer, DestType,
3721                                             CandidateSet);
3722          else
3723            S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3724                                     Initializer, DestType, CandidateSet);
3725        }
3726      }
3727    }
3728  }
3729
3730  // Perform overload resolution. If it fails, return the failed result.
3731  OverloadCandidateSet::iterator Best;
3732  if (OverloadingResult Result
3733        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3734    Sequence.SetOverloadFailure(
3735                        InitializationSequence::FK_UserConversionOverloadFailed,
3736                                Result);
3737    return;
3738  }
3739
3740  FunctionDecl *Function = Best->Function;
3741  S.MarkFunctionReferenced(DeclLoc, Function);
3742  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3743
3744  if (isa<CXXConstructorDecl>(Function)) {
3745    // Add the user-defined conversion step. Any cv-qualification conversion is
3746    // subsumed by the initialization. Per DR5, the created temporary is of the
3747    // cv-unqualified type of the destination.
3748    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3749                                   DestType.getUnqualifiedType(),
3750                                   HadMultipleCandidates);
3751    return;
3752  }
3753
3754  // Add the user-defined conversion step that calls the conversion function.
3755  QualType ConvType = Function->getCallResultType();
3756  if (ConvType->getAs<RecordType>()) {
3757    // If we're converting to a class type, there may be an copy of
3758    // the resulting temporary object (possible to create an object of
3759    // a base class type). That copy is not a separate conversion, so
3760    // we just make a note of the actual destination type (possibly a
3761    // base class of the type returned by the conversion function) and
3762    // let the user-defined conversion step handle the conversion.
3763    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3764                                   HadMultipleCandidates);
3765    return;
3766  }
3767
3768  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3769                                 HadMultipleCandidates);
3770
3771  // If the conversion following the call to the conversion function
3772  // is interesting, add it as a separate step.
3773  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3774      Best->FinalConversion.Third) {
3775    ImplicitConversionSequence ICS;
3776    ICS.setStandard();
3777    ICS.Standard = Best->FinalConversion;
3778    Sequence.AddConversionSequenceStep(ICS, DestType);
3779  }
3780}
3781
3782/// The non-zero enum values here are indexes into diagnostic alternatives.
3783enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3784
3785/// Determines whether this expression is an acceptable ICR source.
3786static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3787                                         bool isAddressOf) {
3788  // Skip parens.
3789  e = e->IgnoreParens();
3790
3791  // Skip address-of nodes.
3792  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3793    if (op->getOpcode() == UO_AddrOf)
3794      return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
3795
3796  // Skip certain casts.
3797  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3798    switch (ce->getCastKind()) {
3799    case CK_Dependent:
3800    case CK_BitCast:
3801    case CK_LValueBitCast:
3802    case CK_NoOp:
3803      return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
3804
3805    case CK_ArrayToPointerDecay:
3806      return IIK_nonscalar;
3807
3808    case CK_NullToPointer:
3809      return IIK_okay;
3810
3811    default:
3812      break;
3813    }
3814
3815  // If we have a declaration reference, it had better be a local variable.
3816  } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3817    if (!isAddressOf) return IIK_nonlocal;
3818
3819    VarDecl *var;
3820    if (isa<DeclRefExpr>(e)) {
3821      var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3822      if (!var) return IIK_nonlocal;
3823    } else {
3824      var = cast<BlockDeclRefExpr>(e)->getDecl();
3825    }
3826
3827    return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3828
3829  // If we have a conditional operator, check both sides.
3830  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3831    if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
3832      return iik;
3833
3834    return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
3835
3836  // These are never scalar.
3837  } else if (isa<ArraySubscriptExpr>(e)) {
3838    return IIK_nonscalar;
3839
3840  // Otherwise, it needs to be a null pointer constant.
3841  } else {
3842    return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3843            ? IIK_okay : IIK_nonlocal);
3844  }
3845
3846  return IIK_nonlocal;
3847}
3848
3849/// Check whether the given expression is a valid operand for an
3850/// indirect copy/restore.
3851static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3852  assert(src->isRValue());
3853
3854  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
3855  if (iik == IIK_okay) return;
3856
3857  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3858    << ((unsigned) iik - 1)  // shift index into diagnostic explanations
3859    << src->getSourceRange();
3860}
3861
3862/// \brief Determine whether we have compatible array types for the
3863/// purposes of GNU by-copy array initialization.
3864static bool hasCompatibleArrayTypes(ASTContext &Context,
3865                                    const ArrayType *Dest,
3866                                    const ArrayType *Source) {
3867  // If the source and destination array types are equivalent, we're
3868  // done.
3869  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3870    return true;
3871
3872  // Make sure that the element types are the same.
3873  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3874    return false;
3875
3876  // The only mismatch we allow is when the destination is an
3877  // incomplete array type and the source is a constant array type.
3878  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3879}
3880
3881static bool tryObjCWritebackConversion(Sema &S,
3882                                       InitializationSequence &Sequence,
3883                                       const InitializedEntity &Entity,
3884                                       Expr *Initializer) {
3885  bool ArrayDecay = false;
3886  QualType ArgType = Initializer->getType();
3887  QualType ArgPointee;
3888  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3889    ArrayDecay = true;
3890    ArgPointee = ArgArrayType->getElementType();
3891    ArgType = S.Context.getPointerType(ArgPointee);
3892  }
3893
3894  // Handle write-back conversion.
3895  QualType ConvertedArgType;
3896  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3897                                   ConvertedArgType))
3898    return false;
3899
3900  // We should copy unless we're passing to an argument explicitly
3901  // marked 'out'.
3902  bool ShouldCopy = true;
3903  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3904    ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3905
3906  // Do we need an lvalue conversion?
3907  if (ArrayDecay || Initializer->isGLValue()) {
3908    ImplicitConversionSequence ICS;
3909    ICS.setStandard();
3910    ICS.Standard.setAsIdentityConversion();
3911
3912    QualType ResultType;
3913    if (ArrayDecay) {
3914      ICS.Standard.First = ICK_Array_To_Pointer;
3915      ResultType = S.Context.getPointerType(ArgPointee);
3916    } else {
3917      ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3918      ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3919    }
3920
3921    Sequence.AddConversionSequenceStep(ICS, ResultType);
3922  }
3923
3924  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3925  return true;
3926}
3927
3928InitializationSequence::InitializationSequence(Sema &S,
3929                                               const InitializedEntity &Entity,
3930                                               const InitializationKind &Kind,
3931                                               Expr **Args,
3932                                               unsigned NumArgs)
3933    : FailedCandidateSet(Kind.getLocation()) {
3934  ASTContext &Context = S.Context;
3935
3936  // C++0x [dcl.init]p16:
3937  //   The semantics of initializers are as follows. The destination type is
3938  //   the type of the object or reference being initialized and the source
3939  //   type is the type of the initializer expression. The source type is not
3940  //   defined when the initializer is a braced-init-list or when it is a
3941  //   parenthesized list of expressions.
3942  QualType DestType = Entity.getType();
3943
3944  if (DestType->isDependentType() ||
3945      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3946    SequenceKind = DependentSequence;
3947    return;
3948  }
3949
3950  // Almost everything is a normal sequence.
3951  setSequenceKind(NormalSequence);
3952
3953  for (unsigned I = 0; I != NumArgs; ++I)
3954    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
3955      // FIXME: should we be doing this here?
3956      ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3957      if (result.isInvalid()) {
3958        SetFailed(FK_PlaceholderType);
3959        return;
3960      }
3961      Args[I] = result.take();
3962    }
3963
3964
3965  QualType SourceType;
3966  Expr *Initializer = 0;
3967  if (NumArgs == 1) {
3968    Initializer = Args[0];
3969    if (!isa<InitListExpr>(Initializer))
3970      SourceType = Initializer->getType();
3971  }
3972
3973  //     - If the initializer is a (non-parenthesized) braced-init-list, the
3974  //       object is list-initialized (8.5.4).
3975  if (Kind.getKind() != InitializationKind::IK_Direct) {
3976    if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3977      TryListInitialization(S, Entity, Kind, InitList, *this);
3978      return;
3979    }
3980  }
3981
3982  //     - If the destination type is a reference type, see 8.5.3.
3983  if (DestType->isReferenceType()) {
3984    // C++0x [dcl.init.ref]p1:
3985    //   A variable declared to be a T& or T&&, that is, "reference to type T"
3986    //   (8.3.2), shall be initialized by an object, or function, of type T or
3987    //   by an object that can be converted into a T.
3988    // (Therefore, multiple arguments are not permitted.)
3989    if (NumArgs != 1)
3990      SetFailed(FK_TooManyInitsForReference);
3991    else
3992      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3993    return;
3994  }
3995
3996  //     - If the initializer is (), the object is value-initialized.
3997  if (Kind.getKind() == InitializationKind::IK_Value ||
3998      (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
3999    TryValueInitialization(S, Entity, Kind, *this);
4000    return;
4001  }
4002
4003  // Handle default initialization.
4004  if (Kind.getKind() == InitializationKind::IK_Default) {
4005    TryDefaultInitialization(S, Entity, Kind, *this);
4006    return;
4007  }
4008
4009  //     - If the destination type is an array of characters, an array of
4010  //       char16_t, an array of char32_t, or an array of wchar_t, and the
4011  //       initializer is a string literal, see 8.5.2.
4012  //     - Otherwise, if the destination type is an array, the program is
4013  //       ill-formed.
4014  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4015    if (Initializer && isa<VariableArrayType>(DestAT)) {
4016      SetFailed(FK_VariableLengthArrayHasInitializer);
4017      return;
4018    }
4019
4020    if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
4021      TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4022      return;
4023    }
4024
4025    // Note: as an GNU C extension, we allow initialization of an
4026    // array from a compound literal that creates an array of the same
4027    // type, so long as the initializer has no side effects.
4028    if (!S.getLangOptions().CPlusPlus && Initializer &&
4029        isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4030        Initializer->getType()->isArrayType()) {
4031      const ArrayType *SourceAT
4032        = Context.getAsArrayType(Initializer->getType());
4033      if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4034        SetFailed(FK_ArrayTypeMismatch);
4035      else if (Initializer->HasSideEffects(S.Context))
4036        SetFailed(FK_NonConstantArrayInit);
4037      else {
4038        AddArrayInitStep(DestType);
4039      }
4040    } else if (DestAT->getElementType()->isAnyCharacterType())
4041      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4042    else
4043      SetFailed(FK_ArrayNeedsInitList);
4044
4045    return;
4046  }
4047
4048  // Determine whether we should consider writeback conversions for
4049  // Objective-C ARC.
4050  bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4051    Entity.getKind() == InitializedEntity::EK_Parameter;
4052
4053  // We're at the end of the line for C: it's either a write-back conversion
4054  // or it's a C assignment. There's no need to check anything else.
4055  if (!S.getLangOptions().CPlusPlus) {
4056    // If allowed, check whether this is an Objective-C writeback conversion.
4057    if (allowObjCWritebackConversion &&
4058        tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4059      return;
4060    }
4061
4062    // Handle initialization in C
4063    AddCAssignmentStep(DestType);
4064    MaybeProduceObjCObject(S, *this, Entity);
4065    return;
4066  }
4067
4068  assert(S.getLangOptions().CPlusPlus);
4069
4070  //     - If the destination type is a (possibly cv-qualified) class type:
4071  if (DestType->isRecordType()) {
4072    //     - If the initialization is direct-initialization, or if it is
4073    //       copy-initialization where the cv-unqualified version of the
4074    //       source type is the same class as, or a derived class of, the
4075    //       class of the destination, constructors are considered. [...]
4076    if (Kind.getKind() == InitializationKind::IK_Direct ||
4077        (Kind.getKind() == InitializationKind::IK_Copy &&
4078         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4079          S.IsDerivedFrom(SourceType, DestType))))
4080      TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
4081                                   Entity.getType(), *this);
4082    //     - Otherwise (i.e., for the remaining copy-initialization cases),
4083    //       user-defined conversion sequences that can convert from the source
4084    //       type to the destination type or (when a conversion function is
4085    //       used) to a derived class thereof are enumerated as described in
4086    //       13.3.1.4, and the best one is chosen through overload resolution
4087    //       (13.3).
4088    else
4089      TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4090    return;
4091  }
4092
4093  if (NumArgs > 1) {
4094    SetFailed(FK_TooManyInitsForScalar);
4095    return;
4096  }
4097  assert(NumArgs == 1 && "Zero-argument case handled above");
4098
4099  //    - Otherwise, if the source type is a (possibly cv-qualified) class
4100  //      type, conversion functions are considered.
4101  if (!SourceType.isNull() && SourceType->isRecordType()) {
4102    TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4103    MaybeProduceObjCObject(S, *this, Entity);
4104    return;
4105  }
4106
4107  //    - Otherwise, the initial value of the object being initialized is the
4108  //      (possibly converted) value of the initializer expression. Standard
4109  //      conversions (Clause 4) will be used, if necessary, to convert the
4110  //      initializer expression to the cv-unqualified version of the
4111  //      destination type; no user-defined conversions are considered.
4112
4113  ImplicitConversionSequence ICS
4114    = S.TryImplicitConversion(Initializer, Entity.getType(),
4115                              /*SuppressUserConversions*/true,
4116                              /*AllowExplicitConversions*/ false,
4117                              /*InOverloadResolution*/ false,
4118                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4119                              allowObjCWritebackConversion);
4120
4121  if (ICS.isStandard() &&
4122      ICS.Standard.Second == ICK_Writeback_Conversion) {
4123    // Objective-C ARC writeback conversion.
4124
4125    // We should copy unless we're passing to an argument explicitly
4126    // marked 'out'.
4127    bool ShouldCopy = true;
4128    if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4129      ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4130
4131    // If there was an lvalue adjustment, add it as a separate conversion.
4132    if (ICS.Standard.First == ICK_Array_To_Pointer ||
4133        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4134      ImplicitConversionSequence LvalueICS;
4135      LvalueICS.setStandard();
4136      LvalueICS.Standard.setAsIdentityConversion();
4137      LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4138      LvalueICS.Standard.First = ICS.Standard.First;
4139      AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4140    }
4141
4142    AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4143  } else if (ICS.isBad()) {
4144    DeclAccessPair dap;
4145    if (Initializer->getType() == Context.OverloadTy &&
4146          !S.ResolveAddressOfOverloadedFunction(Initializer
4147                      , DestType, false, dap))
4148      SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4149    else
4150      SetFailed(InitializationSequence::FK_ConversionFailed);
4151  } else {
4152    AddConversionSequenceStep(ICS, Entity.getType());
4153
4154    MaybeProduceObjCObject(S, *this, Entity);
4155  }
4156}
4157
4158InitializationSequence::~InitializationSequence() {
4159  for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4160                                          StepEnd = Steps.end();
4161       Step != StepEnd; ++Step)
4162    Step->Destroy();
4163}
4164
4165//===----------------------------------------------------------------------===//
4166// Perform initialization
4167//===----------------------------------------------------------------------===//
4168static Sema::AssignmentAction
4169getAssignmentAction(const InitializedEntity &Entity) {
4170  switch(Entity.getKind()) {
4171  case InitializedEntity::EK_Variable:
4172  case InitializedEntity::EK_New:
4173  case InitializedEntity::EK_Exception:
4174  case InitializedEntity::EK_Base:
4175  case InitializedEntity::EK_Delegating:
4176    return Sema::AA_Initializing;
4177
4178  case InitializedEntity::EK_Parameter:
4179    if (Entity.getDecl() &&
4180        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4181      return Sema::AA_Sending;
4182
4183    return Sema::AA_Passing;
4184
4185  case InitializedEntity::EK_Result:
4186    return Sema::AA_Returning;
4187
4188  case InitializedEntity::EK_Temporary:
4189    // FIXME: Can we tell apart casting vs. converting?
4190    return Sema::AA_Casting;
4191
4192  case InitializedEntity::EK_Member:
4193  case InitializedEntity::EK_ArrayElement:
4194  case InitializedEntity::EK_VectorElement:
4195  case InitializedEntity::EK_ComplexElement:
4196  case InitializedEntity::EK_BlockElement:
4197    return Sema::AA_Initializing;
4198  }
4199
4200  llvm_unreachable("Invalid EntityKind!");
4201}
4202
4203/// \brief Whether we should binding a created object as a temporary when
4204/// initializing the given entity.
4205static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4206  switch (Entity.getKind()) {
4207  case InitializedEntity::EK_ArrayElement:
4208  case InitializedEntity::EK_Member:
4209  case InitializedEntity::EK_Result:
4210  case InitializedEntity::EK_New:
4211  case InitializedEntity::EK_Variable:
4212  case InitializedEntity::EK_Base:
4213  case InitializedEntity::EK_Delegating:
4214  case InitializedEntity::EK_VectorElement:
4215  case InitializedEntity::EK_ComplexElement:
4216  case InitializedEntity::EK_Exception:
4217  case InitializedEntity::EK_BlockElement:
4218    return false;
4219
4220  case InitializedEntity::EK_Parameter:
4221  case InitializedEntity::EK_Temporary:
4222    return true;
4223  }
4224
4225  llvm_unreachable("missed an InitializedEntity kind?");
4226}
4227
4228/// \brief Whether the given entity, when initialized with an object
4229/// created for that initialization, requires destruction.
4230static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4231  switch (Entity.getKind()) {
4232    case InitializedEntity::EK_Member:
4233    case InitializedEntity::EK_Result:
4234    case InitializedEntity::EK_New:
4235    case InitializedEntity::EK_Base:
4236    case InitializedEntity::EK_Delegating:
4237    case InitializedEntity::EK_VectorElement:
4238    case InitializedEntity::EK_ComplexElement:
4239    case InitializedEntity::EK_BlockElement:
4240      return false;
4241
4242    case InitializedEntity::EK_Variable:
4243    case InitializedEntity::EK_Parameter:
4244    case InitializedEntity::EK_Temporary:
4245    case InitializedEntity::EK_ArrayElement:
4246    case InitializedEntity::EK_Exception:
4247      return true;
4248  }
4249
4250  llvm_unreachable("missed an InitializedEntity kind?");
4251}
4252
4253/// \brief Look for copy and move constructors and constructor templates, for
4254/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4255static void LookupCopyAndMoveConstructors(Sema &S,
4256                                          OverloadCandidateSet &CandidateSet,
4257                                          CXXRecordDecl *Class,
4258                                          Expr *CurInitExpr) {
4259  DeclContext::lookup_iterator Con, ConEnd;
4260  for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4261       Con != ConEnd; ++Con) {
4262    CXXConstructorDecl *Constructor = 0;
4263
4264    if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4265      // Handle copy/moveconstructors, only.
4266      if (!Constructor || Constructor->isInvalidDecl() ||
4267          !Constructor->isCopyOrMoveConstructor() ||
4268          !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4269        continue;
4270
4271      DeclAccessPair FoundDecl
4272        = DeclAccessPair::make(Constructor, Constructor->getAccess());
4273      S.AddOverloadCandidate(Constructor, FoundDecl,
4274                             &CurInitExpr, 1, CandidateSet);
4275      continue;
4276    }
4277
4278    // Handle constructor templates.
4279    FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4280    if (ConstructorTmpl->isInvalidDecl())
4281      continue;
4282
4283    Constructor = cast<CXXConstructorDecl>(
4284                                         ConstructorTmpl->getTemplatedDecl());
4285    if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4286      continue;
4287
4288    // FIXME: Do we need to limit this to copy-constructor-like
4289    // candidates?
4290    DeclAccessPair FoundDecl
4291      = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4292    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4293                                   &CurInitExpr, 1, CandidateSet, true);
4294  }
4295}
4296
4297/// \brief Get the location at which initialization diagnostics should appear.
4298static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4299                                           Expr *Initializer) {
4300  switch (Entity.getKind()) {
4301  case InitializedEntity::EK_Result:
4302    return Entity.getReturnLoc();
4303
4304  case InitializedEntity::EK_Exception:
4305    return Entity.getThrowLoc();
4306
4307  case InitializedEntity::EK_Variable:
4308    return Entity.getDecl()->getLocation();
4309
4310  case InitializedEntity::EK_ArrayElement:
4311  case InitializedEntity::EK_Member:
4312  case InitializedEntity::EK_Parameter:
4313  case InitializedEntity::EK_Temporary:
4314  case InitializedEntity::EK_New:
4315  case InitializedEntity::EK_Base:
4316  case InitializedEntity::EK_Delegating:
4317  case InitializedEntity::EK_VectorElement:
4318  case InitializedEntity::EK_ComplexElement:
4319  case InitializedEntity::EK_BlockElement:
4320    return Initializer->getLocStart();
4321  }
4322  llvm_unreachable("missed an InitializedEntity kind?");
4323}
4324
4325/// \brief Make a (potentially elidable) temporary copy of the object
4326/// provided by the given initializer by calling the appropriate copy
4327/// constructor.
4328///
4329/// \param S The Sema object used for type-checking.
4330///
4331/// \param T The type of the temporary object, which must either be
4332/// the type of the initializer expression or a superclass thereof.
4333///
4334/// \param Enter The entity being initialized.
4335///
4336/// \param CurInit The initializer expression.
4337///
4338/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4339/// is permitted in C++03 (but not C++0x) when binding a reference to
4340/// an rvalue.
4341///
4342/// \returns An expression that copies the initializer expression into
4343/// a temporary object, or an error expression if a copy could not be
4344/// created.
4345static ExprResult CopyObject(Sema &S,
4346                             QualType T,
4347                             const InitializedEntity &Entity,
4348                             ExprResult CurInit,
4349                             bool IsExtraneousCopy) {
4350  // Determine which class type we're copying to.
4351  Expr *CurInitExpr = (Expr *)CurInit.get();
4352  CXXRecordDecl *Class = 0;
4353  if (const RecordType *Record = T->getAs<RecordType>())
4354    Class = cast<CXXRecordDecl>(Record->getDecl());
4355  if (!Class)
4356    return move(CurInit);
4357
4358  // C++0x [class.copy]p32:
4359  //   When certain criteria are met, an implementation is allowed to
4360  //   omit the copy/move construction of a class object, even if the
4361  //   copy/move constructor and/or destructor for the object have
4362  //   side effects. [...]
4363  //     - when a temporary class object that has not been bound to a
4364  //       reference (12.2) would be copied/moved to a class object
4365  //       with the same cv-unqualified type, the copy/move operation
4366  //       can be omitted by constructing the temporary object
4367  //       directly into the target of the omitted copy/move
4368  //
4369  // Note that the other three bullets are handled elsewhere. Copy
4370  // elision for return statements and throw expressions are handled as part
4371  // of constructor initialization, while copy elision for exception handlers
4372  // is handled by the run-time.
4373  bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4374  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4375
4376  // Make sure that the type we are copying is complete.
4377  if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4378    return move(CurInit);
4379
4380  // Perform overload resolution using the class's copy/move constructors.
4381  // Only consider constructors and constructor templates. Per
4382  // C++0x [dcl.init]p16, second bullet to class types, this initialization
4383  // is direct-initialization.
4384  OverloadCandidateSet CandidateSet(Loc);
4385  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4386
4387  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4388
4389  OverloadCandidateSet::iterator Best;
4390  switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4391  case OR_Success:
4392    break;
4393
4394  case OR_No_Viable_Function:
4395    S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4396           ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4397           : diag::err_temp_copy_no_viable)
4398      << (int)Entity.getKind() << CurInitExpr->getType()
4399      << CurInitExpr->getSourceRange();
4400    CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4401    if (!IsExtraneousCopy || S.isSFINAEContext())
4402      return ExprError();
4403    return move(CurInit);
4404
4405  case OR_Ambiguous:
4406    S.Diag(Loc, diag::err_temp_copy_ambiguous)
4407      << (int)Entity.getKind() << CurInitExpr->getType()
4408      << CurInitExpr->getSourceRange();
4409    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4410    return ExprError();
4411
4412  case OR_Deleted:
4413    S.Diag(Loc, diag::err_temp_copy_deleted)
4414      << (int)Entity.getKind() << CurInitExpr->getType()
4415      << CurInitExpr->getSourceRange();
4416    S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4417      << 1 << Best->Function->isDeleted();
4418    return ExprError();
4419  }
4420
4421  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4422  ASTOwningVector<Expr*> ConstructorArgs(S);
4423  CurInit.release(); // Ownership transferred into MultiExprArg, below.
4424
4425  S.CheckConstructorAccess(Loc, Constructor, Entity,
4426                           Best->FoundDecl.getAccess(), IsExtraneousCopy);
4427
4428  if (IsExtraneousCopy) {
4429    // If this is a totally extraneous copy for C++03 reference
4430    // binding purposes, just return the original initialization
4431    // expression. We don't generate an (elided) copy operation here
4432    // because doing so would require us to pass down a flag to avoid
4433    // infinite recursion, where each step adds another extraneous,
4434    // elidable copy.
4435
4436    // Instantiate the default arguments of any extra parameters in
4437    // the selected copy constructor, as if we were going to create a
4438    // proper call to the copy constructor.
4439    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4440      ParmVarDecl *Parm = Constructor->getParamDecl(I);
4441      if (S.RequireCompleteType(Loc, Parm->getType(),
4442                                S.PDiag(diag::err_call_incomplete_argument)))
4443        break;
4444
4445      // Build the default argument expression; we don't actually care
4446      // if this succeeds or not, because this routine will complain
4447      // if there was a problem.
4448      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4449    }
4450
4451    return S.Owned(CurInitExpr);
4452  }
4453
4454  S.MarkFunctionReferenced(Loc, Constructor);
4455
4456  // Determine the arguments required to actually perform the
4457  // constructor call (we might have derived-to-base conversions, or
4458  // the copy constructor may have default arguments).
4459  if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4460                                Loc, ConstructorArgs))
4461    return ExprError();
4462
4463  // Actually perform the constructor call.
4464  CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4465                                    move_arg(ConstructorArgs),
4466                                    HadMultipleCandidates,
4467                                    /*ZeroInit*/ false,
4468                                    CXXConstructExpr::CK_Complete,
4469                                    SourceRange());
4470
4471  // If we're supposed to bind temporaries, do so.
4472  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4473    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4474  return move(CurInit);
4475}
4476
4477/// \brief Check whether elidable copy construction for binding a reference to
4478/// a temporary would have succeeded if we were building in C++98 mode, for
4479/// -Wc++98-compat.
4480static void CheckCXX98CompatAccessibleCopy(Sema &S,
4481                                           const InitializedEntity &Entity,
4482                                           Expr *CurInitExpr) {
4483  assert(S.getLangOptions().CPlusPlus0x);
4484
4485  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4486  if (!Record)
4487    return;
4488
4489  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4490  if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4491        == DiagnosticsEngine::Ignored)
4492    return;
4493
4494  // Find constructors which would have been considered.
4495  OverloadCandidateSet CandidateSet(Loc);
4496  LookupCopyAndMoveConstructors(
4497      S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4498
4499  // Perform overload resolution.
4500  OverloadCandidateSet::iterator Best;
4501  OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4502
4503  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4504    << OR << (int)Entity.getKind() << CurInitExpr->getType()
4505    << CurInitExpr->getSourceRange();
4506
4507  switch (OR) {
4508  case OR_Success:
4509    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4510                             Best->FoundDecl.getAccess(), Diag);
4511    // FIXME: Check default arguments as far as that's possible.
4512    break;
4513
4514  case OR_No_Viable_Function:
4515    S.Diag(Loc, Diag);
4516    CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4517    break;
4518
4519  case OR_Ambiguous:
4520    S.Diag(Loc, Diag);
4521    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4522    break;
4523
4524  case OR_Deleted:
4525    S.Diag(Loc, Diag);
4526    S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4527      << 1 << Best->Function->isDeleted();
4528    break;
4529  }
4530}
4531
4532void InitializationSequence::PrintInitLocationNote(Sema &S,
4533                                              const InitializedEntity &Entity) {
4534  if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4535    if (Entity.getDecl()->getLocation().isInvalid())
4536      return;
4537
4538    if (Entity.getDecl()->getDeclName())
4539      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4540        << Entity.getDecl()->getDeclName();
4541    else
4542      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4543  }
4544}
4545
4546static bool isReferenceBinding(const InitializationSequence::Step &s) {
4547  return s.Kind == InitializationSequence::SK_BindReference ||
4548         s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4549}
4550
4551static ExprResult
4552PerformConstructorInitialization(Sema &S,
4553                                 const InitializedEntity &Entity,
4554                                 const InitializationKind &Kind,
4555                                 MultiExprArg Args,
4556                                 const InitializationSequence::Step& Step,
4557                                 bool &ConstructorInitRequiresZeroInit) {
4558  unsigned NumArgs = Args.size();
4559  CXXConstructorDecl *Constructor
4560    = cast<CXXConstructorDecl>(Step.Function.Function);
4561  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4562
4563  // Build a call to the selected constructor.
4564  ASTOwningVector<Expr*> ConstructorArgs(S);
4565  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4566                         ? Kind.getEqualLoc()
4567                         : Kind.getLocation();
4568
4569  if (Kind.getKind() == InitializationKind::IK_Default) {
4570    // Force even a trivial, implicit default constructor to be
4571    // semantically checked. We do this explicitly because we don't build
4572    // the definition for completely trivial constructors.
4573    CXXRecordDecl *ClassDecl = Constructor->getParent();
4574    assert(ClassDecl && "No parent class for constructor.");
4575    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4576        ClassDecl->hasTrivialDefaultConstructor() &&
4577        !Constructor->isUsed(false))
4578      S.DefineImplicitDefaultConstructor(Loc, Constructor);
4579  }
4580
4581  ExprResult CurInit = S.Owned((Expr *)0);
4582
4583  // Determine the arguments required to actually perform the constructor
4584  // call.
4585  if (S.CompleteConstructorCall(Constructor, move(Args),
4586                                Loc, ConstructorArgs))
4587    return ExprError();
4588
4589
4590  if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4591      NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4592      (Kind.getKind() == InitializationKind::IK_Direct ||
4593       Kind.getKind() == InitializationKind::IK_Value)) {
4594    // An explicitly-constructed temporary, e.g., X(1, 2).
4595    unsigned NumExprs = ConstructorArgs.size();
4596    Expr **Exprs = (Expr **)ConstructorArgs.take();
4597    S.MarkFunctionReferenced(Loc, Constructor);
4598    S.DiagnoseUseOfDecl(Constructor, Loc);
4599
4600    TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4601    if (!TSInfo)
4602      TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4603
4604    CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4605                                                             Constructor,
4606                                                             TSInfo,
4607                                                             Exprs,
4608                                                             NumExprs,
4609                                                     Kind.getParenRange(),
4610                                                     HadMultipleCandidates,
4611                                         ConstructorInitRequiresZeroInit));
4612  } else {
4613    CXXConstructExpr::ConstructionKind ConstructKind =
4614      CXXConstructExpr::CK_Complete;
4615
4616    if (Entity.getKind() == InitializedEntity::EK_Base) {
4617      ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4618        CXXConstructExpr::CK_VirtualBase :
4619        CXXConstructExpr::CK_NonVirtualBase;
4620    } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4621      ConstructKind = CXXConstructExpr::CK_Delegating;
4622    }
4623
4624    // Only get the parenthesis range if it is a direct construction.
4625    SourceRange parenRange =
4626        Kind.getKind() == InitializationKind::IK_Direct ?
4627        Kind.getParenRange() : SourceRange();
4628
4629    // If the entity allows NRVO, mark the construction as elidable
4630    // unconditionally.
4631    if (Entity.allowsNRVO())
4632      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4633                                        Constructor, /*Elidable=*/true,
4634                                        move_arg(ConstructorArgs),
4635                                        HadMultipleCandidates,
4636                                        ConstructorInitRequiresZeroInit,
4637                                        ConstructKind,
4638                                        parenRange);
4639    else
4640      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4641                                        Constructor,
4642                                        move_arg(ConstructorArgs),
4643                                        HadMultipleCandidates,
4644                                        ConstructorInitRequiresZeroInit,
4645                                        ConstructKind,
4646                                        parenRange);
4647  }
4648  if (CurInit.isInvalid())
4649    return ExprError();
4650
4651  // Only check access if all of that succeeded.
4652  S.CheckConstructorAccess(Loc, Constructor, Entity,
4653                           Step.Function.FoundDecl.getAccess());
4654  S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4655
4656  if (shouldBindAsTemporary(Entity))
4657    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4658
4659  return move(CurInit);
4660}
4661
4662ExprResult
4663InitializationSequence::Perform(Sema &S,
4664                                const InitializedEntity &Entity,
4665                                const InitializationKind &Kind,
4666                                MultiExprArg Args,
4667                                QualType *ResultType) {
4668  if (Failed()) {
4669    unsigned NumArgs = Args.size();
4670    Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
4671    return ExprError();
4672  }
4673
4674  if (getKind() == DependentSequence) {
4675    // If the declaration is a non-dependent, incomplete array type
4676    // that has an initializer, then its type will be completed once
4677    // the initializer is instantiated.
4678    if (ResultType && !Entity.getType()->isDependentType() &&
4679        Args.size() == 1) {
4680      QualType DeclType = Entity.getType();
4681      if (const IncompleteArrayType *ArrayT
4682                           = S.Context.getAsIncompleteArrayType(DeclType)) {
4683        // FIXME: We don't currently have the ability to accurately
4684        // compute the length of an initializer list without
4685        // performing full type-checking of the initializer list
4686        // (since we have to determine where braces are implicitly
4687        // introduced and such).  So, we fall back to making the array
4688        // type a dependently-sized array type with no specified
4689        // bound.
4690        if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4691          SourceRange Brackets;
4692
4693          // Scavange the location of the brackets from the entity, if we can.
4694          if (DeclaratorDecl *DD = Entity.getDecl()) {
4695            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4696              TypeLoc TL = TInfo->getTypeLoc();
4697              if (IncompleteArrayTypeLoc *ArrayLoc
4698                                      = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4699              Brackets = ArrayLoc->getBracketsRange();
4700            }
4701          }
4702
4703          *ResultType
4704            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4705                                                   /*NumElts=*/0,
4706                                                   ArrayT->getSizeModifier(),
4707                                       ArrayT->getIndexTypeCVRQualifiers(),
4708                                                   Brackets);
4709        }
4710
4711      }
4712    }
4713    if (Kind.getKind() == InitializationKind::IK_Direct &&
4714        !Kind.isExplicitCast()) {
4715      // Rebuild the ParenListExpr.
4716      SourceRange ParenRange = Kind.getParenRange();
4717      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4718                                  move(Args));
4719    }
4720    assert(Kind.getKind() == InitializationKind::IK_Copy ||
4721           Kind.isExplicitCast());
4722    return ExprResult(Args.release()[0]);
4723  }
4724
4725  // No steps means no initialization.
4726  if (Steps.empty())
4727    return S.Owned((Expr *)0);
4728
4729  QualType DestType = Entity.getType().getNonReferenceType();
4730  // FIXME: Ugly hack around the fact that Entity.getType() is not
4731  // the same as Entity.getDecl()->getType() in cases involving type merging,
4732  //  and we want latter when it makes sense.
4733  if (ResultType)
4734    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
4735                                     Entity.getType();
4736
4737  ExprResult CurInit = S.Owned((Expr *)0);
4738
4739  // For initialization steps that start with a single initializer,
4740  // grab the only argument out the Args and place it into the "current"
4741  // initializer.
4742  switch (Steps.front().Kind) {
4743  case SK_ResolveAddressOfOverloadedFunction:
4744  case SK_CastDerivedToBaseRValue:
4745  case SK_CastDerivedToBaseXValue:
4746  case SK_CastDerivedToBaseLValue:
4747  case SK_BindReference:
4748  case SK_BindReferenceToTemporary:
4749  case SK_ExtraneousCopyToTemporary:
4750  case SK_UserConversion:
4751  case SK_QualificationConversionLValue:
4752  case SK_QualificationConversionXValue:
4753  case SK_QualificationConversionRValue:
4754  case SK_ConversionSequence:
4755  case SK_ListConstructorCall:
4756  case SK_ListInitialization:
4757  case SK_UnwrapInitList:
4758  case SK_RewrapInitList:
4759  case SK_CAssignment:
4760  case SK_StringInit:
4761  case SK_ObjCObjectConversion:
4762  case SK_ArrayInit:
4763  case SK_PassByIndirectCopyRestore:
4764  case SK_PassByIndirectRestore:
4765  case SK_ProduceObjCObject:
4766  case SK_StdInitializerList: {
4767    assert(Args.size() == 1);
4768    CurInit = Args.get()[0];
4769    if (!CurInit.get()) return ExprError();
4770    break;
4771  }
4772
4773  case SK_ConstructorInitialization:
4774  case SK_ZeroInitialization:
4775    break;
4776  }
4777
4778  // Walk through the computed steps for the initialization sequence,
4779  // performing the specified conversions along the way.
4780  bool ConstructorInitRequiresZeroInit = false;
4781  for (step_iterator Step = step_begin(), StepEnd = step_end();
4782       Step != StepEnd; ++Step) {
4783    if (CurInit.isInvalid())
4784      return ExprError();
4785
4786    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
4787
4788    switch (Step->Kind) {
4789    case SK_ResolveAddressOfOverloadedFunction:
4790      // Overload resolution determined which function invoke; update the
4791      // initializer to reflect that choice.
4792      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
4793      S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
4794      CurInit = S.FixOverloadedFunctionReference(move(CurInit),
4795                                                 Step->Function.FoundDecl,
4796                                                 Step->Function.Function);
4797      break;
4798
4799    case SK_CastDerivedToBaseRValue:
4800    case SK_CastDerivedToBaseXValue:
4801    case SK_CastDerivedToBaseLValue: {
4802      // We have a derived-to-base cast that produces either an rvalue or an
4803      // lvalue. Perform that cast.
4804
4805      CXXCastPath BasePath;
4806
4807      // Casts to inaccessible base classes are allowed with C-style casts.
4808      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4809      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
4810                                         CurInit.get()->getLocStart(),
4811                                         CurInit.get()->getSourceRange(),
4812                                         &BasePath, IgnoreBaseAccess))
4813        return ExprError();
4814
4815      if (S.BasePathInvolvesVirtualBase(BasePath)) {
4816        QualType T = SourceType;
4817        if (const PointerType *Pointer = T->getAs<PointerType>())
4818          T = Pointer->getPointeeType();
4819        if (const RecordType *RecordTy = T->getAs<RecordType>())
4820          S.MarkVTableUsed(CurInit.get()->getLocStart(),
4821                           cast<CXXRecordDecl>(RecordTy->getDecl()));
4822      }
4823
4824      ExprValueKind VK =
4825          Step->Kind == SK_CastDerivedToBaseLValue ?
4826              VK_LValue :
4827              (Step->Kind == SK_CastDerivedToBaseXValue ?
4828                   VK_XValue :
4829                   VK_RValue);
4830      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4831                                                 Step->Type,
4832                                                 CK_DerivedToBase,
4833                                                 CurInit.get(),
4834                                                 &BasePath, VK));
4835      break;
4836    }
4837
4838    case SK_BindReference:
4839      if (FieldDecl *BitField = CurInit.get()->getBitField()) {
4840        // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4841        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
4842          << Entity.getType().isVolatileQualified()
4843          << BitField->getDeclName()
4844          << CurInit.get()->getSourceRange();
4845        S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
4846        return ExprError();
4847      }
4848
4849      if (CurInit.get()->refersToVectorElement()) {
4850        // References cannot bind to vector elements.
4851        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4852          << Entity.getType().isVolatileQualified()
4853          << CurInit.get()->getSourceRange();
4854        PrintInitLocationNote(S, Entity);
4855        return ExprError();
4856      }
4857
4858      // Reference binding does not have any corresponding ASTs.
4859
4860      // Check exception specifications
4861      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4862        return ExprError();
4863
4864      break;
4865
4866    case SK_BindReferenceToTemporary:
4867      // Check exception specifications
4868      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4869        return ExprError();
4870
4871      // Materialize the temporary into memory.
4872      CurInit = new (S.Context) MaterializeTemporaryExpr(
4873                                         Entity.getType().getNonReferenceType(),
4874                                                         CurInit.get(),
4875                                     Entity.getType()->isLValueReferenceType());
4876
4877      // If we're binding to an Objective-C object that has lifetime, we
4878      // need cleanups.
4879      if (S.getLangOptions().ObjCAutoRefCount &&
4880          CurInit.get()->getType()->isObjCLifetimeType())
4881        S.ExprNeedsCleanups = true;
4882
4883      break;
4884
4885    case SK_ExtraneousCopyToTemporary:
4886      CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
4887                           /*IsExtraneousCopy=*/true);
4888      break;
4889
4890    case SK_UserConversion: {
4891      // We have a user-defined conversion that invokes either a constructor
4892      // or a conversion function.
4893      CastKind CastKind;
4894      bool IsCopy = false;
4895      FunctionDecl *Fn = Step->Function.Function;
4896      DeclAccessPair FoundFn = Step->Function.FoundDecl;
4897      bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
4898      bool CreatedObject = false;
4899      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
4900        // Build a call to the selected constructor.
4901        ASTOwningVector<Expr*> ConstructorArgs(S);
4902        SourceLocation Loc = CurInit.get()->getLocStart();
4903        CurInit.release(); // Ownership transferred into MultiExprArg, below.
4904
4905        // Determine the arguments required to actually perform the constructor
4906        // call.
4907        Expr *Arg = CurInit.get();
4908        if (S.CompleteConstructorCall(Constructor,
4909                                      MultiExprArg(&Arg, 1),
4910                                      Loc, ConstructorArgs))
4911          return ExprError();
4912
4913        // Build an expression that constructs a temporary.
4914        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
4915                                          move_arg(ConstructorArgs),
4916                                          HadMultipleCandidates,
4917                                          /*ZeroInit*/ false,
4918                                          CXXConstructExpr::CK_Complete,
4919                                          SourceRange());
4920        if (CurInit.isInvalid())
4921          return ExprError();
4922
4923        S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
4924                                 FoundFn.getAccess());
4925        S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4926
4927        CastKind = CK_ConstructorConversion;
4928        QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4929        if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4930            S.IsDerivedFrom(SourceType, Class))
4931          IsCopy = true;
4932
4933        CreatedObject = true;
4934      } else {
4935        // Build a call to the conversion function.
4936        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
4937        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
4938                                    FoundFn);
4939        S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4940
4941        // FIXME: Should we move this initialization into a separate
4942        // derived-to-base conversion? I believe the answer is "no", because
4943        // we don't want to turn off access control here for c-style casts.
4944        ExprResult CurInitExprRes =
4945          S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4946                                                FoundFn, Conversion);
4947        if(CurInitExprRes.isInvalid())
4948          return ExprError();
4949        CurInit = move(CurInitExprRes);
4950
4951        // Build the actual call to the conversion function.
4952        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4953                                           HadMultipleCandidates);
4954        if (CurInit.isInvalid() || !CurInit.get())
4955          return ExprError();
4956
4957        CastKind = CK_UserDefinedConversion;
4958
4959        CreatedObject = Conversion->getResultType()->isRecordType();
4960      }
4961
4962      bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
4963      bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4964
4965      if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
4966        QualType T = CurInit.get()->getType();
4967        if (const RecordType *Record = T->getAs<RecordType>()) {
4968          CXXDestructorDecl *Destructor
4969            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
4970          S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
4971                                  S.PDiag(diag::err_access_dtor_temp) << T);
4972          S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
4973          S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
4974        }
4975      }
4976
4977      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4978                                                 CurInit.get()->getType(),
4979                                                 CastKind, CurInit.get(), 0,
4980                                                CurInit.get()->getValueKind()));
4981      if (MaybeBindToTemp)
4982        CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4983      if (RequiresCopy)
4984        CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4985                             move(CurInit), /*IsExtraneousCopy=*/false);
4986      break;
4987    }
4988
4989    case SK_QualificationConversionLValue:
4990    case SK_QualificationConversionXValue:
4991    case SK_QualificationConversionRValue: {
4992      // Perform a qualification conversion; these can never go wrong.
4993      ExprValueKind VK =
4994          Step->Kind == SK_QualificationConversionLValue ?
4995              VK_LValue :
4996              (Step->Kind == SK_QualificationConversionXValue ?
4997                   VK_XValue :
4998                   VK_RValue);
4999      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5000      break;
5001    }
5002
5003    case SK_ConversionSequence: {
5004      Sema::CheckedConversionKind CCK
5005        = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5006        : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5007        : Kind.isExplicitCast()? Sema::CCK_OtherCast
5008        : Sema::CCK_ImplicitConversion;
5009      ExprResult CurInitExprRes =
5010        S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5011                                    getAssignmentAction(Entity), CCK);
5012      if (CurInitExprRes.isInvalid())
5013        return ExprError();
5014      CurInit = move(CurInitExprRes);
5015      break;
5016    }
5017
5018    case SK_ListInitialization: {
5019      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5020      // Hack: We must pass *ResultType if available in order to set the type
5021      // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5022      // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5023      // temporary, not a reference, so we should pass Ty.
5024      // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5025      // Since this step is never used for a reference directly, we explicitly
5026      // unwrap references here and rewrap them afterwards.
5027      // We also need to create a InitializeTemporary entity for this.
5028      QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5029      bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5030      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5031      InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5032          InitList, Ty, /*VerifyOnly=*/false,
5033          Kind.getKind() != InitializationKind::IK_DirectList ||
5034            !S.getLangOptions().CPlusPlus0x);
5035      if (PerformInitList.HadError())
5036        return ExprError();
5037
5038      if (ResultType) {
5039        if ((*ResultType)->isRValueReferenceType())
5040          Ty = S.Context.getRValueReferenceType(Ty);
5041        else if ((*ResultType)->isLValueReferenceType())
5042          Ty = S.Context.getLValueReferenceType(Ty,
5043            (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5044        *ResultType = Ty;
5045      }
5046
5047      InitListExpr *StructuredInitList =
5048          PerformInitList.getFullyStructuredList();
5049      CurInit.release();
5050      CurInit = S.Owned(StructuredInitList);
5051      break;
5052    }
5053
5054    case SK_ListConstructorCall: {
5055      // When an initializer list is passed for a parameter of type "reference
5056      // to object", we don't get an EK_Temporary entity, but instead an
5057      // EK_Parameter entity with reference type.
5058      // FIXME: This is a hack. Why is this necessary here, but not in other
5059      // places where implicit temporaries are created?
5060      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5061                                        Entity.getType().getNonReferenceType());
5062      bool UseTemporary = Entity.getType()->isReferenceType();
5063      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5064      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5065      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5066                                                                   Entity,
5067                                                 Kind, move(Arg), *Step,
5068                                               ConstructorInitRequiresZeroInit);
5069      break;
5070    }
5071
5072    case SK_UnwrapInitList:
5073      CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5074      break;
5075
5076    case SK_RewrapInitList: {
5077      Expr *E = CurInit.take();
5078      InitListExpr *Syntactic = Step->WrappingSyntacticList;
5079      InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5080          Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5081      ILE->setSyntacticForm(Syntactic);
5082      ILE->setType(E->getType());
5083      ILE->setValueKind(E->getValueKind());
5084      CurInit = S.Owned(ILE);
5085      break;
5086    }
5087
5088    case SK_ConstructorInitialization:
5089      CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5090                                                 *Step,
5091                                               ConstructorInitRequiresZeroInit);
5092      break;
5093
5094    case SK_ZeroInitialization: {
5095      step_iterator NextStep = Step;
5096      ++NextStep;
5097      if (NextStep != StepEnd &&
5098          NextStep->Kind == SK_ConstructorInitialization) {
5099        // The need for zero-initialization is recorded directly into
5100        // the call to the object's constructor within the next step.
5101        ConstructorInitRequiresZeroInit = true;
5102      } else if (Kind.getKind() == InitializationKind::IK_Value &&
5103                 S.getLangOptions().CPlusPlus &&
5104                 !Kind.isImplicitValueInit()) {
5105        TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5106        if (!TSInfo)
5107          TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5108                                                    Kind.getRange().getBegin());
5109
5110        CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5111                              TSInfo->getType().getNonLValueExprType(S.Context),
5112                                                                 TSInfo,
5113                                                    Kind.getRange().getEnd()));
5114      } else {
5115        CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5116      }
5117      break;
5118    }
5119
5120    case SK_CAssignment: {
5121      QualType SourceType = CurInit.get()->getType();
5122      ExprResult Result = move(CurInit);
5123      Sema::AssignConvertType ConvTy =
5124        S.CheckSingleAssignmentConstraints(Step->Type, Result);
5125      if (Result.isInvalid())
5126        return ExprError();
5127      CurInit = move(Result);
5128
5129      // If this is a call, allow conversion to a transparent union.
5130      ExprResult CurInitExprRes = move(CurInit);
5131      if (ConvTy != Sema::Compatible &&
5132          Entity.getKind() == InitializedEntity::EK_Parameter &&
5133          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5134            == Sema::Compatible)
5135        ConvTy = Sema::Compatible;
5136      if (CurInitExprRes.isInvalid())
5137        return ExprError();
5138      CurInit = move(CurInitExprRes);
5139
5140      bool Complained;
5141      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5142                                     Step->Type, SourceType,
5143                                     CurInit.get(),
5144                                     getAssignmentAction(Entity),
5145                                     &Complained)) {
5146        PrintInitLocationNote(S, Entity);
5147        return ExprError();
5148      } else if (Complained)
5149        PrintInitLocationNote(S, Entity);
5150      break;
5151    }
5152
5153    case SK_StringInit: {
5154      QualType Ty = Step->Type;
5155      CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5156                      S.Context.getAsArrayType(Ty), S);
5157      break;
5158    }
5159
5160    case SK_ObjCObjectConversion:
5161      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5162                          CK_ObjCObjectLValueCast,
5163                          CurInit.get()->getValueKind());
5164      break;
5165
5166    case SK_ArrayInit:
5167      // Okay: we checked everything before creating this step. Note that
5168      // this is a GNU extension.
5169      S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5170        << Step->Type << CurInit.get()->getType()
5171        << CurInit.get()->getSourceRange();
5172
5173      // If the destination type is an incomplete array type, update the
5174      // type accordingly.
5175      if (ResultType) {
5176        if (const IncompleteArrayType *IncompleteDest
5177                           = S.Context.getAsIncompleteArrayType(Step->Type)) {
5178          if (const ConstantArrayType *ConstantSource
5179                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5180            *ResultType = S.Context.getConstantArrayType(
5181                                             IncompleteDest->getElementType(),
5182                                             ConstantSource->getSize(),
5183                                             ArrayType::Normal, 0);
5184          }
5185        }
5186      }
5187      break;
5188
5189    case SK_PassByIndirectCopyRestore:
5190    case SK_PassByIndirectRestore:
5191      checkIndirectCopyRestoreSource(S, CurInit.get());
5192      CurInit = S.Owned(new (S.Context)
5193                        ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5194                                Step->Kind == SK_PassByIndirectCopyRestore));
5195      break;
5196
5197    case SK_ProduceObjCObject:
5198      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5199                                                 CK_ARCProduceObject,
5200                                                 CurInit.take(), 0, VK_RValue));
5201      break;
5202
5203    case SK_StdInitializerList: {
5204      QualType Dest = Step->Type;
5205      QualType E;
5206      bool Success = S.isStdInitializerList(Dest, &E);
5207      (void)Success;
5208      assert(Success && "Destination type changed?");
5209      InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5210      unsigned NumInits = ILE->getNumInits();
5211      SmallVector<Expr*, 16> Converted(NumInits);
5212      InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5213          S.Context.getConstantArrayType(E,
5214              llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5215                          NumInits),
5216              ArrayType::Normal, 0));
5217      InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5218          0, HiddenArray);
5219      for (unsigned i = 0; i < NumInits; ++i) {
5220        Element.setElementIndex(i);
5221        ExprResult Init = S.Owned(ILE->getInit(i));
5222        ExprResult Res = S.PerformCopyInitialization(Element,
5223                                                     Init.get()->getExprLoc(),
5224                                                     Init);
5225        assert(!Res.isInvalid() && "Result changed since try phase.");
5226        Converted[i] = Res.take();
5227      }
5228      InitListExpr *Semantic = new (S.Context)
5229          InitListExpr(S.Context, ILE->getLBraceLoc(),
5230                       Converted.data(), NumInits, ILE->getRBraceLoc());
5231      Semantic->setSyntacticForm(ILE);
5232      Semantic->setType(Dest);
5233      CurInit = S.Owned(Semantic);
5234      break;
5235    }
5236    }
5237  }
5238
5239  // Diagnose non-fatal problems with the completed initialization.
5240  if (Entity.getKind() == InitializedEntity::EK_Member &&
5241      cast<FieldDecl>(Entity.getDecl())->isBitField())
5242    S.CheckBitFieldInitialization(Kind.getLocation(),
5243                                  cast<FieldDecl>(Entity.getDecl()),
5244                                  CurInit.get());
5245
5246  return move(CurInit);
5247}
5248
5249//===----------------------------------------------------------------------===//
5250// Diagnose initialization failures
5251//===----------------------------------------------------------------------===//
5252bool InitializationSequence::Diagnose(Sema &S,
5253                                      const InitializedEntity &Entity,
5254                                      const InitializationKind &Kind,
5255                                      Expr **Args, unsigned NumArgs) {
5256  if (!Failed())
5257    return false;
5258
5259  QualType DestType = Entity.getType();
5260  switch (Failure) {
5261  case FK_TooManyInitsForReference:
5262    // FIXME: Customize for the initialized entity?
5263    if (NumArgs == 0)
5264      S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5265        << DestType.getNonReferenceType();
5266    else  // FIXME: diagnostic below could be better!
5267      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5268        << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
5269    break;
5270
5271  case FK_ArrayNeedsInitList:
5272  case FK_ArrayNeedsInitListOrStringLiteral:
5273    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5274      << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5275    break;
5276
5277  case FK_ArrayTypeMismatch:
5278  case FK_NonConstantArrayInit:
5279    S.Diag(Kind.getLocation(),
5280           (Failure == FK_ArrayTypeMismatch
5281              ? diag::err_array_init_different_type
5282              : diag::err_array_init_non_constant_array))
5283      << DestType.getNonReferenceType()
5284      << Args[0]->getType()
5285      << Args[0]->getSourceRange();
5286    break;
5287
5288  case FK_VariableLengthArrayHasInitializer:
5289    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5290      << Args[0]->getSourceRange();
5291    break;
5292
5293  case FK_AddressOfOverloadFailed: {
5294    DeclAccessPair Found;
5295    S.ResolveAddressOfOverloadedFunction(Args[0],
5296                                         DestType.getNonReferenceType(),
5297                                         true,
5298                                         Found);
5299    break;
5300  }
5301
5302  case FK_ReferenceInitOverloadFailed:
5303  case FK_UserConversionOverloadFailed:
5304    switch (FailedOverloadResult) {
5305    case OR_Ambiguous:
5306      if (Failure == FK_UserConversionOverloadFailed)
5307        S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5308          << Args[0]->getType() << DestType
5309          << Args[0]->getSourceRange();
5310      else
5311        S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5312          << DestType << Args[0]->getType()
5313          << Args[0]->getSourceRange();
5314
5315      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
5316      break;
5317
5318    case OR_No_Viable_Function:
5319      S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5320        << Args[0]->getType() << DestType.getNonReferenceType()
5321        << Args[0]->getSourceRange();
5322      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
5323      break;
5324
5325    case OR_Deleted: {
5326      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5327        << Args[0]->getType() << DestType.getNonReferenceType()
5328        << Args[0]->getSourceRange();
5329      OverloadCandidateSet::iterator Best;
5330      OverloadingResult Ovl
5331        = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5332                                                true);
5333      if (Ovl == OR_Deleted) {
5334        S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5335          << 1 << Best->Function->isDeleted();
5336      } else {
5337        llvm_unreachable("Inconsistent overload resolution?");
5338      }
5339      break;
5340    }
5341
5342    case OR_Success:
5343      llvm_unreachable("Conversion did not fail!");
5344    }
5345    break;
5346
5347  case FK_NonConstLValueReferenceBindingToTemporary:
5348    if (isa<InitListExpr>(Args[0])) {
5349      S.Diag(Kind.getLocation(),
5350             diag::err_lvalue_reference_bind_to_initlist)
5351      << DestType.getNonReferenceType().isVolatileQualified()
5352      << DestType.getNonReferenceType()
5353      << Args[0]->getSourceRange();
5354      break;
5355    }
5356    // Intentional fallthrough
5357
5358  case FK_NonConstLValueReferenceBindingToUnrelated:
5359    S.Diag(Kind.getLocation(),
5360           Failure == FK_NonConstLValueReferenceBindingToTemporary
5361             ? diag::err_lvalue_reference_bind_to_temporary
5362             : diag::err_lvalue_reference_bind_to_unrelated)
5363      << DestType.getNonReferenceType().isVolatileQualified()
5364      << DestType.getNonReferenceType()
5365      << Args[0]->getType()
5366      << Args[0]->getSourceRange();
5367    break;
5368
5369  case FK_RValueReferenceBindingToLValue:
5370    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
5371      << DestType.getNonReferenceType() << Args[0]->getType()
5372      << Args[0]->getSourceRange();
5373    break;
5374
5375  case FK_ReferenceInitDropsQualifiers:
5376    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5377      << DestType.getNonReferenceType()
5378      << Args[0]->getType()
5379      << Args[0]->getSourceRange();
5380    break;
5381
5382  case FK_ReferenceInitFailed:
5383    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5384      << DestType.getNonReferenceType()
5385      << Args[0]->isLValue()
5386      << Args[0]->getType()
5387      << Args[0]->getSourceRange();
5388    if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5389        Args[0]->getType()->isObjCObjectPointerType())
5390      S.EmitRelatedResultTypeNote(Args[0]);
5391    break;
5392
5393  case FK_ConversionFailed: {
5394    QualType FromType = Args[0]->getType();
5395    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
5396      << (int)Entity.getKind()
5397      << DestType
5398      << Args[0]->isLValue()
5399      << FromType
5400      << Args[0]->getSourceRange();
5401    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5402    S.Diag(Kind.getLocation(), PDiag);
5403    if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5404        Args[0]->getType()->isObjCObjectPointerType())
5405      S.EmitRelatedResultTypeNote(Args[0]);
5406    break;
5407  }
5408
5409  case FK_ConversionFromPropertyFailed:
5410    // No-op. This error has already been reported.
5411    break;
5412
5413  case FK_TooManyInitsForScalar: {
5414    SourceRange R;
5415
5416    if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5417      R = SourceRange(InitList->getInit(0)->getLocEnd(),
5418                      InitList->getLocEnd());
5419    else
5420      R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
5421
5422    R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5423    if (Kind.isCStyleOrFunctionalCast())
5424      S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5425        << R;
5426    else
5427      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5428        << /*scalar=*/2 << R;
5429    break;
5430  }
5431
5432  case FK_ReferenceBindingToInitList:
5433    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5434      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5435    break;
5436
5437  case FK_InitListBadDestinationType:
5438    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5439      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5440    break;
5441
5442  case FK_ListConstructorOverloadFailed:
5443  case FK_ConstructorOverloadFailed: {
5444    SourceRange ArgsRange;
5445    if (NumArgs)
5446      ArgsRange = SourceRange(Args[0]->getLocStart(),
5447                              Args[NumArgs - 1]->getLocEnd());
5448
5449    if (Failure == FK_ListConstructorOverloadFailed) {
5450      assert(NumArgs == 1 && "List construction from other than 1 argument.");
5451      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5452      Args = InitList->getInits();
5453      NumArgs = InitList->getNumInits();
5454    }
5455
5456    // FIXME: Using "DestType" for the entity we're printing is probably
5457    // bad.
5458    switch (FailedOverloadResult) {
5459      case OR_Ambiguous:
5460        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5461          << DestType << ArgsRange;
5462        FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5463                                          Args, NumArgs);
5464        break;
5465
5466      case OR_No_Viable_Function:
5467        if (Kind.getKind() == InitializationKind::IK_Default &&
5468            (Entity.getKind() == InitializedEntity::EK_Base ||
5469             Entity.getKind() == InitializedEntity::EK_Member) &&
5470            isa<CXXConstructorDecl>(S.CurContext)) {
5471          // This is implicit default initialization of a member or
5472          // base within a constructor. If no viable function was
5473          // found, notify the user that she needs to explicitly
5474          // initialize this base/member.
5475          CXXConstructorDecl *Constructor
5476            = cast<CXXConstructorDecl>(S.CurContext);
5477          if (Entity.getKind() == InitializedEntity::EK_Base) {
5478            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5479              << Constructor->isImplicit()
5480              << S.Context.getTypeDeclType(Constructor->getParent())
5481              << /*base=*/0
5482              << Entity.getType();
5483
5484            RecordDecl *BaseDecl
5485              = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5486                                                                  ->getDecl();
5487            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5488              << S.Context.getTagDeclType(BaseDecl);
5489          } else {
5490            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5491              << Constructor->isImplicit()
5492              << S.Context.getTypeDeclType(Constructor->getParent())
5493              << /*member=*/1
5494              << Entity.getName();
5495            S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5496
5497            if (const RecordType *Record
5498                                 = Entity.getType()->getAs<RecordType>())
5499              S.Diag(Record->getDecl()->getLocation(),
5500                     diag::note_previous_decl)
5501                << S.Context.getTagDeclType(Record->getDecl());
5502          }
5503          break;
5504        }
5505
5506        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5507          << DestType << ArgsRange;
5508        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
5509        break;
5510
5511      case OR_Deleted: {
5512        S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5513          << true << DestType << ArgsRange;
5514        OverloadCandidateSet::iterator Best;
5515        OverloadingResult Ovl
5516          = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5517        if (Ovl == OR_Deleted) {
5518          S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5519            << 1 << Best->Function->isDeleted();
5520        } else {
5521          llvm_unreachable("Inconsistent overload resolution?");
5522        }
5523        break;
5524      }
5525
5526      case OR_Success:
5527        llvm_unreachable("Conversion did not fail!");
5528    }
5529  }
5530  break;
5531
5532  case FK_DefaultInitOfConst:
5533    if (Entity.getKind() == InitializedEntity::EK_Member &&
5534        isa<CXXConstructorDecl>(S.CurContext)) {
5535      // This is implicit default-initialization of a const member in
5536      // a constructor. Complain that it needs to be explicitly
5537      // initialized.
5538      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5539      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5540        << Constructor->isImplicit()
5541        << S.Context.getTypeDeclType(Constructor->getParent())
5542        << /*const=*/1
5543        << Entity.getName();
5544      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5545        << Entity.getName();
5546    } else {
5547      S.Diag(Kind.getLocation(), diag::err_default_init_const)
5548        << DestType << (bool)DestType->getAs<RecordType>();
5549    }
5550    break;
5551
5552  case FK_Incomplete:
5553    S.RequireCompleteType(Kind.getLocation(), DestType,
5554                          diag::err_init_incomplete_type);
5555    break;
5556
5557  case FK_ListInitializationFailed: {
5558    // Run the init list checker again to emit diagnostics.
5559    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5560    QualType DestType = Entity.getType();
5561    InitListChecker DiagnoseInitList(S, Entity, InitList,
5562            DestType, /*VerifyOnly=*/false,
5563            Kind.getKind() != InitializationKind::IK_DirectList ||
5564              !S.getLangOptions().CPlusPlus0x);
5565    assert(DiagnoseInitList.HadError() &&
5566           "Inconsistent init list check result.");
5567    break;
5568  }
5569
5570  case FK_PlaceholderType: {
5571    // FIXME: Already diagnosed!
5572    break;
5573  }
5574
5575  case FK_InitListElementCopyFailure: {
5576    // Try to perform all copies again.
5577    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5578    unsigned NumInits = InitList->getNumInits();
5579    QualType DestType = Entity.getType();
5580    QualType E;
5581    bool Success = S.isStdInitializerList(DestType, &E);
5582    (void)Success;
5583    assert(Success && "Where did the std::initializer_list go?");
5584    InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5585        S.Context.getConstantArrayType(E,
5586            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5587                        NumInits),
5588            ArrayType::Normal, 0));
5589    InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5590        0, HiddenArray);
5591    // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5592    // where the init list type is wrong, e.g.
5593    //   std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5594    // FIXME: Emit a note if we hit the limit?
5595    int ErrorCount = 0;
5596    for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5597      Element.setElementIndex(i);
5598      ExprResult Init = S.Owned(InitList->getInit(i));
5599      if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5600           .isInvalid())
5601        ++ErrorCount;
5602    }
5603    break;
5604  }
5605  }
5606
5607  PrintInitLocationNote(S, Entity);
5608  return true;
5609}
5610
5611void InitializationSequence::dump(raw_ostream &OS) const {
5612  switch (SequenceKind) {
5613  case FailedSequence: {
5614    OS << "Failed sequence: ";
5615    switch (Failure) {
5616    case FK_TooManyInitsForReference:
5617      OS << "too many initializers for reference";
5618      break;
5619
5620    case FK_ArrayNeedsInitList:
5621      OS << "array requires initializer list";
5622      break;
5623
5624    case FK_ArrayNeedsInitListOrStringLiteral:
5625      OS << "array requires initializer list or string literal";
5626      break;
5627
5628    case FK_ArrayTypeMismatch:
5629      OS << "array type mismatch";
5630      break;
5631
5632    case FK_NonConstantArrayInit:
5633      OS << "non-constant array initializer";
5634      break;
5635
5636    case FK_AddressOfOverloadFailed:
5637      OS << "address of overloaded function failed";
5638      break;
5639
5640    case FK_ReferenceInitOverloadFailed:
5641      OS << "overload resolution for reference initialization failed";
5642      break;
5643
5644    case FK_NonConstLValueReferenceBindingToTemporary:
5645      OS << "non-const lvalue reference bound to temporary";
5646      break;
5647
5648    case FK_NonConstLValueReferenceBindingToUnrelated:
5649      OS << "non-const lvalue reference bound to unrelated type";
5650      break;
5651
5652    case FK_RValueReferenceBindingToLValue:
5653      OS << "rvalue reference bound to an lvalue";
5654      break;
5655
5656    case FK_ReferenceInitDropsQualifiers:
5657      OS << "reference initialization drops qualifiers";
5658      break;
5659
5660    case FK_ReferenceInitFailed:
5661      OS << "reference initialization failed";
5662      break;
5663
5664    case FK_ConversionFailed:
5665      OS << "conversion failed";
5666      break;
5667
5668    case FK_ConversionFromPropertyFailed:
5669      OS << "conversion from property failed";
5670      break;
5671
5672    case FK_TooManyInitsForScalar:
5673      OS << "too many initializers for scalar";
5674      break;
5675
5676    case FK_ReferenceBindingToInitList:
5677      OS << "referencing binding to initializer list";
5678      break;
5679
5680    case FK_InitListBadDestinationType:
5681      OS << "initializer list for non-aggregate, non-scalar type";
5682      break;
5683
5684    case FK_UserConversionOverloadFailed:
5685      OS << "overloading failed for user-defined conversion";
5686      break;
5687
5688    case FK_ConstructorOverloadFailed:
5689      OS << "constructor overloading failed";
5690      break;
5691
5692    case FK_DefaultInitOfConst:
5693      OS << "default initialization of a const variable";
5694      break;
5695
5696    case FK_Incomplete:
5697      OS << "initialization of incomplete type";
5698      break;
5699
5700    case FK_ListInitializationFailed:
5701      OS << "list initialization checker failure";
5702      break;
5703
5704    case FK_VariableLengthArrayHasInitializer:
5705      OS << "variable length array has an initializer";
5706      break;
5707
5708    case FK_PlaceholderType:
5709      OS << "initializer expression isn't contextually valid";
5710      break;
5711
5712    case FK_ListConstructorOverloadFailed:
5713      OS << "list constructor overloading failed";
5714      break;
5715
5716    case FK_InitListElementCopyFailure:
5717      OS << "copy construction of initializer list element failed";
5718      break;
5719    }
5720    OS << '\n';
5721    return;
5722  }
5723
5724  case DependentSequence:
5725    OS << "Dependent sequence\n";
5726    return;
5727
5728  case NormalSequence:
5729    OS << "Normal sequence: ";
5730    break;
5731  }
5732
5733  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5734    if (S != step_begin()) {
5735      OS << " -> ";
5736    }
5737
5738    switch (S->Kind) {
5739    case SK_ResolveAddressOfOverloadedFunction:
5740      OS << "resolve address of overloaded function";
5741      break;
5742
5743    case SK_CastDerivedToBaseRValue:
5744      OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5745      break;
5746
5747    case SK_CastDerivedToBaseXValue:
5748      OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5749      break;
5750
5751    case SK_CastDerivedToBaseLValue:
5752      OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5753      break;
5754
5755    case SK_BindReference:
5756      OS << "bind reference to lvalue";
5757      break;
5758
5759    case SK_BindReferenceToTemporary:
5760      OS << "bind reference to a temporary";
5761      break;
5762
5763    case SK_ExtraneousCopyToTemporary:
5764      OS << "extraneous C++03 copy to temporary";
5765      break;
5766
5767    case SK_UserConversion:
5768      OS << "user-defined conversion via " << *S->Function.Function;
5769      break;
5770
5771    case SK_QualificationConversionRValue:
5772      OS << "qualification conversion (rvalue)";
5773      break;
5774
5775    case SK_QualificationConversionXValue:
5776      OS << "qualification conversion (xvalue)";
5777      break;
5778
5779    case SK_QualificationConversionLValue:
5780      OS << "qualification conversion (lvalue)";
5781      break;
5782
5783    case SK_ConversionSequence:
5784      OS << "implicit conversion sequence (";
5785      S->ICS->DebugPrint(); // FIXME: use OS
5786      OS << ")";
5787      break;
5788
5789    case SK_ListInitialization:
5790      OS << "list aggregate initialization";
5791      break;
5792
5793    case SK_ListConstructorCall:
5794      OS << "list initialization via constructor";
5795      break;
5796
5797    case SK_UnwrapInitList:
5798      OS << "unwrap reference initializer list";
5799      break;
5800
5801    case SK_RewrapInitList:
5802      OS << "rewrap reference initializer list";
5803      break;
5804
5805    case SK_ConstructorInitialization:
5806      OS << "constructor initialization";
5807      break;
5808
5809    case SK_ZeroInitialization:
5810      OS << "zero initialization";
5811      break;
5812
5813    case SK_CAssignment:
5814      OS << "C assignment";
5815      break;
5816
5817    case SK_StringInit:
5818      OS << "string initialization";
5819      break;
5820
5821    case SK_ObjCObjectConversion:
5822      OS << "Objective-C object conversion";
5823      break;
5824
5825    case SK_ArrayInit:
5826      OS << "array initialization";
5827      break;
5828
5829    case SK_PassByIndirectCopyRestore:
5830      OS << "pass by indirect copy and restore";
5831      break;
5832
5833    case SK_PassByIndirectRestore:
5834      OS << "pass by indirect restore";
5835      break;
5836
5837    case SK_ProduceObjCObject:
5838      OS << "Objective-C object retension";
5839      break;
5840
5841    case SK_StdInitializerList:
5842      OS << "std::initializer_list from initializer list";
5843      break;
5844    }
5845  }
5846}
5847
5848void InitializationSequence::dump() const {
5849  dump(llvm::errs());
5850}
5851
5852static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5853                                        QualType EntityType,
5854                                        const Expr *PreInit,
5855                                        const Expr *PostInit) {
5856  if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5857    return;
5858
5859  // A narrowing conversion can only appear as the final implicit conversion in
5860  // an initialization sequence.
5861  const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5862  if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5863    return;
5864
5865  const ImplicitConversionSequence &ICS = *LastStep.ICS;
5866  const StandardConversionSequence *SCS = 0;
5867  switch (ICS.getKind()) {
5868  case ImplicitConversionSequence::StandardConversion:
5869    SCS = &ICS.Standard;
5870    break;
5871  case ImplicitConversionSequence::UserDefinedConversion:
5872    SCS = &ICS.UserDefined.After;
5873    break;
5874  case ImplicitConversionSequence::AmbiguousConversion:
5875  case ImplicitConversionSequence::EllipsisConversion:
5876  case ImplicitConversionSequence::BadConversion:
5877    return;
5878  }
5879
5880  // Determine the type prior to the narrowing conversion. If a conversion
5881  // operator was used, this may be different from both the type of the entity
5882  // and of the pre-initialization expression.
5883  QualType PreNarrowingType = PreInit->getType();
5884  if (Seq.step_begin() + 1 != Seq.step_end())
5885    PreNarrowingType = Seq.step_end()[-2].Type;
5886
5887  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5888  APValue ConstantValue;
5889  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
5890  case NK_Not_Narrowing:
5891    // No narrowing occurred.
5892    return;
5893
5894  case NK_Type_Narrowing:
5895    // This was a floating-to-integer conversion, which is always considered a
5896    // narrowing conversion even if the value is a constant and can be
5897    // represented exactly as an integer.
5898    S.Diag(PostInit->getLocStart(),
5899           S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5900             diag::warn_init_list_type_narrowing
5901           : S.isSFINAEContext()?
5902             diag::err_init_list_type_narrowing_sfinae
5903           : diag::err_init_list_type_narrowing)
5904      << PostInit->getSourceRange()
5905      << PreNarrowingType.getLocalUnqualifiedType()
5906      << EntityType.getLocalUnqualifiedType();
5907    break;
5908
5909  case NK_Constant_Narrowing:
5910    // A constant value was narrowed.
5911    S.Diag(PostInit->getLocStart(),
5912           S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5913             diag::warn_init_list_constant_narrowing
5914           : S.isSFINAEContext()?
5915             diag::err_init_list_constant_narrowing_sfinae
5916           : diag::err_init_list_constant_narrowing)
5917      << PostInit->getSourceRange()
5918      << ConstantValue.getAsString(S.getASTContext(), EntityType)
5919      << EntityType.getLocalUnqualifiedType();
5920    break;
5921
5922  case NK_Variable_Narrowing:
5923    // A variable's value may have been narrowed.
5924    S.Diag(PostInit->getLocStart(),
5925           S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5926             diag::warn_init_list_variable_narrowing
5927           : S.isSFINAEContext()?
5928             diag::err_init_list_variable_narrowing_sfinae
5929           : diag::err_init_list_variable_narrowing)
5930      << PostInit->getSourceRange()
5931      << PreNarrowingType.getLocalUnqualifiedType()
5932      << EntityType.getLocalUnqualifiedType();
5933    break;
5934  }
5935
5936  SmallString<128> StaticCast;
5937  llvm::raw_svector_ostream OS(StaticCast);
5938  OS << "static_cast<";
5939  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5940    // It's important to use the typedef's name if there is one so that the
5941    // fixit doesn't break code using types like int64_t.
5942    //
5943    // FIXME: This will break if the typedef requires qualification.  But
5944    // getQualifiedNameAsString() includes non-machine-parsable components.
5945    OS << *TT->getDecl();
5946  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5947    OS << BT->getName(S.getLangOptions());
5948  else {
5949    // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
5950    // with a broken cast.
5951    return;
5952  }
5953  OS << ">(";
5954  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5955    << PostInit->getSourceRange()
5956    << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
5957    << FixItHint::CreateInsertion(
5958      S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
5959}
5960
5961//===----------------------------------------------------------------------===//
5962// Initialization helper functions
5963//===----------------------------------------------------------------------===//
5964bool
5965Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5966                                   ExprResult Init) {
5967  if (Init.isInvalid())
5968    return false;
5969
5970  Expr *InitE = Init.get();
5971  assert(InitE && "No initialization expression");
5972
5973  InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5974                                                           SourceLocation());
5975  InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5976  return !Seq.Failed();
5977}
5978
5979ExprResult
5980Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5981                                SourceLocation EqualLoc,
5982                                ExprResult Init,
5983                                bool TopLevelOfInitList) {
5984  if (Init.isInvalid())
5985    return ExprError();
5986
5987  Expr *InitE = Init.get();
5988  assert(InitE && "No initialization expression?");
5989
5990  if (EqualLoc.isInvalid())
5991    EqualLoc = InitE->getLocStart();
5992
5993  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5994                                                           EqualLoc);
5995  InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5996  Init.release();
5997
5998  ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5999
6000  if (!Result.isInvalid() && TopLevelOfInitList)
6001    DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6002                                InitE, Result.get());
6003
6004  return Result;
6005}
6006