SemaInit.cpp revision 36859ebc8a597bd07f9645684f4d361c918e0859
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/Parse/Designator.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/DiagnosticSema.h"
20using namespace clang;
21
22/// Recursively replaces NULL values within the given initializer list
23/// with expressions that perform value-initialization of the
24/// appropriate type.
25static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
26  assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
27  if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
28    unsigned Init = 0, NumInits = ILE->getNumInits();
29    for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
30                                 FieldEnd = RType->getDecl()->field_end();
31         Field != FieldEnd; ++Field) {
32      if (Field->isUnnamedBitfield())
33        continue;
34
35      if (Init >= NumInits)
36        break;
37
38      // FIXME: Check for fields with reference type in C++?
39      if (!ILE->getInit(Init))
40        ILE->setInit(Init,
41                     new (Context) CXXZeroInitValueExpr(Field->getType(),
42                                                        SourceLocation(),
43                                                        SourceLocation()));
44      else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
45        fillInValueInitializations(Context, InnerILE);
46      ++Init;
47    }
48
49    return;
50  }
51
52  QualType ElementType;
53
54  if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
55    ElementType = AType->getElementType();
56  else if (const VectorType *VType = ILE->getType()->getAsVectorType())
57    ElementType = VType->getElementType();
58  else
59    ElementType = ILE->getType();
60
61  for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
62       ++Init) {
63    if (!ILE->getInit(Init))
64      ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
65                                                            SourceLocation(),
66                                                            SourceLocation()));
67    else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
68      fillInValueInitializations(Context, InnerILE);
69  }
70}
71
72InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
73  hadError = false;
74  SemaRef = S;
75
76  unsigned newIndex = 0;
77  unsigned newStructuredIndex = 0;
78  FullyStructuredList
79    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
80  CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
81
82  if (!hadError) {
83    fillInValueInitializations(SemaRef->Context, FullyStructuredList);
84  }
85}
86
87int InitListChecker::numArrayElements(QualType DeclType) {
88  // FIXME: use a proper constant
89  int maxElements = 0x7FFFFFFF;
90  if (const ConstantArrayType *CAT =
91        SemaRef->Context.getAsConstantArrayType(DeclType)) {
92    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
93  }
94  return maxElements;
95}
96
97int InitListChecker::numStructUnionElements(QualType DeclType) {
98  RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
99  int InitializableMembers = 0;
100  for (RecordDecl::field_iterator Field = structDecl->field_begin(),
101                               FieldEnd = structDecl->field_end();
102       Field != FieldEnd; ++Field) {
103    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
104      ++InitializableMembers;
105  }
106  if (structDecl->isUnion())
107    return std::min(InitializableMembers, 1);
108  return InitializableMembers - structDecl->hasFlexibleArrayMember();
109}
110
111void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
112                                            QualType T, unsigned &Index,
113                                            InitListExpr *StructuredList,
114                                            unsigned &StructuredIndex) {
115  int maxElements = 0;
116
117  if (T->isArrayType())
118    maxElements = numArrayElements(T);
119  else if (T->isStructureType() || T->isUnionType())
120    maxElements = numStructUnionElements(T);
121  else if (T->isVectorType())
122    maxElements = T->getAsVectorType()->getNumElements();
123  else
124    assert(0 && "CheckImplicitInitList(): Illegal type");
125
126  // FIXME: Perhaps we should move this warning elsewhere?
127  if (maxElements == 0) {
128    SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
129                  diag::err_implicit_empty_initializer);
130    ++Index;
131    hadError = true;
132    return;
133  }
134
135  // Build a structured initializer list corresponding to this subobject.
136  InitListExpr *StructuredSubobjectInitList
137    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
138                                 StructuredIndex,
139                                 ParentIList->getInit(Index)->getSourceRange());
140  unsigned StructuredSubobjectInitIndex = 0;
141
142  // Check the element types and build the structural subobject.
143  CheckListElementTypes(ParentIList, T, false, Index,
144                        StructuredSubobjectInitList,
145                        StructuredSubobjectInitIndex);
146}
147
148void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
149                                            unsigned &Index,
150                                            InitListExpr *StructuredList,
151                                            unsigned &StructuredIndex) {
152  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
153  SyntacticToSemantic[IList] = StructuredList;
154  StructuredList->setSyntacticForm(IList);
155  CheckListElementTypes(IList, T, true, Index, StructuredList,
156                        StructuredIndex);
157  IList->setType(T);
158  StructuredList->setType(T);
159  if (hadError)
160    return;
161
162  if (Index < IList->getNumInits()) {
163    // We have leftover initializers
164    if (IList->getNumInits() > 0 &&
165        SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
166      // Special-case
167      SemaRef->Diag(IList->getInit(Index)->getLocStart(),
168                    diag::err_excess_initializers_in_char_array_initializer)
169        << IList->getInit(Index)->getSourceRange();
170      hadError = true;
171    } else if (!T->isIncompleteType()) {
172      // Don't warn for incomplete types, since we'll get an error elsewhere
173      SemaRef->Diag(IList->getInit(Index)->getLocStart(),
174                    diag::warn_excess_initializers)
175        << IList->getInit(Index)->getSourceRange();
176    }
177  }
178
179  if (T->isScalarType())
180    SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
181      << IList->getSourceRange();
182}
183
184void InitListChecker::CheckListElementTypes(InitListExpr *IList,
185                                            QualType &DeclType,
186                                            bool SubobjectIsDesignatorContext,
187                                            unsigned &Index,
188                                            InitListExpr *StructuredList,
189                                            unsigned &StructuredIndex) {
190  if (DeclType->isScalarType()) {
191    CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
192  } else if (DeclType->isVectorType()) {
193    CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
194  } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
195    if (DeclType->isStructureType() || DeclType->isUnionType()) {
196      RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
197      CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
198                            SubobjectIsDesignatorContext, Index,
199                            StructuredList, StructuredIndex);
200    } else if (DeclType->isArrayType()) {
201      llvm::APSInt Zero(
202                      SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
203                      false);
204      CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
205                     StructuredList, StructuredIndex);
206    }
207    else
208      assert(0 && "Aggregate that isn't a structure or array?!");
209  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
210    // This type is invalid, issue a diagnostic.
211    ++Index;
212    SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
213      << DeclType;
214    hadError = true;
215  } else {
216    // In C, all types are either scalars or aggregates, but
217    // additional handling is needed here for C++ (and possibly others?).
218    assert(0 && "Unsupported initializer type");
219  }
220}
221
222void InitListChecker::CheckSubElementType(InitListExpr *IList,
223                                          QualType ElemType,
224                                          unsigned &Index,
225                                          InitListExpr *StructuredList,
226                                          unsigned &StructuredIndex) {
227  Expr *expr = IList->getInit(Index);
228  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
229    unsigned newIndex = 0;
230    unsigned newStructuredIndex = 0;
231    InitListExpr *newStructuredList
232      = getStructuredSubobjectInit(IList, Index, ElemType,
233                                   StructuredList, StructuredIndex,
234                                   SubInitList->getSourceRange());
235    CheckExplicitInitList(SubInitList, ElemType, newIndex,
236                          newStructuredList, newStructuredIndex);
237    ++StructuredIndex;
238    ++Index;
239  } else if (StringLiteral *lit =
240             SemaRef->IsStringLiteralInit(expr, ElemType)) {
241    SemaRef->CheckStringLiteralInit(lit, ElemType);
242    UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
243    ++Index;
244  } else if (ElemType->isScalarType()) {
245    CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
246  } else if (expr->getType()->getAsRecordType() &&
247             SemaRef->Context.typesAreCompatible(
248               expr->getType().getUnqualifiedType(),
249               ElemType.getUnqualifiedType())) {
250    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
251    ++Index;
252    // FIXME: Add checking
253  } else {
254    CheckImplicitInitList(IList, ElemType, Index, StructuredList,
255                          StructuredIndex);
256    ++StructuredIndex;
257 }
258}
259
260void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
261                                      unsigned &Index,
262                                      InitListExpr *StructuredList,
263                                      unsigned &StructuredIndex) {
264  if (Index < IList->getNumInits()) {
265    Expr *expr = IList->getInit(Index);
266    if (isa<InitListExpr>(expr)) {
267      SemaRef->Diag(IList->getLocStart(),
268                    diag::err_many_braces_around_scalar_init)
269        << IList->getSourceRange();
270      hadError = true;
271      ++Index;
272      ++StructuredIndex;
273      return;
274    } else if (isa<DesignatedInitExpr>(expr)) {
275      SemaRef->Diag(expr->getSourceRange().getBegin(),
276                    diag::err_designator_for_scalar_init)
277        << DeclType << expr->getSourceRange();
278      hadError = true;
279      ++Index;
280      ++StructuredIndex;
281      return;
282    }
283
284    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
285    if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
286      hadError = true; // types weren't compatible.
287    else if (savExpr != expr) {
288      // The type was promoted, update initializer list.
289      IList->setInit(Index, expr);
290    }
291    if (hadError)
292      ++StructuredIndex;
293    else
294      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
295    ++Index;
296  } else {
297    SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
298      << IList->getSourceRange();
299    hadError = true;
300    ++Index;
301    ++StructuredIndex;
302    return;
303  }
304}
305
306void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
307                                      unsigned &Index,
308                                      InitListExpr *StructuredList,
309                                      unsigned &StructuredIndex) {
310  if (Index < IList->getNumInits()) {
311    const VectorType *VT = DeclType->getAsVectorType();
312    int maxElements = VT->getNumElements();
313    QualType elementType = VT->getElementType();
314
315    for (int i = 0; i < maxElements; ++i) {
316      // Don't attempt to go past the end of the init list
317      if (Index >= IList->getNumInits())
318        break;
319      CheckSubElementType(IList, elementType, Index,
320                          StructuredList, StructuredIndex);
321    }
322  }
323}
324
325void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
326                                     llvm::APSInt elementIndex,
327                                     bool SubobjectIsDesignatorContext,
328                                     unsigned &Index,
329                                     InitListExpr *StructuredList,
330                                     unsigned &StructuredIndex) {
331  // Check for the special-case of initializing an array with a string.
332  if (Index < IList->getNumInits()) {
333    if (StringLiteral *lit =
334        SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
335      SemaRef->CheckStringLiteralInit(lit, DeclType);
336      // We place the string literal directly into the resulting
337      // initializer list. This is the only place where the structure
338      // of the structured initializer list doesn't match exactly,
339      // because doing so would involve allocating one character
340      // constant for each string.
341      UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
342      StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
343      ++Index;
344      return;
345    }
346  }
347  if (const VariableArrayType *VAT =
348        SemaRef->Context.getAsVariableArrayType(DeclType)) {
349    // Check for VLAs; in standard C it would be possible to check this
350    // earlier, but I don't know where clang accepts VLAs (gcc accepts
351    // them in all sorts of strange places).
352    SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
353                  diag::err_variable_object_no_init)
354      << VAT->getSizeExpr()->getSourceRange();
355    hadError = true;
356    ++Index;
357    ++StructuredIndex;
358    return;
359  }
360
361  // We might know the maximum number of elements in advance.
362  llvm::APSInt maxElements(elementIndex.getBitWidth(),
363                           elementIndex.isUnsigned());
364  bool maxElementsKnown = false;
365  if (const ConstantArrayType *CAT =
366        SemaRef->Context.getAsConstantArrayType(DeclType)) {
367    maxElements = CAT->getSize();
368    elementIndex.extOrTrunc(maxElements.getBitWidth());
369    elementIndex.setIsUnsigned(maxElements.isUnsigned());
370    maxElementsKnown = true;
371  }
372
373  QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
374                             ->getElementType();
375  while (Index < IList->getNumInits()) {
376    Expr *Init = IList->getInit(Index);
377    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
378      // If we're not the subobject that matches up with the '{' for
379      // the designator, we shouldn't be handling the
380      // designator. Return immediately.
381      if (!SubobjectIsDesignatorContext)
382        return;
383
384      // Handle this designated initializer. elementIndex will be
385      // updated to be the next array element we'll initialize.
386      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
387                                     DeclType, 0, &elementIndex, Index,
388                                     StructuredList, StructuredIndex)) {
389        hadError = true;
390        continue;
391      }
392
393      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
394        maxElements.extend(elementIndex.getBitWidth());
395      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
396        elementIndex.extend(maxElements.getBitWidth());
397      elementIndex.setIsUnsigned(maxElements.isUnsigned());
398
399      // If the array is of incomplete type, keep track of the number of
400      // elements in the initializer.
401      if (!maxElementsKnown && elementIndex > maxElements)
402        maxElements = elementIndex;
403
404      continue;
405    }
406
407    // If we know the maximum number of elements, and we've already
408    // hit it, stop consuming elements in the initializer list.
409    if (maxElementsKnown && elementIndex == maxElements)
410      break;
411
412    // Check this element.
413    CheckSubElementType(IList, elementType, Index,
414                        StructuredList, StructuredIndex);
415    ++elementIndex;
416
417    // If the array is of incomplete type, keep track of the number of
418    // elements in the initializer.
419    if (!maxElementsKnown && elementIndex > maxElements)
420      maxElements = elementIndex;
421  }
422  if (DeclType->isIncompleteArrayType()) {
423    // If this is an incomplete array type, the actual type needs to
424    // be calculated here.
425    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
426    if (maxElements == Zero) {
427      // Sizing an array implicitly to zero is not allowed by ISO C,
428      // but is supported by GNU.
429      SemaRef->Diag(IList->getLocStart(),
430                    diag::ext_typecheck_zero_array_size);
431    }
432
433    DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
434                                                     ArrayType::Normal, 0);
435  }
436}
437
438void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
439                                            QualType DeclType,
440                                            RecordDecl::field_iterator Field,
441                                            bool SubobjectIsDesignatorContext,
442                                            unsigned &Index,
443                                            InitListExpr *StructuredList,
444                                            unsigned &StructuredIndex) {
445  RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
446
447  // If the record is invalid, some of it's members are invalid. To avoid
448  // confusion, we forgo checking the intializer for the entire record.
449  if (structDecl->isInvalidDecl()) {
450    hadError = true;
451    return;
452  }
453  // If structDecl is a forward declaration, this loop won't do
454  // anything except look at designated initializers; That's okay,
455  // because an error should get printed out elsewhere. It might be
456  // worthwhile to skip over the rest of the initializer, though.
457  RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
458  RecordDecl::field_iterator FieldEnd = RD->field_end();
459  while (Index < IList->getNumInits()) {
460    Expr *Init = IList->getInit(Index);
461
462    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
463      // If we're not the subobject that matches up with the '{' for
464      // the designator, we shouldn't be handling the
465      // designator. Return immediately.
466      if (!SubobjectIsDesignatorContext)
467        return;
468
469      // Handle this designated initializer. Field will be updated to
470      // the next field that we'll be initializing.
471      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
472                                     DeclType, &Field, 0, Index,
473                                     StructuredList, StructuredIndex))
474        hadError = true;
475
476      continue;
477    }
478
479    if (Field == FieldEnd) {
480      // We've run out of fields. We're done.
481      break;
482    }
483
484    // If we've hit the flexible array member at the end, we're done.
485    if (Field->getType()->isIncompleteArrayType())
486      break;
487
488    if (!Field->getIdentifier() && Field->isBitField()) {
489      // Don't initialize unnamed bitfields, e.g. "int : 20;"
490      ++Field;
491      continue;
492    }
493
494    CheckSubElementType(IList, Field->getType(), Index,
495                        StructuredList, StructuredIndex);
496    if (DeclType->isUnionType())
497      break;
498
499    ++Field;
500  }
501
502  // FIXME: Implement flexible array initialization GCC extension (it's a
503  // really messy extension to implement, unfortunately...the necessary
504  // information isn't actually even here!)
505}
506
507/// @brief Check the well-formedness of a C99 designated initializer.
508///
509/// Determines whether the designated initializer @p DIE, which
510/// resides at the given @p Index within the initializer list @p
511/// IList, is well-formed for a current object of type @p DeclType
512/// (C99 6.7.8). The actual subobject that this designator refers to
513/// within the current subobject is returned in either
514/// @p NextField or @p NextElementIndex (whichever is appropriate).
515///
516/// @param IList  The initializer list in which this designated
517/// initializer occurs.
518///
519/// @param DIE  The designated initializer and its initialization
520/// expression.
521///
522/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
523/// into which the designation in @p DIE should refer.
524///
525/// @param NextField  If non-NULL and the first designator in @p DIE is
526/// a field, this will be set to the field declaration corresponding
527/// to the field named by the designator.
528///
529/// @param NextElementIndex  If non-NULL and the first designator in @p
530/// DIE is an array designator or GNU array-range designator, this
531/// will be set to the last index initialized by this designator.
532///
533/// @param Index  Index into @p IList where the designated initializer
534/// @p DIE occurs.
535///
536/// @param StructuredList  The initializer list expression that
537/// describes all of the subobject initializers in the order they'll
538/// actually be initialized.
539///
540/// @returns true if there was an error, false otherwise.
541bool
542InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
543                                      DesignatedInitExpr *DIE,
544                                      DesignatedInitExpr::designators_iterator D,
545                                      QualType &CurrentObjectType,
546                                      RecordDecl::field_iterator *NextField,
547                                      llvm::APSInt *NextElementIndex,
548                                      unsigned &Index,
549                                      InitListExpr *StructuredList,
550                                      unsigned &StructuredIndex,
551                                      bool FinishSubobjectInit) {
552  if (D == DIE->designators_end()) {
553    // Check the actual initialization for the designated object type.
554    bool prevHadError = hadError;
555
556    // Temporarily remove the designator expression from the
557    // initializer list that the child calls see, so that we don't try
558    // to re-process the designator.
559    unsigned OldIndex = Index;
560    IList->setInit(OldIndex, DIE->getInit());
561
562    CheckSubElementType(IList, CurrentObjectType, Index,
563                        StructuredList, StructuredIndex);
564
565    // Restore the designated initializer expression in the syntactic
566    // form of the initializer list.
567    if (IList->getInit(OldIndex) != DIE->getInit())
568      DIE->setInit(IList->getInit(OldIndex));
569    IList->setInit(OldIndex, DIE);
570
571    return hadError && !prevHadError;
572  }
573
574  bool IsFirstDesignator = (D == DIE->designators_begin());
575  assert((IsFirstDesignator || StructuredList) &&
576         "Need a non-designated initializer list to start from");
577
578  // Determine the structural initializer list that corresponds to the
579  // current subobject.
580  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
581    : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
582                                 StructuredIndex,
583                                 SourceRange(D->getStartLocation(),
584                                             DIE->getSourceRange().getEnd()));
585  assert(StructuredList && "Expected a structured initializer list");
586
587  if (D->isFieldDesignator()) {
588    // C99 6.7.8p7:
589    //
590    //   If a designator has the form
591    //
592    //      . identifier
593    //
594    //   then the current object (defined below) shall have
595    //   structure or union type and the identifier shall be the
596    //   name of a member of that type.
597    const RecordType *RT = CurrentObjectType->getAsRecordType();
598    if (!RT) {
599      SourceLocation Loc = D->getDotLoc();
600      if (Loc.isInvalid())
601        Loc = D->getFieldLoc();
602      SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
603        << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
604      ++Index;
605      return true;
606    }
607
608    // Note: we perform a linear search of the fields here, despite
609    // the fact that we have a faster lookup method, because we always
610    // need to compute the field's index.
611    IdentifierInfo *FieldName = D->getFieldName();
612    unsigned FieldIndex = 0;
613    RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
614                            FieldEnd = RT->getDecl()->field_end();
615    for (; Field != FieldEnd; ++Field) {
616      if (Field->isUnnamedBitfield())
617        continue;
618
619      if (Field->getIdentifier() == FieldName)
620        break;
621
622      ++FieldIndex;
623    }
624
625    if (Field == FieldEnd) {
626      // We did not find the field we're looking for. Produce a
627      // suitable diagnostic and return a failure.
628      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
629      if (Lookup.first == Lookup.second) {
630        // Name lookup didn't find anything.
631        SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
632          << FieldName << CurrentObjectType;
633      } else {
634        // Name lookup found something, but it wasn't a field.
635        SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
636          << FieldName;
637        SemaRef->Diag((*Lookup.first)->getLocation(),
638                      diag::note_field_designator_found);
639      }
640
641      ++Index;
642      return true;
643    } else if (cast<RecordDecl>((*Field)->getDeclContext())
644                 ->isAnonymousStructOrUnion()) {
645      SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
646        << FieldName
647        << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
648            (int)SemaRef->getLangOptions().CPlusPlus);
649      SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
650      ++Index;
651      return true;
652    }
653
654    // All of the fields of a union are located at the same place in
655    // the initializer list.
656    if (RT->getDecl()->isUnion())
657      FieldIndex = 0;
658
659    // Update the designator with the field declaration.
660    D->setField(*Field);
661
662    // Make sure that our non-designated initializer list has space
663    // for a subobject corresponding to this field.
664    if (FieldIndex >= StructuredList->getNumInits())
665      StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
666
667    // Recurse to check later designated subobjects.
668    QualType FieldType = (*Field)->getType();
669    unsigned newStructuredIndex = FieldIndex;
670    if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
671                                   StructuredList, newStructuredIndex))
672      return true;
673
674    // Find the position of the next field to be initialized in this
675    // subobject.
676    ++Field;
677    ++FieldIndex;
678
679    // If this the first designator, our caller will continue checking
680    // the rest of this struct/class/union subobject.
681    if (IsFirstDesignator) {
682      if (NextField)
683        *NextField = Field;
684      StructuredIndex = FieldIndex;
685      return false;
686    }
687
688    if (!FinishSubobjectInit)
689      return false;
690
691    // Check the remaining fields within this class/struct/union subobject.
692    bool prevHadError = hadError;
693    CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
694                          StructuredList, FieldIndex);
695    return hadError && !prevHadError;
696  }
697
698  // C99 6.7.8p6:
699  //
700  //   If a designator has the form
701  //
702  //      [ constant-expression ]
703  //
704  //   then the current object (defined below) shall have array
705  //   type and the expression shall be an integer constant
706  //   expression. If the array is of unknown size, any
707  //   nonnegative value is valid.
708  //
709  // Additionally, cope with the GNU extension that permits
710  // designators of the form
711  //
712  //      [ constant-expression ... constant-expression ]
713  const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
714  if (!AT) {
715    SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
716      << CurrentObjectType;
717    ++Index;
718    return true;
719  }
720
721  Expr *IndexExpr = 0;
722  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
723  if (D->isArrayDesignator()) {
724    IndexExpr = DIE->getArrayIndex(*D);
725
726    bool ConstExpr
727      = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
728    assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
729
730    DesignatedEndIndex = DesignatedStartIndex;
731  } else {
732    assert(D->isArrayRangeDesignator() && "Need array-range designator");
733
734    bool StartConstExpr
735      = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
736                                                           SemaRef->Context);
737    assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
738
739    bool EndConstExpr
740      = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
741                                                         SemaRef->Context);
742    assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
743
744    IndexExpr = DIE->getArrayRangeEnd(*D);
745
746    if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
747      SemaRef->Diag(D->getEllipsisLoc(),
748                    diag::warn_gnu_array_range_designator_side_effects)
749        << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
750  }
751
752  if (isa<ConstantArrayType>(AT)) {
753    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
754    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
755    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
756    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
757    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
758    if (DesignatedEndIndex >= MaxElements) {
759      SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
760                    diag::err_array_designator_too_large)
761        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
762        << IndexExpr->getSourceRange();
763      ++Index;
764      return true;
765    }
766  } else {
767    // Make sure the bit-widths and signedness match.
768    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
769      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
770    else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
771      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
772    DesignatedStartIndex.setIsUnsigned(true);
773    DesignatedEndIndex.setIsUnsigned(true);
774  }
775
776  // Make sure that our non-designated initializer list has space
777  // for a subobject corresponding to this array element.
778  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
779    StructuredList->resizeInits(SemaRef->Context,
780                                DesignatedEndIndex.getZExtValue() + 1);
781
782  // Repeatedly perform subobject initializations in the range
783  // [DesignatedStartIndex, DesignatedEndIndex].
784
785  // Move to the next designator
786  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
787  unsigned OldIndex = Index;
788  ++D;
789  while (DesignatedStartIndex <= DesignatedEndIndex) {
790    // Recurse to check later designated subobjects.
791    QualType ElementType = AT->getElementType();
792    Index = OldIndex;
793    if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
794                                   StructuredList, ElementIndex,
795                                   (DesignatedStartIndex == DesignatedEndIndex)))
796      return true;
797
798    // Move to the next index in the array that we'll be initializing.
799    ++DesignatedStartIndex;
800    ElementIndex = DesignatedStartIndex.getZExtValue();
801  }
802
803  // If this the first designator, our caller will continue checking
804  // the rest of this array subobject.
805  if (IsFirstDesignator) {
806    if (NextElementIndex)
807      *NextElementIndex = DesignatedStartIndex;
808    StructuredIndex = ElementIndex;
809    return false;
810  }
811
812  if (!FinishSubobjectInit)
813    return false;
814
815  // Check the remaining elements within this array subobject.
816  bool prevHadError = hadError;
817  CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
818                 StructuredList, ElementIndex);
819  return hadError && !prevHadError;
820}
821
822// Get the structured initializer list for a subobject of type
823// @p CurrentObjectType.
824InitListExpr *
825InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
826                                            QualType CurrentObjectType,
827                                            InitListExpr *StructuredList,
828                                            unsigned StructuredIndex,
829                                            SourceRange InitRange) {
830  Expr *ExistingInit = 0;
831  if (!StructuredList)
832    ExistingInit = SyntacticToSemantic[IList];
833  else if (StructuredIndex < StructuredList->getNumInits())
834    ExistingInit = StructuredList->getInit(StructuredIndex);
835
836  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
837    return Result;
838
839  if (ExistingInit) {
840    // We are creating an initializer list that initializes the
841    // subobjects of the current object, but there was already an
842    // initialization that completely initialized the current
843    // subobject, e.g., by a compound literal:
844    //
845    // struct X { int a, b; };
846    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
847    //
848    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
849    // designated initializer re-initializes the whole
850    // subobject [0], overwriting previous initializers.
851    SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
852      << InitRange;
853    SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
854                  diag::note_previous_initializer)
855      << /*FIXME:has side effects=*/0
856      << ExistingInit->getSourceRange();
857  }
858
859  InitListExpr *Result
860    = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
861                                          SourceLocation());
862  Result->setType(CurrentObjectType);
863
864  // Link this new initializer list into the structured initializer
865  // lists.
866  if (StructuredList)
867    StructuredList->updateInit(StructuredIndex, Result);
868  else {
869    Result->setSyntacticForm(IList);
870    SyntacticToSemantic[IList] = Result;
871  }
872
873  return Result;
874}
875
876/// Update the initializer at index @p StructuredIndex within the
877/// structured initializer list to the value @p expr.
878void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
879                                                  unsigned &StructuredIndex,
880                                                  Expr *expr) {
881  // No structured initializer list to update
882  if (!StructuredList)
883    return;
884
885  if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
886    // This initializer overwrites a previous initializer. Warn.
887    SemaRef->Diag(expr->getSourceRange().getBegin(),
888                  diag::warn_initializer_overrides)
889      << expr->getSourceRange();
890    SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
891                  diag::note_previous_initializer)
892      << /*FIXME:has side effects=*/0
893      << PrevInit->getSourceRange();
894  }
895
896  ++StructuredIndex;
897}
898
899/// Check that the given Index expression is a valid array designator
900/// value. This is essentailly just a wrapper around
901/// Expr::isIntegerConstantExpr that also checks for negative values
902/// and produces a reasonable diagnostic if there is a
903/// failure. Returns true if there was an error, false otherwise.  If
904/// everything went okay, Value will receive the value of the constant
905/// expression.
906static bool
907CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
908  SourceLocation Loc = Index->getSourceRange().getBegin();
909
910  // Make sure this is an integer constant expression.
911  if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
912    return Self.Diag(Loc, diag::err_array_designator_nonconstant)
913      << Index->getSourceRange();
914
915  // Make sure this constant expression is non-negative.
916  llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
917                    Value.isUnsigned());
918  if (Value < Zero)
919    return Self.Diag(Loc, diag::err_array_designator_negative)
920      << Value.toString(10) << Index->getSourceRange();
921
922  Value.setIsUnsigned(true);
923  return false;
924}
925
926Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
927                                                        SourceLocation Loc,
928                                                        bool UsedColonSyntax,
929                                                        OwningExprResult Init) {
930  typedef DesignatedInitExpr::Designator ASTDesignator;
931
932  bool Invalid = false;
933  llvm::SmallVector<ASTDesignator, 32> Designators;
934  llvm::SmallVector<Expr *, 32> InitExpressions;
935
936  // Build designators and check array designator expressions.
937  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
938    const Designator &D = Desig.getDesignator(Idx);
939    switch (D.getKind()) {
940    case Designator::FieldDesignator:
941      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
942                                          D.getFieldLoc()));
943      break;
944
945    case Designator::ArrayDesignator: {
946      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
947      llvm::APSInt IndexValue;
948      if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
949        Invalid = true;
950      else {
951        Designators.push_back(ASTDesignator(InitExpressions.size(),
952                                            D.getLBracketLoc(),
953                                            D.getRBracketLoc()));
954        InitExpressions.push_back(Index);
955      }
956      break;
957    }
958
959    case Designator::ArrayRangeDesignator: {
960      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
961      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
962      llvm::APSInt StartValue;
963      llvm::APSInt EndValue;
964      if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
965          CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
966        Invalid = true;
967      else {
968        // Make sure we're comparing values with the same bit width.
969        if (StartValue.getBitWidth() > EndValue.getBitWidth())
970          EndValue.extend(StartValue.getBitWidth());
971        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
972          StartValue.extend(EndValue.getBitWidth());
973
974        if (EndValue < StartValue) {
975          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
976            << StartValue.toString(10) << EndValue.toString(10)
977            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
978          Invalid = true;
979        } else {
980          Designators.push_back(ASTDesignator(InitExpressions.size(),
981                                              D.getLBracketLoc(),
982                                              D.getEllipsisLoc(),
983                                              D.getRBracketLoc()));
984          InitExpressions.push_back(StartIndex);
985          InitExpressions.push_back(EndIndex);
986        }
987      }
988      break;
989    }
990    }
991  }
992
993  if (Invalid || Init.isInvalid())
994    return ExprError();
995
996  // Clear out the expressions within the designation.
997  Desig.ClearExprs(*this);
998
999  DesignatedInitExpr *DIE
1000    = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1001                                 &InitExpressions[0], InitExpressions.size(),
1002                                 Loc, UsedColonSyntax,
1003                                 static_cast<Expr *>(Init.release()));
1004  return Owned(DIE);
1005}
1006