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