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