SemaInit.cpp revision ac5fc7c6bcb494b60fee7ce615ac931c5db6135e
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. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
14// This file also implements Sema::CheckInitializerTypes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
19#include "clang/Parse/Designator.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include <map>
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
30static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
31  const ArrayType *AT = Context.getAsArrayType(DeclType);
32  if (!AT) return 0;
33
34  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
35    return 0;
36
37  // See if this is a string literal or @encode.
38  Init = Init->IgnoreParens();
39
40  // Handle @encode, which is a narrow string.
41  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
42    return Init;
43
44  // Otherwise we can only handle string literals.
45  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
46  if (SL == 0) return 0;
47
48  QualType ElemTy = Context.getCanonicalType(AT->getElementType());
49  // char array can be initialized with a narrow string.
50  // Only allow char x[] = "foo";  not char x[] = L"foo";
51  if (!SL->isWide())
52    return ElemTy->isCharType() ? Init : 0;
53
54  // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
55  // correction from DR343): "An array with element type compatible with a
56  // qualified or unqualified version of wchar_t may be initialized by a wide
57  // string literal, optionally enclosed in braces."
58  if (Context.typesAreCompatible(Context.getWCharType(),
59                                 ElemTy.getUnqualifiedType()))
60    return Init;
61
62  return 0;
63}
64
65static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
66                                   bool DirectInit, Sema &S) {
67  // Get the type before calling CheckSingleAssignmentConstraints(), since
68  // it can promote the expression.
69  QualType InitType = Init->getType();
70
71  if (S.getLangOptions().CPlusPlus) {
72    // FIXME: I dislike this error message. A lot.
73    if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
74      return S.Diag(Init->getSourceRange().getBegin(),
75                    diag::err_typecheck_convert_incompatible)
76        << DeclType << Init->getType() << "initializing"
77        << Init->getSourceRange();
78    return false;
79  }
80
81  Sema::AssignConvertType ConvTy =
82    S.CheckSingleAssignmentConstraints(DeclType, Init);
83  return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
84                                  InitType, Init, "initializing");
85}
86
87static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
88  // Get the length of the string as parsed.
89  uint64_t StrLength =
90    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
91
92
93  const ArrayType *AT = S.Context.getAsArrayType(DeclT);
94  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
95    // C99 6.7.8p14. We have an array of character type with unknown size
96    // being initialized to a string literal.
97    llvm::APSInt ConstVal(32);
98    ConstVal = StrLength;
99    // Return a new array type (C99 6.7.8p22).
100    DeclT = S.Context.getConstantArrayWithoutExprType(IAT->getElementType(),
101                                                      ConstVal,
102                                                      ArrayType::Normal, 0);
103    return;
104  }
105
106  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
107
108  // C99 6.7.8p14. We have an array of character type with known size.  However,
109  // the size may be smaller or larger than the string we are initializing.
110  // FIXME: Avoid truncation for 64-bit length strings.
111  if (StrLength-1 > CAT->getSize().getZExtValue())
112    S.Diag(Str->getSourceRange().getBegin(),
113           diag::warn_initializer_string_for_char_array_too_long)
114      << Str->getSourceRange();
115
116  // Set the type to the actual size that we are initializing.  If we have
117  // something like:
118  //   char x[1] = "foo";
119  // then this will set the string literal's type to char[1].
120  Str->setType(DeclT);
121}
122
123bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
124                                 SourceLocation InitLoc,
125                                 DeclarationName InitEntity, bool DirectInit) {
126  if (DeclType->isDependentType() ||
127      Init->isTypeDependent() || Init->isValueDependent())
128    return false;
129
130  // C++ [dcl.init.ref]p1:
131  //   A variable declared to be a T& or T&&, that is "reference to type T"
132  //   (8.3.2), shall be initialized by an object, or function, of
133  //   type T or by an object that can be converted into a T.
134  if (DeclType->isReferenceType())
135    return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
136
137  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
138  // of unknown size ("[]") or an object type that is not a variable array type.
139  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
140    return Diag(InitLoc,  diag::err_variable_object_no_init)
141    << VAT->getSizeExpr()->getSourceRange();
142
143  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
144  if (!InitList) {
145    // FIXME: Handle wide strings
146    if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
147      CheckStringInit(Str, DeclType, *this);
148      return false;
149    }
150
151    // C++ [dcl.init]p14:
152    //   -- If the destination type is a (possibly cv-qualified) class
153    //      type:
154    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
155      QualType DeclTypeC = Context.getCanonicalType(DeclType);
156      QualType InitTypeC = Context.getCanonicalType(Init->getType());
157
158      //   -- If the initialization is direct-initialization, or if it is
159      //      copy-initialization where the cv-unqualified version of the
160      //      source type is the same class as, or a derived class of, the
161      //      class of the destination, constructors are considered.
162      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
163          IsDerivedFrom(InitTypeC, DeclTypeC)) {
164        const CXXRecordDecl *RD =
165          cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
166
167        // No need to make a CXXConstructExpr if both the ctor and dtor are
168        // trivial.
169        if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
170          return false;
171
172        CXXConstructorDecl *Constructor
173        = PerformInitializationByConstructor(DeclType, &Init, 1,
174                                             InitLoc, Init->getSourceRange(),
175                                             InitEntity,
176                                             DirectInit? IK_Direct : IK_Copy);
177        if (!Constructor)
178          return true;
179
180        Init = CXXConstructExpr::Create(Context, DeclType, Constructor, false,
181                                        &Init, 1);
182        return false;
183      }
184
185      //   -- Otherwise (i.e., for the remaining copy-initialization
186      //      cases), user-defined conversion sequences that can
187      //      convert from the source type to the destination type or
188      //      (when a conversion function is used) to a derived class
189      //      thereof are enumerated as described in 13.3.1.4, and the
190      //      best one is chosen through overload resolution
191      //      (13.3). If the conversion cannot be done or is
192      //      ambiguous, the initialization is ill-formed. The
193      //      function selected is called with the initializer
194      //      expression as its argument; if the function is a
195      //      constructor, the call initializes a temporary of the
196      //      destination type.
197      // FIXME: We're pretending to do copy elision here; return to this when we
198      // have ASTs for such things.
199      if (!PerformImplicitConversion(Init, DeclType, "initializing"))
200        return false;
201
202      if (InitEntity)
203        return Diag(InitLoc, diag::err_cannot_initialize_decl)
204          << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
205          << Init->getType() << Init->getSourceRange();
206      return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
207        << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
208        << Init->getType() << Init->getSourceRange();
209    }
210
211    // C99 6.7.8p16.
212    if (DeclType->isArrayType())
213      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
214        << Init->getSourceRange();
215
216    return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
217  }
218
219  bool hadError = CheckInitList(InitList, DeclType);
220  Init = InitList;
221  return hadError;
222}
223
224//===----------------------------------------------------------------------===//
225// Semantic checking for initializer lists.
226//===----------------------------------------------------------------------===//
227
228/// @brief Semantic checking for initializer lists.
229///
230/// The InitListChecker class contains a set of routines that each
231/// handle the initialization of a certain kind of entity, e.g.,
232/// arrays, vectors, struct/union types, scalars, etc. The
233/// InitListChecker itself performs a recursive walk of the subobject
234/// structure of the type to be initialized, while stepping through
235/// the initializer list one element at a time. The IList and Index
236/// parameters to each of the Check* routines contain the active
237/// (syntactic) initializer list and the index into that initializer
238/// list that represents the current initializer. Each routine is
239/// responsible for moving that Index forward as it consumes elements.
240///
241/// Each Check* routine also has a StructuredList/StructuredIndex
242/// arguments, which contains the current the "structured" (semantic)
243/// initializer list and the index into that initializer list where we
244/// are copying initializers as we map them over to the semantic
245/// list. Once we have completed our recursive walk of the subobject
246/// structure, we will have constructed a full semantic initializer
247/// list.
248///
249/// C99 designators cause changes in the initializer list traversal,
250/// because they make the initialization "jump" into a specific
251/// subobject and then continue the initialization from that
252/// point. CheckDesignatedInitializer() recursively steps into the
253/// designated subobject and manages backing out the recursion to
254/// initialize the subobjects after the one designated.
255namespace {
256class InitListChecker {
257  Sema &SemaRef;
258  bool hadError;
259  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
260  InitListExpr *FullyStructuredList;
261
262  void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
263                             unsigned &Index, InitListExpr *StructuredList,
264                             unsigned &StructuredIndex,
265                             bool TopLevelObject = false);
266  void CheckExplicitInitList(InitListExpr *IList, QualType &T,
267                             unsigned &Index, InitListExpr *StructuredList,
268                             unsigned &StructuredIndex,
269                             bool TopLevelObject = false);
270  void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
271                             bool SubobjectIsDesignatorContext,
272                             unsigned &Index,
273                             InitListExpr *StructuredList,
274                             unsigned &StructuredIndex,
275                             bool TopLevelObject = false);
276  void CheckSubElementType(InitListExpr *IList, QualType ElemType,
277                           unsigned &Index,
278                           InitListExpr *StructuredList,
279                           unsigned &StructuredIndex);
280  void CheckScalarType(InitListExpr *IList, QualType DeclType,
281                       unsigned &Index,
282                       InitListExpr *StructuredList,
283                       unsigned &StructuredIndex);
284  void CheckReferenceType(InitListExpr *IList, QualType DeclType,
285                          unsigned &Index,
286                          InitListExpr *StructuredList,
287                          unsigned &StructuredIndex);
288  void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
289                       InitListExpr *StructuredList,
290                       unsigned &StructuredIndex);
291  void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
292                             RecordDecl::field_iterator Field,
293                             bool SubobjectIsDesignatorContext, unsigned &Index,
294                             InitListExpr *StructuredList,
295                             unsigned &StructuredIndex,
296                             bool TopLevelObject = false);
297  void CheckArrayType(InitListExpr *IList, QualType &DeclType,
298                      llvm::APSInt elementIndex,
299                      bool SubobjectIsDesignatorContext, unsigned &Index,
300                      InitListExpr *StructuredList,
301                      unsigned &StructuredIndex);
302  bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
303                                  unsigned DesigIdx,
304                                  QualType &CurrentObjectType,
305                                  RecordDecl::field_iterator *NextField,
306                                  llvm::APSInt *NextElementIndex,
307                                  unsigned &Index,
308                                  InitListExpr *StructuredList,
309                                  unsigned &StructuredIndex,
310                                  bool FinishSubobjectInit,
311                                  bool TopLevelObject);
312  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
313                                           QualType CurrentObjectType,
314                                           InitListExpr *StructuredList,
315                                           unsigned StructuredIndex,
316                                           SourceRange InitRange);
317  void UpdateStructuredListElement(InitListExpr *StructuredList,
318                                   unsigned &StructuredIndex,
319                                   Expr *expr);
320  int numArrayElements(QualType DeclType);
321  int numStructUnionElements(QualType DeclType);
322
323  void FillInValueInitializations(InitListExpr *ILE);
324public:
325  InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
326  bool HadError() { return hadError; }
327
328  // @brief Retrieves the fully-structured initializer list used for
329  // semantic analysis and code generation.
330  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
331};
332} // end anonymous namespace
333
334/// Recursively replaces NULL values within the given initializer list
335/// with expressions that perform value-initialization of the
336/// appropriate type.
337void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
338  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
339         "Should not have void type");
340  SourceLocation Loc = ILE->getSourceRange().getBegin();
341  if (ILE->getSyntacticForm())
342    Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
343
344  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
345    unsigned Init = 0, NumInits = ILE->getNumInits();
346    for (RecordDecl::field_iterator
347           Field = RType->getDecl()->field_begin(),
348           FieldEnd = RType->getDecl()->field_end();
349         Field != FieldEnd; ++Field) {
350      if (Field->isUnnamedBitfield())
351        continue;
352
353      if (Init >= NumInits || !ILE->getInit(Init)) {
354        if (Field->getType()->isReferenceType()) {
355          // C++ [dcl.init.aggr]p9:
356          //   If an incomplete or empty initializer-list leaves a
357          //   member of reference type uninitialized, the program is
358          //   ill-formed.
359          SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
360            << Field->getType()
361            << ILE->getSyntacticForm()->getSourceRange();
362          SemaRef.Diag(Field->getLocation(),
363                        diag::note_uninit_reference_member);
364          hadError = true;
365          return;
366        } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
367          hadError = true;
368          return;
369        }
370
371        // FIXME: If value-initialization involves calling a constructor, should
372        // we make that call explicit in the representation (even when it means
373        // extending the initializer list)?
374        if (Init < NumInits && !hadError)
375          ILE->setInit(Init,
376              new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
377      } else if (InitListExpr *InnerILE
378                 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
379        FillInValueInitializations(InnerILE);
380      ++Init;
381
382      // Only look at the first initialization of a union.
383      if (RType->getDecl()->isUnion())
384        break;
385    }
386
387    return;
388  }
389
390  QualType ElementType;
391
392  unsigned NumInits = ILE->getNumInits();
393  unsigned NumElements = NumInits;
394  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
395    ElementType = AType->getElementType();
396    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
397      NumElements = CAType->getSize().getZExtValue();
398  } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
399    ElementType = VType->getElementType();
400    NumElements = VType->getNumElements();
401  } else
402    ElementType = ILE->getType();
403
404  for (unsigned Init = 0; Init != NumElements; ++Init) {
405    if (Init >= NumInits || !ILE->getInit(Init)) {
406      if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
407        hadError = true;
408        return;
409      }
410
411      // FIXME: If value-initialization involves calling a constructor, should
412      // we make that call explicit in the representation (even when it means
413      // extending the initializer list)?
414      if (Init < NumInits && !hadError)
415        ILE->setInit(Init,
416                     new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
417    } else if (InitListExpr *InnerILE
418               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
419      FillInValueInitializations(InnerILE);
420  }
421}
422
423
424InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
425  : SemaRef(S) {
426  hadError = false;
427
428  unsigned newIndex = 0;
429  unsigned newStructuredIndex = 0;
430  FullyStructuredList
431    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
432  CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
433                        /*TopLevelObject=*/true);
434
435  if (!hadError)
436    FillInValueInitializations(FullyStructuredList);
437}
438
439int InitListChecker::numArrayElements(QualType DeclType) {
440  // FIXME: use a proper constant
441  int maxElements = 0x7FFFFFFF;
442  if (const ConstantArrayType *CAT =
443        SemaRef.Context.getAsConstantArrayType(DeclType)) {
444    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
445  }
446  return maxElements;
447}
448
449int InitListChecker::numStructUnionElements(QualType DeclType) {
450  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
451  int InitializableMembers = 0;
452  for (RecordDecl::field_iterator
453         Field = structDecl->field_begin(),
454         FieldEnd = structDecl->field_end();
455       Field != FieldEnd; ++Field) {
456    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
457      ++InitializableMembers;
458  }
459  if (structDecl->isUnion())
460    return std::min(InitializableMembers, 1);
461  return InitializableMembers - structDecl->hasFlexibleArrayMember();
462}
463
464void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
465                                            QualType T, unsigned &Index,
466                                            InitListExpr *StructuredList,
467                                            unsigned &StructuredIndex,
468                                            bool TopLevelObject) {
469  int maxElements = 0;
470
471  if (T->isArrayType())
472    maxElements = numArrayElements(T);
473  else if (T->isStructureType() || T->isUnionType())
474    maxElements = numStructUnionElements(T);
475  else if (T->isVectorType())
476    maxElements = T->getAsVectorType()->getNumElements();
477  else
478    assert(0 && "CheckImplicitInitList(): Illegal type");
479
480  if (maxElements == 0) {
481    SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
482                  diag::err_implicit_empty_initializer);
483    ++Index;
484    hadError = true;
485    return;
486  }
487
488  // Build a structured initializer list corresponding to this subobject.
489  InitListExpr *StructuredSubobjectInitList
490    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
491                                 StructuredIndex,
492          SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
493                      ParentIList->getSourceRange().getEnd()));
494  unsigned StructuredSubobjectInitIndex = 0;
495
496  // Check the element types and build the structural subobject.
497  unsigned StartIndex = Index;
498  CheckListElementTypes(ParentIList, T, false, Index,
499                        StructuredSubobjectInitList,
500                        StructuredSubobjectInitIndex,
501                        TopLevelObject);
502  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
503  StructuredSubobjectInitList->setType(T);
504
505  // Update the structured sub-object initializer so that it's ending
506  // range corresponds with the end of the last initializer it used.
507  if (EndIndex < ParentIList->getNumInits()) {
508    SourceLocation EndLoc
509      = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
510    StructuredSubobjectInitList->setRBraceLoc(EndLoc);
511  }
512}
513
514void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
515                                            unsigned &Index,
516                                            InitListExpr *StructuredList,
517                                            unsigned &StructuredIndex,
518                                            bool TopLevelObject) {
519  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
520  SyntacticToSemantic[IList] = StructuredList;
521  StructuredList->setSyntacticForm(IList);
522  CheckListElementTypes(IList, T, true, Index, StructuredList,
523                        StructuredIndex, TopLevelObject);
524  IList->setType(T);
525  StructuredList->setType(T);
526  if (hadError)
527    return;
528
529  if (Index < IList->getNumInits()) {
530    // We have leftover initializers
531    if (StructuredIndex == 1 &&
532        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
533      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
534      if (SemaRef.getLangOptions().CPlusPlus) {
535        DK = diag::err_excess_initializers_in_char_array_initializer;
536        hadError = true;
537      }
538      // Special-case
539      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
540        << IList->getInit(Index)->getSourceRange();
541    } else if (!T->isIncompleteType()) {
542      // Don't complain for incomplete types, since we'll get an error
543      // elsewhere
544      QualType CurrentObjectType = StructuredList->getType();
545      int initKind =
546        CurrentObjectType->isArrayType()? 0 :
547        CurrentObjectType->isVectorType()? 1 :
548        CurrentObjectType->isScalarType()? 2 :
549        CurrentObjectType->isUnionType()? 3 :
550        4;
551
552      unsigned DK = diag::warn_excess_initializers;
553      if (SemaRef.getLangOptions().CPlusPlus) {
554        DK = diag::err_excess_initializers;
555        hadError = true;
556      }
557      if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
558        DK = diag::err_excess_initializers;
559        hadError = true;
560      }
561
562      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
563        << initKind << IList->getInit(Index)->getSourceRange();
564    }
565  }
566
567  if (T->isScalarType() && !TopLevelObject)
568    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
569      << IList->getSourceRange()
570      << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
571      << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
572}
573
574void InitListChecker::CheckListElementTypes(InitListExpr *IList,
575                                            QualType &DeclType,
576                                            bool SubobjectIsDesignatorContext,
577                                            unsigned &Index,
578                                            InitListExpr *StructuredList,
579                                            unsigned &StructuredIndex,
580                                            bool TopLevelObject) {
581  if (DeclType->isScalarType()) {
582    CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
583  } else if (DeclType->isVectorType()) {
584    CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
585  } else if (DeclType->isAggregateType()) {
586    if (DeclType->isRecordType()) {
587      RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
588      CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
589                            SubobjectIsDesignatorContext, Index,
590                            StructuredList, StructuredIndex,
591                            TopLevelObject);
592    } else if (DeclType->isArrayType()) {
593      llvm::APSInt Zero(
594                      SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
595                      false);
596      CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
597                     StructuredList, StructuredIndex);
598    } else
599      assert(0 && "Aggregate that isn't a structure or array?!");
600  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
601    // This type is invalid, issue a diagnostic.
602    ++Index;
603    SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
604      << DeclType;
605    hadError = true;
606  } else if (DeclType->isRecordType()) {
607    // C++ [dcl.init]p14:
608    //   [...] If the class is an aggregate (8.5.1), and the initializer
609    //   is a brace-enclosed list, see 8.5.1.
610    //
611    // Note: 8.5.1 is handled below; here, we diagnose the case where
612    // we have an initializer list and a destination type that is not
613    // an aggregate.
614    // FIXME: In C++0x, this is yet another form of initialization.
615    SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
616      << DeclType << IList->getSourceRange();
617    hadError = true;
618  } else if (DeclType->isReferenceType()) {
619    CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
620  } else {
621    // In C, all types are either scalars or aggregates, but
622    // additional handling is needed here for C++ (and possibly others?).
623    assert(0 && "Unsupported initializer type");
624  }
625}
626
627void InitListChecker::CheckSubElementType(InitListExpr *IList,
628                                          QualType ElemType,
629                                          unsigned &Index,
630                                          InitListExpr *StructuredList,
631                                          unsigned &StructuredIndex) {
632  Expr *expr = IList->getInit(Index);
633  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
634    unsigned newIndex = 0;
635    unsigned newStructuredIndex = 0;
636    InitListExpr *newStructuredList
637      = getStructuredSubobjectInit(IList, Index, ElemType,
638                                   StructuredList, StructuredIndex,
639                                   SubInitList->getSourceRange());
640    CheckExplicitInitList(SubInitList, ElemType, newIndex,
641                          newStructuredList, newStructuredIndex);
642    ++StructuredIndex;
643    ++Index;
644  } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
645    CheckStringInit(Str, ElemType, SemaRef);
646    UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
647    ++Index;
648  } else if (ElemType->isScalarType()) {
649    CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
650  } else if (ElemType->isReferenceType()) {
651    CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
652  } else {
653    if (SemaRef.getLangOptions().CPlusPlus) {
654      // C++ [dcl.init.aggr]p12:
655      //   All implicit type conversions (clause 4) are considered when
656      //   initializing the aggregate member with an ini- tializer from
657      //   an initializer-list. If the initializer can initialize a
658      //   member, the member is initialized. [...]
659      ImplicitConversionSequence ICS
660        = SemaRef.TryCopyInitialization(expr, ElemType);
661      if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
662        if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
663                                               "initializing"))
664          hadError = true;
665        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
666        ++Index;
667        return;
668      }
669
670      // Fall through for subaggregate initialization
671    } else {
672      // C99 6.7.8p13:
673      //
674      //   The initializer for a structure or union object that has
675      //   automatic storage duration shall be either an initializer
676      //   list as described below, or a single expression that has
677      //   compatible structure or union type. In the latter case, the
678      //   initial value of the object, including unnamed members, is
679      //   that of the expression.
680      if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
681          SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
682        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
683        ++Index;
684        return;
685      }
686
687      // Fall through for subaggregate initialization
688    }
689
690    // C++ [dcl.init.aggr]p12:
691    //
692    //   [...] Otherwise, if the member is itself a non-empty
693    //   subaggregate, brace elision is assumed and the initializer is
694    //   considered for the initialization of the first member of
695    //   the subaggregate.
696    if (ElemType->isAggregateType() || ElemType->isVectorType()) {
697      CheckImplicitInitList(IList, ElemType, Index, StructuredList,
698                            StructuredIndex);
699      ++StructuredIndex;
700    } else {
701      // We cannot initialize this element, so let
702      // PerformCopyInitialization produce the appropriate diagnostic.
703      SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
704      hadError = true;
705      ++Index;
706      ++StructuredIndex;
707    }
708  }
709}
710
711void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
712                                      unsigned &Index,
713                                      InitListExpr *StructuredList,
714                                      unsigned &StructuredIndex) {
715  if (Index < IList->getNumInits()) {
716    Expr *expr = IList->getInit(Index);
717    if (isa<InitListExpr>(expr)) {
718      SemaRef.Diag(IList->getLocStart(),
719                    diag::err_many_braces_around_scalar_init)
720        << IList->getSourceRange();
721      hadError = true;
722      ++Index;
723      ++StructuredIndex;
724      return;
725    } else if (isa<DesignatedInitExpr>(expr)) {
726      SemaRef.Diag(expr->getSourceRange().getBegin(),
727                    diag::err_designator_for_scalar_init)
728        << DeclType << expr->getSourceRange();
729      hadError = true;
730      ++Index;
731      ++StructuredIndex;
732      return;
733    }
734
735    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
736    if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
737      hadError = true; // types weren't compatible.
738    else if (savExpr != expr) {
739      // The type was promoted, update initializer list.
740      IList->setInit(Index, expr);
741    }
742    if (hadError)
743      ++StructuredIndex;
744    else
745      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
746    ++Index;
747  } else {
748    SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
749      << IList->getSourceRange();
750    hadError = true;
751    ++Index;
752    ++StructuredIndex;
753    return;
754  }
755}
756
757void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
758                                         unsigned &Index,
759                                         InitListExpr *StructuredList,
760                                         unsigned &StructuredIndex) {
761  if (Index < IList->getNumInits()) {
762    Expr *expr = IList->getInit(Index);
763    if (isa<InitListExpr>(expr)) {
764      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
765        << DeclType << IList->getSourceRange();
766      hadError = true;
767      ++Index;
768      ++StructuredIndex;
769      return;
770    }
771
772    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
773    if (SemaRef.CheckReferenceInit(expr, DeclType))
774      hadError = true;
775    else if (savExpr != expr) {
776      // The type was promoted, update initializer list.
777      IList->setInit(Index, expr);
778    }
779    if (hadError)
780      ++StructuredIndex;
781    else
782      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
783    ++Index;
784  } else {
785    // FIXME: It would be wonderful if we could point at the actual member. In
786    // general, it would be useful to pass location information down the stack,
787    // so that we know the location (or decl) of the "current object" being
788    // initialized.
789    SemaRef.Diag(IList->getLocStart(),
790                  diag::err_init_reference_member_uninitialized)
791      << DeclType
792      << IList->getSourceRange();
793    hadError = true;
794    ++Index;
795    ++StructuredIndex;
796    return;
797  }
798}
799
800void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
801                                      unsigned &Index,
802                                      InitListExpr *StructuredList,
803                                      unsigned &StructuredIndex) {
804  if (Index < IList->getNumInits()) {
805    const VectorType *VT = DeclType->getAsVectorType();
806    int maxElements = VT->getNumElements();
807    QualType elementType = VT->getElementType();
808
809    for (int i = 0; i < maxElements; ++i) {
810      // Don't attempt to go past the end of the init list
811      if (Index >= IList->getNumInits())
812        break;
813      CheckSubElementType(IList, elementType, Index,
814                          StructuredList, StructuredIndex);
815    }
816  }
817}
818
819void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
820                                     llvm::APSInt elementIndex,
821                                     bool SubobjectIsDesignatorContext,
822                                     unsigned &Index,
823                                     InitListExpr *StructuredList,
824                                     unsigned &StructuredIndex) {
825  // Check for the special-case of initializing an array with a string.
826  if (Index < IList->getNumInits()) {
827    if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
828                                 SemaRef.Context)) {
829      CheckStringInit(Str, DeclType, SemaRef);
830      // We place the string literal directly into the resulting
831      // initializer list. This is the only place where the structure
832      // of the structured initializer list doesn't match exactly,
833      // because doing so would involve allocating one character
834      // constant for each string.
835      UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
836      StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
837      ++Index;
838      return;
839    }
840  }
841  if (const VariableArrayType *VAT =
842        SemaRef.Context.getAsVariableArrayType(DeclType)) {
843    // Check for VLAs; in standard C it would be possible to check this
844    // earlier, but I don't know where clang accepts VLAs (gcc accepts
845    // them in all sorts of strange places).
846    SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
847                  diag::err_variable_object_no_init)
848      << VAT->getSizeExpr()->getSourceRange();
849    hadError = true;
850    ++Index;
851    ++StructuredIndex;
852    return;
853  }
854
855  // We might know the maximum number of elements in advance.
856  llvm::APSInt maxElements(elementIndex.getBitWidth(),
857                           elementIndex.isUnsigned());
858  bool maxElementsKnown = false;
859  if (const ConstantArrayType *CAT =
860        SemaRef.Context.getAsConstantArrayType(DeclType)) {
861    maxElements = CAT->getSize();
862    elementIndex.extOrTrunc(maxElements.getBitWidth());
863    elementIndex.setIsUnsigned(maxElements.isUnsigned());
864    maxElementsKnown = true;
865  }
866
867  QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
868                             ->getElementType();
869  while (Index < IList->getNumInits()) {
870    Expr *Init = IList->getInit(Index);
871    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
872      // If we're not the subobject that matches up with the '{' for
873      // the designator, we shouldn't be handling the
874      // designator. Return immediately.
875      if (!SubobjectIsDesignatorContext)
876        return;
877
878      // Handle this designated initializer. elementIndex will be
879      // updated to be the next array element we'll initialize.
880      if (CheckDesignatedInitializer(IList, DIE, 0,
881                                     DeclType, 0, &elementIndex, Index,
882                                     StructuredList, StructuredIndex, true,
883                                     false)) {
884        hadError = true;
885        continue;
886      }
887
888      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
889        maxElements.extend(elementIndex.getBitWidth());
890      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
891        elementIndex.extend(maxElements.getBitWidth());
892      elementIndex.setIsUnsigned(maxElements.isUnsigned());
893
894      // If the array is of incomplete type, keep track of the number of
895      // elements in the initializer.
896      if (!maxElementsKnown && elementIndex > maxElements)
897        maxElements = elementIndex;
898
899      continue;
900    }
901
902    // If we know the maximum number of elements, and we've already
903    // hit it, stop consuming elements in the initializer list.
904    if (maxElementsKnown && elementIndex == maxElements)
905      break;
906
907    // Check this element.
908    CheckSubElementType(IList, elementType, Index,
909                        StructuredList, StructuredIndex);
910    ++elementIndex;
911
912    // If the array is of incomplete type, keep track of the number of
913    // elements in the initializer.
914    if (!maxElementsKnown && elementIndex > maxElements)
915      maxElements = elementIndex;
916  }
917  if (!hadError && DeclType->isIncompleteArrayType()) {
918    // If this is an incomplete array type, the actual type needs to
919    // be calculated here.
920    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
921    if (maxElements == Zero) {
922      // Sizing an array implicitly to zero is not allowed by ISO C,
923      // but is supported by GNU.
924      SemaRef.Diag(IList->getLocStart(),
925                    diag::ext_typecheck_zero_array_size);
926    }
927
928    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
929                                                     ArrayType::Normal, 0);
930  }
931}
932
933void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
934                                            QualType DeclType,
935                                            RecordDecl::field_iterator Field,
936                                            bool SubobjectIsDesignatorContext,
937                                            unsigned &Index,
938                                            InitListExpr *StructuredList,
939                                            unsigned &StructuredIndex,
940                                            bool TopLevelObject) {
941  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
942
943  // If the record is invalid, some of it's members are invalid. To avoid
944  // confusion, we forgo checking the intializer for the entire record.
945  if (structDecl->isInvalidDecl()) {
946    hadError = true;
947    return;
948  }
949
950  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
951    // Value-initialize the first named member of the union.
952    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
953    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
954         Field != FieldEnd; ++Field) {
955      if (Field->getDeclName()) {
956        StructuredList->setInitializedFieldInUnion(*Field);
957        break;
958      }
959    }
960    return;
961  }
962
963  // If structDecl is a forward declaration, this loop won't do
964  // anything except look at designated initializers; That's okay,
965  // because an error should get printed out elsewhere. It might be
966  // worthwhile to skip over the rest of the initializer, though.
967  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
968  RecordDecl::field_iterator FieldEnd = RD->field_end();
969  bool InitializedSomething = false;
970  while (Index < IList->getNumInits()) {
971    Expr *Init = IList->getInit(Index);
972
973    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
974      // If we're not the subobject that matches up with the '{' for
975      // the designator, we shouldn't be handling the
976      // designator. Return immediately.
977      if (!SubobjectIsDesignatorContext)
978        return;
979
980      // Handle this designated initializer. Field will be updated to
981      // the next field that we'll be initializing.
982      if (CheckDesignatedInitializer(IList, DIE, 0,
983                                     DeclType, &Field, 0, Index,
984                                     StructuredList, StructuredIndex,
985                                     true, TopLevelObject))
986        hadError = true;
987
988      InitializedSomething = true;
989      continue;
990    }
991
992    if (Field == FieldEnd) {
993      // We've run out of fields. We're done.
994      break;
995    }
996
997    // We've already initialized a member of a union. We're done.
998    if (InitializedSomething && DeclType->isUnionType())
999      break;
1000
1001    // If we've hit the flexible array member at the end, we're done.
1002    if (Field->getType()->isIncompleteArrayType())
1003      break;
1004
1005    if (Field->isUnnamedBitfield()) {
1006      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1007      ++Field;
1008      continue;
1009    }
1010
1011    CheckSubElementType(IList, Field->getType(), Index,
1012                        StructuredList, StructuredIndex);
1013    InitializedSomething = true;
1014
1015    if (DeclType->isUnionType()) {
1016      // Initialize the first field within the union.
1017      StructuredList->setInitializedFieldInUnion(*Field);
1018    }
1019
1020    ++Field;
1021  }
1022
1023  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1024      Index >= IList->getNumInits())
1025    return;
1026
1027  // Handle GNU flexible array initializers.
1028  if (!TopLevelObject &&
1029      (!isa<InitListExpr>(IList->getInit(Index)) ||
1030       cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
1031    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1032                  diag::err_flexible_array_init_nonempty)
1033      << IList->getInit(Index)->getSourceRange().getBegin();
1034    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1035      << *Field;
1036    hadError = true;
1037    ++Index;
1038    return;
1039  } else {
1040    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1041                 diag::ext_flexible_array_init)
1042      << IList->getInit(Index)->getSourceRange().getBegin();
1043    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1044      << *Field;
1045  }
1046
1047  if (isa<InitListExpr>(IList->getInit(Index)))
1048    CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1049                        StructuredIndex);
1050  else
1051    CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1052                          StructuredIndex);
1053}
1054
1055/// \brief Expand a field designator that refers to a member of an
1056/// anonymous struct or union into a series of field designators that
1057/// refers to the field within the appropriate subobject.
1058///
1059/// Field/FieldIndex will be updated to point to the (new)
1060/// currently-designated field.
1061static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1062                                           DesignatedInitExpr *DIE,
1063                                           unsigned DesigIdx,
1064                                           FieldDecl *Field,
1065                                        RecordDecl::field_iterator &FieldIter,
1066                                           unsigned &FieldIndex) {
1067  typedef DesignatedInitExpr::Designator Designator;
1068
1069  // Build the path from the current object to the member of the
1070  // anonymous struct/union (backwards).
1071  llvm::SmallVector<FieldDecl *, 4> Path;
1072  SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1073
1074  // Build the replacement designators.
1075  llvm::SmallVector<Designator, 4> Replacements;
1076  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1077         FI = Path.rbegin(), FIEnd = Path.rend();
1078       FI != FIEnd; ++FI) {
1079    if (FI + 1 == FIEnd)
1080      Replacements.push_back(Designator((IdentifierInfo *)0,
1081                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1082                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1083    else
1084      Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1085                                        SourceLocation()));
1086    Replacements.back().setField(*FI);
1087  }
1088
1089  // Expand the current designator into the set of replacement
1090  // designators, so we have a full subobject path down to where the
1091  // member of the anonymous struct/union is actually stored.
1092  DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1093                        &Replacements[0] + Replacements.size());
1094
1095  // Update FieldIter/FieldIndex;
1096  RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1097  FieldIter = Record->field_begin();
1098  FieldIndex = 0;
1099  for (RecordDecl::field_iterator FEnd = Record->field_end();
1100       FieldIter != FEnd; ++FieldIter) {
1101    if (FieldIter->isUnnamedBitfield())
1102        continue;
1103
1104    if (*FieldIter == Path.back())
1105      return;
1106
1107    ++FieldIndex;
1108  }
1109
1110  assert(false && "Unable to find anonymous struct/union field");
1111}
1112
1113/// @brief Check the well-formedness of a C99 designated initializer.
1114///
1115/// Determines whether the designated initializer @p DIE, which
1116/// resides at the given @p Index within the initializer list @p
1117/// IList, is well-formed for a current object of type @p DeclType
1118/// (C99 6.7.8). The actual subobject that this designator refers to
1119/// within the current subobject is returned in either
1120/// @p NextField or @p NextElementIndex (whichever is appropriate).
1121///
1122/// @param IList  The initializer list in which this designated
1123/// initializer occurs.
1124///
1125/// @param DIE The designated initializer expression.
1126///
1127/// @param DesigIdx  The index of the current designator.
1128///
1129/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
1130/// into which the designation in @p DIE should refer.
1131///
1132/// @param NextField  If non-NULL and the first designator in @p DIE is
1133/// a field, this will be set to the field declaration corresponding
1134/// to the field named by the designator.
1135///
1136/// @param NextElementIndex  If non-NULL and the first designator in @p
1137/// DIE is an array designator or GNU array-range designator, this
1138/// will be set to the last index initialized by this designator.
1139///
1140/// @param Index  Index into @p IList where the designated initializer
1141/// @p DIE occurs.
1142///
1143/// @param StructuredList  The initializer list expression that
1144/// describes all of the subobject initializers in the order they'll
1145/// actually be initialized.
1146///
1147/// @returns true if there was an error, false otherwise.
1148bool
1149InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1150                                      DesignatedInitExpr *DIE,
1151                                      unsigned DesigIdx,
1152                                      QualType &CurrentObjectType,
1153                                      RecordDecl::field_iterator *NextField,
1154                                      llvm::APSInt *NextElementIndex,
1155                                      unsigned &Index,
1156                                      InitListExpr *StructuredList,
1157                                      unsigned &StructuredIndex,
1158                                            bool FinishSubobjectInit,
1159                                            bool TopLevelObject) {
1160  if (DesigIdx == DIE->size()) {
1161    // Check the actual initialization for the designated object type.
1162    bool prevHadError = hadError;
1163
1164    // Temporarily remove the designator expression from the
1165    // initializer list that the child calls see, so that we don't try
1166    // to re-process the designator.
1167    unsigned OldIndex = Index;
1168    IList->setInit(OldIndex, DIE->getInit());
1169
1170    CheckSubElementType(IList, CurrentObjectType, Index,
1171                        StructuredList, StructuredIndex);
1172
1173    // Restore the designated initializer expression in the syntactic
1174    // form of the initializer list.
1175    if (IList->getInit(OldIndex) != DIE->getInit())
1176      DIE->setInit(IList->getInit(OldIndex));
1177    IList->setInit(OldIndex, DIE);
1178
1179    return hadError && !prevHadError;
1180  }
1181
1182  bool IsFirstDesignator = (DesigIdx == 0);
1183  assert((IsFirstDesignator || StructuredList) &&
1184         "Need a non-designated initializer list to start from");
1185
1186  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1187  // Determine the structural initializer list that corresponds to the
1188  // current subobject.
1189  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1190    : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1191                                 StructuredList, StructuredIndex,
1192                                 SourceRange(D->getStartLocation(),
1193                                             DIE->getSourceRange().getEnd()));
1194  assert(StructuredList && "Expected a structured initializer list");
1195
1196  if (D->isFieldDesignator()) {
1197    // C99 6.7.8p7:
1198    //
1199    //   If a designator has the form
1200    //
1201    //      . identifier
1202    //
1203    //   then the current object (defined below) shall have
1204    //   structure or union type and the identifier shall be the
1205    //   name of a member of that type.
1206    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1207    if (!RT) {
1208      SourceLocation Loc = D->getDotLoc();
1209      if (Loc.isInvalid())
1210        Loc = D->getFieldLoc();
1211      SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1212        << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1213      ++Index;
1214      return true;
1215    }
1216
1217    // Note: we perform a linear search of the fields here, despite
1218    // the fact that we have a faster lookup method, because we always
1219    // need to compute the field's index.
1220    FieldDecl *KnownField = D->getField();
1221    IdentifierInfo *FieldName = D->getFieldName();
1222    unsigned FieldIndex = 0;
1223    RecordDecl::field_iterator
1224      Field = RT->getDecl()->field_begin(),
1225      FieldEnd = RT->getDecl()->field_end();
1226    for (; Field != FieldEnd; ++Field) {
1227      if (Field->isUnnamedBitfield())
1228        continue;
1229
1230      if (KnownField == *Field || Field->getIdentifier() == FieldName)
1231        break;
1232
1233      ++FieldIndex;
1234    }
1235
1236    if (Field == FieldEnd) {
1237      // There was no normal field in the struct with the designated
1238      // name. Perform another lookup for this name, which may find
1239      // something that we can't designate (e.g., a member function),
1240      // may find nothing, or may find a member of an anonymous
1241      // struct/union.
1242      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1243      if (Lookup.first == Lookup.second) {
1244        // Name lookup didn't find anything.
1245        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1246          << FieldName << CurrentObjectType;
1247        ++Index;
1248        return true;
1249      } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1250                 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1251                   ->isAnonymousStructOrUnion()) {
1252        // Handle an field designator that refers to a member of an
1253        // anonymous struct or union.
1254        ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1255                                       cast<FieldDecl>(*Lookup.first),
1256                                       Field, FieldIndex);
1257        D = DIE->getDesignator(DesigIdx);
1258      } else {
1259        // Name lookup found something, but it wasn't a field.
1260        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1261          << FieldName;
1262        SemaRef.Diag((*Lookup.first)->getLocation(),
1263                      diag::note_field_designator_found);
1264        ++Index;
1265        return true;
1266      }
1267    } else if (!KnownField &&
1268               cast<RecordDecl>((*Field)->getDeclContext())
1269                 ->isAnonymousStructOrUnion()) {
1270      ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1271                                     Field, FieldIndex);
1272      D = DIE->getDesignator(DesigIdx);
1273    }
1274
1275    // All of the fields of a union are located at the same place in
1276    // the initializer list.
1277    if (RT->getDecl()->isUnion()) {
1278      FieldIndex = 0;
1279      StructuredList->setInitializedFieldInUnion(*Field);
1280    }
1281
1282    // Update the designator with the field declaration.
1283    D->setField(*Field);
1284
1285    // Make sure that our non-designated initializer list has space
1286    // for a subobject corresponding to this field.
1287    if (FieldIndex >= StructuredList->getNumInits())
1288      StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1289
1290    // This designator names a flexible array member.
1291    if (Field->getType()->isIncompleteArrayType()) {
1292      bool Invalid = false;
1293      if ((DesigIdx + 1) != DIE->size()) {
1294        // We can't designate an object within the flexible array
1295        // member (because GCC doesn't allow it).
1296        DesignatedInitExpr::Designator *NextD
1297          = DIE->getDesignator(DesigIdx + 1);
1298        SemaRef.Diag(NextD->getStartLocation(),
1299                      diag::err_designator_into_flexible_array_member)
1300          << SourceRange(NextD->getStartLocation(),
1301                         DIE->getSourceRange().getEnd());
1302        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1303          << *Field;
1304        Invalid = true;
1305      }
1306
1307      if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1308        // The initializer is not an initializer list.
1309        SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1310                      diag::err_flexible_array_init_needs_braces)
1311          << DIE->getInit()->getSourceRange();
1312        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1313          << *Field;
1314        Invalid = true;
1315      }
1316
1317      // Handle GNU flexible array initializers.
1318      if (!Invalid && !TopLevelObject &&
1319          cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1320        SemaRef.Diag(DIE->getSourceRange().getBegin(),
1321                      diag::err_flexible_array_init_nonempty)
1322          << DIE->getSourceRange().getBegin();
1323        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1324          << *Field;
1325        Invalid = true;
1326      }
1327
1328      if (Invalid) {
1329        ++Index;
1330        return true;
1331      }
1332
1333      // Initialize the array.
1334      bool prevHadError = hadError;
1335      unsigned newStructuredIndex = FieldIndex;
1336      unsigned OldIndex = Index;
1337      IList->setInit(Index, DIE->getInit());
1338      CheckSubElementType(IList, Field->getType(), Index,
1339                          StructuredList, newStructuredIndex);
1340      IList->setInit(OldIndex, DIE);
1341      if (hadError && !prevHadError) {
1342        ++Field;
1343        ++FieldIndex;
1344        if (NextField)
1345          *NextField = Field;
1346        StructuredIndex = FieldIndex;
1347        return true;
1348      }
1349    } else {
1350      // Recurse to check later designated subobjects.
1351      QualType FieldType = (*Field)->getType();
1352      unsigned newStructuredIndex = FieldIndex;
1353      if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1354                                     Index, StructuredList, newStructuredIndex,
1355                                     true, false))
1356        return true;
1357    }
1358
1359    // Find the position of the next field to be initialized in this
1360    // subobject.
1361    ++Field;
1362    ++FieldIndex;
1363
1364    // If this the first designator, our caller will continue checking
1365    // the rest of this struct/class/union subobject.
1366    if (IsFirstDesignator) {
1367      if (NextField)
1368        *NextField = Field;
1369      StructuredIndex = FieldIndex;
1370      return false;
1371    }
1372
1373    if (!FinishSubobjectInit)
1374      return false;
1375
1376    // We've already initialized something in the union; we're done.
1377    if (RT->getDecl()->isUnion())
1378      return hadError;
1379
1380    // Check the remaining fields within this class/struct/union subobject.
1381    bool prevHadError = hadError;
1382    CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1383                          StructuredList, FieldIndex);
1384    return hadError && !prevHadError;
1385  }
1386
1387  // C99 6.7.8p6:
1388  //
1389  //   If a designator has the form
1390  //
1391  //      [ constant-expression ]
1392  //
1393  //   then the current object (defined below) shall have array
1394  //   type and the expression shall be an integer constant
1395  //   expression. If the array is of unknown size, any
1396  //   nonnegative value is valid.
1397  //
1398  // Additionally, cope with the GNU extension that permits
1399  // designators of the form
1400  //
1401  //      [ constant-expression ... constant-expression ]
1402  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1403  if (!AT) {
1404    SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1405      << CurrentObjectType;
1406    ++Index;
1407    return true;
1408  }
1409
1410  Expr *IndexExpr = 0;
1411  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1412  if (D->isArrayDesignator()) {
1413    IndexExpr = DIE->getArrayIndex(*D);
1414    DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
1415    DesignatedEndIndex = DesignatedStartIndex;
1416  } else {
1417    assert(D->isArrayRangeDesignator() && "Need array-range designator");
1418
1419
1420    DesignatedStartIndex =
1421      DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1422    DesignatedEndIndex =
1423      DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
1424    IndexExpr = DIE->getArrayRangeEnd(*D);
1425
1426    if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
1427      FullyStructuredList->sawArrayRangeDesignator();
1428  }
1429
1430  if (isa<ConstantArrayType>(AT)) {
1431    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1432    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1433    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1434    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1435    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1436    if (DesignatedEndIndex >= MaxElements) {
1437      SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1438                    diag::err_array_designator_too_large)
1439        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1440        << IndexExpr->getSourceRange();
1441      ++Index;
1442      return true;
1443    }
1444  } else {
1445    // Make sure the bit-widths and signedness match.
1446    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1447      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1448    else if (DesignatedStartIndex.getBitWidth() <
1449             DesignatedEndIndex.getBitWidth())
1450      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1451    DesignatedStartIndex.setIsUnsigned(true);
1452    DesignatedEndIndex.setIsUnsigned(true);
1453  }
1454
1455  // Make sure that our non-designated initializer list has space
1456  // for a subobject corresponding to this array element.
1457  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1458    StructuredList->resizeInits(SemaRef.Context,
1459                                DesignatedEndIndex.getZExtValue() + 1);
1460
1461  // Repeatedly perform subobject initializations in the range
1462  // [DesignatedStartIndex, DesignatedEndIndex].
1463
1464  // Move to the next designator
1465  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1466  unsigned OldIndex = Index;
1467  while (DesignatedStartIndex <= DesignatedEndIndex) {
1468    // Recurse to check later designated subobjects.
1469    QualType ElementType = AT->getElementType();
1470    Index = OldIndex;
1471    if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1472                                   Index, StructuredList, ElementIndex,
1473                                   (DesignatedStartIndex == DesignatedEndIndex),
1474                                   false))
1475      return true;
1476
1477    // Move to the next index in the array that we'll be initializing.
1478    ++DesignatedStartIndex;
1479    ElementIndex = DesignatedStartIndex.getZExtValue();
1480  }
1481
1482  // If this the first designator, our caller will continue checking
1483  // the rest of this array subobject.
1484  if (IsFirstDesignator) {
1485    if (NextElementIndex)
1486      *NextElementIndex = DesignatedStartIndex;
1487    StructuredIndex = ElementIndex;
1488    return false;
1489  }
1490
1491  if (!FinishSubobjectInit)
1492    return false;
1493
1494  // Check the remaining elements within this array subobject.
1495  bool prevHadError = hadError;
1496  CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
1497                 StructuredList, ElementIndex);
1498  return hadError && !prevHadError;
1499}
1500
1501// Get the structured initializer list for a subobject of type
1502// @p CurrentObjectType.
1503InitListExpr *
1504InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1505                                            QualType CurrentObjectType,
1506                                            InitListExpr *StructuredList,
1507                                            unsigned StructuredIndex,
1508                                            SourceRange InitRange) {
1509  Expr *ExistingInit = 0;
1510  if (!StructuredList)
1511    ExistingInit = SyntacticToSemantic[IList];
1512  else if (StructuredIndex < StructuredList->getNumInits())
1513    ExistingInit = StructuredList->getInit(StructuredIndex);
1514
1515  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1516    return Result;
1517
1518  if (ExistingInit) {
1519    // We are creating an initializer list that initializes the
1520    // subobjects of the current object, but there was already an
1521    // initialization that completely initialized the current
1522    // subobject, e.g., by a compound literal:
1523    //
1524    // struct X { int a, b; };
1525    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1526    //
1527    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1528    // designated initializer re-initializes the whole
1529    // subobject [0], overwriting previous initializers.
1530    SemaRef.Diag(InitRange.getBegin(),
1531                 diag::warn_subobject_initializer_overrides)
1532      << InitRange;
1533    SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
1534                  diag::note_previous_initializer)
1535      << /*FIXME:has side effects=*/0
1536      << ExistingInit->getSourceRange();
1537  }
1538
1539  InitListExpr *Result
1540    = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1541                                         InitRange.getEnd());
1542
1543  Result->setType(CurrentObjectType);
1544
1545  // Pre-allocate storage for the structured initializer list.
1546  unsigned NumElements = 0;
1547  unsigned NumInits = 0;
1548  if (!StructuredList)
1549    NumInits = IList->getNumInits();
1550  else if (Index < IList->getNumInits()) {
1551    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1552      NumInits = SubList->getNumInits();
1553  }
1554
1555  if (const ArrayType *AType
1556      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1557    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1558      NumElements = CAType->getSize().getZExtValue();
1559      // Simple heuristic so that we don't allocate a very large
1560      // initializer with many empty entries at the end.
1561      if (NumInits && NumElements > NumInits)
1562        NumElements = 0;
1563    }
1564  } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1565    NumElements = VType->getNumElements();
1566  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
1567    RecordDecl *RDecl = RType->getDecl();
1568    if (RDecl->isUnion())
1569      NumElements = 1;
1570    else
1571      NumElements = std::distance(RDecl->field_begin(),
1572                                  RDecl->field_end());
1573  }
1574
1575  if (NumElements < NumInits)
1576    NumElements = IList->getNumInits();
1577
1578  Result->reserveInits(NumElements);
1579
1580  // Link this new initializer list into the structured initializer
1581  // lists.
1582  if (StructuredList)
1583    StructuredList->updateInit(StructuredIndex, Result);
1584  else {
1585    Result->setSyntacticForm(IList);
1586    SyntacticToSemantic[IList] = Result;
1587  }
1588
1589  return Result;
1590}
1591
1592/// Update the initializer at index @p StructuredIndex within the
1593/// structured initializer list to the value @p expr.
1594void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1595                                                  unsigned &StructuredIndex,
1596                                                  Expr *expr) {
1597  // No structured initializer list to update
1598  if (!StructuredList)
1599    return;
1600
1601  if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1602    // This initializer overwrites a previous initializer. Warn.
1603    SemaRef.Diag(expr->getSourceRange().getBegin(),
1604                  diag::warn_initializer_overrides)
1605      << expr->getSourceRange();
1606    SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
1607                  diag::note_previous_initializer)
1608      << /*FIXME:has side effects=*/0
1609      << PrevInit->getSourceRange();
1610  }
1611
1612  ++StructuredIndex;
1613}
1614
1615/// Check that the given Index expression is a valid array designator
1616/// value. This is essentailly just a wrapper around
1617/// VerifyIntegerConstantExpression that also checks for negative values
1618/// and produces a reasonable diagnostic if there is a
1619/// failure. Returns true if there was an error, false otherwise.  If
1620/// everything went okay, Value will receive the value of the constant
1621/// expression.
1622static bool
1623CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
1624  SourceLocation Loc = Index->getSourceRange().getBegin();
1625
1626  // Make sure this is an integer constant expression.
1627  if (S.VerifyIntegerConstantExpression(Index, &Value))
1628    return true;
1629
1630  if (Value.isSigned() && Value.isNegative())
1631    return S.Diag(Loc, diag::err_array_designator_negative)
1632      << Value.toString(10) << Index->getSourceRange();
1633
1634  Value.setIsUnsigned(true);
1635  return false;
1636}
1637
1638Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1639                                                        SourceLocation Loc,
1640                                                        bool GNUSyntax,
1641                                                        OwningExprResult Init) {
1642  typedef DesignatedInitExpr::Designator ASTDesignator;
1643
1644  bool Invalid = false;
1645  llvm::SmallVector<ASTDesignator, 32> Designators;
1646  llvm::SmallVector<Expr *, 32> InitExpressions;
1647
1648  // Build designators and check array designator expressions.
1649  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1650    const Designator &D = Desig.getDesignator(Idx);
1651    switch (D.getKind()) {
1652    case Designator::FieldDesignator:
1653      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1654                                          D.getFieldLoc()));
1655      break;
1656
1657    case Designator::ArrayDesignator: {
1658      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1659      llvm::APSInt IndexValue;
1660      if (!Index->isTypeDependent() &&
1661          !Index->isValueDependent() &&
1662          CheckArrayDesignatorExpr(*this, Index, IndexValue))
1663        Invalid = true;
1664      else {
1665        Designators.push_back(ASTDesignator(InitExpressions.size(),
1666                                            D.getLBracketLoc(),
1667                                            D.getRBracketLoc()));
1668        InitExpressions.push_back(Index);
1669      }
1670      break;
1671    }
1672
1673    case Designator::ArrayRangeDesignator: {
1674      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1675      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1676      llvm::APSInt StartValue;
1677      llvm::APSInt EndValue;
1678      bool StartDependent = StartIndex->isTypeDependent() ||
1679                            StartIndex->isValueDependent();
1680      bool EndDependent = EndIndex->isTypeDependent() ||
1681                          EndIndex->isValueDependent();
1682      if ((!StartDependent &&
1683           CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1684          (!EndDependent &&
1685           CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
1686        Invalid = true;
1687      else {
1688        // Make sure we're comparing values with the same bit width.
1689        if (StartDependent || EndDependent) {
1690          // Nothing to compute.
1691        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
1692          EndValue.extend(StartValue.getBitWidth());
1693        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1694          StartValue.extend(EndValue.getBitWidth());
1695
1696        if (!StartDependent && !EndDependent && EndValue < StartValue) {
1697          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1698            << StartValue.toString(10) << EndValue.toString(10)
1699            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1700          Invalid = true;
1701        } else {
1702          Designators.push_back(ASTDesignator(InitExpressions.size(),
1703                                              D.getLBracketLoc(),
1704                                              D.getEllipsisLoc(),
1705                                              D.getRBracketLoc()));
1706          InitExpressions.push_back(StartIndex);
1707          InitExpressions.push_back(EndIndex);
1708        }
1709      }
1710      break;
1711    }
1712    }
1713  }
1714
1715  if (Invalid || Init.isInvalid())
1716    return ExprError();
1717
1718  // Clear out the expressions within the designation.
1719  Desig.ClearExprs(*this);
1720
1721  DesignatedInitExpr *DIE
1722    = DesignatedInitExpr::Create(Context,
1723                                 Designators.data(), Designators.size(),
1724                                 InitExpressions.data(), InitExpressions.size(),
1725                                 Loc, GNUSyntax, Init.takeAs<Expr>());
1726  return Owned(DIE);
1727}
1728
1729bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1730  InitListChecker CheckInitList(*this, InitList, DeclType);
1731  if (!CheckInitList.HadError())
1732    InitList = CheckInitList.getFullyStructuredList();
1733
1734  return CheckInitList.HadError();
1735}
1736
1737/// \brief Diagnose any semantic errors with value-initialization of
1738/// the given type.
1739///
1740/// Value-initialization effectively zero-initializes any types
1741/// without user-declared constructors, and calls the default
1742/// constructor for a for any type that has a user-declared
1743/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1744/// a type with a user-declared constructor does not have an
1745/// accessible, non-deleted default constructor. In C, everything can
1746/// be value-initialized, which corresponds to C's notion of
1747/// initializing objects with static storage duration when no
1748/// initializer is provided for that object.
1749///
1750/// \returns true if there was an error, false otherwise.
1751bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1752  // C++ [dcl.init]p5:
1753  //
1754  //   To value-initialize an object of type T means:
1755
1756  //     -- if T is an array type, then each element is value-initialized;
1757  if (const ArrayType *AT = Context.getAsArrayType(Type))
1758    return CheckValueInitialization(AT->getElementType(), Loc);
1759
1760  if (const RecordType *RT = Type->getAs<RecordType>()) {
1761    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1762      // -- if T is a class type (clause 9) with a user-declared
1763      //    constructor (12.1), then the default constructor for T is
1764      //    called (and the initialization is ill-formed if T has no
1765      //    accessible default constructor);
1766      if (ClassDecl->hasUserDeclaredConstructor())
1767        // FIXME: Eventually, we'll need to put the constructor decl into the
1768        // AST.
1769        return PerformInitializationByConstructor(Type, 0, 0, Loc,
1770                                                  SourceRange(Loc),
1771                                                  DeclarationName(),
1772                                                  IK_Direct);
1773    }
1774  }
1775
1776  if (Type->isReferenceType()) {
1777    // C++ [dcl.init]p5:
1778    //   [...] A program that calls for default-initialization or
1779    //   value-initialization of an entity of reference type is
1780    //   ill-formed. [...]
1781    // FIXME: Once we have code that goes through this path, add an actual
1782    // diagnostic :)
1783  }
1784
1785  return false;
1786}
1787