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