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