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