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