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