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