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