SemaInit.cpp revision 1d0c9a8d0573d1f670f484cc17aa94f06be971a5
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 or reference of type T is defined as
2703  //   follows:
2704  //   - If T is an aggregate, aggregate initialization is performed.
2705  if (DestType->isAggregateType())
2706    return false;
2707
2708  //   - Otherwise, if the initializer list has no elements and T is a class
2709  //     type with a default constructor, the object is value-initialized.
2710  if (List->getNumInits() == 0) {
2711    if (CXXConstructorDecl *DefaultConstructor =
2712            S.LookupDefaultConstructor(DestRecordDecl)) {
2713      if (DefaultConstructor->isDeleted() ||
2714          S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2715        // Fake an overload resolution failure.
2716        OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2717        DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2718                                              DefaultConstructor->getAccess());
2719        if (FunctionTemplateDecl *ConstructorTmpl =
2720                dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2721          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2722                                         /*ExplicitArgs*/ 0,
2723                                         0, 0, CandidateSet,
2724                                         /*SuppressUserConversions*/ false);
2725        else
2726          S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2727                                 0, 0, CandidateSet,
2728                                 /*SuppressUserConversions*/ false);
2729        Sequence.SetOverloadFailure(
2730                       InitializationSequence::FK_ListConstructorOverloadFailed,
2731                       OR_Deleted);
2732      } else
2733        Sequence.AddConstructorInitializationStep(DefaultConstructor,
2734                                                DefaultConstructor->getAccess(),
2735                                                  DestType,
2736                                                  /*MultipleCandidates=*/false,
2737                                                  /*FromInitList=*/true,
2738                                                  /*AsInitList=*/false);
2739      return true;
2740    }
2741  }
2742
2743  //   - Otherwise, if T is a specialization of std::initializer_list, [...]
2744  QualType E;
2745  if (S.isStdInitializerList(DestType, &E)) {
2746    // Check that each individual element can be copy-constructed. But since we
2747    // have no place to store further information, we'll recalculate everything
2748    // later.
2749    InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2750        S.Context.getConstantArrayType(E,
2751            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2752                        List->getNumInits()),
2753            ArrayType::Normal, 0));
2754    InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2755        0, HiddenArray);
2756    for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2757      Element.setElementIndex(i);
2758      if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2759        Sequence.SetFailed(
2760            InitializationSequence::FK_InitListElementCopyFailure);
2761        return true;
2762      }
2763    }
2764    Sequence.AddStdInitializerListConstructionStep(DestType);
2765    return true;
2766  }
2767
2768  // Not a special case.
2769  return false;
2770}
2771
2772static OverloadingResult
2773ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2774                           Expr **Args, unsigned NumArgs,
2775                           OverloadCandidateSet &CandidateSet,
2776                           DeclContext::lookup_iterator Con,
2777                           DeclContext::lookup_iterator ConEnd,
2778                           OverloadCandidateSet::iterator &Best,
2779                           bool CopyInitializing, bool AllowExplicit,
2780                           bool OnlyListConstructors) {
2781  CandidateSet.clear();
2782
2783  for (; Con != ConEnd; ++Con) {
2784    NamedDecl *D = *Con;
2785    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2786    bool SuppressUserConversions = false;
2787
2788    // Find the constructor (which may be a template).
2789    CXXConstructorDecl *Constructor = 0;
2790    FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2791    if (ConstructorTmpl)
2792      Constructor = cast<CXXConstructorDecl>(
2793                                           ConstructorTmpl->getTemplatedDecl());
2794    else {
2795      Constructor = cast<CXXConstructorDecl>(D);
2796
2797      // If we're performing copy initialization using a copy constructor, we
2798      // suppress user-defined conversions on the arguments.
2799      // FIXME: Move constructors?
2800      if (CopyInitializing && Constructor->isCopyConstructor())
2801        SuppressUserConversions = true;
2802    }
2803
2804    if (!Constructor->isInvalidDecl() &&
2805        (AllowExplicit || !Constructor->isExplicit()) &&
2806        (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
2807      if (ConstructorTmpl)
2808        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2809                                       /*ExplicitArgs*/ 0,
2810                                       Args, NumArgs, CandidateSet,
2811                                       SuppressUserConversions);
2812      else
2813        S.AddOverloadCandidate(Constructor, FoundDecl,
2814                               Args, NumArgs, CandidateSet,
2815                               SuppressUserConversions);
2816    }
2817  }
2818
2819  // Perform overload resolution and return the result.
2820  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2821}
2822
2823/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2824/// enumerates the constructors of the initialized entity and performs overload
2825/// resolution to select the best.
2826/// If InitListSyntax is true, this is list-initialization of a non-aggregate
2827/// class type.
2828static void TryConstructorInitialization(Sema &S,
2829                                         const InitializedEntity &Entity,
2830                                         const InitializationKind &Kind,
2831                                         Expr **Args, unsigned NumArgs,
2832                                         QualType DestType,
2833                                         InitializationSequence &Sequence,
2834                                         bool InitListSyntax = false) {
2835  assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2836         "InitListSyntax must come with a single initializer list argument.");
2837
2838  // Check constructor arguments for self reference.
2839  if (DeclaratorDecl *DD = Entity.getDecl())
2840    // Parameters arguments are occassionially constructed with itself,
2841    // for instance, in recursive functions.  Skip them.
2842    if (!isa<ParmVarDecl>(DD))
2843      for (unsigned i = 0; i < NumArgs; ++i)
2844        S.CheckSelfReference(DD, Args[i]);
2845
2846  // The type we're constructing needs to be complete.
2847  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2848    Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2849    return;
2850  }
2851
2852  const RecordType *DestRecordType = DestType->getAs<RecordType>();
2853  assert(DestRecordType && "Constructor initialization requires record type");
2854  CXXRecordDecl *DestRecordDecl
2855    = cast<CXXRecordDecl>(DestRecordType->getDecl());
2856
2857  if (InitListSyntax &&
2858      TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2859                                      DestRecordDecl, DestType, Sequence))
2860    return;
2861
2862  // Build the candidate set directly in the initialization sequence
2863  // structure, so that it will persist if we fail.
2864  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2865
2866  // Determine whether we are allowed to call explicit constructors or
2867  // explicit conversion operators.
2868  bool AllowExplicit = Kind.AllowExplicit();
2869  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
2870
2871  //   - Otherwise, if T is a class type, constructors are considered. The
2872  //     applicable constructors are enumerated, and the best one is chosen
2873  //     through overload resolution.
2874  DeclContext::lookup_iterator ConStart, ConEnd;
2875  llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
2876
2877  OverloadingResult Result = OR_No_Viable_Function;
2878  OverloadCandidateSet::iterator Best;
2879  bool AsInitializerList = false;
2880
2881  // C++11 [over.match.list]p1:
2882  //   When objects of non-aggregate type T are list-initialized, overload
2883  //   resolution selects the constructor in two phases:
2884  //   - Initially, the candidate functions are the initializer-list
2885  //     constructors of the class T and the argument list consists of the
2886  //     initializer list as a single argument.
2887  if (InitListSyntax) {
2888    AsInitializerList = true;
2889    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2890                                        CandidateSet, ConStart, ConEnd, Best,
2891                                        CopyInitialization, AllowExplicit,
2892                                        /*OnlyListConstructor=*/true);
2893
2894    // Time to unwrap the init list.
2895    InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2896    Args = ILE->getInits();
2897    NumArgs = ILE->getNumInits();
2898  }
2899
2900  // C++11 [over.match.list]p1:
2901  //   - If no viable initializer-list constructor is found, overload resolution
2902  //     is performed again, where the candidate functions are all the
2903  //     constructors of the class T nad the argument list consists of the
2904  //     elements of the initializer list.
2905  if (Result == OR_No_Viable_Function) {
2906    AsInitializerList = false;
2907    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2908                                        CandidateSet, ConStart, ConEnd, Best,
2909                                        CopyInitialization, AllowExplicit,
2910                                        /*OnlyListConstructors=*/false);
2911  }
2912  if (Result) {
2913    Sequence.SetOverloadFailure(InitListSyntax ?
2914                      InitializationSequence::FK_ListConstructorOverloadFailed :
2915                      InitializationSequence::FK_ConstructorOverloadFailed,
2916                                Result);
2917    return;
2918  }
2919
2920  // C++0x [dcl.init]p6:
2921  //   If a program calls for the default initialization of an object
2922  //   of a const-qualified type T, T shall be a class type with a
2923  //   user-provided default constructor.
2924  if (Kind.getKind() == InitializationKind::IK_Default &&
2925      Entity.getType().isConstQualified() &&
2926      cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2927    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2928    return;
2929  }
2930
2931  // Add the constructor initialization step. Any cv-qualification conversion is
2932  // subsumed by the initialization.
2933  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2934  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2935  Sequence.AddConstructorInitializationStep(CtorDecl,
2936                                            Best->FoundDecl.getAccess(),
2937                                            DestType, HadMultipleCandidates,
2938                                            InitListSyntax, AsInitializerList);
2939}
2940
2941static bool
2942ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2943                                             Expr *Initializer,
2944                                             QualType &SourceType,
2945                                             QualType &UnqualifiedSourceType,
2946                                             QualType UnqualifiedTargetType,
2947                                             InitializationSequence &Sequence) {
2948  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2949        S.Context.OverloadTy) {
2950    DeclAccessPair Found;
2951    bool HadMultipleCandidates = false;
2952    if (FunctionDecl *Fn
2953        = S.ResolveAddressOfOverloadedFunction(Initializer,
2954                                               UnqualifiedTargetType,
2955                                               false, Found,
2956                                               &HadMultipleCandidates)) {
2957      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2958                                                HadMultipleCandidates);
2959      SourceType = Fn->getType();
2960      UnqualifiedSourceType = SourceType.getUnqualifiedType();
2961    } else if (!UnqualifiedTargetType->isRecordType()) {
2962      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2963      return true;
2964    }
2965  }
2966  return false;
2967}
2968
2969static void TryReferenceInitializationCore(Sema &S,
2970                                           const InitializedEntity &Entity,
2971                                           const InitializationKind &Kind,
2972                                           Expr *Initializer,
2973                                           QualType cv1T1, QualType T1,
2974                                           Qualifiers T1Quals,
2975                                           QualType cv2T2, QualType T2,
2976                                           Qualifiers T2Quals,
2977                                           InitializationSequence &Sequence);
2978
2979static void TryListInitialization(Sema &S,
2980                                  const InitializedEntity &Entity,
2981                                  const InitializationKind &Kind,
2982                                  InitListExpr *InitList,
2983                                  InitializationSequence &Sequence);
2984
2985/// \brief Attempt list initialization of a reference.
2986static void TryReferenceListInitialization(Sema &S,
2987                                           const InitializedEntity &Entity,
2988                                           const InitializationKind &Kind,
2989                                           InitListExpr *InitList,
2990                                           InitializationSequence &Sequence)
2991{
2992  // First, catch C++03 where this isn't possible.
2993  if (!S.getLangOptions().CPlusPlus0x) {
2994    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2995    return;
2996  }
2997
2998  QualType DestType = Entity.getType();
2999  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3000  Qualifiers T1Quals;
3001  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3002
3003  // Reference initialization via an initializer list works thus:
3004  // If the initializer list consists of a single element that is
3005  // reference-related to the referenced type, bind directly to that element
3006  // (possibly creating temporaries).
3007  // Otherwise, initialize a temporary with the initializer list and
3008  // bind to that.
3009  if (InitList->getNumInits() == 1) {
3010    Expr *Initializer = InitList->getInit(0);
3011    QualType cv2T2 = Initializer->getType();
3012    Qualifiers T2Quals;
3013    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3014
3015    // If this fails, creating a temporary wouldn't work either.
3016    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3017                                                     T1, Sequence))
3018      return;
3019
3020    SourceLocation DeclLoc = Initializer->getLocStart();
3021    bool dummy1, dummy2, dummy3;
3022    Sema::ReferenceCompareResult RefRelationship
3023      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3024                                       dummy2, dummy3);
3025    if (RefRelationship >= Sema::Ref_Related) {
3026      // Try to bind the reference here.
3027      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3028                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
3029      if (Sequence)
3030        Sequence.RewrapReferenceInitList(cv1T1, InitList);
3031      return;
3032    }
3033  }
3034
3035  // Not reference-related. Create a temporary and bind to that.
3036  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3037
3038  TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3039  if (Sequence) {
3040    if (DestType->isRValueReferenceType() ||
3041        (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3042      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3043    else
3044      Sequence.SetFailed(
3045          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3046  }
3047}
3048
3049/// \brief Attempt list initialization (C++0x [dcl.init.list])
3050static void TryListInitialization(Sema &S,
3051                                  const InitializedEntity &Entity,
3052                                  const InitializationKind &Kind,
3053                                  InitListExpr *InitList,
3054                                  InitializationSequence &Sequence) {
3055  QualType DestType = Entity.getType();
3056
3057  // C++ doesn't allow scalar initialization with more than one argument.
3058  // But C99 complex numbers are scalars and it makes sense there.
3059  if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3060      !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3061    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3062    return;
3063  }
3064  if (DestType->isReferenceType()) {
3065    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3066    return;
3067  }
3068  if (DestType->isRecordType() && !DestType->isAggregateType()) {
3069    if (S.getLangOptions().CPlusPlus0x) {
3070      Expr *Arg = InitList;
3071      // A direct-initializer is not list-syntax, i.e. there's no special
3072      // treatment of "A a({1, 2});".
3073      TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3074                    Sequence, Kind.getKind() != InitializationKind::IK_Direct);
3075    } else
3076      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3077    return;
3078  }
3079
3080  InitListChecker CheckInitList(S, Entity, InitList,
3081          DestType, /*VerifyOnly=*/true,
3082          Kind.getKind() != InitializationKind::IK_DirectList ||
3083            !S.getLangOptions().CPlusPlus0x);
3084  if (CheckInitList.HadError()) {
3085    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3086    return;
3087  }
3088
3089  // Add the list initialization step with the built init list.
3090  Sequence.AddListInitializationStep(DestType);
3091}
3092
3093/// \brief Try a reference initialization that involves calling a conversion
3094/// function.
3095static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3096                                             const InitializedEntity &Entity,
3097                                             const InitializationKind &Kind,
3098                                                          Expr *Initializer,
3099                                                          bool AllowRValues,
3100                                             InitializationSequence &Sequence) {
3101  QualType DestType = Entity.getType();
3102  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3103  QualType T1 = cv1T1.getUnqualifiedType();
3104  QualType cv2T2 = Initializer->getType();
3105  QualType T2 = cv2T2.getUnqualifiedType();
3106
3107  bool DerivedToBase;
3108  bool ObjCConversion;
3109  bool ObjCLifetimeConversion;
3110  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3111                                         T1, T2, DerivedToBase,
3112                                         ObjCConversion,
3113                                         ObjCLifetimeConversion) &&
3114         "Must have incompatible references when binding via conversion");
3115  (void)DerivedToBase;
3116  (void)ObjCConversion;
3117  (void)ObjCLifetimeConversion;
3118
3119  // Build the candidate set directly in the initialization sequence
3120  // structure, so that it will persist if we fail.
3121  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3122  CandidateSet.clear();
3123
3124  // Determine whether we are allowed to call explicit constructors or
3125  // explicit conversion operators.
3126  bool AllowExplicit = Kind.AllowExplicit();
3127
3128  const RecordType *T1RecordType = 0;
3129  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3130      !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3131    // The type we're converting to is a class type. Enumerate its constructors
3132    // to see if there is a suitable conversion.
3133    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3134
3135    DeclContext::lookup_iterator Con, ConEnd;
3136    for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
3137         Con != ConEnd; ++Con) {
3138      NamedDecl *D = *Con;
3139      DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3140
3141      // Find the constructor (which may be a template).
3142      CXXConstructorDecl *Constructor = 0;
3143      FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3144      if (ConstructorTmpl)
3145        Constructor = cast<CXXConstructorDecl>(
3146                                         ConstructorTmpl->getTemplatedDecl());
3147      else
3148        Constructor = cast<CXXConstructorDecl>(D);
3149
3150      if (!Constructor->isInvalidDecl() &&
3151          Constructor->isConvertingConstructor(AllowExplicit)) {
3152        if (ConstructorTmpl)
3153          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3154                                         /*ExplicitArgs*/ 0,
3155                                         &Initializer, 1, CandidateSet,
3156                                         /*SuppressUserConversions=*/true);
3157        else
3158          S.AddOverloadCandidate(Constructor, FoundDecl,
3159                                 &Initializer, 1, CandidateSet,
3160                                 /*SuppressUserConversions=*/true);
3161      }
3162    }
3163  }
3164  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3165    return OR_No_Viable_Function;
3166
3167  const RecordType *T2RecordType = 0;
3168  if ((T2RecordType = T2->getAs<RecordType>()) &&
3169      !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3170    // The type we're converting from is a class type, enumerate its conversion
3171    // functions.
3172    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3173
3174    const UnresolvedSetImpl *Conversions
3175      = T2RecordDecl->getVisibleConversionFunctions();
3176    for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3177           E = Conversions->end(); I != E; ++I) {
3178      NamedDecl *D = *I;
3179      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3180      if (isa<UsingShadowDecl>(D))
3181        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3182
3183      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3184      CXXConversionDecl *Conv;
3185      if (ConvTemplate)
3186        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3187      else
3188        Conv = cast<CXXConversionDecl>(D);
3189
3190      // If the conversion function doesn't return a reference type,
3191      // it can't be considered for this conversion unless we're allowed to
3192      // consider rvalues.
3193      // FIXME: Do we need to make sure that we only consider conversion
3194      // candidates with reference-compatible results? That might be needed to
3195      // break recursion.
3196      if ((AllowExplicit || !Conv->isExplicit()) &&
3197          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3198        if (ConvTemplate)
3199          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3200                                           ActingDC, Initializer,
3201                                           DestType, CandidateSet);
3202        else
3203          S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3204                                   Initializer, DestType, CandidateSet);
3205      }
3206    }
3207  }
3208  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3209    return OR_No_Viable_Function;
3210
3211  SourceLocation DeclLoc = Initializer->getLocStart();
3212
3213  // Perform overload resolution. If it fails, return the failed result.
3214  OverloadCandidateSet::iterator Best;
3215  if (OverloadingResult Result
3216        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3217    return Result;
3218
3219  FunctionDecl *Function = Best->Function;
3220
3221  // This is the overload that will actually be used for the initialization, so
3222  // mark it as used.
3223  S.MarkFunctionReferenced(DeclLoc, Function);
3224
3225  // Compute the returned type of the conversion.
3226  if (isa<CXXConversionDecl>(Function))
3227    T2 = Function->getResultType();
3228  else
3229    T2 = cv1T1;
3230
3231  // Add the user-defined conversion step.
3232  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3233  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3234                                 T2.getNonLValueExprType(S.Context),
3235                                 HadMultipleCandidates);
3236
3237  // Determine whether we need to perform derived-to-base or
3238  // cv-qualification adjustments.
3239  ExprValueKind VK = VK_RValue;
3240  if (T2->isLValueReferenceType())
3241    VK = VK_LValue;
3242  else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3243    VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3244
3245  bool NewDerivedToBase = false;
3246  bool NewObjCConversion = false;
3247  bool NewObjCLifetimeConversion = false;
3248  Sema::ReferenceCompareResult NewRefRelationship
3249    = S.CompareReferenceRelationship(DeclLoc, T1,
3250                                     T2.getNonLValueExprType(S.Context),
3251                                     NewDerivedToBase, NewObjCConversion,
3252                                     NewObjCLifetimeConversion);
3253  if (NewRefRelationship == Sema::Ref_Incompatible) {
3254    // If the type we've converted to is not reference-related to the
3255    // type we're looking for, then there is another conversion step
3256    // we need to perform to produce a temporary of the right type
3257    // that we'll be binding to.
3258    ImplicitConversionSequence ICS;
3259    ICS.setStandard();
3260    ICS.Standard = Best->FinalConversion;
3261    T2 = ICS.Standard.getToType(2);
3262    Sequence.AddConversionSequenceStep(ICS, T2);
3263  } else if (NewDerivedToBase)
3264    Sequence.AddDerivedToBaseCastStep(
3265                                S.Context.getQualifiedType(T1,
3266                                  T2.getNonReferenceType().getQualifiers()),
3267                                      VK);
3268  else if (NewObjCConversion)
3269    Sequence.AddObjCObjectConversionStep(
3270                                S.Context.getQualifiedType(T1,
3271                                  T2.getNonReferenceType().getQualifiers()));
3272
3273  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3274    Sequence.AddQualificationConversionStep(cv1T1, VK);
3275
3276  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3277  return OR_Success;
3278}
3279
3280static void CheckCXX98CompatAccessibleCopy(Sema &S,
3281                                           const InitializedEntity &Entity,
3282                                           Expr *CurInitExpr);
3283
3284/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3285static void TryReferenceInitialization(Sema &S,
3286                                       const InitializedEntity &Entity,
3287                                       const InitializationKind &Kind,
3288                                       Expr *Initializer,
3289                                       InitializationSequence &Sequence) {
3290  QualType DestType = Entity.getType();
3291  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3292  Qualifiers T1Quals;
3293  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3294  QualType cv2T2 = Initializer->getType();
3295  Qualifiers T2Quals;
3296  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3297
3298  // If the initializer is the address of an overloaded function, try
3299  // to resolve the overloaded function. If all goes well, T2 is the
3300  // type of the resulting function.
3301  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3302                                                   T1, Sequence))
3303    return;
3304
3305  // Delegate everything else to a subfunction.
3306  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3307                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
3308}
3309
3310/// \brief Reference initialization without resolving overloaded functions.
3311static void TryReferenceInitializationCore(Sema &S,
3312                                           const InitializedEntity &Entity,
3313                                           const InitializationKind &Kind,
3314                                           Expr *Initializer,
3315                                           QualType cv1T1, QualType T1,
3316                                           Qualifiers T1Quals,
3317                                           QualType cv2T2, QualType T2,
3318                                           Qualifiers T2Quals,
3319                                           InitializationSequence &Sequence) {
3320  QualType DestType = Entity.getType();
3321  SourceLocation DeclLoc = Initializer->getLocStart();
3322  // Compute some basic properties of the types and the initializer.
3323  bool isLValueRef = DestType->isLValueReferenceType();
3324  bool isRValueRef = !isLValueRef;
3325  bool DerivedToBase = false;
3326  bool ObjCConversion = false;
3327  bool ObjCLifetimeConversion = false;
3328  Expr::Classification InitCategory = Initializer->Classify(S.Context);
3329  Sema::ReferenceCompareResult RefRelationship
3330    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3331                                     ObjCConversion, ObjCLifetimeConversion);
3332
3333  // C++0x [dcl.init.ref]p5:
3334  //   A reference to type "cv1 T1" is initialized by an expression of type
3335  //   "cv2 T2" as follows:
3336  //
3337  //     - If the reference is an lvalue reference and the initializer
3338  //       expression
3339  // Note the analogous bullet points for rvlaue refs to functions. Because
3340  // there are no function rvalues in C++, rvalue refs to functions are treated
3341  // like lvalue refs.
3342  OverloadingResult ConvOvlResult = OR_Success;
3343  bool T1Function = T1->isFunctionType();
3344  if (isLValueRef || T1Function) {
3345    if (InitCategory.isLValue() &&
3346        (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3347         (Kind.isCStyleOrFunctionalCast() &&
3348          RefRelationship == Sema::Ref_Related))) {
3349      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3350      //     reference-compatible with "cv2 T2," or
3351      //
3352      // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3353      // bit-field when we're determining whether the reference initialization
3354      // can occur. However, we do pay attention to whether it is a bit-field
3355      // to decide whether we're actually binding to a temporary created from
3356      // the bit-field.
3357      if (DerivedToBase)
3358        Sequence.AddDerivedToBaseCastStep(
3359                         S.Context.getQualifiedType(T1, T2Quals),
3360                         VK_LValue);
3361      else if (ObjCConversion)
3362        Sequence.AddObjCObjectConversionStep(
3363                                     S.Context.getQualifiedType(T1, T2Quals));
3364
3365      if (T1Quals != T2Quals)
3366        Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
3367      bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
3368        (Initializer->getBitField() || Initializer->refersToVectorElement());
3369      Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
3370      return;
3371    }
3372
3373    //     - has a class type (i.e., T2 is a class type), where T1 is not
3374    //       reference-related to T2, and can be implicitly converted to an
3375    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3376    //       with "cv3 T3" (this conversion is selected by enumerating the
3377    //       applicable conversion functions (13.3.1.6) and choosing the best
3378    //       one through overload resolution (13.3)),
3379    // If we have an rvalue ref to function type here, the rhs must be
3380    // an rvalue.
3381    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3382        (isLValueRef || InitCategory.isRValue())) {
3383      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3384                                                       Initializer,
3385                                                   /*AllowRValues=*/isRValueRef,
3386                                                       Sequence);
3387      if (ConvOvlResult == OR_Success)
3388        return;
3389      if (ConvOvlResult != OR_No_Viable_Function) {
3390        Sequence.SetOverloadFailure(
3391                      InitializationSequence::FK_ReferenceInitOverloadFailed,
3392                                    ConvOvlResult);
3393      }
3394    }
3395  }
3396
3397  //     - Otherwise, the reference shall be an lvalue reference to a
3398  //       non-volatile const type (i.e., cv1 shall be const), or the reference
3399  //       shall be an rvalue reference.
3400  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3401    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3402      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3403    else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3404      Sequence.SetOverloadFailure(
3405                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3406                                  ConvOvlResult);
3407    else
3408      Sequence.SetFailed(InitCategory.isLValue()
3409        ? (RefRelationship == Sema::Ref_Related
3410             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3411             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3412        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3413
3414    return;
3415  }
3416
3417  //    - If the initializer expression
3418  //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3419  //        "cv1 T1" is reference-compatible with "cv2 T2"
3420  // Note: functions are handled below.
3421  if (!T1Function &&
3422      (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3423       (Kind.isCStyleOrFunctionalCast() &&
3424        RefRelationship == Sema::Ref_Related)) &&
3425      (InitCategory.isXValue() ||
3426       (InitCategory.isPRValue() && T2->isRecordType()) ||
3427       (InitCategory.isPRValue() && T2->isArrayType()))) {
3428    ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3429    if (InitCategory.isPRValue() && T2->isRecordType()) {
3430      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3431      // compiler the freedom to perform a copy here or bind to the
3432      // object, while C++0x requires that we bind directly to the
3433      // object. Hence, we always bind to the object without making an
3434      // extra copy. However, in C++03 requires that we check for the
3435      // presence of a suitable copy constructor:
3436      //
3437      //   The constructor that would be used to make the copy shall
3438      //   be callable whether or not the copy is actually done.
3439      if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
3440        Sequence.AddExtraneousCopyToTemporary(cv2T2);
3441      else if (S.getLangOptions().CPlusPlus0x)
3442        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3443    }
3444
3445    if (DerivedToBase)
3446      Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3447                                        ValueKind);
3448    else if (ObjCConversion)
3449      Sequence.AddObjCObjectConversionStep(
3450                                       S.Context.getQualifiedType(T1, T2Quals));
3451
3452    if (T1Quals != T2Quals)
3453      Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
3454    Sequence.AddReferenceBindingStep(cv1T1,
3455                                 /*bindingTemporary=*/InitCategory.isPRValue());
3456    return;
3457  }
3458
3459  //       - has a class type (i.e., T2 is a class type), where T1 is not
3460  //         reference-related to T2, and can be implicitly converted to an
3461  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3462  //         where "cv1 T1" is reference-compatible with "cv3 T3",
3463  if (T2->isRecordType()) {
3464    if (RefRelationship == Sema::Ref_Incompatible) {
3465      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3466                                                       Kind, Initializer,
3467                                                       /*AllowRValues=*/true,
3468                                                       Sequence);
3469      if (ConvOvlResult)
3470        Sequence.SetOverloadFailure(
3471                      InitializationSequence::FK_ReferenceInitOverloadFailed,
3472                                    ConvOvlResult);
3473
3474      return;
3475    }
3476
3477    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3478    return;
3479  }
3480
3481  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3482  //        from the initializer expression using the rules for a non-reference
3483  //        copy initialization (8.5). The reference is then bound to the
3484  //        temporary. [...]
3485
3486  // Determine whether we are allowed to call explicit constructors or
3487  // explicit conversion operators.
3488  bool AllowExplicit = Kind.AllowExplicit();
3489
3490  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3491
3492  ImplicitConversionSequence ICS
3493    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3494                              /*SuppressUserConversions*/ false,
3495                              AllowExplicit,
3496                              /*FIXME:InOverloadResolution=*/false,
3497                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3498                              /*AllowObjCWritebackConversion=*/false);
3499
3500  if (ICS.isBad()) {
3501    // FIXME: Use the conversion function set stored in ICS to turn
3502    // this into an overloading ambiguity diagnostic. However, we need
3503    // to keep that set as an OverloadCandidateSet rather than as some
3504    // other kind of set.
3505    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3506      Sequence.SetOverloadFailure(
3507                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3508                                  ConvOvlResult);
3509    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3510      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3511    else
3512      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3513    return;
3514  } else {
3515    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3516  }
3517
3518  //        [...] If T1 is reference-related to T2, cv1 must be the
3519  //        same cv-qualification as, or greater cv-qualification
3520  //        than, cv2; otherwise, the program is ill-formed.
3521  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3522  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3523  if (RefRelationship == Sema::Ref_Related &&
3524      (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3525    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3526    return;
3527  }
3528
3529  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3530  //   reference, the initializer expression shall not be an lvalue.
3531  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3532      InitCategory.isLValue()) {
3533    Sequence.SetFailed(
3534                    InitializationSequence::FK_RValueReferenceBindingToLValue);
3535    return;
3536  }
3537
3538  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3539  return;
3540}
3541
3542/// \brief Attempt character array initialization from a string literal
3543/// (C++ [dcl.init.string], C99 6.7.8).
3544static void TryStringLiteralInitialization(Sema &S,
3545                                           const InitializedEntity &Entity,
3546                                           const InitializationKind &Kind,
3547                                           Expr *Initializer,
3548                                       InitializationSequence &Sequence) {
3549  Sequence.AddStringInitStep(Entity.getType());
3550}
3551
3552/// \brief Attempt value initialization (C++ [dcl.init]p7).
3553static void TryValueInitialization(Sema &S,
3554                                   const InitializedEntity &Entity,
3555                                   const InitializationKind &Kind,
3556                                   InitializationSequence &Sequence) {
3557  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3558  //
3559  //   To value-initialize an object of type T means:
3560  QualType T = Entity.getType();
3561
3562  //     -- if T is an array type, then each element is value-initialized;
3563  T = S.Context.getBaseElementType(T);
3564
3565  if (const RecordType *RT = T->getAs<RecordType>()) {
3566    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3567      // C++98:
3568      // -- if T is a class type (clause 9) with a user-declared
3569      //    constructor (12.1), then the default constructor for T is
3570      //    called (and the initialization is ill-formed if T has no
3571      //    accessible default constructor);
3572      if (!S.getLangOptions().CPlusPlus0x) {
3573        if (ClassDecl->hasUserDeclaredConstructor())
3574          // FIXME: we really want to refer to a single subobject of the array,
3575          // but Entity doesn't have a way to capture that (yet).
3576          return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3577                                              T, Sequence);
3578      } else {
3579        // C++11:
3580        // -- if T is a class type (clause 9) with either no default constructor
3581        //    (12.1 [class.ctor]) or a default constructor that is user-provided
3582        //    or deleted, then the object is default-initialized;
3583        CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3584        if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3585          return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3586                                              T, Sequence);
3587      }
3588
3589      // -- if T is a (possibly cv-qualified) non-union class type without a
3590      //    user-provided or deleted default constructor, then the object is
3591      //    zero-initialized and, if T has a non-trivial default constructor,
3592      //    default-initialized;
3593      if ((ClassDecl->getTagKind() == TTK_Class ||
3594           ClassDecl->getTagKind() == TTK_Struct)) {
3595        Sequence.AddZeroInitializationStep(Entity.getType());
3596        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3597      }
3598    }
3599  }
3600
3601  Sequence.AddZeroInitializationStep(Entity.getType());
3602}
3603
3604/// \brief Attempt default initialization (C++ [dcl.init]p6).
3605static void TryDefaultInitialization(Sema &S,
3606                                     const InitializedEntity &Entity,
3607                                     const InitializationKind &Kind,
3608                                     InitializationSequence &Sequence) {
3609  assert(Kind.getKind() == InitializationKind::IK_Default);
3610
3611  // C++ [dcl.init]p6:
3612  //   To default-initialize an object of type T means:
3613  //     - if T is an array type, each element is default-initialized;
3614  QualType DestType = S.Context.getBaseElementType(Entity.getType());
3615
3616  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
3617  //       constructor for T is called (and the initialization is ill-formed if
3618  //       T has no accessible default constructor);
3619  if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
3620    TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3621    return;
3622  }
3623
3624  //     - otherwise, no initialization is performed.
3625
3626  //   If a program calls for the default initialization of an object of
3627  //   a const-qualified type T, T shall be a class type with a user-provided
3628  //   default constructor.
3629  if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
3630    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3631    return;
3632  }
3633
3634  // If the destination type has a lifetime property, zero-initialize it.
3635  if (DestType.getQualifiers().hasObjCLifetime()) {
3636    Sequence.AddZeroInitializationStep(Entity.getType());
3637    return;
3638  }
3639}
3640
3641/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3642/// which enumerates all conversion functions and performs overload resolution
3643/// to select the best.
3644static void TryUserDefinedConversion(Sema &S,
3645                                     const InitializedEntity &Entity,
3646                                     const InitializationKind &Kind,
3647                                     Expr *Initializer,
3648                                     InitializationSequence &Sequence) {
3649  QualType DestType = Entity.getType();
3650  assert(!DestType->isReferenceType() && "References are handled elsewhere");
3651  QualType SourceType = Initializer->getType();
3652  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3653         "Must have a class type to perform a user-defined conversion");
3654
3655  // Build the candidate set directly in the initialization sequence
3656  // structure, so that it will persist if we fail.
3657  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3658  CandidateSet.clear();
3659
3660  // Determine whether we are allowed to call explicit constructors or
3661  // explicit conversion operators.
3662  bool AllowExplicit = Kind.AllowExplicit();
3663
3664  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3665    // The type we're converting to is a class type. Enumerate its constructors
3666    // to see if there is a suitable conversion.
3667    CXXRecordDecl *DestRecordDecl
3668      = cast<CXXRecordDecl>(DestRecordType->getDecl());
3669
3670    // Try to complete the type we're converting to.
3671    if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3672      DeclContext::lookup_iterator Con, ConEnd;
3673      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3674           Con != ConEnd; ++Con) {
3675        NamedDecl *D = *Con;
3676        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3677
3678        // Find the constructor (which may be a template).
3679        CXXConstructorDecl *Constructor = 0;
3680        FunctionTemplateDecl *ConstructorTmpl
3681          = dyn_cast<FunctionTemplateDecl>(D);
3682        if (ConstructorTmpl)
3683          Constructor = cast<CXXConstructorDecl>(
3684                                           ConstructorTmpl->getTemplatedDecl());
3685        else
3686          Constructor = cast<CXXConstructorDecl>(D);
3687
3688        if (!Constructor->isInvalidDecl() &&
3689            Constructor->isConvertingConstructor(AllowExplicit)) {
3690          if (ConstructorTmpl)
3691            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3692                                           /*ExplicitArgs*/ 0,
3693                                           &Initializer, 1, CandidateSet,
3694                                           /*SuppressUserConversions=*/true);
3695          else
3696            S.AddOverloadCandidate(Constructor, FoundDecl,
3697                                   &Initializer, 1, CandidateSet,
3698                                   /*SuppressUserConversions=*/true);
3699        }
3700      }
3701    }
3702  }
3703
3704  SourceLocation DeclLoc = Initializer->getLocStart();
3705
3706  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3707    // The type we're converting from is a class type, enumerate its conversion
3708    // functions.
3709
3710    // We can only enumerate the conversion functions for a complete type; if
3711    // the type isn't complete, simply skip this step.
3712    if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3713      CXXRecordDecl *SourceRecordDecl
3714        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3715
3716      const UnresolvedSetImpl *Conversions
3717        = SourceRecordDecl->getVisibleConversionFunctions();
3718      for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3719           E = Conversions->end();
3720           I != E; ++I) {
3721        NamedDecl *D = *I;
3722        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3723        if (isa<UsingShadowDecl>(D))
3724          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3725
3726        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3727        CXXConversionDecl *Conv;
3728        if (ConvTemplate)
3729          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3730        else
3731          Conv = cast<CXXConversionDecl>(D);
3732
3733        if (AllowExplicit || !Conv->isExplicit()) {
3734          if (ConvTemplate)
3735            S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3736                                             ActingDC, Initializer, DestType,
3737                                             CandidateSet);
3738          else
3739            S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3740                                     Initializer, DestType, CandidateSet);
3741        }
3742      }
3743    }
3744  }
3745
3746  // Perform overload resolution. If it fails, return the failed result.
3747  OverloadCandidateSet::iterator Best;
3748  if (OverloadingResult Result
3749        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3750    Sequence.SetOverloadFailure(
3751                        InitializationSequence::FK_UserConversionOverloadFailed,
3752                                Result);
3753    return;
3754  }
3755
3756  FunctionDecl *Function = Best->Function;
3757  S.MarkFunctionReferenced(DeclLoc, Function);
3758  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3759
3760  if (isa<CXXConstructorDecl>(Function)) {
3761    // Add the user-defined conversion step. Any cv-qualification conversion is
3762    // subsumed by the initialization. Per DR5, the created temporary is of the
3763    // cv-unqualified type of the destination.
3764    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3765                                   DestType.getUnqualifiedType(),
3766                                   HadMultipleCandidates);
3767    return;
3768  }
3769
3770  // Add the user-defined conversion step that calls the conversion function.
3771  QualType ConvType = Function->getCallResultType();
3772  if (ConvType->getAs<RecordType>()) {
3773    // If we're converting to a class type, there may be an copy of
3774    // the resulting temporary object (possible to create an object of
3775    // a base class type). That copy is not a separate conversion, so
3776    // we just make a note of the actual destination type (possibly a
3777    // base class of the type returned by the conversion function) and
3778    // let the user-defined conversion step handle the conversion.
3779    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3780                                   HadMultipleCandidates);
3781    return;
3782  }
3783
3784  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3785                                 HadMultipleCandidates);
3786
3787  // If the conversion following the call to the conversion function
3788  // is interesting, add it as a separate step.
3789  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3790      Best->FinalConversion.Third) {
3791    ImplicitConversionSequence ICS;
3792    ICS.setStandard();
3793    ICS.Standard = Best->FinalConversion;
3794    Sequence.AddConversionSequenceStep(ICS, DestType);
3795  }
3796}
3797
3798/// The non-zero enum values here are indexes into diagnostic alternatives.
3799enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3800
3801/// Determines whether this expression is an acceptable ICR source.
3802static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3803                                         bool isAddressOf) {
3804  // Skip parens.
3805  e = e->IgnoreParens();
3806
3807  // Skip address-of nodes.
3808  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3809    if (op->getOpcode() == UO_AddrOf)
3810      return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
3811
3812  // Skip certain casts.
3813  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3814    switch (ce->getCastKind()) {
3815    case CK_Dependent:
3816    case CK_BitCast:
3817    case CK_LValueBitCast:
3818    case CK_NoOp:
3819      return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
3820
3821    case CK_ArrayToPointerDecay:
3822      return IIK_nonscalar;
3823
3824    case CK_NullToPointer:
3825      return IIK_okay;
3826
3827    default:
3828      break;
3829    }
3830
3831  // If we have a declaration reference, it had better be a local variable.
3832  } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3833    if (!isAddressOf) return IIK_nonlocal;
3834
3835    VarDecl *var;
3836    if (isa<DeclRefExpr>(e)) {
3837      var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3838      if (!var) return IIK_nonlocal;
3839    } else {
3840      var = cast<BlockDeclRefExpr>(e)->getDecl();
3841    }
3842
3843    return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3844
3845  // If we have a conditional operator, check both sides.
3846  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3847    if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
3848      return iik;
3849
3850    return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
3851
3852  // These are never scalar.
3853  } else if (isa<ArraySubscriptExpr>(e)) {
3854    return IIK_nonscalar;
3855
3856  // Otherwise, it needs to be a null pointer constant.
3857  } else {
3858    return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3859            ? IIK_okay : IIK_nonlocal);
3860  }
3861
3862  return IIK_nonlocal;
3863}
3864
3865/// Check whether the given expression is a valid operand for an
3866/// indirect copy/restore.
3867static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3868  assert(src->isRValue());
3869
3870  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
3871  if (iik == IIK_okay) return;
3872
3873  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3874    << ((unsigned) iik - 1)  // shift index into diagnostic explanations
3875    << src->getSourceRange();
3876}
3877
3878/// \brief Determine whether we have compatible array types for the
3879/// purposes of GNU by-copy array initialization.
3880static bool hasCompatibleArrayTypes(ASTContext &Context,
3881                                    const ArrayType *Dest,
3882                                    const ArrayType *Source) {
3883  // If the source and destination array types are equivalent, we're
3884  // done.
3885  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3886    return true;
3887
3888  // Make sure that the element types are the same.
3889  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3890    return false;
3891
3892  // The only mismatch we allow is when the destination is an
3893  // incomplete array type and the source is a constant array type.
3894  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3895}
3896
3897static bool tryObjCWritebackConversion(Sema &S,
3898                                       InitializationSequence &Sequence,
3899                                       const InitializedEntity &Entity,
3900                                       Expr *Initializer) {
3901  bool ArrayDecay = false;
3902  QualType ArgType = Initializer->getType();
3903  QualType ArgPointee;
3904  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3905    ArrayDecay = true;
3906    ArgPointee = ArgArrayType->getElementType();
3907    ArgType = S.Context.getPointerType(ArgPointee);
3908  }
3909
3910  // Handle write-back conversion.
3911  QualType ConvertedArgType;
3912  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3913                                   ConvertedArgType))
3914    return false;
3915
3916  // We should copy unless we're passing to an argument explicitly
3917  // marked 'out'.
3918  bool ShouldCopy = true;
3919  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3920    ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3921
3922  // Do we need an lvalue conversion?
3923  if (ArrayDecay || Initializer->isGLValue()) {
3924    ImplicitConversionSequence ICS;
3925    ICS.setStandard();
3926    ICS.Standard.setAsIdentityConversion();
3927
3928    QualType ResultType;
3929    if (ArrayDecay) {
3930      ICS.Standard.First = ICK_Array_To_Pointer;
3931      ResultType = S.Context.getPointerType(ArgPointee);
3932    } else {
3933      ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3934      ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3935    }
3936
3937    Sequence.AddConversionSequenceStep(ICS, ResultType);
3938  }
3939
3940  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3941  return true;
3942}
3943
3944InitializationSequence::InitializationSequence(Sema &S,
3945                                               const InitializedEntity &Entity,
3946                                               const InitializationKind &Kind,
3947                                               Expr **Args,
3948                                               unsigned NumArgs)
3949    : FailedCandidateSet(Kind.getLocation()) {
3950  ASTContext &Context = S.Context;
3951
3952  // C++0x [dcl.init]p16:
3953  //   The semantics of initializers are as follows. The destination type is
3954  //   the type of the object or reference being initialized and the source
3955  //   type is the type of the initializer expression. The source type is not
3956  //   defined when the initializer is a braced-init-list or when it is a
3957  //   parenthesized list of expressions.
3958  QualType DestType = Entity.getType();
3959
3960  if (DestType->isDependentType() ||
3961      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3962    SequenceKind = DependentSequence;
3963    return;
3964  }
3965
3966  // Almost everything is a normal sequence.
3967  setSequenceKind(NormalSequence);
3968
3969  for (unsigned I = 0; I != NumArgs; ++I)
3970    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
3971      // FIXME: should we be doing this here?
3972      ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3973      if (result.isInvalid()) {
3974        SetFailed(FK_PlaceholderType);
3975        return;
3976      }
3977      Args[I] = result.take();
3978    }
3979
3980
3981  QualType SourceType;
3982  Expr *Initializer = 0;
3983  if (NumArgs == 1) {
3984    Initializer = Args[0];
3985    if (!isa<InitListExpr>(Initializer))
3986      SourceType = Initializer->getType();
3987  }
3988
3989  //     - If the initializer is a (non-parenthesized) braced-init-list, the
3990  //       object is list-initialized (8.5.4).
3991  if (Kind.getKind() != InitializationKind::IK_Direct) {
3992    if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3993      TryListInitialization(S, Entity, Kind, InitList, *this);
3994      return;
3995    }
3996  }
3997
3998  //     - If the destination type is a reference type, see 8.5.3.
3999  if (DestType->isReferenceType()) {
4000    // C++0x [dcl.init.ref]p1:
4001    //   A variable declared to be a T& or T&&, that is, "reference to type T"
4002    //   (8.3.2), shall be initialized by an object, or function, of type T or
4003    //   by an object that can be converted into a T.
4004    // (Therefore, multiple arguments are not permitted.)
4005    if (NumArgs != 1)
4006      SetFailed(FK_TooManyInitsForReference);
4007    else
4008      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4009    return;
4010  }
4011
4012  //     - If the initializer is (), the object is value-initialized.
4013  if (Kind.getKind() == InitializationKind::IK_Value ||
4014      (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
4015    TryValueInitialization(S, Entity, Kind, *this);
4016    return;
4017  }
4018
4019  // Handle default initialization.
4020  if (Kind.getKind() == InitializationKind::IK_Default) {
4021    TryDefaultInitialization(S, Entity, Kind, *this);
4022    return;
4023  }
4024
4025  //     - If the destination type is an array of characters, an array of
4026  //       char16_t, an array of char32_t, or an array of wchar_t, and the
4027  //       initializer is a string literal, see 8.5.2.
4028  //     - Otherwise, if the destination type is an array, the program is
4029  //       ill-formed.
4030  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4031    if (Initializer && isa<VariableArrayType>(DestAT)) {
4032      SetFailed(FK_VariableLengthArrayHasInitializer);
4033      return;
4034    }
4035
4036    if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
4037      TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4038      return;
4039    }
4040
4041    // Note: as an GNU C extension, we allow initialization of an
4042    // array from a compound literal that creates an array of the same
4043    // type, so long as the initializer has no side effects.
4044    if (!S.getLangOptions().CPlusPlus && Initializer &&
4045        isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4046        Initializer->getType()->isArrayType()) {
4047      const ArrayType *SourceAT
4048        = Context.getAsArrayType(Initializer->getType());
4049      if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4050        SetFailed(FK_ArrayTypeMismatch);
4051      else if (Initializer->HasSideEffects(S.Context))
4052        SetFailed(FK_NonConstantArrayInit);
4053      else {
4054        AddArrayInitStep(DestType);
4055      }
4056    } else if (DestAT->getElementType()->isAnyCharacterType())
4057      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4058    else
4059      SetFailed(FK_ArrayNeedsInitList);
4060
4061    return;
4062  }
4063
4064  // Determine whether we should consider writeback conversions for
4065  // Objective-C ARC.
4066  bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4067    Entity.getKind() == InitializedEntity::EK_Parameter;
4068
4069  // We're at the end of the line for C: it's either a write-back conversion
4070  // or it's a C assignment. There's no need to check anything else.
4071  if (!S.getLangOptions().CPlusPlus) {
4072    // If allowed, check whether this is an Objective-C writeback conversion.
4073    if (allowObjCWritebackConversion &&
4074        tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4075      return;
4076    }
4077
4078    // Handle initialization in C
4079    AddCAssignmentStep(DestType);
4080    MaybeProduceObjCObject(S, *this, Entity);
4081    return;
4082  }
4083
4084  assert(S.getLangOptions().CPlusPlus);
4085
4086  //     - If the destination type is a (possibly cv-qualified) class type:
4087  if (DestType->isRecordType()) {
4088    //     - If the initialization is direct-initialization, or if it is
4089    //       copy-initialization where the cv-unqualified version of the
4090    //       source type is the same class as, or a derived class of, the
4091    //       class of the destination, constructors are considered. [...]
4092    if (Kind.getKind() == InitializationKind::IK_Direct ||
4093        (Kind.getKind() == InitializationKind::IK_Copy &&
4094         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4095          S.IsDerivedFrom(SourceType, DestType))))
4096      TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
4097                                   Entity.getType(), *this);
4098    //     - Otherwise (i.e., for the remaining copy-initialization cases),
4099    //       user-defined conversion sequences that can convert from the source
4100    //       type to the destination type or (when a conversion function is
4101    //       used) to a derived class thereof are enumerated as described in
4102    //       13.3.1.4, and the best one is chosen through overload resolution
4103    //       (13.3).
4104    else
4105      TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4106    return;
4107  }
4108
4109  if (NumArgs > 1) {
4110    SetFailed(FK_TooManyInitsForScalar);
4111    return;
4112  }
4113  assert(NumArgs == 1 && "Zero-argument case handled above");
4114
4115  //    - Otherwise, if the source type is a (possibly cv-qualified) class
4116  //      type, conversion functions are considered.
4117  if (!SourceType.isNull() && SourceType->isRecordType()) {
4118    TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4119    MaybeProduceObjCObject(S, *this, Entity);
4120    return;
4121  }
4122
4123  //    - Otherwise, the initial value of the object being initialized is the
4124  //      (possibly converted) value of the initializer expression. Standard
4125  //      conversions (Clause 4) will be used, if necessary, to convert the
4126  //      initializer expression to the cv-unqualified version of the
4127  //      destination type; no user-defined conversions are considered.
4128
4129  ImplicitConversionSequence ICS
4130    = S.TryImplicitConversion(Initializer, Entity.getType(),
4131                              /*SuppressUserConversions*/true,
4132                              /*AllowExplicitConversions*/ false,
4133                              /*InOverloadResolution*/ false,
4134                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4135                              allowObjCWritebackConversion);
4136
4137  if (ICS.isStandard() &&
4138      ICS.Standard.Second == ICK_Writeback_Conversion) {
4139    // Objective-C ARC writeback conversion.
4140
4141    // We should copy unless we're passing to an argument explicitly
4142    // marked 'out'.
4143    bool ShouldCopy = true;
4144    if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4145      ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4146
4147    // If there was an lvalue adjustment, add it as a separate conversion.
4148    if (ICS.Standard.First == ICK_Array_To_Pointer ||
4149        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4150      ImplicitConversionSequence LvalueICS;
4151      LvalueICS.setStandard();
4152      LvalueICS.Standard.setAsIdentityConversion();
4153      LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4154      LvalueICS.Standard.First = ICS.Standard.First;
4155      AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4156    }
4157
4158    AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4159  } else if (ICS.isBad()) {
4160    DeclAccessPair dap;
4161    if (Initializer->getType() == Context.OverloadTy &&
4162          !S.ResolveAddressOfOverloadedFunction(Initializer
4163                      , DestType, false, dap))
4164      SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4165    else
4166      SetFailed(InitializationSequence::FK_ConversionFailed);
4167  } else {
4168    AddConversionSequenceStep(ICS, Entity.getType());
4169
4170    MaybeProduceObjCObject(S, *this, Entity);
4171  }
4172}
4173
4174InitializationSequence::~InitializationSequence() {
4175  for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4176                                          StepEnd = Steps.end();
4177       Step != StepEnd; ++Step)
4178    Step->Destroy();
4179}
4180
4181//===----------------------------------------------------------------------===//
4182// Perform initialization
4183//===----------------------------------------------------------------------===//
4184static Sema::AssignmentAction
4185getAssignmentAction(const InitializedEntity &Entity) {
4186  switch(Entity.getKind()) {
4187  case InitializedEntity::EK_Variable:
4188  case InitializedEntity::EK_New:
4189  case InitializedEntity::EK_Exception:
4190  case InitializedEntity::EK_Base:
4191  case InitializedEntity::EK_Delegating:
4192    return Sema::AA_Initializing;
4193
4194  case InitializedEntity::EK_Parameter:
4195    if (Entity.getDecl() &&
4196        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4197      return Sema::AA_Sending;
4198
4199    return Sema::AA_Passing;
4200
4201  case InitializedEntity::EK_Result:
4202    return Sema::AA_Returning;
4203
4204  case InitializedEntity::EK_Temporary:
4205    // FIXME: Can we tell apart casting vs. converting?
4206    return Sema::AA_Casting;
4207
4208  case InitializedEntity::EK_Member:
4209  case InitializedEntity::EK_ArrayElement:
4210  case InitializedEntity::EK_VectorElement:
4211  case InitializedEntity::EK_ComplexElement:
4212  case InitializedEntity::EK_BlockElement:
4213    return Sema::AA_Initializing;
4214  }
4215
4216  llvm_unreachable("Invalid EntityKind!");
4217}
4218
4219/// \brief Whether we should binding a created object as a temporary when
4220/// initializing the given entity.
4221static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4222  switch (Entity.getKind()) {
4223  case InitializedEntity::EK_ArrayElement:
4224  case InitializedEntity::EK_Member:
4225  case InitializedEntity::EK_Result:
4226  case InitializedEntity::EK_New:
4227  case InitializedEntity::EK_Variable:
4228  case InitializedEntity::EK_Base:
4229  case InitializedEntity::EK_Delegating:
4230  case InitializedEntity::EK_VectorElement:
4231  case InitializedEntity::EK_ComplexElement:
4232  case InitializedEntity::EK_Exception:
4233  case InitializedEntity::EK_BlockElement:
4234    return false;
4235
4236  case InitializedEntity::EK_Parameter:
4237  case InitializedEntity::EK_Temporary:
4238    return true;
4239  }
4240
4241  llvm_unreachable("missed an InitializedEntity kind?");
4242}
4243
4244/// \brief Whether the given entity, when initialized with an object
4245/// created for that initialization, requires destruction.
4246static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4247  switch (Entity.getKind()) {
4248    case InitializedEntity::EK_Member:
4249    case InitializedEntity::EK_Result:
4250    case InitializedEntity::EK_New:
4251    case InitializedEntity::EK_Base:
4252    case InitializedEntity::EK_Delegating:
4253    case InitializedEntity::EK_VectorElement:
4254    case InitializedEntity::EK_ComplexElement:
4255    case InitializedEntity::EK_BlockElement:
4256      return false;
4257
4258    case InitializedEntity::EK_Variable:
4259    case InitializedEntity::EK_Parameter:
4260    case InitializedEntity::EK_Temporary:
4261    case InitializedEntity::EK_ArrayElement:
4262    case InitializedEntity::EK_Exception:
4263      return true;
4264  }
4265
4266  llvm_unreachable("missed an InitializedEntity kind?");
4267}
4268
4269/// \brief Look for copy and move constructors and constructor templates, for
4270/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4271static void LookupCopyAndMoveConstructors(Sema &S,
4272                                          OverloadCandidateSet &CandidateSet,
4273                                          CXXRecordDecl *Class,
4274                                          Expr *CurInitExpr) {
4275  DeclContext::lookup_iterator Con, ConEnd;
4276  for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4277       Con != ConEnd; ++Con) {
4278    CXXConstructorDecl *Constructor = 0;
4279
4280    if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4281      // Handle copy/moveconstructors, only.
4282      if (!Constructor || Constructor->isInvalidDecl() ||
4283          !Constructor->isCopyOrMoveConstructor() ||
4284          !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4285        continue;
4286
4287      DeclAccessPair FoundDecl
4288        = DeclAccessPair::make(Constructor, Constructor->getAccess());
4289      S.AddOverloadCandidate(Constructor, FoundDecl,
4290                             &CurInitExpr, 1, CandidateSet);
4291      continue;
4292    }
4293
4294    // Handle constructor templates.
4295    FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4296    if (ConstructorTmpl->isInvalidDecl())
4297      continue;
4298
4299    Constructor = cast<CXXConstructorDecl>(
4300                                         ConstructorTmpl->getTemplatedDecl());
4301    if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4302      continue;
4303
4304    // FIXME: Do we need to limit this to copy-constructor-like
4305    // candidates?
4306    DeclAccessPair FoundDecl
4307      = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4308    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4309                                   &CurInitExpr, 1, CandidateSet, true);
4310  }
4311}
4312
4313/// \brief Get the location at which initialization diagnostics should appear.
4314static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4315                                           Expr *Initializer) {
4316  switch (Entity.getKind()) {
4317  case InitializedEntity::EK_Result:
4318    return Entity.getReturnLoc();
4319
4320  case InitializedEntity::EK_Exception:
4321    return Entity.getThrowLoc();
4322
4323  case InitializedEntity::EK_Variable:
4324    return Entity.getDecl()->getLocation();
4325
4326  case InitializedEntity::EK_ArrayElement:
4327  case InitializedEntity::EK_Member:
4328  case InitializedEntity::EK_Parameter:
4329  case InitializedEntity::EK_Temporary:
4330  case InitializedEntity::EK_New:
4331  case InitializedEntity::EK_Base:
4332  case InitializedEntity::EK_Delegating:
4333  case InitializedEntity::EK_VectorElement:
4334  case InitializedEntity::EK_ComplexElement:
4335  case InitializedEntity::EK_BlockElement:
4336    return Initializer->getLocStart();
4337  }
4338  llvm_unreachable("missed an InitializedEntity kind?");
4339}
4340
4341/// \brief Make a (potentially elidable) temporary copy of the object
4342/// provided by the given initializer by calling the appropriate copy
4343/// constructor.
4344///
4345/// \param S The Sema object used for type-checking.
4346///
4347/// \param T The type of the temporary object, which must either be
4348/// the type of the initializer expression or a superclass thereof.
4349///
4350/// \param Enter The entity being initialized.
4351///
4352/// \param CurInit The initializer expression.
4353///
4354/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4355/// is permitted in C++03 (but not C++0x) when binding a reference to
4356/// an rvalue.
4357///
4358/// \returns An expression that copies the initializer expression into
4359/// a temporary object, or an error expression if a copy could not be
4360/// created.
4361static ExprResult CopyObject(Sema &S,
4362                             QualType T,
4363                             const InitializedEntity &Entity,
4364                             ExprResult CurInit,
4365                             bool IsExtraneousCopy) {
4366  // Determine which class type we're copying to.
4367  Expr *CurInitExpr = (Expr *)CurInit.get();
4368  CXXRecordDecl *Class = 0;
4369  if (const RecordType *Record = T->getAs<RecordType>())
4370    Class = cast<CXXRecordDecl>(Record->getDecl());
4371  if (!Class)
4372    return move(CurInit);
4373
4374  // C++0x [class.copy]p32:
4375  //   When certain criteria are met, an implementation is allowed to
4376  //   omit the copy/move construction of a class object, even if the
4377  //   copy/move constructor and/or destructor for the object have
4378  //   side effects. [...]
4379  //     - when a temporary class object that has not been bound to a
4380  //       reference (12.2) would be copied/moved to a class object
4381  //       with the same cv-unqualified type, the copy/move operation
4382  //       can be omitted by constructing the temporary object
4383  //       directly into the target of the omitted copy/move
4384  //
4385  // Note that the other three bullets are handled elsewhere. Copy
4386  // elision for return statements and throw expressions are handled as part
4387  // of constructor initialization, while copy elision for exception handlers
4388  // is handled by the run-time.
4389  bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4390  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4391
4392  // Make sure that the type we are copying is complete.
4393  if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4394    return move(CurInit);
4395
4396  // Perform overload resolution using the class's copy/move constructors.
4397  // Only consider constructors and constructor templates. Per
4398  // C++0x [dcl.init]p16, second bullet to class types, this initialization
4399  // is direct-initialization.
4400  OverloadCandidateSet CandidateSet(Loc);
4401  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4402
4403  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4404
4405  OverloadCandidateSet::iterator Best;
4406  switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4407  case OR_Success:
4408    break;
4409
4410  case OR_No_Viable_Function:
4411    S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4412           ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4413           : diag::err_temp_copy_no_viable)
4414      << (int)Entity.getKind() << CurInitExpr->getType()
4415      << CurInitExpr->getSourceRange();
4416    CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4417    if (!IsExtraneousCopy || S.isSFINAEContext())
4418      return ExprError();
4419    return move(CurInit);
4420
4421  case OR_Ambiguous:
4422    S.Diag(Loc, diag::err_temp_copy_ambiguous)
4423      << (int)Entity.getKind() << CurInitExpr->getType()
4424      << CurInitExpr->getSourceRange();
4425    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4426    return ExprError();
4427
4428  case OR_Deleted:
4429    S.Diag(Loc, diag::err_temp_copy_deleted)
4430      << (int)Entity.getKind() << CurInitExpr->getType()
4431      << CurInitExpr->getSourceRange();
4432    S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4433      << 1 << Best->Function->isDeleted();
4434    return ExprError();
4435  }
4436
4437  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4438  ASTOwningVector<Expr*> ConstructorArgs(S);
4439  CurInit.release(); // Ownership transferred into MultiExprArg, below.
4440
4441  S.CheckConstructorAccess(Loc, Constructor, Entity,
4442                           Best->FoundDecl.getAccess(), IsExtraneousCopy);
4443
4444  if (IsExtraneousCopy) {
4445    // If this is a totally extraneous copy for C++03 reference
4446    // binding purposes, just return the original initialization
4447    // expression. We don't generate an (elided) copy operation here
4448    // because doing so would require us to pass down a flag to avoid
4449    // infinite recursion, where each step adds another extraneous,
4450    // elidable copy.
4451
4452    // Instantiate the default arguments of any extra parameters in
4453    // the selected copy constructor, as if we were going to create a
4454    // proper call to the copy constructor.
4455    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4456      ParmVarDecl *Parm = Constructor->getParamDecl(I);
4457      if (S.RequireCompleteType(Loc, Parm->getType(),
4458                                S.PDiag(diag::err_call_incomplete_argument)))
4459        break;
4460
4461      // Build the default argument expression; we don't actually care
4462      // if this succeeds or not, because this routine will complain
4463      // if there was a problem.
4464      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4465    }
4466
4467    return S.Owned(CurInitExpr);
4468  }
4469
4470  S.MarkFunctionReferenced(Loc, Constructor);
4471
4472  // Determine the arguments required to actually perform the
4473  // constructor call (we might have derived-to-base conversions, or
4474  // the copy constructor may have default arguments).
4475  if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4476                                Loc, ConstructorArgs))
4477    return ExprError();
4478
4479  // Actually perform the constructor call.
4480  CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4481                                    move_arg(ConstructorArgs),
4482                                    HadMultipleCandidates,
4483                                    /*ZeroInit*/ false,
4484                                    CXXConstructExpr::CK_Complete,
4485                                    SourceRange());
4486
4487  // If we're supposed to bind temporaries, do so.
4488  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4489    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4490  return move(CurInit);
4491}
4492
4493/// \brief Check whether elidable copy construction for binding a reference to
4494/// a temporary would have succeeded if we were building in C++98 mode, for
4495/// -Wc++98-compat.
4496static void CheckCXX98CompatAccessibleCopy(Sema &S,
4497                                           const InitializedEntity &Entity,
4498                                           Expr *CurInitExpr) {
4499  assert(S.getLangOptions().CPlusPlus0x);
4500
4501  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4502  if (!Record)
4503    return;
4504
4505  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4506  if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4507        == DiagnosticsEngine::Ignored)
4508    return;
4509
4510  // Find constructors which would have been considered.
4511  OverloadCandidateSet CandidateSet(Loc);
4512  LookupCopyAndMoveConstructors(
4513      S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4514
4515  // Perform overload resolution.
4516  OverloadCandidateSet::iterator Best;
4517  OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4518
4519  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4520    << OR << (int)Entity.getKind() << CurInitExpr->getType()
4521    << CurInitExpr->getSourceRange();
4522
4523  switch (OR) {
4524  case OR_Success:
4525    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4526                             Best->FoundDecl.getAccess(), Diag);
4527    // FIXME: Check default arguments as far as that's possible.
4528    break;
4529
4530  case OR_No_Viable_Function:
4531    S.Diag(Loc, Diag);
4532    CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4533    break;
4534
4535  case OR_Ambiguous:
4536    S.Diag(Loc, Diag);
4537    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4538    break;
4539
4540  case OR_Deleted:
4541    S.Diag(Loc, Diag);
4542    S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4543      << 1 << Best->Function->isDeleted();
4544    break;
4545  }
4546}
4547
4548void InitializationSequence::PrintInitLocationNote(Sema &S,
4549                                              const InitializedEntity &Entity) {
4550  if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4551    if (Entity.getDecl()->getLocation().isInvalid())
4552      return;
4553
4554    if (Entity.getDecl()->getDeclName())
4555      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4556        << Entity.getDecl()->getDeclName();
4557    else
4558      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4559  }
4560}
4561
4562static bool isReferenceBinding(const InitializationSequence::Step &s) {
4563  return s.Kind == InitializationSequence::SK_BindReference ||
4564         s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4565}
4566
4567static ExprResult
4568PerformConstructorInitialization(Sema &S,
4569                                 const InitializedEntity &Entity,
4570                                 const InitializationKind &Kind,
4571                                 MultiExprArg Args,
4572                                 const InitializationSequence::Step& Step,
4573                                 bool &ConstructorInitRequiresZeroInit) {
4574  unsigned NumArgs = Args.size();
4575  CXXConstructorDecl *Constructor
4576    = cast<CXXConstructorDecl>(Step.Function.Function);
4577  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4578
4579  // Build a call to the selected constructor.
4580  ASTOwningVector<Expr*> ConstructorArgs(S);
4581  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4582                         ? Kind.getEqualLoc()
4583                         : Kind.getLocation();
4584
4585  if (Kind.getKind() == InitializationKind::IK_Default) {
4586    // Force even a trivial, implicit default constructor to be
4587    // semantically checked. We do this explicitly because we don't build
4588    // the definition for completely trivial constructors.
4589    CXXRecordDecl *ClassDecl = Constructor->getParent();
4590    assert(ClassDecl && "No parent class for constructor.");
4591    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4592        ClassDecl->hasTrivialDefaultConstructor() &&
4593        !Constructor->isUsed(false))
4594      S.DefineImplicitDefaultConstructor(Loc, Constructor);
4595  }
4596
4597  ExprResult CurInit = S.Owned((Expr *)0);
4598
4599  // Determine the arguments required to actually perform the constructor
4600  // call.
4601  if (S.CompleteConstructorCall(Constructor, move(Args),
4602                                Loc, ConstructorArgs))
4603    return ExprError();
4604
4605
4606  if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4607      NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4608      (Kind.getKind() == InitializationKind::IK_Direct ||
4609       Kind.getKind() == InitializationKind::IK_Value)) {
4610    // An explicitly-constructed temporary, e.g., X(1, 2).
4611    unsigned NumExprs = ConstructorArgs.size();
4612    Expr **Exprs = (Expr **)ConstructorArgs.take();
4613    S.MarkFunctionReferenced(Loc, Constructor);
4614    S.DiagnoseUseOfDecl(Constructor, Loc);
4615
4616    TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4617    if (!TSInfo)
4618      TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4619
4620    CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4621                                                             Constructor,
4622                                                             TSInfo,
4623                                                             Exprs,
4624                                                             NumExprs,
4625                                                     Kind.getParenRange(),
4626                                                     HadMultipleCandidates,
4627                                         ConstructorInitRequiresZeroInit));
4628  } else {
4629    CXXConstructExpr::ConstructionKind ConstructKind =
4630      CXXConstructExpr::CK_Complete;
4631
4632    if (Entity.getKind() == InitializedEntity::EK_Base) {
4633      ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4634        CXXConstructExpr::CK_VirtualBase :
4635        CXXConstructExpr::CK_NonVirtualBase;
4636    } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4637      ConstructKind = CXXConstructExpr::CK_Delegating;
4638    }
4639
4640    // Only get the parenthesis range if it is a direct construction.
4641    SourceRange parenRange =
4642        Kind.getKind() == InitializationKind::IK_Direct ?
4643        Kind.getParenRange() : SourceRange();
4644
4645    // If the entity allows NRVO, mark the construction as elidable
4646    // unconditionally.
4647    if (Entity.allowsNRVO())
4648      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4649                                        Constructor, /*Elidable=*/true,
4650                                        move_arg(ConstructorArgs),
4651                                        HadMultipleCandidates,
4652                                        ConstructorInitRequiresZeroInit,
4653                                        ConstructKind,
4654                                        parenRange);
4655    else
4656      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4657                                        Constructor,
4658                                        move_arg(ConstructorArgs),
4659                                        HadMultipleCandidates,
4660                                        ConstructorInitRequiresZeroInit,
4661                                        ConstructKind,
4662                                        parenRange);
4663  }
4664  if (CurInit.isInvalid())
4665    return ExprError();
4666
4667  // Only check access if all of that succeeded.
4668  S.CheckConstructorAccess(Loc, Constructor, Entity,
4669                           Step.Function.FoundDecl.getAccess());
4670  S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4671
4672  if (shouldBindAsTemporary(Entity))
4673    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4674
4675  return move(CurInit);
4676}
4677
4678ExprResult
4679InitializationSequence::Perform(Sema &S,
4680                                const InitializedEntity &Entity,
4681                                const InitializationKind &Kind,
4682                                MultiExprArg Args,
4683                                QualType *ResultType) {
4684  if (Failed()) {
4685    unsigned NumArgs = Args.size();
4686    Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
4687    return ExprError();
4688  }
4689
4690  if (getKind() == DependentSequence) {
4691    // If the declaration is a non-dependent, incomplete array type
4692    // that has an initializer, then its type will be completed once
4693    // the initializer is instantiated.
4694    if (ResultType && !Entity.getType()->isDependentType() &&
4695        Args.size() == 1) {
4696      QualType DeclType = Entity.getType();
4697      if (const IncompleteArrayType *ArrayT
4698                           = S.Context.getAsIncompleteArrayType(DeclType)) {
4699        // FIXME: We don't currently have the ability to accurately
4700        // compute the length of an initializer list without
4701        // performing full type-checking of the initializer list
4702        // (since we have to determine where braces are implicitly
4703        // introduced and such).  So, we fall back to making the array
4704        // type a dependently-sized array type with no specified
4705        // bound.
4706        if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4707          SourceRange Brackets;
4708
4709          // Scavange the location of the brackets from the entity, if we can.
4710          if (DeclaratorDecl *DD = Entity.getDecl()) {
4711            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4712              TypeLoc TL = TInfo->getTypeLoc();
4713              if (IncompleteArrayTypeLoc *ArrayLoc
4714                                      = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4715              Brackets = ArrayLoc->getBracketsRange();
4716            }
4717          }
4718
4719          *ResultType
4720            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4721                                                   /*NumElts=*/0,
4722                                                   ArrayT->getSizeModifier(),
4723                                       ArrayT->getIndexTypeCVRQualifiers(),
4724                                                   Brackets);
4725        }
4726
4727      }
4728    }
4729    if (Kind.getKind() == InitializationKind::IK_Direct &&
4730        !Kind.isExplicitCast()) {
4731      // Rebuild the ParenListExpr.
4732      SourceRange ParenRange = Kind.getParenRange();
4733      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4734                                  move(Args));
4735    }
4736    assert(Kind.getKind() == InitializationKind::IK_Copy ||
4737           Kind.isExplicitCast());
4738    return ExprResult(Args.release()[0]);
4739  }
4740
4741  // No steps means no initialization.
4742  if (Steps.empty())
4743    return S.Owned((Expr *)0);
4744
4745  QualType DestType = Entity.getType().getNonReferenceType();
4746  // FIXME: Ugly hack around the fact that Entity.getType() is not
4747  // the same as Entity.getDecl()->getType() in cases involving type merging,
4748  //  and we want latter when it makes sense.
4749  if (ResultType)
4750    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
4751                                     Entity.getType();
4752
4753  ExprResult CurInit = S.Owned((Expr *)0);
4754
4755  // For initialization steps that start with a single initializer,
4756  // grab the only argument out the Args and place it into the "current"
4757  // initializer.
4758  switch (Steps.front().Kind) {
4759  case SK_ResolveAddressOfOverloadedFunction:
4760  case SK_CastDerivedToBaseRValue:
4761  case SK_CastDerivedToBaseXValue:
4762  case SK_CastDerivedToBaseLValue:
4763  case SK_BindReference:
4764  case SK_BindReferenceToTemporary:
4765  case SK_ExtraneousCopyToTemporary:
4766  case SK_UserConversion:
4767  case SK_QualificationConversionLValue:
4768  case SK_QualificationConversionXValue:
4769  case SK_QualificationConversionRValue:
4770  case SK_ConversionSequence:
4771  case SK_ListConstructorCall:
4772  case SK_ListInitialization:
4773  case SK_UnwrapInitList:
4774  case SK_RewrapInitList:
4775  case SK_CAssignment:
4776  case SK_StringInit:
4777  case SK_ObjCObjectConversion:
4778  case SK_ArrayInit:
4779  case SK_PassByIndirectCopyRestore:
4780  case SK_PassByIndirectRestore:
4781  case SK_ProduceObjCObject:
4782  case SK_StdInitializerList: {
4783    assert(Args.size() == 1);
4784    CurInit = Args.get()[0];
4785    if (!CurInit.get()) return ExprError();
4786    break;
4787  }
4788
4789  case SK_ConstructorInitialization:
4790  case SK_ZeroInitialization:
4791    break;
4792  }
4793
4794  // Walk through the computed steps for the initialization sequence,
4795  // performing the specified conversions along the way.
4796  bool ConstructorInitRequiresZeroInit = false;
4797  for (step_iterator Step = step_begin(), StepEnd = step_end();
4798       Step != StepEnd; ++Step) {
4799    if (CurInit.isInvalid())
4800      return ExprError();
4801
4802    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
4803
4804    switch (Step->Kind) {
4805    case SK_ResolveAddressOfOverloadedFunction:
4806      // Overload resolution determined which function invoke; update the
4807      // initializer to reflect that choice.
4808      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
4809      S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
4810      CurInit = S.FixOverloadedFunctionReference(move(CurInit),
4811                                                 Step->Function.FoundDecl,
4812                                                 Step->Function.Function);
4813      break;
4814
4815    case SK_CastDerivedToBaseRValue:
4816    case SK_CastDerivedToBaseXValue:
4817    case SK_CastDerivedToBaseLValue: {
4818      // We have a derived-to-base cast that produces either an rvalue or an
4819      // lvalue. Perform that cast.
4820
4821      CXXCastPath BasePath;
4822
4823      // Casts to inaccessible base classes are allowed with C-style casts.
4824      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4825      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
4826                                         CurInit.get()->getLocStart(),
4827                                         CurInit.get()->getSourceRange(),
4828                                         &BasePath, IgnoreBaseAccess))
4829        return ExprError();
4830
4831      if (S.BasePathInvolvesVirtualBase(BasePath)) {
4832        QualType T = SourceType;
4833        if (const PointerType *Pointer = T->getAs<PointerType>())
4834          T = Pointer->getPointeeType();
4835        if (const RecordType *RecordTy = T->getAs<RecordType>())
4836          S.MarkVTableUsed(CurInit.get()->getLocStart(),
4837                           cast<CXXRecordDecl>(RecordTy->getDecl()));
4838      }
4839
4840      ExprValueKind VK =
4841          Step->Kind == SK_CastDerivedToBaseLValue ?
4842              VK_LValue :
4843              (Step->Kind == SK_CastDerivedToBaseXValue ?
4844                   VK_XValue :
4845                   VK_RValue);
4846      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4847                                                 Step->Type,
4848                                                 CK_DerivedToBase,
4849                                                 CurInit.get(),
4850                                                 &BasePath, VK));
4851      break;
4852    }
4853
4854    case SK_BindReference:
4855      if (FieldDecl *BitField = CurInit.get()->getBitField()) {
4856        // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4857        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
4858          << Entity.getType().isVolatileQualified()
4859          << BitField->getDeclName()
4860          << CurInit.get()->getSourceRange();
4861        S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
4862        return ExprError();
4863      }
4864
4865      if (CurInit.get()->refersToVectorElement()) {
4866        // References cannot bind to vector elements.
4867        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4868          << Entity.getType().isVolatileQualified()
4869          << CurInit.get()->getSourceRange();
4870        PrintInitLocationNote(S, Entity);
4871        return ExprError();
4872      }
4873
4874      // Reference binding does not have any corresponding ASTs.
4875
4876      // Check exception specifications
4877      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4878        return ExprError();
4879
4880      break;
4881
4882    case SK_BindReferenceToTemporary:
4883      // Check exception specifications
4884      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4885        return ExprError();
4886
4887      // Materialize the temporary into memory.
4888      CurInit = new (S.Context) MaterializeTemporaryExpr(
4889                                         Entity.getType().getNonReferenceType(),
4890                                                         CurInit.get(),
4891                                     Entity.getType()->isLValueReferenceType());
4892
4893      // If we're binding to an Objective-C object that has lifetime, we
4894      // need cleanups.
4895      if (S.getLangOptions().ObjCAutoRefCount &&
4896          CurInit.get()->getType()->isObjCLifetimeType())
4897        S.ExprNeedsCleanups = true;
4898
4899      break;
4900
4901    case SK_ExtraneousCopyToTemporary:
4902      CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
4903                           /*IsExtraneousCopy=*/true);
4904      break;
4905
4906    case SK_UserConversion: {
4907      // We have a user-defined conversion that invokes either a constructor
4908      // or a conversion function.
4909      CastKind CastKind;
4910      bool IsCopy = false;
4911      FunctionDecl *Fn = Step->Function.Function;
4912      DeclAccessPair FoundFn = Step->Function.FoundDecl;
4913      bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
4914      bool CreatedObject = false;
4915      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
4916        // Build a call to the selected constructor.
4917        ASTOwningVector<Expr*> ConstructorArgs(S);
4918        SourceLocation Loc = CurInit.get()->getLocStart();
4919        CurInit.release(); // Ownership transferred into MultiExprArg, below.
4920
4921        // Determine the arguments required to actually perform the constructor
4922        // call.
4923        Expr *Arg = CurInit.get();
4924        if (S.CompleteConstructorCall(Constructor,
4925                                      MultiExprArg(&Arg, 1),
4926                                      Loc, ConstructorArgs))
4927          return ExprError();
4928
4929        // Build an expression that constructs a temporary.
4930        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
4931                                          move_arg(ConstructorArgs),
4932                                          HadMultipleCandidates,
4933                                          /*ZeroInit*/ false,
4934                                          CXXConstructExpr::CK_Complete,
4935                                          SourceRange());
4936        if (CurInit.isInvalid())
4937          return ExprError();
4938
4939        S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
4940                                 FoundFn.getAccess());
4941        S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4942
4943        CastKind = CK_ConstructorConversion;
4944        QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4945        if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4946            S.IsDerivedFrom(SourceType, Class))
4947          IsCopy = true;
4948
4949        CreatedObject = true;
4950      } else {
4951        // Build a call to the conversion function.
4952        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
4953        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
4954                                    FoundFn);
4955        S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4956
4957        // FIXME: Should we move this initialization into a separate
4958        // derived-to-base conversion? I believe the answer is "no", because
4959        // we don't want to turn off access control here for c-style casts.
4960        ExprResult CurInitExprRes =
4961          S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4962                                                FoundFn, Conversion);
4963        if(CurInitExprRes.isInvalid())
4964          return ExprError();
4965        CurInit = move(CurInitExprRes);
4966
4967        // Build the actual call to the conversion function.
4968        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4969                                           HadMultipleCandidates);
4970        if (CurInit.isInvalid() || !CurInit.get())
4971          return ExprError();
4972
4973        CastKind = CK_UserDefinedConversion;
4974
4975        CreatedObject = Conversion->getResultType()->isRecordType();
4976      }
4977
4978      bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
4979      bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4980
4981      if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
4982        QualType T = CurInit.get()->getType();
4983        if (const RecordType *Record = T->getAs<RecordType>()) {
4984          CXXDestructorDecl *Destructor
4985            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
4986          S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
4987                                  S.PDiag(diag::err_access_dtor_temp) << T);
4988          S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
4989          S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
4990        }
4991      }
4992
4993      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4994                                                 CurInit.get()->getType(),
4995                                                 CastKind, CurInit.get(), 0,
4996                                                CurInit.get()->getValueKind()));
4997      if (MaybeBindToTemp)
4998        CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4999      if (RequiresCopy)
5000        CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5001                             move(CurInit), /*IsExtraneousCopy=*/false);
5002      break;
5003    }
5004
5005    case SK_QualificationConversionLValue:
5006    case SK_QualificationConversionXValue:
5007    case SK_QualificationConversionRValue: {
5008      // Perform a qualification conversion; these can never go wrong.
5009      ExprValueKind VK =
5010          Step->Kind == SK_QualificationConversionLValue ?
5011              VK_LValue :
5012              (Step->Kind == SK_QualificationConversionXValue ?
5013                   VK_XValue :
5014                   VK_RValue);
5015      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5016      break;
5017    }
5018
5019    case SK_ConversionSequence: {
5020      Sema::CheckedConversionKind CCK
5021        = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5022        : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5023        : Kind.isExplicitCast()? Sema::CCK_OtherCast
5024        : Sema::CCK_ImplicitConversion;
5025      ExprResult CurInitExprRes =
5026        S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5027                                    getAssignmentAction(Entity), CCK);
5028      if (CurInitExprRes.isInvalid())
5029        return ExprError();
5030      CurInit = move(CurInitExprRes);
5031      break;
5032    }
5033
5034    case SK_ListInitialization: {
5035      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5036      // Hack: We must pass *ResultType if available in order to set the type
5037      // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5038      // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5039      // temporary, not a reference, so we should pass Ty.
5040      // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5041      // Since this step is never used for a reference directly, we explicitly
5042      // unwrap references here and rewrap them afterwards.
5043      // We also need to create a InitializeTemporary entity for this.
5044      QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5045      bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5046      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5047      InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5048          InitList, Ty, /*VerifyOnly=*/false,
5049          Kind.getKind() != InitializationKind::IK_DirectList ||
5050            !S.getLangOptions().CPlusPlus0x);
5051      if (PerformInitList.HadError())
5052        return ExprError();
5053
5054      if (ResultType) {
5055        if ((*ResultType)->isRValueReferenceType())
5056          Ty = S.Context.getRValueReferenceType(Ty);
5057        else if ((*ResultType)->isLValueReferenceType())
5058          Ty = S.Context.getLValueReferenceType(Ty,
5059            (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5060        *ResultType = Ty;
5061      }
5062
5063      InitListExpr *StructuredInitList =
5064          PerformInitList.getFullyStructuredList();
5065      CurInit.release();
5066      CurInit = S.Owned(StructuredInitList);
5067      break;
5068    }
5069
5070    case SK_ListConstructorCall: {
5071      // When an initializer list is passed for a parameter of type "reference
5072      // to object", we don't get an EK_Temporary entity, but instead an
5073      // EK_Parameter entity with reference type.
5074      // FIXME: This is a hack. Why is this necessary here, but not in other
5075      // places where implicit temporaries are created?
5076      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5077                                        Entity.getType().getNonReferenceType());
5078      bool UseTemporary = Entity.getType()->isReferenceType();
5079      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5080      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5081      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5082                                                                   Entity,
5083                                                 Kind, move(Arg), *Step,
5084                                               ConstructorInitRequiresZeroInit);
5085      break;
5086    }
5087
5088    case SK_UnwrapInitList:
5089      CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5090      break;
5091
5092    case SK_RewrapInitList: {
5093      Expr *E = CurInit.take();
5094      InitListExpr *Syntactic = Step->WrappingSyntacticList;
5095      InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5096          Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5097      ILE->setSyntacticForm(Syntactic);
5098      ILE->setType(E->getType());
5099      ILE->setValueKind(E->getValueKind());
5100      CurInit = S.Owned(ILE);
5101      break;
5102    }
5103
5104    case SK_ConstructorInitialization:
5105      CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5106                                                 *Step,
5107                                               ConstructorInitRequiresZeroInit);
5108      break;
5109
5110    case SK_ZeroInitialization: {
5111      step_iterator NextStep = Step;
5112      ++NextStep;
5113      if (NextStep != StepEnd &&
5114          NextStep->Kind == SK_ConstructorInitialization) {
5115        // The need for zero-initialization is recorded directly into
5116        // the call to the object's constructor within the next step.
5117        ConstructorInitRequiresZeroInit = true;
5118      } else if (Kind.getKind() == InitializationKind::IK_Value &&
5119                 S.getLangOptions().CPlusPlus &&
5120                 !Kind.isImplicitValueInit()) {
5121        TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5122        if (!TSInfo)
5123          TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5124                                                    Kind.getRange().getBegin());
5125
5126        CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5127                              TSInfo->getType().getNonLValueExprType(S.Context),
5128                                                                 TSInfo,
5129                                                    Kind.getRange().getEnd()));
5130      } else {
5131        CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5132      }
5133      break;
5134    }
5135
5136    case SK_CAssignment: {
5137      QualType SourceType = CurInit.get()->getType();
5138      ExprResult Result = move(CurInit);
5139      Sema::AssignConvertType ConvTy =
5140        S.CheckSingleAssignmentConstraints(Step->Type, Result);
5141      if (Result.isInvalid())
5142        return ExprError();
5143      CurInit = move(Result);
5144
5145      // If this is a call, allow conversion to a transparent union.
5146      ExprResult CurInitExprRes = move(CurInit);
5147      if (ConvTy != Sema::Compatible &&
5148          Entity.getKind() == InitializedEntity::EK_Parameter &&
5149          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5150            == Sema::Compatible)
5151        ConvTy = Sema::Compatible;
5152      if (CurInitExprRes.isInvalid())
5153        return ExprError();
5154      CurInit = move(CurInitExprRes);
5155
5156      bool Complained;
5157      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5158                                     Step->Type, SourceType,
5159                                     CurInit.get(),
5160                                     getAssignmentAction(Entity),
5161                                     &Complained)) {
5162        PrintInitLocationNote(S, Entity);
5163        return ExprError();
5164      } else if (Complained)
5165        PrintInitLocationNote(S, Entity);
5166      break;
5167    }
5168
5169    case SK_StringInit: {
5170      QualType Ty = Step->Type;
5171      CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5172                      S.Context.getAsArrayType(Ty), S);
5173      break;
5174    }
5175
5176    case SK_ObjCObjectConversion:
5177      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5178                          CK_ObjCObjectLValueCast,
5179                          CurInit.get()->getValueKind());
5180      break;
5181
5182    case SK_ArrayInit:
5183      // Okay: we checked everything before creating this step. Note that
5184      // this is a GNU extension.
5185      S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5186        << Step->Type << CurInit.get()->getType()
5187        << CurInit.get()->getSourceRange();
5188
5189      // If the destination type is an incomplete array type, update the
5190      // type accordingly.
5191      if (ResultType) {
5192        if (const IncompleteArrayType *IncompleteDest
5193                           = S.Context.getAsIncompleteArrayType(Step->Type)) {
5194          if (const ConstantArrayType *ConstantSource
5195                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5196            *ResultType = S.Context.getConstantArrayType(
5197                                             IncompleteDest->getElementType(),
5198                                             ConstantSource->getSize(),
5199                                             ArrayType::Normal, 0);
5200          }
5201        }
5202      }
5203      break;
5204
5205    case SK_PassByIndirectCopyRestore:
5206    case SK_PassByIndirectRestore:
5207      checkIndirectCopyRestoreSource(S, CurInit.get());
5208      CurInit = S.Owned(new (S.Context)
5209                        ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5210                                Step->Kind == SK_PassByIndirectCopyRestore));
5211      break;
5212
5213    case SK_ProduceObjCObject:
5214      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5215                                                 CK_ARCProduceObject,
5216                                                 CurInit.take(), 0, VK_RValue));
5217      break;
5218
5219    case SK_StdInitializerList: {
5220      QualType Dest = Step->Type;
5221      QualType E;
5222      bool Success = S.isStdInitializerList(Dest, &E);
5223      (void)Success;
5224      assert(Success && "Destination type changed?");
5225      InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5226      unsigned NumInits = ILE->getNumInits();
5227      SmallVector<Expr*, 16> Converted(NumInits);
5228      InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5229          S.Context.getConstantArrayType(E,
5230              llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5231                          NumInits),
5232              ArrayType::Normal, 0));
5233      InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5234          0, HiddenArray);
5235      for (unsigned i = 0; i < NumInits; ++i) {
5236        Element.setElementIndex(i);
5237        ExprResult Init = S.Owned(ILE->getInit(i));
5238        ExprResult Res = S.PerformCopyInitialization(Element,
5239                                                     Init.get()->getExprLoc(),
5240                                                     Init);
5241        assert(!Res.isInvalid() && "Result changed since try phase.");
5242        Converted[i] = Res.take();
5243      }
5244      InitListExpr *Semantic = new (S.Context)
5245          InitListExpr(S.Context, ILE->getLBraceLoc(),
5246                       Converted.data(), NumInits, ILE->getRBraceLoc());
5247      Semantic->setSyntacticForm(ILE);
5248      Semantic->setType(Dest);
5249      CurInit = S.Owned(Semantic);
5250      break;
5251    }
5252    }
5253  }
5254
5255  // Diagnose non-fatal problems with the completed initialization.
5256  if (Entity.getKind() == InitializedEntity::EK_Member &&
5257      cast<FieldDecl>(Entity.getDecl())->isBitField())
5258    S.CheckBitFieldInitialization(Kind.getLocation(),
5259                                  cast<FieldDecl>(Entity.getDecl()),
5260                                  CurInit.get());
5261
5262  return move(CurInit);
5263}
5264
5265//===----------------------------------------------------------------------===//
5266// Diagnose initialization failures
5267//===----------------------------------------------------------------------===//
5268bool InitializationSequence::Diagnose(Sema &S,
5269                                      const InitializedEntity &Entity,
5270                                      const InitializationKind &Kind,
5271                                      Expr **Args, unsigned NumArgs) {
5272  if (!Failed())
5273    return false;
5274
5275  QualType DestType = Entity.getType();
5276  switch (Failure) {
5277  case FK_TooManyInitsForReference:
5278    // FIXME: Customize for the initialized entity?
5279    if (NumArgs == 0)
5280      S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5281        << DestType.getNonReferenceType();
5282    else  // FIXME: diagnostic below could be better!
5283      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5284        << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
5285    break;
5286
5287  case FK_ArrayNeedsInitList:
5288  case FK_ArrayNeedsInitListOrStringLiteral:
5289    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5290      << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5291    break;
5292
5293  case FK_ArrayTypeMismatch:
5294  case FK_NonConstantArrayInit:
5295    S.Diag(Kind.getLocation(),
5296           (Failure == FK_ArrayTypeMismatch
5297              ? diag::err_array_init_different_type
5298              : diag::err_array_init_non_constant_array))
5299      << DestType.getNonReferenceType()
5300      << Args[0]->getType()
5301      << Args[0]->getSourceRange();
5302    break;
5303
5304  case FK_VariableLengthArrayHasInitializer:
5305    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5306      << Args[0]->getSourceRange();
5307    break;
5308
5309  case FK_AddressOfOverloadFailed: {
5310    DeclAccessPair Found;
5311    S.ResolveAddressOfOverloadedFunction(Args[0],
5312                                         DestType.getNonReferenceType(),
5313                                         true,
5314                                         Found);
5315    break;
5316  }
5317
5318  case FK_ReferenceInitOverloadFailed:
5319  case FK_UserConversionOverloadFailed:
5320    switch (FailedOverloadResult) {
5321    case OR_Ambiguous:
5322      if (Failure == FK_UserConversionOverloadFailed)
5323        S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5324          << Args[0]->getType() << DestType
5325          << Args[0]->getSourceRange();
5326      else
5327        S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5328          << DestType << Args[0]->getType()
5329          << Args[0]->getSourceRange();
5330
5331      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
5332      break;
5333
5334    case OR_No_Viable_Function:
5335      S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5336        << Args[0]->getType() << DestType.getNonReferenceType()
5337        << Args[0]->getSourceRange();
5338      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
5339      break;
5340
5341    case OR_Deleted: {
5342      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5343        << Args[0]->getType() << DestType.getNonReferenceType()
5344        << Args[0]->getSourceRange();
5345      OverloadCandidateSet::iterator Best;
5346      OverloadingResult Ovl
5347        = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5348                                                true);
5349      if (Ovl == OR_Deleted) {
5350        S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5351          << 1 << Best->Function->isDeleted();
5352      } else {
5353        llvm_unreachable("Inconsistent overload resolution?");
5354      }
5355      break;
5356    }
5357
5358    case OR_Success:
5359      llvm_unreachable("Conversion did not fail!");
5360    }
5361    break;
5362
5363  case FK_NonConstLValueReferenceBindingToTemporary:
5364    if (isa<InitListExpr>(Args[0])) {
5365      S.Diag(Kind.getLocation(),
5366             diag::err_lvalue_reference_bind_to_initlist)
5367      << DestType.getNonReferenceType().isVolatileQualified()
5368      << DestType.getNonReferenceType()
5369      << Args[0]->getSourceRange();
5370      break;
5371    }
5372    // Intentional fallthrough
5373
5374  case FK_NonConstLValueReferenceBindingToUnrelated:
5375    S.Diag(Kind.getLocation(),
5376           Failure == FK_NonConstLValueReferenceBindingToTemporary
5377             ? diag::err_lvalue_reference_bind_to_temporary
5378             : diag::err_lvalue_reference_bind_to_unrelated)
5379      << DestType.getNonReferenceType().isVolatileQualified()
5380      << DestType.getNonReferenceType()
5381      << Args[0]->getType()
5382      << Args[0]->getSourceRange();
5383    break;
5384
5385  case FK_RValueReferenceBindingToLValue:
5386    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
5387      << DestType.getNonReferenceType() << Args[0]->getType()
5388      << Args[0]->getSourceRange();
5389    break;
5390
5391  case FK_ReferenceInitDropsQualifiers:
5392    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5393      << DestType.getNonReferenceType()
5394      << Args[0]->getType()
5395      << Args[0]->getSourceRange();
5396    break;
5397
5398  case FK_ReferenceInitFailed:
5399    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5400      << DestType.getNonReferenceType()
5401      << Args[0]->isLValue()
5402      << Args[0]->getType()
5403      << Args[0]->getSourceRange();
5404    if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5405        Args[0]->getType()->isObjCObjectPointerType())
5406      S.EmitRelatedResultTypeNote(Args[0]);
5407    break;
5408
5409  case FK_ConversionFailed: {
5410    QualType FromType = Args[0]->getType();
5411    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
5412      << (int)Entity.getKind()
5413      << DestType
5414      << Args[0]->isLValue()
5415      << FromType
5416      << Args[0]->getSourceRange();
5417    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5418    S.Diag(Kind.getLocation(), PDiag);
5419    if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5420        Args[0]->getType()->isObjCObjectPointerType())
5421      S.EmitRelatedResultTypeNote(Args[0]);
5422    break;
5423  }
5424
5425  case FK_ConversionFromPropertyFailed:
5426    // No-op. This error has already been reported.
5427    break;
5428
5429  case FK_TooManyInitsForScalar: {
5430    SourceRange R;
5431
5432    if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5433      R = SourceRange(InitList->getInit(0)->getLocEnd(),
5434                      InitList->getLocEnd());
5435    else
5436      R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
5437
5438    R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5439    if (Kind.isCStyleOrFunctionalCast())
5440      S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5441        << R;
5442    else
5443      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5444        << /*scalar=*/2 << R;
5445    break;
5446  }
5447
5448  case FK_ReferenceBindingToInitList:
5449    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5450      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5451    break;
5452
5453  case FK_InitListBadDestinationType:
5454    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5455      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5456    break;
5457
5458  case FK_ListConstructorOverloadFailed:
5459  case FK_ConstructorOverloadFailed: {
5460    SourceRange ArgsRange;
5461    if (NumArgs)
5462      ArgsRange = SourceRange(Args[0]->getLocStart(),
5463                              Args[NumArgs - 1]->getLocEnd());
5464
5465    if (Failure == FK_ListConstructorOverloadFailed) {
5466      assert(NumArgs == 1 && "List construction from other than 1 argument.");
5467      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5468      Args = InitList->getInits();
5469      NumArgs = InitList->getNumInits();
5470    }
5471
5472    // FIXME: Using "DestType" for the entity we're printing is probably
5473    // bad.
5474    switch (FailedOverloadResult) {
5475      case OR_Ambiguous:
5476        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5477          << DestType << ArgsRange;
5478        FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5479                                          Args, NumArgs);
5480        break;
5481
5482      case OR_No_Viable_Function:
5483        if (Kind.getKind() == InitializationKind::IK_Default &&
5484            (Entity.getKind() == InitializedEntity::EK_Base ||
5485             Entity.getKind() == InitializedEntity::EK_Member) &&
5486            isa<CXXConstructorDecl>(S.CurContext)) {
5487          // This is implicit default initialization of a member or
5488          // base within a constructor. If no viable function was
5489          // found, notify the user that she needs to explicitly
5490          // initialize this base/member.
5491          CXXConstructorDecl *Constructor
5492            = cast<CXXConstructorDecl>(S.CurContext);
5493          if (Entity.getKind() == InitializedEntity::EK_Base) {
5494            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5495              << Constructor->isImplicit()
5496              << S.Context.getTypeDeclType(Constructor->getParent())
5497              << /*base=*/0
5498              << Entity.getType();
5499
5500            RecordDecl *BaseDecl
5501              = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5502                                                                  ->getDecl();
5503            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5504              << S.Context.getTagDeclType(BaseDecl);
5505          } else {
5506            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5507              << Constructor->isImplicit()
5508              << S.Context.getTypeDeclType(Constructor->getParent())
5509              << /*member=*/1
5510              << Entity.getName();
5511            S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5512
5513            if (const RecordType *Record
5514                                 = Entity.getType()->getAs<RecordType>())
5515              S.Diag(Record->getDecl()->getLocation(),
5516                     diag::note_previous_decl)
5517                << S.Context.getTagDeclType(Record->getDecl());
5518          }
5519          break;
5520        }
5521
5522        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5523          << DestType << ArgsRange;
5524        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
5525        break;
5526
5527      case OR_Deleted: {
5528        S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5529          << true << DestType << ArgsRange;
5530        OverloadCandidateSet::iterator Best;
5531        OverloadingResult Ovl
5532          = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5533        if (Ovl == OR_Deleted) {
5534          S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5535            << 1 << Best->Function->isDeleted();
5536        } else {
5537          llvm_unreachable("Inconsistent overload resolution?");
5538        }
5539        break;
5540      }
5541
5542      case OR_Success:
5543        llvm_unreachable("Conversion did not fail!");
5544    }
5545  }
5546  break;
5547
5548  case FK_DefaultInitOfConst:
5549    if (Entity.getKind() == InitializedEntity::EK_Member &&
5550        isa<CXXConstructorDecl>(S.CurContext)) {
5551      // This is implicit default-initialization of a const member in
5552      // a constructor. Complain that it needs to be explicitly
5553      // initialized.
5554      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5555      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5556        << Constructor->isImplicit()
5557        << S.Context.getTypeDeclType(Constructor->getParent())
5558        << /*const=*/1
5559        << Entity.getName();
5560      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5561        << Entity.getName();
5562    } else {
5563      S.Diag(Kind.getLocation(), diag::err_default_init_const)
5564        << DestType << (bool)DestType->getAs<RecordType>();
5565    }
5566    break;
5567
5568  case FK_Incomplete:
5569    S.RequireCompleteType(Kind.getLocation(), DestType,
5570                          diag::err_init_incomplete_type);
5571    break;
5572
5573  case FK_ListInitializationFailed: {
5574    // Run the init list checker again to emit diagnostics.
5575    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5576    QualType DestType = Entity.getType();
5577    InitListChecker DiagnoseInitList(S, Entity, InitList,
5578            DestType, /*VerifyOnly=*/false,
5579            Kind.getKind() != InitializationKind::IK_DirectList ||
5580              !S.getLangOptions().CPlusPlus0x);
5581    assert(DiagnoseInitList.HadError() &&
5582           "Inconsistent init list check result.");
5583    break;
5584  }
5585
5586  case FK_PlaceholderType: {
5587    // FIXME: Already diagnosed!
5588    break;
5589  }
5590
5591  case FK_InitListElementCopyFailure: {
5592    // Try to perform all copies again.
5593    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5594    unsigned NumInits = InitList->getNumInits();
5595    QualType DestType = Entity.getType();
5596    QualType E;
5597    bool Success = S.isStdInitializerList(DestType, &E);
5598    (void)Success;
5599    assert(Success && "Where did the std::initializer_list go?");
5600    InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5601        S.Context.getConstantArrayType(E,
5602            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5603                        NumInits),
5604            ArrayType::Normal, 0));
5605    InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5606        0, HiddenArray);
5607    // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5608    // where the init list type is wrong, e.g.
5609    //   std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5610    // FIXME: Emit a note if we hit the limit?
5611    int ErrorCount = 0;
5612    for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5613      Element.setElementIndex(i);
5614      ExprResult Init = S.Owned(InitList->getInit(i));
5615      if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5616           .isInvalid())
5617        ++ErrorCount;
5618    }
5619    break;
5620  }
5621  }
5622
5623  PrintInitLocationNote(S, Entity);
5624  return true;
5625}
5626
5627void InitializationSequence::dump(raw_ostream &OS) const {
5628  switch (SequenceKind) {
5629  case FailedSequence: {
5630    OS << "Failed sequence: ";
5631    switch (Failure) {
5632    case FK_TooManyInitsForReference:
5633      OS << "too many initializers for reference";
5634      break;
5635
5636    case FK_ArrayNeedsInitList:
5637      OS << "array requires initializer list";
5638      break;
5639
5640    case FK_ArrayNeedsInitListOrStringLiteral:
5641      OS << "array requires initializer list or string literal";
5642      break;
5643
5644    case FK_ArrayTypeMismatch:
5645      OS << "array type mismatch";
5646      break;
5647
5648    case FK_NonConstantArrayInit:
5649      OS << "non-constant array initializer";
5650      break;
5651
5652    case FK_AddressOfOverloadFailed:
5653      OS << "address of overloaded function failed";
5654      break;
5655
5656    case FK_ReferenceInitOverloadFailed:
5657      OS << "overload resolution for reference initialization failed";
5658      break;
5659
5660    case FK_NonConstLValueReferenceBindingToTemporary:
5661      OS << "non-const lvalue reference bound to temporary";
5662      break;
5663
5664    case FK_NonConstLValueReferenceBindingToUnrelated:
5665      OS << "non-const lvalue reference bound to unrelated type";
5666      break;
5667
5668    case FK_RValueReferenceBindingToLValue:
5669      OS << "rvalue reference bound to an lvalue";
5670      break;
5671
5672    case FK_ReferenceInitDropsQualifiers:
5673      OS << "reference initialization drops qualifiers";
5674      break;
5675
5676    case FK_ReferenceInitFailed:
5677      OS << "reference initialization failed";
5678      break;
5679
5680    case FK_ConversionFailed:
5681      OS << "conversion failed";
5682      break;
5683
5684    case FK_ConversionFromPropertyFailed:
5685      OS << "conversion from property failed";
5686      break;
5687
5688    case FK_TooManyInitsForScalar:
5689      OS << "too many initializers for scalar";
5690      break;
5691
5692    case FK_ReferenceBindingToInitList:
5693      OS << "referencing binding to initializer list";
5694      break;
5695
5696    case FK_InitListBadDestinationType:
5697      OS << "initializer list for non-aggregate, non-scalar type";
5698      break;
5699
5700    case FK_UserConversionOverloadFailed:
5701      OS << "overloading failed for user-defined conversion";
5702      break;
5703
5704    case FK_ConstructorOverloadFailed:
5705      OS << "constructor overloading failed";
5706      break;
5707
5708    case FK_DefaultInitOfConst:
5709      OS << "default initialization of a const variable";
5710      break;
5711
5712    case FK_Incomplete:
5713      OS << "initialization of incomplete type";
5714      break;
5715
5716    case FK_ListInitializationFailed:
5717      OS << "list initialization checker failure";
5718      break;
5719
5720    case FK_VariableLengthArrayHasInitializer:
5721      OS << "variable length array has an initializer";
5722      break;
5723
5724    case FK_PlaceholderType:
5725      OS << "initializer expression isn't contextually valid";
5726      break;
5727
5728    case FK_ListConstructorOverloadFailed:
5729      OS << "list constructor overloading failed";
5730      break;
5731
5732    case FK_InitListElementCopyFailure:
5733      OS << "copy construction of initializer list element failed";
5734      break;
5735    }
5736    OS << '\n';
5737    return;
5738  }
5739
5740  case DependentSequence:
5741    OS << "Dependent sequence\n";
5742    return;
5743
5744  case NormalSequence:
5745    OS << "Normal sequence: ";
5746    break;
5747  }
5748
5749  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5750    if (S != step_begin()) {
5751      OS << " -> ";
5752    }
5753
5754    switch (S->Kind) {
5755    case SK_ResolveAddressOfOverloadedFunction:
5756      OS << "resolve address of overloaded function";
5757      break;
5758
5759    case SK_CastDerivedToBaseRValue:
5760      OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5761      break;
5762
5763    case SK_CastDerivedToBaseXValue:
5764      OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5765      break;
5766
5767    case SK_CastDerivedToBaseLValue:
5768      OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5769      break;
5770
5771    case SK_BindReference:
5772      OS << "bind reference to lvalue";
5773      break;
5774
5775    case SK_BindReferenceToTemporary:
5776      OS << "bind reference to a temporary";
5777      break;
5778
5779    case SK_ExtraneousCopyToTemporary:
5780      OS << "extraneous C++03 copy to temporary";
5781      break;
5782
5783    case SK_UserConversion:
5784      OS << "user-defined conversion via " << *S->Function.Function;
5785      break;
5786
5787    case SK_QualificationConversionRValue:
5788      OS << "qualification conversion (rvalue)";
5789      break;
5790
5791    case SK_QualificationConversionXValue:
5792      OS << "qualification conversion (xvalue)";
5793      break;
5794
5795    case SK_QualificationConversionLValue:
5796      OS << "qualification conversion (lvalue)";
5797      break;
5798
5799    case SK_ConversionSequence:
5800      OS << "implicit conversion sequence (";
5801      S->ICS->DebugPrint(); // FIXME: use OS
5802      OS << ")";
5803      break;
5804
5805    case SK_ListInitialization:
5806      OS << "list aggregate initialization";
5807      break;
5808
5809    case SK_ListConstructorCall:
5810      OS << "list initialization via constructor";
5811      break;
5812
5813    case SK_UnwrapInitList:
5814      OS << "unwrap reference initializer list";
5815      break;
5816
5817    case SK_RewrapInitList:
5818      OS << "rewrap reference initializer list";
5819      break;
5820
5821    case SK_ConstructorInitialization:
5822      OS << "constructor initialization";
5823      break;
5824
5825    case SK_ZeroInitialization:
5826      OS << "zero initialization";
5827      break;
5828
5829    case SK_CAssignment:
5830      OS << "C assignment";
5831      break;
5832
5833    case SK_StringInit:
5834      OS << "string initialization";
5835      break;
5836
5837    case SK_ObjCObjectConversion:
5838      OS << "Objective-C object conversion";
5839      break;
5840
5841    case SK_ArrayInit:
5842      OS << "array initialization";
5843      break;
5844
5845    case SK_PassByIndirectCopyRestore:
5846      OS << "pass by indirect copy and restore";
5847      break;
5848
5849    case SK_PassByIndirectRestore:
5850      OS << "pass by indirect restore";
5851      break;
5852
5853    case SK_ProduceObjCObject:
5854      OS << "Objective-C object retension";
5855      break;
5856
5857    case SK_StdInitializerList:
5858      OS << "std::initializer_list from initializer list";
5859      break;
5860    }
5861  }
5862}
5863
5864void InitializationSequence::dump() const {
5865  dump(llvm::errs());
5866}
5867
5868static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5869                                        QualType EntityType,
5870                                        const Expr *PreInit,
5871                                        const Expr *PostInit) {
5872  if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5873    return;
5874
5875  // A narrowing conversion can only appear as the final implicit conversion in
5876  // an initialization sequence.
5877  const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5878  if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5879    return;
5880
5881  const ImplicitConversionSequence &ICS = *LastStep.ICS;
5882  const StandardConversionSequence *SCS = 0;
5883  switch (ICS.getKind()) {
5884  case ImplicitConversionSequence::StandardConversion:
5885    SCS = &ICS.Standard;
5886    break;
5887  case ImplicitConversionSequence::UserDefinedConversion:
5888    SCS = &ICS.UserDefined.After;
5889    break;
5890  case ImplicitConversionSequence::AmbiguousConversion:
5891  case ImplicitConversionSequence::EllipsisConversion:
5892  case ImplicitConversionSequence::BadConversion:
5893    return;
5894  }
5895
5896  // Determine the type prior to the narrowing conversion. If a conversion
5897  // operator was used, this may be different from both the type of the entity
5898  // and of the pre-initialization expression.
5899  QualType PreNarrowingType = PreInit->getType();
5900  if (Seq.step_begin() + 1 != Seq.step_end())
5901    PreNarrowingType = Seq.step_end()[-2].Type;
5902
5903  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5904  APValue ConstantValue;
5905  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
5906  case NK_Not_Narrowing:
5907    // No narrowing occurred.
5908    return;
5909
5910  case NK_Type_Narrowing:
5911    // This was a floating-to-integer conversion, which is always considered a
5912    // narrowing conversion even if the value is a constant and can be
5913    // represented exactly as an integer.
5914    S.Diag(PostInit->getLocStart(),
5915           S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5916             diag::warn_init_list_type_narrowing
5917           : S.isSFINAEContext()?
5918             diag::err_init_list_type_narrowing_sfinae
5919           : diag::err_init_list_type_narrowing)
5920      << PostInit->getSourceRange()
5921      << PreNarrowingType.getLocalUnqualifiedType()
5922      << EntityType.getLocalUnqualifiedType();
5923    break;
5924
5925  case NK_Constant_Narrowing:
5926    // A constant value was narrowed.
5927    S.Diag(PostInit->getLocStart(),
5928           S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5929             diag::warn_init_list_constant_narrowing
5930           : S.isSFINAEContext()?
5931             diag::err_init_list_constant_narrowing_sfinae
5932           : diag::err_init_list_constant_narrowing)
5933      << PostInit->getSourceRange()
5934      << ConstantValue.getAsString(S.getASTContext(), EntityType)
5935      << EntityType.getLocalUnqualifiedType();
5936    break;
5937
5938  case NK_Variable_Narrowing:
5939    // A variable's value may have been narrowed.
5940    S.Diag(PostInit->getLocStart(),
5941           S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5942             diag::warn_init_list_variable_narrowing
5943           : S.isSFINAEContext()?
5944             diag::err_init_list_variable_narrowing_sfinae
5945           : diag::err_init_list_variable_narrowing)
5946      << PostInit->getSourceRange()
5947      << PreNarrowingType.getLocalUnqualifiedType()
5948      << EntityType.getLocalUnqualifiedType();
5949    break;
5950  }
5951
5952  SmallString<128> StaticCast;
5953  llvm::raw_svector_ostream OS(StaticCast);
5954  OS << "static_cast<";
5955  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5956    // It's important to use the typedef's name if there is one so that the
5957    // fixit doesn't break code using types like int64_t.
5958    //
5959    // FIXME: This will break if the typedef requires qualification.  But
5960    // getQualifiedNameAsString() includes non-machine-parsable components.
5961    OS << *TT->getDecl();
5962  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5963    OS << BT->getName(S.getLangOptions());
5964  else {
5965    // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
5966    // with a broken cast.
5967    return;
5968  }
5969  OS << ">(";
5970  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5971    << PostInit->getSourceRange()
5972    << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
5973    << FixItHint::CreateInsertion(
5974      S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
5975}
5976
5977//===----------------------------------------------------------------------===//
5978// Initialization helper functions
5979//===----------------------------------------------------------------------===//
5980bool
5981Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5982                                   ExprResult Init) {
5983  if (Init.isInvalid())
5984    return false;
5985
5986  Expr *InitE = Init.get();
5987  assert(InitE && "No initialization expression");
5988
5989  InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5990                                                           SourceLocation());
5991  InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5992  return !Seq.Failed();
5993}
5994
5995ExprResult
5996Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5997                                SourceLocation EqualLoc,
5998                                ExprResult Init,
5999                                bool TopLevelOfInitList) {
6000  if (Init.isInvalid())
6001    return ExprError();
6002
6003  Expr *InitE = Init.get();
6004  assert(InitE && "No initialization expression?");
6005
6006  if (EqualLoc.isInvalid())
6007    EqualLoc = InitE->getLocStart();
6008
6009  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6010                                                           EqualLoc);
6011  InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6012  Init.release();
6013
6014  ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6015
6016  if (!Result.isInvalid() && TopLevelOfInitList)
6017    DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6018                                InitE, Result.get());
6019
6020  return Result;
6021}
6022