SemaInit.cpp revision 538a4c24fd066b19d85fe24add5fb9bdbbe971ab
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 entry
11//  point is Sema::CheckInitList(), but all of the work is performed
12//  within the InitListChecker class.
13//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
17#include "clang/Parse/Designator.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include <map>
21using namespace clang;
22
23/// @brief Semantic checking for initializer lists.
24///
25/// The InitListChecker class contains a set of routines that each
26/// handle the initialization of a certain kind of entity, e.g.,
27/// arrays, vectors, struct/union types, scalars, etc. The
28/// InitListChecker itself performs a recursive walk of the subobject
29/// structure of the type to be initialized, while stepping through
30/// the initializer list one element at a time. The IList and Index
31/// parameters to each of the Check* routines contain the active
32/// (syntactic) initializer list and the index into that initializer
33/// list that represents the current initializer. Each routine is
34/// responsible for moving that Index forward as it consumes elements.
35///
36/// Each Check* routine also has a StructuredList/StructuredIndex
37/// arguments, which contains the current the "structured" (semantic)
38/// initializer list and the index into that initializer list where we
39/// are copying initializers as we map them over to the semantic
40/// list. Once we have completed our recursive walk of the subobject
41/// structure, we will have constructed a full semantic initializer
42/// list.
43///
44/// C99 designators cause changes in the initializer list traversal,
45/// because they make the initialization "jump" into a specific
46/// subobject and then continue the initialization from that
47/// point. CheckDesignatedInitializer() recursively steps into the
48/// designated subobject and manages backing out the recursion to
49/// initialize the subobjects after the one designated.
50namespace clang {
51class InitListChecker {
52  Sema *SemaRef;
53  bool hadError;
54  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
55  InitListExpr *FullyStructuredList;
56
57  void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
58                             unsigned &Index, InitListExpr *StructuredList,
59                             unsigned &StructuredIndex);
60  void CheckExplicitInitList(InitListExpr *IList, QualType &T,
61                             unsigned &Index, InitListExpr *StructuredList,
62                             unsigned &StructuredIndex);
63  void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
64                             bool SubobjectIsDesignatorContext,
65                             unsigned &Index,
66                             InitListExpr *StructuredList,
67                             unsigned &StructuredIndex);
68  void CheckSubElementType(InitListExpr *IList, QualType ElemType,
69                           unsigned &Index,
70                           InitListExpr *StructuredList,
71                           unsigned &StructuredIndex);
72  void CheckScalarType(InitListExpr *IList, QualType DeclType,
73                       unsigned &Index,
74                       InitListExpr *StructuredList,
75                       unsigned &StructuredIndex);
76  void CheckReferenceType(InitListExpr *IList, QualType DeclType,
77                          unsigned &Index,
78                          InitListExpr *StructuredList,
79                          unsigned &StructuredIndex);
80  void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
81                       InitListExpr *StructuredList,
82                       unsigned &StructuredIndex);
83  void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
84                             RecordDecl::field_iterator Field,
85                             bool SubobjectIsDesignatorContext, unsigned &Index,
86                             InitListExpr *StructuredList,
87                             unsigned &StructuredIndex);
88  void CheckArrayType(InitListExpr *IList, QualType &DeclType,
89                      llvm::APSInt elementIndex,
90                      bool SubobjectIsDesignatorContext, unsigned &Index,
91                      InitListExpr *StructuredList,
92                      unsigned &StructuredIndex);
93  bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
94                                  DesignatedInitExpr::designators_iterator D,
95                                  QualType &CurrentObjectType,
96                                  RecordDecl::field_iterator *NextField,
97                                  llvm::APSInt *NextElementIndex,
98                                  unsigned &Index,
99                                  InitListExpr *StructuredList,
100                                  unsigned &StructuredIndex,
101                                  bool FinishSubobjectInit = true);
102  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
103                                           QualType CurrentObjectType,
104                                           InitListExpr *StructuredList,
105                                           unsigned StructuredIndex,
106                                           SourceRange InitRange);
107  void UpdateStructuredListElement(InitListExpr *StructuredList,
108                                   unsigned &StructuredIndex,
109                                   Expr *expr);
110  int numArrayElements(QualType DeclType);
111  int numStructUnionElements(QualType DeclType);
112
113  void FillInValueInitializations(InitListExpr *ILE);
114public:
115  InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
116  bool HadError() { return hadError; }
117
118  // @brief Retrieves the fully-structured initializer list used for
119  // semantic analysis and code generation.
120  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
121};
122}
123
124/// Recursively replaces NULL values within the given initializer list
125/// with expressions that perform value-initialization of the
126/// appropriate type.
127void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
128  assert((ILE->getType() != SemaRef->Context.VoidTy) &&
129         "Should not have void type");
130  SourceLocation Loc = ILE->getSourceRange().getBegin();
131  if (ILE->getSyntacticForm())
132    Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
133
134  if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
135    unsigned Init = 0, NumInits = ILE->getNumInits();
136    for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
137                                 FieldEnd = RType->getDecl()->field_end();
138         Field != FieldEnd; ++Field) {
139      if (Field->isUnnamedBitfield())
140        continue;
141
142      if (Init >= NumInits || !ILE->getInit(Init)) {
143        if (Field->getType()->isReferenceType()) {
144          // C++ [dcl.init.aggr]p9:
145          //   If an incomplete or empty initializer-list leaves a
146          //   member of reference type uninitialized, the program is
147          //   ill-formed.
148          SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
149            << Field->getType()
150            << ILE->getSyntacticForm()->getSourceRange();
151          SemaRef->Diag(Field->getLocation(),
152                        diag::note_uninit_reference_member);
153          hadError = true;
154          return;
155        } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
156          hadError = true;
157          return;
158        }
159
160        // FIXME: If value-initialization involves calling a
161        // constructor, should we make that call explicit in the
162        // representation (even when it means extending the
163        // initializer list)?
164        if (Init < NumInits && !hadError)
165          ILE->setInit(Init,
166              new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
167      } else if (InitListExpr *InnerILE
168                 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
169        FillInValueInitializations(InnerILE);
170      ++Init;
171
172      // Only look at the first initialization of a union.
173      if (RType->getDecl()->isUnion())
174        break;
175    }
176
177    return;
178  }
179
180  QualType ElementType;
181
182  unsigned NumInits = ILE->getNumInits();
183  unsigned NumElements = NumInits;
184  if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
185    ElementType = AType->getElementType();
186    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
187      NumElements = CAType->getSize().getZExtValue();
188  } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
189    ElementType = VType->getElementType();
190    NumElements = VType->getNumElements();
191  } else
192    ElementType = ILE->getType();
193
194  for (unsigned Init = 0; Init != NumElements; ++Init) {
195    if (Init >= NumInits || !ILE->getInit(Init)) {
196      if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
197        hadError = true;
198        return;
199      }
200
201      // FIXME: If value-initialization involves calling a
202      // constructor, should we make that call explicit in the
203      // representation (even when it means extending the
204      // initializer list)?
205      if (Init < NumInits && !hadError)
206        ILE->setInit(Init,
207                     new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
208    }
209    else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
210      FillInValueInitializations(InnerILE);
211  }
212}
213
214
215InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
216  hadError = false;
217  SemaRef = S;
218
219  unsigned newIndex = 0;
220  unsigned newStructuredIndex = 0;
221  FullyStructuredList
222    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
223  CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
224
225  if (!hadError)
226    FillInValueInitializations(FullyStructuredList);
227}
228
229int InitListChecker::numArrayElements(QualType DeclType) {
230  // FIXME: use a proper constant
231  int maxElements = 0x7FFFFFFF;
232  if (const ConstantArrayType *CAT =
233        SemaRef->Context.getAsConstantArrayType(DeclType)) {
234    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
235  }
236  return maxElements;
237}
238
239int InitListChecker::numStructUnionElements(QualType DeclType) {
240  RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
241  int InitializableMembers = 0;
242  for (RecordDecl::field_iterator Field = structDecl->field_begin(),
243                               FieldEnd = structDecl->field_end();
244       Field != FieldEnd; ++Field) {
245    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
246      ++InitializableMembers;
247  }
248  if (structDecl->isUnion())
249    return std::min(InitializableMembers, 1);
250  return InitializableMembers - structDecl->hasFlexibleArrayMember();
251}
252
253void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
254                                            QualType T, unsigned &Index,
255                                            InitListExpr *StructuredList,
256                                            unsigned &StructuredIndex) {
257  int maxElements = 0;
258
259  if (T->isArrayType())
260    maxElements = numArrayElements(T);
261  else if (T->isStructureType() || T->isUnionType())
262    maxElements = numStructUnionElements(T);
263  else if (T->isVectorType())
264    maxElements = T->getAsVectorType()->getNumElements();
265  else
266    assert(0 && "CheckImplicitInitList(): Illegal type");
267
268  if (maxElements == 0) {
269    SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
270                  diag::err_implicit_empty_initializer);
271    ++Index;
272    hadError = true;
273    return;
274  }
275
276  // Build a structured initializer list corresponding to this subobject.
277  InitListExpr *StructuredSubobjectInitList
278    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
279                                 StructuredIndex,
280                                 ParentIList->getInit(Index)->getSourceRange());
281  unsigned StructuredSubobjectInitIndex = 0;
282
283  // Check the element types and build the structural subobject.
284  unsigned StartIndex = Index;
285  CheckListElementTypes(ParentIList, T, false, Index,
286                        StructuredSubobjectInitList,
287                        StructuredSubobjectInitIndex);
288  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
289
290  // Update the structured sub-object initialize so that it's ending
291  // range corresponds with the end of the last initializer it used.
292  if (EndIndex < ParentIList->getNumInits()) {
293    SourceLocation EndLoc
294      = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
295    StructuredSubobjectInitList->setRBraceLoc(EndLoc);
296  }
297}
298
299void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
300                                            unsigned &Index,
301                                            InitListExpr *StructuredList,
302                                            unsigned &StructuredIndex) {
303  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
304  SyntacticToSemantic[IList] = StructuredList;
305  StructuredList->setSyntacticForm(IList);
306  CheckListElementTypes(IList, T, true, Index, StructuredList,
307                        StructuredIndex);
308  IList->setType(T);
309  StructuredList->setType(T);
310  if (hadError)
311    return;
312
313  if (Index < IList->getNumInits()) {
314    // We have leftover initializers
315    if (IList->getNumInits() > 0 &&
316        SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
317      // Special-case
318      SemaRef->Diag(IList->getInit(Index)->getLocStart(),
319                    diag::err_excess_initializers_in_char_array_initializer)
320        << IList->getInit(Index)->getSourceRange();
321      hadError = true;
322    } else if (!T->isIncompleteType()) {
323      // Don't complain for incomplete types, since we'll get an error
324      // elsewhere
325      SemaRef->Diag(IList->getInit(Index)->getLocStart(),
326                    diag::err_excess_initializers)
327        << IList->getInit(Index)->getSourceRange();
328    }
329  }
330
331  if (T->isScalarType())
332    SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
333      << IList->getSourceRange();
334}
335
336void InitListChecker::CheckListElementTypes(InitListExpr *IList,
337                                            QualType &DeclType,
338                                            bool SubobjectIsDesignatorContext,
339                                            unsigned &Index,
340                                            InitListExpr *StructuredList,
341                                            unsigned &StructuredIndex) {
342  if (DeclType->isScalarType()) {
343    CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
344  } else if (DeclType->isVectorType()) {
345    CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
346  } else if (DeclType->isAggregateType()) {
347    if (DeclType->isRecordType()) {
348      RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
349      CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
350                            SubobjectIsDesignatorContext, Index,
351                            StructuredList, StructuredIndex);
352    } else if (DeclType->isArrayType()) {
353      llvm::APSInt Zero(
354                      SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
355                      false);
356      CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
357                     StructuredList, StructuredIndex);
358    }
359    else
360      assert(0 && "Aggregate that isn't a structure or array?!");
361  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
362    // This type is invalid, issue a diagnostic.
363    ++Index;
364    SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
365      << DeclType;
366    hadError = true;
367  } else if (DeclType->isRecordType()) {
368    // C++ [dcl.init]p14:
369    //   [...] If the class is an aggregate (8.5.1), and the initializer
370    //   is a brace-enclosed list, see 8.5.1.
371    //
372    // Note: 8.5.1 is handled below; here, we diagnose the case where
373    // we have an initializer list and a destination type that is not
374    // an aggregate.
375    // FIXME: In C++0x, this is yet another form of initialization.
376    SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
377      << DeclType << IList->getSourceRange();
378    hadError = true;
379  } else if (DeclType->isReferenceType()) {
380    CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
381  } else {
382    // In C, all types are either scalars or aggregates, but
383    // additional handling is needed here for C++ (and possibly others?).
384    assert(0 && "Unsupported initializer type");
385  }
386}
387
388void InitListChecker::CheckSubElementType(InitListExpr *IList,
389                                          QualType ElemType,
390                                          unsigned &Index,
391                                          InitListExpr *StructuredList,
392                                          unsigned &StructuredIndex) {
393  Expr *expr = IList->getInit(Index);
394  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
395    unsigned newIndex = 0;
396    unsigned newStructuredIndex = 0;
397    InitListExpr *newStructuredList
398      = getStructuredSubobjectInit(IList, Index, ElemType,
399                                   StructuredList, StructuredIndex,
400                                   SubInitList->getSourceRange());
401    CheckExplicitInitList(SubInitList, ElemType, newIndex,
402                          newStructuredList, newStructuredIndex);
403    ++StructuredIndex;
404    ++Index;
405  } else if (StringLiteral *lit =
406             SemaRef->IsStringLiteralInit(expr, ElemType)) {
407    SemaRef->CheckStringLiteralInit(lit, ElemType);
408    UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
409    ++Index;
410  } else if (ElemType->isScalarType()) {
411    CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
412  } else if (ElemType->isReferenceType()) {
413    CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
414  } else {
415    if (SemaRef->getLangOptions().CPlusPlus) {
416      // C++ [dcl.init.aggr]p12:
417      //   All implicit type conversions (clause 4) are considered when
418      //   initializing the aggregate member with an ini- tializer from
419      //   an initializer-list. If the initializer can initialize a
420      //   member, the member is initialized. [...]
421      ImplicitConversionSequence ICS
422        = SemaRef->TryCopyInitialization(expr, ElemType);
423      if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
424        if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
425                                               "initializing"))
426          hadError = true;
427        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
428        ++Index;
429        return;
430      }
431
432      // Fall through for subaggregate initialization
433    } else {
434      // C99 6.7.8p13:
435      //
436      //   The initializer for a structure or union object that has
437      //   automatic storage duration shall be either an initializer
438      //   list as described below, or a single expression that has
439      //   compatible structure or union type. In the latter case, the
440      //   initial value of the object, including unnamed members, is
441      //   that of the expression.
442      QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
443      QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
444      if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
445                                          ElemTypeCanon.getUnqualifiedType())) {
446        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
447        ++Index;
448        return;
449      }
450
451      // Fall through for subaggregate initialization
452    }
453
454    // C++ [dcl.init.aggr]p12:
455    //
456    //   [...] Otherwise, if the member is itself a non-empty
457    //   subaggregate, brace elision is assumed and the initializer is
458    //   considered for the initialization of the first member of
459    //   the subaggregate.
460    if (ElemType->isAggregateType() || ElemType->isVectorType()) {
461      CheckImplicitInitList(IList, ElemType, Index, StructuredList,
462                            StructuredIndex);
463      ++StructuredIndex;
464    } else {
465      // We cannot initialize this element, so let
466      // PerformCopyInitialization produce the appropriate diagnostic.
467      SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
468      hadError = true;
469      ++Index;
470      ++StructuredIndex;
471    }
472  }
473}
474
475void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
476                                      unsigned &Index,
477                                      InitListExpr *StructuredList,
478                                      unsigned &StructuredIndex) {
479  if (Index < IList->getNumInits()) {
480    Expr *expr = IList->getInit(Index);
481    if (isa<InitListExpr>(expr)) {
482      SemaRef->Diag(IList->getLocStart(),
483                    diag::err_many_braces_around_scalar_init)
484        << IList->getSourceRange();
485      hadError = true;
486      ++Index;
487      ++StructuredIndex;
488      return;
489    } else if (isa<DesignatedInitExpr>(expr)) {
490      SemaRef->Diag(expr->getSourceRange().getBegin(),
491                    diag::err_designator_for_scalar_init)
492        << DeclType << expr->getSourceRange();
493      hadError = true;
494      ++Index;
495      ++StructuredIndex;
496      return;
497    }
498
499    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
500    if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
501      hadError = true; // types weren't compatible.
502    else if (savExpr != expr) {
503      // The type was promoted, update initializer list.
504      IList->setInit(Index, expr);
505    }
506    if (hadError)
507      ++StructuredIndex;
508    else
509      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
510    ++Index;
511  } else {
512    SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
513      << IList->getSourceRange();
514    hadError = true;
515    ++Index;
516    ++StructuredIndex;
517    return;
518  }
519}
520
521void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
522                                         unsigned &Index,
523                                         InitListExpr *StructuredList,
524                                         unsigned &StructuredIndex) {
525  if (Index < IList->getNumInits()) {
526    Expr *expr = IList->getInit(Index);
527    if (isa<InitListExpr>(expr)) {
528      SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
529        << DeclType << IList->getSourceRange();
530      hadError = true;
531      ++Index;
532      ++StructuredIndex;
533      return;
534    }
535
536    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
537    if (SemaRef->CheckReferenceInit(expr, DeclType))
538      hadError = true;
539    else if (savExpr != expr) {
540      // The type was promoted, update initializer list.
541      IList->setInit(Index, expr);
542    }
543    if (hadError)
544      ++StructuredIndex;
545    else
546      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
547    ++Index;
548  } else {
549    // FIXME: It would be wonderful if we could point at the actual
550    // member. In general, it would be useful to pass location
551    // information down the stack, so that we know the location (or
552    // decl) of the "current object" being initialized.
553    SemaRef->Diag(IList->getLocStart(),
554                  diag::err_init_reference_member_uninitialized)
555      << DeclType
556      << IList->getSourceRange();
557    hadError = true;
558    ++Index;
559    ++StructuredIndex;
560    return;
561  }
562}
563
564void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
565                                      unsigned &Index,
566                                      InitListExpr *StructuredList,
567                                      unsigned &StructuredIndex) {
568  if (Index < IList->getNumInits()) {
569    const VectorType *VT = DeclType->getAsVectorType();
570    int maxElements = VT->getNumElements();
571    QualType elementType = VT->getElementType();
572
573    for (int i = 0; i < maxElements; ++i) {
574      // Don't attempt to go past the end of the init list
575      if (Index >= IList->getNumInits())
576        break;
577      CheckSubElementType(IList, elementType, Index,
578                          StructuredList, StructuredIndex);
579    }
580  }
581}
582
583void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
584                                     llvm::APSInt elementIndex,
585                                     bool SubobjectIsDesignatorContext,
586                                     unsigned &Index,
587                                     InitListExpr *StructuredList,
588                                     unsigned &StructuredIndex) {
589  // Check for the special-case of initializing an array with a string.
590  if (Index < IList->getNumInits()) {
591    if (StringLiteral *lit =
592        SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
593      SemaRef->CheckStringLiteralInit(lit, DeclType);
594      // We place the string literal directly into the resulting
595      // initializer list. This is the only place where the structure
596      // of the structured initializer list doesn't match exactly,
597      // because doing so would involve allocating one character
598      // constant for each string.
599      UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
600      StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
601      ++Index;
602      return;
603    }
604  }
605  if (const VariableArrayType *VAT =
606        SemaRef->Context.getAsVariableArrayType(DeclType)) {
607    // Check for VLAs; in standard C it would be possible to check this
608    // earlier, but I don't know where clang accepts VLAs (gcc accepts
609    // them in all sorts of strange places).
610    SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
611                  diag::err_variable_object_no_init)
612      << VAT->getSizeExpr()->getSourceRange();
613    hadError = true;
614    ++Index;
615    ++StructuredIndex;
616    return;
617  }
618
619  // We might know the maximum number of elements in advance.
620  llvm::APSInt maxElements(elementIndex.getBitWidth(),
621                           elementIndex.isUnsigned());
622  bool maxElementsKnown = false;
623  if (const ConstantArrayType *CAT =
624        SemaRef->Context.getAsConstantArrayType(DeclType)) {
625    maxElements = CAT->getSize();
626    elementIndex.extOrTrunc(maxElements.getBitWidth());
627    elementIndex.setIsUnsigned(maxElements.isUnsigned());
628    maxElementsKnown = true;
629  }
630
631  QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
632                             ->getElementType();
633  while (Index < IList->getNumInits()) {
634    Expr *Init = IList->getInit(Index);
635    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
636      // If we're not the subobject that matches up with the '{' for
637      // the designator, we shouldn't be handling the
638      // designator. Return immediately.
639      if (!SubobjectIsDesignatorContext)
640        return;
641
642      // Handle this designated initializer. elementIndex will be
643      // updated to be the next array element we'll initialize.
644      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
645                                     DeclType, 0, &elementIndex, Index,
646                                     StructuredList, StructuredIndex)) {
647        hadError = true;
648        continue;
649      }
650
651      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
652        maxElements.extend(elementIndex.getBitWidth());
653      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
654        elementIndex.extend(maxElements.getBitWidth());
655      elementIndex.setIsUnsigned(maxElements.isUnsigned());
656
657      // If the array is of incomplete type, keep track of the number of
658      // elements in the initializer.
659      if (!maxElementsKnown && elementIndex > maxElements)
660        maxElements = elementIndex;
661
662      continue;
663    }
664
665    // If we know the maximum number of elements, and we've already
666    // hit it, stop consuming elements in the initializer list.
667    if (maxElementsKnown && elementIndex == maxElements)
668      break;
669
670    // Check this element.
671    CheckSubElementType(IList, elementType, Index,
672                        StructuredList, StructuredIndex);
673    ++elementIndex;
674
675    // If the array is of incomplete type, keep track of the number of
676    // elements in the initializer.
677    if (!maxElementsKnown && elementIndex > maxElements)
678      maxElements = elementIndex;
679  }
680  if (DeclType->isIncompleteArrayType()) {
681    // If this is an incomplete array type, the actual type needs to
682    // be calculated here.
683    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
684    if (maxElements == Zero) {
685      // Sizing an array implicitly to zero is not allowed by ISO C,
686      // but is supported by GNU.
687      SemaRef->Diag(IList->getLocStart(),
688                    diag::ext_typecheck_zero_array_size);
689    }
690
691    DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
692                                                     ArrayType::Normal, 0);
693  }
694}
695
696void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
697                                            QualType DeclType,
698                                            RecordDecl::field_iterator Field,
699                                            bool SubobjectIsDesignatorContext,
700                                            unsigned &Index,
701                                            InitListExpr *StructuredList,
702                                            unsigned &StructuredIndex) {
703  RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
704
705  // If the record is invalid, some of it's members are invalid. To avoid
706  // confusion, we forgo checking the intializer for the entire record.
707  if (structDecl->isInvalidDecl()) {
708    hadError = true;
709    return;
710  }
711
712  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
713    // Value-initialize the first named member of the union.
714    RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
715    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
716         Field != FieldEnd; ++Field) {
717      if (Field->getDeclName()) {
718        StructuredList->setInitializedFieldInUnion(*Field);
719        break;
720      }
721    }
722    return;
723  }
724
725
726
727  // If structDecl is a forward declaration, this loop won't do
728  // anything except look at designated initializers; That's okay,
729  // because an error should get printed out elsewhere. It might be
730  // worthwhile to skip over the rest of the initializer, though.
731  RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
732  RecordDecl::field_iterator FieldEnd = RD->field_end();
733  while (Index < IList->getNumInits()) {
734    Expr *Init = IList->getInit(Index);
735
736    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
737      // If we're not the subobject that matches up with the '{' for
738      // the designator, we shouldn't be handling the
739      // designator. Return immediately.
740      if (!SubobjectIsDesignatorContext)
741        return;
742
743      // Handle this designated initializer. Field will be updated to
744      // the next field that we'll be initializing.
745      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
746                                     DeclType, &Field, 0, Index,
747                                     StructuredList, StructuredIndex))
748        hadError = true;
749
750      // Abort early for unions: the designator handled the
751      // initialization of the appropriate field.
752      if (DeclType->isUnionType())
753        break;
754
755      continue;
756    }
757
758    if (Field == FieldEnd) {
759      // We've run out of fields. We're done.
760      break;
761    }
762
763    // If we've hit the flexible array member at the end, we're done.
764    if (Field->getType()->isIncompleteArrayType())
765      break;
766
767    if (Field->isUnnamedBitfield()) {
768      // Don't initialize unnamed bitfields, e.g. "int : 20;"
769      ++Field;
770      continue;
771    }
772
773    CheckSubElementType(IList, Field->getType(), Index,
774                        StructuredList, StructuredIndex);
775
776    if (DeclType->isUnionType()) {
777      // Initialize the first field within the union.
778      StructuredList->setInitializedFieldInUnion(*Field);
779      break;
780    }
781
782    ++Field;
783  }
784
785  // FIXME: Implement flexible array initialization GCC extension (it's a
786  // really messy extension to implement, unfortunately...the necessary
787  // information isn't actually even here!)
788}
789
790/// @brief Check the well-formedness of a C99 designated initializer.
791///
792/// Determines whether the designated initializer @p DIE, which
793/// resides at the given @p Index within the initializer list @p
794/// IList, is well-formed for a current object of type @p DeclType
795/// (C99 6.7.8). The actual subobject that this designator refers to
796/// within the current subobject is returned in either
797/// @p NextField or @p NextElementIndex (whichever is appropriate).
798///
799/// @param IList  The initializer list in which this designated
800/// initializer occurs.
801///
802/// @param DIE  The designated initializer and its initialization
803/// expression.
804///
805/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
806/// into which the designation in @p DIE should refer.
807///
808/// @param NextField  If non-NULL and the first designator in @p DIE is
809/// a field, this will be set to the field declaration corresponding
810/// to the field named by the designator.
811///
812/// @param NextElementIndex  If non-NULL and the first designator in @p
813/// DIE is an array designator or GNU array-range designator, this
814/// will be set to the last index initialized by this designator.
815///
816/// @param Index  Index into @p IList where the designated initializer
817/// @p DIE occurs.
818///
819/// @param StructuredList  The initializer list expression that
820/// describes all of the subobject initializers in the order they'll
821/// actually be initialized.
822///
823/// @returns true if there was an error, false otherwise.
824bool
825InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
826                                      DesignatedInitExpr *DIE,
827                                      DesignatedInitExpr::designators_iterator D,
828                                      QualType &CurrentObjectType,
829                                      RecordDecl::field_iterator *NextField,
830                                      llvm::APSInt *NextElementIndex,
831                                      unsigned &Index,
832                                      InitListExpr *StructuredList,
833                                      unsigned &StructuredIndex,
834                                      bool FinishSubobjectInit) {
835  if (D == DIE->designators_end()) {
836    // Check the actual initialization for the designated object type.
837    bool prevHadError = hadError;
838
839    // Temporarily remove the designator expression from the
840    // initializer list that the child calls see, so that we don't try
841    // to re-process the designator.
842    unsigned OldIndex = Index;
843    IList->setInit(OldIndex, DIE->getInit());
844
845    CheckSubElementType(IList, CurrentObjectType, Index,
846                        StructuredList, StructuredIndex);
847
848    // Restore the designated initializer expression in the syntactic
849    // form of the initializer list.
850    if (IList->getInit(OldIndex) != DIE->getInit())
851      DIE->setInit(IList->getInit(OldIndex));
852    IList->setInit(OldIndex, DIE);
853
854    return hadError && !prevHadError;
855  }
856
857  bool IsFirstDesignator = (D == DIE->designators_begin());
858  assert((IsFirstDesignator || StructuredList) &&
859         "Need a non-designated initializer list to start from");
860
861  // Determine the structural initializer list that corresponds to the
862  // current subobject.
863  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
864    : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
865                                 StructuredIndex,
866                                 SourceRange(D->getStartLocation(),
867                                             DIE->getSourceRange().getEnd()));
868  assert(StructuredList && "Expected a structured initializer list");
869
870  if (D->isFieldDesignator()) {
871    // C99 6.7.8p7:
872    //
873    //   If a designator has the form
874    //
875    //      . identifier
876    //
877    //   then the current object (defined below) shall have
878    //   structure or union type and the identifier shall be the
879    //   name of a member of that type.
880    const RecordType *RT = CurrentObjectType->getAsRecordType();
881    if (!RT) {
882      SourceLocation Loc = D->getDotLoc();
883      if (Loc.isInvalid())
884        Loc = D->getFieldLoc();
885      SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
886        << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
887      ++Index;
888      return true;
889    }
890
891    // Note: we perform a linear search of the fields here, despite
892    // the fact that we have a faster lookup method, because we always
893    // need to compute the field's index.
894    IdentifierInfo *FieldName = D->getFieldName();
895    unsigned FieldIndex = 0;
896    RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
897                            FieldEnd = RT->getDecl()->field_end();
898    for (; Field != FieldEnd; ++Field) {
899      if (Field->isUnnamedBitfield())
900        continue;
901
902      if (Field->getIdentifier() == FieldName)
903        break;
904
905      ++FieldIndex;
906    }
907
908    if (Field == FieldEnd) {
909      // We did not find the field we're looking for. Produce a
910      // suitable diagnostic and return a failure.
911      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
912      if (Lookup.first == Lookup.second) {
913        // Name lookup didn't find anything.
914        SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
915          << FieldName << CurrentObjectType;
916      } else {
917        // Name lookup found something, but it wasn't a field.
918        SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
919          << FieldName;
920        SemaRef->Diag((*Lookup.first)->getLocation(),
921                      diag::note_field_designator_found);
922      }
923
924      ++Index;
925      return true;
926    } else if (cast<RecordDecl>((*Field)->getDeclContext())
927                 ->isAnonymousStructOrUnion()) {
928      SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
929        << FieldName
930        << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
931            (int)SemaRef->getLangOptions().CPlusPlus);
932      SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
933      ++Index;
934      return true;
935    }
936
937    // All of the fields of a union are located at the same place in
938    // the initializer list.
939    if (RT->getDecl()->isUnion()) {
940      FieldIndex = 0;
941      StructuredList->setInitializedFieldInUnion(*Field);
942    }
943
944    // Update the designator with the field declaration.
945    D->setField(*Field);
946
947    // Make sure that our non-designated initializer list has space
948    // for a subobject corresponding to this field.
949    if (FieldIndex >= StructuredList->getNumInits())
950      StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
951
952    // Recurse to check later designated subobjects.
953    QualType FieldType = (*Field)->getType();
954    unsigned newStructuredIndex = FieldIndex;
955    if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
956                                   StructuredList, newStructuredIndex))
957      return true;
958
959    // Find the position of the next field to be initialized in this
960    // subobject.
961    ++Field;
962    ++FieldIndex;
963
964    // If this the first designator, our caller will continue checking
965    // the rest of this struct/class/union subobject.
966    if (IsFirstDesignator) {
967      if (NextField)
968        *NextField = Field;
969      StructuredIndex = FieldIndex;
970      return false;
971    }
972
973    if (!FinishSubobjectInit)
974      return false;
975
976    // Check the remaining fields within this class/struct/union subobject.
977    bool prevHadError = hadError;
978    CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
979                          StructuredList, FieldIndex);
980    return hadError && !prevHadError;
981  }
982
983  // C99 6.7.8p6:
984  //
985  //   If a designator has the form
986  //
987  //      [ constant-expression ]
988  //
989  //   then the current object (defined below) shall have array
990  //   type and the expression shall be an integer constant
991  //   expression. If the array is of unknown size, any
992  //   nonnegative value is valid.
993  //
994  // Additionally, cope with the GNU extension that permits
995  // designators of the form
996  //
997  //      [ constant-expression ... constant-expression ]
998  const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
999  if (!AT) {
1000    SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1001      << CurrentObjectType;
1002    ++Index;
1003    return true;
1004  }
1005
1006  Expr *IndexExpr = 0;
1007  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1008  if (D->isArrayDesignator()) {
1009    IndexExpr = DIE->getArrayIndex(*D);
1010
1011    bool ConstExpr
1012      = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1013    assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1014
1015    DesignatedEndIndex = DesignatedStartIndex;
1016  } else {
1017    assert(D->isArrayRangeDesignator() && "Need array-range designator");
1018
1019    bool StartConstExpr
1020      = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1021                                                           SemaRef->Context);
1022    assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1023
1024    bool EndConstExpr
1025      = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1026                                                         SemaRef->Context);
1027    assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1028
1029    IndexExpr = DIE->getArrayRangeEnd(*D);
1030
1031    if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
1032      FullyStructuredList->sawArrayRangeDesignator();
1033  }
1034
1035  if (isa<ConstantArrayType>(AT)) {
1036    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1037    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1038    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1039    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1040    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1041    if (DesignatedEndIndex >= MaxElements) {
1042      SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1043                    diag::err_array_designator_too_large)
1044        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1045        << IndexExpr->getSourceRange();
1046      ++Index;
1047      return true;
1048    }
1049  } else {
1050    // Make sure the bit-widths and signedness match.
1051    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1052      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1053    else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1054      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1055    DesignatedStartIndex.setIsUnsigned(true);
1056    DesignatedEndIndex.setIsUnsigned(true);
1057  }
1058
1059  // Make sure that our non-designated initializer list has space
1060  // for a subobject corresponding to this array element.
1061  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1062    StructuredList->resizeInits(SemaRef->Context,
1063                                DesignatedEndIndex.getZExtValue() + 1);
1064
1065  // Repeatedly perform subobject initializations in the range
1066  // [DesignatedStartIndex, DesignatedEndIndex].
1067
1068  // Move to the next designator
1069  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1070  unsigned OldIndex = Index;
1071  ++D;
1072  while (DesignatedStartIndex <= DesignatedEndIndex) {
1073    // Recurse to check later designated subobjects.
1074    QualType ElementType = AT->getElementType();
1075    Index = OldIndex;
1076    if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1077                                   StructuredList, ElementIndex,
1078                                   (DesignatedStartIndex == DesignatedEndIndex)))
1079      return true;
1080
1081    // Move to the next index in the array that we'll be initializing.
1082    ++DesignatedStartIndex;
1083    ElementIndex = DesignatedStartIndex.getZExtValue();
1084  }
1085
1086  // If this the first designator, our caller will continue checking
1087  // the rest of this array subobject.
1088  if (IsFirstDesignator) {
1089    if (NextElementIndex)
1090      *NextElementIndex = DesignatedStartIndex;
1091    StructuredIndex = ElementIndex;
1092    return false;
1093  }
1094
1095  if (!FinishSubobjectInit)
1096    return false;
1097
1098  // Check the remaining elements within this array subobject.
1099  bool prevHadError = hadError;
1100  CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
1101                 StructuredList, ElementIndex);
1102  return hadError && !prevHadError;
1103}
1104
1105// Get the structured initializer list for a subobject of type
1106// @p CurrentObjectType.
1107InitListExpr *
1108InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1109                                            QualType CurrentObjectType,
1110                                            InitListExpr *StructuredList,
1111                                            unsigned StructuredIndex,
1112                                            SourceRange InitRange) {
1113  Expr *ExistingInit = 0;
1114  if (!StructuredList)
1115    ExistingInit = SyntacticToSemantic[IList];
1116  else if (StructuredIndex < StructuredList->getNumInits())
1117    ExistingInit = StructuredList->getInit(StructuredIndex);
1118
1119  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1120    return Result;
1121
1122  if (ExistingInit) {
1123    // We are creating an initializer list that initializes the
1124    // subobjects of the current object, but there was already an
1125    // initialization that completely initialized the current
1126    // subobject, e.g., by a compound literal:
1127    //
1128    // struct X { int a, b; };
1129    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1130    //
1131    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1132    // designated initializer re-initializes the whole
1133    // subobject [0], overwriting previous initializers.
1134    SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1135      << InitRange;
1136    SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1137                  diag::note_previous_initializer)
1138      << /*FIXME:has side effects=*/0
1139      << ExistingInit->getSourceRange();
1140  }
1141
1142  SourceLocation StartLoc;
1143  if (Index < IList->getNumInits())
1144    StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
1145  InitListExpr *Result
1146    = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1147                                          IList->getSourceRange().getEnd());
1148  Result->setType(CurrentObjectType);
1149
1150  // Link this new initializer list into the structured initializer
1151  // lists.
1152  if (StructuredList)
1153    StructuredList->updateInit(StructuredIndex, Result);
1154  else {
1155    Result->setSyntacticForm(IList);
1156    SyntacticToSemantic[IList] = Result;
1157  }
1158
1159  return Result;
1160}
1161
1162/// Update the initializer at index @p StructuredIndex within the
1163/// structured initializer list to the value @p expr.
1164void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1165                                                  unsigned &StructuredIndex,
1166                                                  Expr *expr) {
1167  // No structured initializer list to update
1168  if (!StructuredList)
1169    return;
1170
1171  if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1172    // This initializer overwrites a previous initializer. Warn.
1173    SemaRef->Diag(expr->getSourceRange().getBegin(),
1174                  diag::warn_initializer_overrides)
1175      << expr->getSourceRange();
1176    SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1177                  diag::note_previous_initializer)
1178      << /*FIXME:has side effects=*/0
1179      << PrevInit->getSourceRange();
1180  }
1181
1182  ++StructuredIndex;
1183}
1184
1185/// Check that the given Index expression is a valid array designator
1186/// value. This is essentailly just a wrapper around
1187/// Expr::isIntegerConstantExpr that also checks for negative values
1188/// and produces a reasonable diagnostic if there is a
1189/// failure. Returns true if there was an error, false otherwise.  If
1190/// everything went okay, Value will receive the value of the constant
1191/// expression.
1192static bool
1193CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1194  SourceLocation Loc = Index->getSourceRange().getBegin();
1195
1196  // Make sure this is an integer constant expression.
1197  if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1198    return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1199      << Index->getSourceRange();
1200
1201  // Make sure this constant expression is non-negative.
1202  llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1203                    Value.isUnsigned());
1204  if (Value < Zero)
1205    return Self.Diag(Loc, diag::err_array_designator_negative)
1206      << Value.toString(10) << Index->getSourceRange();
1207
1208  Value.setIsUnsigned(true);
1209  return false;
1210}
1211
1212Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1213                                                        SourceLocation Loc,
1214                                                        bool UsedColonSyntax,
1215                                                        OwningExprResult Init) {
1216  typedef DesignatedInitExpr::Designator ASTDesignator;
1217
1218  bool Invalid = false;
1219  llvm::SmallVector<ASTDesignator, 32> Designators;
1220  llvm::SmallVector<Expr *, 32> InitExpressions;
1221
1222  // Build designators and check array designator expressions.
1223  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1224    const Designator &D = Desig.getDesignator(Idx);
1225    switch (D.getKind()) {
1226    case Designator::FieldDesignator:
1227      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1228                                          D.getFieldLoc()));
1229      break;
1230
1231    case Designator::ArrayDesignator: {
1232      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1233      llvm::APSInt IndexValue;
1234      if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1235        Invalid = true;
1236      else {
1237        Designators.push_back(ASTDesignator(InitExpressions.size(),
1238                                            D.getLBracketLoc(),
1239                                            D.getRBracketLoc()));
1240        InitExpressions.push_back(Index);
1241      }
1242      break;
1243    }
1244
1245    case Designator::ArrayRangeDesignator: {
1246      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1247      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1248      llvm::APSInt StartValue;
1249      llvm::APSInt EndValue;
1250      if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1251          CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1252        Invalid = true;
1253      else {
1254        // Make sure we're comparing values with the same bit width.
1255        if (StartValue.getBitWidth() > EndValue.getBitWidth())
1256          EndValue.extend(StartValue.getBitWidth());
1257        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1258          StartValue.extend(EndValue.getBitWidth());
1259
1260        if (EndValue < StartValue) {
1261          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1262            << StartValue.toString(10) << EndValue.toString(10)
1263            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1264          Invalid = true;
1265        } else {
1266          Designators.push_back(ASTDesignator(InitExpressions.size(),
1267                                              D.getLBracketLoc(),
1268                                              D.getEllipsisLoc(),
1269                                              D.getRBracketLoc()));
1270          InitExpressions.push_back(StartIndex);
1271          InitExpressions.push_back(EndIndex);
1272        }
1273      }
1274      break;
1275    }
1276    }
1277  }
1278
1279  if (Invalid || Init.isInvalid())
1280    return ExprError();
1281
1282  // Clear out the expressions within the designation.
1283  Desig.ClearExprs(*this);
1284
1285  DesignatedInitExpr *DIE
1286    = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1287                                 &InitExpressions[0], InitExpressions.size(),
1288                                 Loc, UsedColonSyntax,
1289                                 static_cast<Expr *>(Init.release()));
1290  return Owned(DIE);
1291}
1292
1293bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1294  InitListChecker CheckInitList(this, InitList, DeclType);
1295  if (!CheckInitList.HadError())
1296    InitList = CheckInitList.getFullyStructuredList();
1297
1298  return CheckInitList.HadError();
1299}
1300
1301/// \brief Diagnose any semantic errors with value-initialization of
1302/// the given type.
1303///
1304/// Value-initialization effectively zero-initializes any types
1305/// without user-declared constructors, and calls the default
1306/// constructor for a for any type that has a user-declared
1307/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1308/// a type with a user-declared constructor does not have an
1309/// accessible, non-deleted default constructor. In C, everything can
1310/// be value-initialized, which corresponds to C's notion of
1311/// initializing objects with static storage duration when no
1312/// initializer is provided for that object.
1313///
1314/// \returns true if there was an error, false otherwise.
1315bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1316  // C++ [dcl.init]p5:
1317  //
1318  //   To value-initialize an object of type T means:
1319
1320  //     -- if T is an array type, then each element is value-initialized;
1321  if (const ArrayType *AT = Context.getAsArrayType(Type))
1322    return CheckValueInitialization(AT->getElementType(), Loc);
1323
1324  if (const RecordType *RT = Type->getAsRecordType()) {
1325    if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1326      // -- if T is a class type (clause 9) with a user-declared
1327      //    constructor (12.1), then the default constructor for T is
1328      //    called (and the initialization is ill-formed if T has no
1329      //    accessible default constructor);
1330      if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1331        // FIXME: Eventually, we'll need to put the constructor decl
1332        // into the AST.
1333        return PerformInitializationByConstructor(Type, 0, 0, Loc,
1334                                                  SourceRange(Loc),
1335                                                  DeclarationName(),
1336                                                  IK_Direct);
1337    }
1338  }
1339
1340  if (Type->isReferenceType()) {
1341    // C++ [dcl.init]p5:
1342    //   [...] A program that calls for default-initialization or
1343    //   value-initialization of an entity of reference type is
1344    //   ill-formed. [...]
1345  }
1346
1347  return false;
1348}
1349