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