SemaInit.cpp revision 00874ad5bb1845b7dfa3d39411ecfc09df321ad7
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 "SemaInit.h" 19#include "Sema.h" 20#include "clang/Parse/Designator.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "llvm/Support/ErrorHandling.h" 25#include <map> 26using namespace clang; 27 28//===----------------------------------------------------------------------===// 29// Sema Initialization Checking 30//===----------------------------------------------------------------------===// 31 32static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) { 33 const ArrayType *AT = Context.getAsArrayType(DeclType); 34 if (!AT) return 0; 35 36 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 37 return 0; 38 39 // See if this is a string literal or @encode. 40 Init = Init->IgnoreParens(); 41 42 // Handle @encode, which is a narrow string. 43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 44 return Init; 45 46 // Otherwise we can only handle string literals. 47 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 48 if (SL == 0) return 0; 49 50 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 51 // char array can be initialized with a narrow string. 52 // Only allow char x[] = "foo"; not char x[] = L"foo"; 53 if (!SL->isWide()) 54 return ElemTy->isCharType() ? Init : 0; 55 56 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 57 // correction from DR343): "An array with element type compatible with a 58 // qualified or unqualified version of wchar_t may be initialized by a wide 59 // string literal, optionally enclosed in braces." 60 if (Context.typesAreCompatible(Context.getWCharType(), 61 ElemTy.getUnqualifiedType())) 62 return Init; 63 64 return 0; 65} 66 67static bool CheckSingleInitializer(Expr *&Init, QualType DeclType, 68 bool DirectInit, Sema &S) { 69 // Get the type before calling CheckSingleAssignmentConstraints(), since 70 // it can promote the expression. 71 QualType InitType = Init->getType(); 72 73 if (S.getLangOptions().CPlusPlus) { 74 // FIXME: I dislike this error message. A lot. 75 if (S.PerformImplicitConversion(Init, DeclType, 76 "initializing", DirectInit)) { 77 ImplicitConversionSequence ICS; 78 OverloadCandidateSet CandidateSet; 79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined, 80 CandidateSet, 81 true, false, false) != OR_Ambiguous) 82 return S.Diag(Init->getSourceRange().getBegin(), 83 diag::err_typecheck_convert_incompatible) 84 << DeclType << Init->getType() << "initializing" 85 << Init->getSourceRange(); 86 S.Diag(Init->getSourceRange().getBegin(), 87 diag::err_typecheck_convert_ambiguous) 88 << DeclType << Init->getType() << Init->getSourceRange(); 89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 90 return true; 91 } 92 return false; 93 } 94 95 Sema::AssignConvertType ConvTy = 96 S.CheckSingleAssignmentConstraints(DeclType, Init); 97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 98 InitType, Init, "initializing"); 99} 100 101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) { 102 // Get the length of the string as parsed. 103 uint64_t StrLength = 104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 105 106 107 const ArrayType *AT = S.Context.getAsArrayType(DeclT); 108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 109 // C99 6.7.8p14. We have an array of character type with unknown size 110 // being initialized to a string literal. 111 llvm::APSInt ConstVal(32); 112 ConstVal = StrLength; 113 // Return a new array type (C99 6.7.8p22). 114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 115 ConstVal, 116 ArrayType::Normal, 0); 117 return; 118 } 119 120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 121 122 // C99 6.7.8p14. We have an array of character type with known size. However, 123 // the size may be smaller or larger than the string we are initializing. 124 // FIXME: Avoid truncation for 64-bit length strings. 125 if (StrLength-1 > CAT->getSize().getZExtValue()) 126 S.Diag(Str->getSourceRange().getBegin(), 127 diag::warn_initializer_string_for_char_array_too_long) 128 << Str->getSourceRange(); 129 130 // Set the type to the actual size that we are initializing. If we have 131 // something like: 132 // char x[1] = "foo"; 133 // then this will set the string literal's type to char[1]. 134 Str->setType(DeclT); 135} 136 137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType, 138 SourceLocation InitLoc, 139 DeclarationName InitEntity, bool DirectInit) { 140 if (DeclType->isDependentType() || 141 Init->isTypeDependent() || Init->isValueDependent()) { 142 // We have either a dependent type or a type- or value-dependent 143 // initializer, so we don't perform any additional checking at 144 // this point. 145 146 // If the declaration is a non-dependent, incomplete array type 147 // that has an initializer, then its type will be completed once 148 // the initializer is instantiated. 149 if (!DeclType->isDependentType()) { 150 if (const IncompleteArrayType *ArrayT 151 = Context.getAsIncompleteArrayType(DeclType)) { 152 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 153 if (!ILE->isTypeDependent()) { 154 // Compute the constant array type from the length of the 155 // initializer list. 156 // FIXME: This will be wrong if there are designated 157 // initializations. Good thing they don't exist in C++! 158 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()), 159 ILE->getNumInits()); 160 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0); 161 if (NumElements == Zero) { 162 // Sizing an array implicitly to zero is not allowed by ISO C, 163 // but is supported by GNU. 164 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size); 165 } 166 167 DeclType = Context.getConstantArrayType(ArrayT->getElementType(), 168 NumElements, 169 ArrayT->getSizeModifier(), 170 ArrayT->getIndexTypeCVRQualifiers()); 171 return false; 172 } 173 } 174 175 // Make the array type-dependent by making it dependently-sized. 176 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(), 177 /*NumElts=*/0, 178 ArrayT->getSizeModifier(), 179 ArrayT->getIndexTypeCVRQualifiers(), 180 SourceRange()); 181 } 182 } 183 184 return false; 185 } 186 187 // C++ [dcl.init.ref]p1: 188 // A variable declared to be a T& or T&&, that is "reference to type T" 189 // (8.3.2), shall be initialized by an object, or function, of 190 // type T or by an object that can be converted into a T. 191 if (DeclType->isReferenceType()) 192 return CheckReferenceInit(Init, DeclType, InitLoc, 193 /*SuppressUserConversions=*/false, 194 /*AllowExplicit=*/DirectInit, 195 /*ForceRValue=*/false); 196 197 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 198 // of unknown size ("[]") or an object type that is not a variable array type. 199 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 200 return Diag(InitLoc, diag::err_variable_object_no_init) 201 << VAT->getSizeExpr()->getSourceRange(); 202 203 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 204 if (!InitList) { 205 // FIXME: Handle wide strings 206 if (Expr *Str = IsStringInit(Init, DeclType, Context)) { 207 CheckStringInit(Str, DeclType, *this); 208 return false; 209 } 210 211 // C++ [dcl.init]p14: 212 // -- If the destination type is a (possibly cv-qualified) class 213 // type: 214 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) { 215 QualType DeclTypeC = Context.getCanonicalType(DeclType); 216 QualType InitTypeC = Context.getCanonicalType(Init->getType()); 217 218 // -- If the initialization is direct-initialization, or if it is 219 // copy-initialization where the cv-unqualified version of the 220 // source type is the same class as, or a derived class of, the 221 // class of the destination, constructors are considered. 222 if ((DeclTypeC.getLocalUnqualifiedType() 223 == InitTypeC.getLocalUnqualifiedType()) || 224 IsDerivedFrom(InitTypeC, DeclTypeC)) { 225 const CXXRecordDecl *RD = 226 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl()); 227 228 // No need to make a CXXConstructExpr if both the ctor and dtor are 229 // trivial. 230 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor()) 231 return false; 232 233 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 234 235 // FIXME: Poor location information 236 InitializationKind InitKind 237 = InitializationKind::CreateCopy(Init->getLocStart(), 238 SourceLocation()); 239 if (DirectInit) 240 InitKind = InitializationKind::CreateDirect(Init->getLocStart(), 241 SourceLocation(), 242 SourceLocation()); 243 CXXConstructorDecl *Constructor 244 = PerformInitializationByConstructor(DeclType, 245 MultiExprArg(*this, 246 (void **)&Init, 1), 247 InitLoc, Init->getSourceRange(), 248 InitEntity, InitKind, 249 ConstructorArgs); 250 if (!Constructor) 251 return true; 252 253 OwningExprResult InitResult = 254 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 255 DeclType, Constructor, 256 move_arg(ConstructorArgs)); 257 if (InitResult.isInvalid()) 258 return true; 259 260 Init = InitResult.takeAs<Expr>(); 261 return false; 262 } 263 264 // -- Otherwise (i.e., for the remaining copy-initialization 265 // cases), user-defined conversion sequences that can 266 // convert from the source type to the destination type or 267 // (when a conversion function is used) to a derived class 268 // thereof are enumerated as described in 13.3.1.4, and the 269 // best one is chosen through overload resolution 270 // (13.3). If the conversion cannot be done or is 271 // ambiguous, the initialization is ill-formed. The 272 // function selected is called with the initializer 273 // expression as its argument; if the function is a 274 // constructor, the call initializes a temporary of the 275 // destination type. 276 // FIXME: We're pretending to do copy elision here; return to this when we 277 // have ASTs for such things. 278 if (!PerformImplicitConversion(Init, DeclType, "initializing")) 279 return false; 280 281 if (InitEntity) 282 return Diag(InitLoc, diag::err_cannot_initialize_decl) 283 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid) 284 << Init->getType() << Init->getSourceRange(); 285 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname) 286 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid) 287 << Init->getType() << Init->getSourceRange(); 288 } 289 290 // C99 6.7.8p16. 291 if (DeclType->isArrayType()) 292 return Diag(Init->getLocStart(), diag::err_array_init_list_required) 293 << Init->getSourceRange(); 294 295 return CheckSingleInitializer(Init, DeclType, DirectInit, *this); 296 } 297 298 bool hadError = CheckInitList(InitList, DeclType); 299 Init = InitList; 300 return hadError; 301} 302 303//===----------------------------------------------------------------------===// 304// Semantic checking for initializer lists. 305//===----------------------------------------------------------------------===// 306 307/// @brief Semantic checking for initializer lists. 308/// 309/// The InitListChecker class contains a set of routines that each 310/// handle the initialization of a certain kind of entity, e.g., 311/// arrays, vectors, struct/union types, scalars, etc. The 312/// InitListChecker itself performs a recursive walk of the subobject 313/// structure of the type to be initialized, while stepping through 314/// the initializer list one element at a time. The IList and Index 315/// parameters to each of the Check* routines contain the active 316/// (syntactic) initializer list and the index into that initializer 317/// list that represents the current initializer. Each routine is 318/// responsible for moving that Index forward as it consumes elements. 319/// 320/// Each Check* routine also has a StructuredList/StructuredIndex 321/// arguments, which contains the current the "structured" (semantic) 322/// initializer list and the index into that initializer list where we 323/// are copying initializers as we map them over to the semantic 324/// list. Once we have completed our recursive walk of the subobject 325/// structure, we will have constructed a full semantic initializer 326/// list. 327/// 328/// C99 designators cause changes in the initializer list traversal, 329/// because they make the initialization "jump" into a specific 330/// subobject and then continue the initialization from that 331/// point. CheckDesignatedInitializer() recursively steps into the 332/// designated subobject and manages backing out the recursion to 333/// initialize the subobjects after the one designated. 334namespace { 335class InitListChecker { 336 Sema &SemaRef; 337 bool hadError; 338 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 339 InitListExpr *FullyStructuredList; 340 341 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T, 342 unsigned &Index, InitListExpr *StructuredList, 343 unsigned &StructuredIndex, 344 bool TopLevelObject = false); 345 void CheckExplicitInitList(InitListExpr *IList, QualType &T, 346 unsigned &Index, InitListExpr *StructuredList, 347 unsigned &StructuredIndex, 348 bool TopLevelObject = false); 349 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType, 350 bool SubobjectIsDesignatorContext, 351 unsigned &Index, 352 InitListExpr *StructuredList, 353 unsigned &StructuredIndex, 354 bool TopLevelObject = false); 355 void CheckSubElementType(InitListExpr *IList, QualType ElemType, 356 unsigned &Index, 357 InitListExpr *StructuredList, 358 unsigned &StructuredIndex); 359 void CheckScalarType(InitListExpr *IList, QualType DeclType, 360 unsigned &Index, 361 InitListExpr *StructuredList, 362 unsigned &StructuredIndex); 363 void CheckReferenceType(InitListExpr *IList, QualType DeclType, 364 unsigned &Index, 365 InitListExpr *StructuredList, 366 unsigned &StructuredIndex); 367 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index, 368 InitListExpr *StructuredList, 369 unsigned &StructuredIndex); 370 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType, 371 RecordDecl::field_iterator Field, 372 bool SubobjectIsDesignatorContext, unsigned &Index, 373 InitListExpr *StructuredList, 374 unsigned &StructuredIndex, 375 bool TopLevelObject = false); 376 void CheckArrayType(InitListExpr *IList, QualType &DeclType, 377 llvm::APSInt elementIndex, 378 bool SubobjectIsDesignatorContext, unsigned &Index, 379 InitListExpr *StructuredList, 380 unsigned &StructuredIndex); 381 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE, 382 unsigned DesigIdx, 383 QualType &CurrentObjectType, 384 RecordDecl::field_iterator *NextField, 385 llvm::APSInt *NextElementIndex, 386 unsigned &Index, 387 InitListExpr *StructuredList, 388 unsigned &StructuredIndex, 389 bool FinishSubobjectInit, 390 bool TopLevelObject); 391 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 392 QualType CurrentObjectType, 393 InitListExpr *StructuredList, 394 unsigned StructuredIndex, 395 SourceRange InitRange); 396 void UpdateStructuredListElement(InitListExpr *StructuredList, 397 unsigned &StructuredIndex, 398 Expr *expr); 399 int numArrayElements(QualType DeclType); 400 int numStructUnionElements(QualType DeclType); 401 402 void FillInValueInitializations(InitListExpr *ILE); 403public: 404 InitListChecker(Sema &S, InitListExpr *IL, QualType &T); 405 bool HadError() { return hadError; } 406 407 // @brief Retrieves the fully-structured initializer list used for 408 // semantic analysis and code generation. 409 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 410}; 411} // end anonymous namespace 412 413/// Recursively replaces NULL values within the given initializer list 414/// with expressions that perform value-initialization of the 415/// appropriate type. 416void InitListChecker::FillInValueInitializations(InitListExpr *ILE) { 417 assert((ILE->getType() != SemaRef.Context.VoidTy) && 418 "Should not have void type"); 419 SourceLocation Loc = ILE->getSourceRange().getBegin(); 420 if (ILE->getSyntacticForm()) 421 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 422 423 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 424 unsigned Init = 0, NumInits = ILE->getNumInits(); 425 for (RecordDecl::field_iterator 426 Field = RType->getDecl()->field_begin(), 427 FieldEnd = RType->getDecl()->field_end(); 428 Field != FieldEnd; ++Field) { 429 if (Field->isUnnamedBitfield()) 430 continue; 431 432 if (Init >= NumInits || !ILE->getInit(Init)) { 433 if (Field->getType()->isReferenceType()) { 434 // C++ [dcl.init.aggr]p9: 435 // If an incomplete or empty initializer-list leaves a 436 // member of reference type uninitialized, the program is 437 // ill-formed. 438 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 439 << Field->getType() 440 << ILE->getSyntacticForm()->getSourceRange(); 441 SemaRef.Diag(Field->getLocation(), 442 diag::note_uninit_reference_member); 443 hadError = true; 444 return; 445 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) { 446 hadError = true; 447 return; 448 } 449 450 // FIXME: If value-initialization involves calling a constructor, should 451 // we make that call explicit in the representation (even when it means 452 // extending the initializer list)? 453 if (Init < NumInits && !hadError) 454 ILE->setInit(Init, 455 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType())); 456 } else if (InitListExpr *InnerILE 457 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 458 FillInValueInitializations(InnerILE); 459 ++Init; 460 461 // Only look at the first initialization of a union. 462 if (RType->getDecl()->isUnion()) 463 break; 464 } 465 466 return; 467 } 468 469 QualType ElementType; 470 471 unsigned NumInits = ILE->getNumInits(); 472 unsigned NumElements = NumInits; 473 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 474 ElementType = AType->getElementType(); 475 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 476 NumElements = CAType->getSize().getZExtValue(); 477 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 478 ElementType = VType->getElementType(); 479 NumElements = VType->getNumElements(); 480 } else 481 ElementType = ILE->getType(); 482 483 for (unsigned Init = 0; Init != NumElements; ++Init) { 484 if (Init >= NumInits || !ILE->getInit(Init)) { 485 if (SemaRef.CheckValueInitialization(ElementType, Loc)) { 486 hadError = true; 487 return; 488 } 489 490 // FIXME: If value-initialization involves calling a constructor, should 491 // we make that call explicit in the representation (even when it means 492 // extending the initializer list)? 493 if (Init < NumInits && !hadError) 494 ILE->setInit(Init, 495 new (SemaRef.Context) ImplicitValueInitExpr(ElementType)); 496 } else if (InitListExpr *InnerILE 497 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 498 FillInValueInitializations(InnerILE); 499 } 500} 501 502 503InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T) 504 : SemaRef(S) { 505 hadError = false; 506 507 unsigned newIndex = 0; 508 unsigned newStructuredIndex = 0; 509 FullyStructuredList 510 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 511 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex, 512 /*TopLevelObject=*/true); 513 514 if (!hadError) 515 FillInValueInitializations(FullyStructuredList); 516} 517 518int InitListChecker::numArrayElements(QualType DeclType) { 519 // FIXME: use a proper constant 520 int maxElements = 0x7FFFFFFF; 521 if (const ConstantArrayType *CAT = 522 SemaRef.Context.getAsConstantArrayType(DeclType)) { 523 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 524 } 525 return maxElements; 526} 527 528int InitListChecker::numStructUnionElements(QualType DeclType) { 529 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 530 int InitializableMembers = 0; 531 for (RecordDecl::field_iterator 532 Field = structDecl->field_begin(), 533 FieldEnd = structDecl->field_end(); 534 Field != FieldEnd; ++Field) { 535 if ((*Field)->getIdentifier() || !(*Field)->isBitField()) 536 ++InitializableMembers; 537 } 538 if (structDecl->isUnion()) 539 return std::min(InitializableMembers, 1); 540 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 541} 542 543void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList, 544 QualType T, unsigned &Index, 545 InitListExpr *StructuredList, 546 unsigned &StructuredIndex, 547 bool TopLevelObject) { 548 int maxElements = 0; 549 550 if (T->isArrayType()) 551 maxElements = numArrayElements(T); 552 else if (T->isStructureType() || T->isUnionType()) 553 maxElements = numStructUnionElements(T); 554 else if (T->isVectorType()) 555 maxElements = T->getAs<VectorType>()->getNumElements(); 556 else 557 assert(0 && "CheckImplicitInitList(): Illegal type"); 558 559 if (maxElements == 0) { 560 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 561 diag::err_implicit_empty_initializer); 562 ++Index; 563 hadError = true; 564 return; 565 } 566 567 // Build a structured initializer list corresponding to this subobject. 568 InitListExpr *StructuredSubobjectInitList 569 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 570 StructuredIndex, 571 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 572 ParentIList->getSourceRange().getEnd())); 573 unsigned StructuredSubobjectInitIndex = 0; 574 575 // Check the element types and build the structural subobject. 576 unsigned StartIndex = Index; 577 CheckListElementTypes(ParentIList, T, false, Index, 578 StructuredSubobjectInitList, 579 StructuredSubobjectInitIndex, 580 TopLevelObject); 581 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 582 StructuredSubobjectInitList->setType(T); 583 584 // Update the structured sub-object initializer so that it's ending 585 // range corresponds with the end of the last initializer it used. 586 if (EndIndex < ParentIList->getNumInits()) { 587 SourceLocation EndLoc 588 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 589 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 590 } 591} 592 593void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T, 594 unsigned &Index, 595 InitListExpr *StructuredList, 596 unsigned &StructuredIndex, 597 bool TopLevelObject) { 598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 599 SyntacticToSemantic[IList] = StructuredList; 600 StructuredList->setSyntacticForm(IList); 601 CheckListElementTypes(IList, T, true, Index, StructuredList, 602 StructuredIndex, TopLevelObject); 603 IList->setType(T); 604 StructuredList->setType(T); 605 if (hadError) 606 return; 607 608 if (Index < IList->getNumInits()) { 609 // We have leftover initializers 610 if (StructuredIndex == 1 && 611 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 612 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 613 if (SemaRef.getLangOptions().CPlusPlus) { 614 DK = diag::err_excess_initializers_in_char_array_initializer; 615 hadError = true; 616 } 617 // Special-case 618 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 619 << IList->getInit(Index)->getSourceRange(); 620 } else if (!T->isIncompleteType()) { 621 // Don't complain for incomplete types, since we'll get an error 622 // elsewhere 623 QualType CurrentObjectType = StructuredList->getType(); 624 int initKind = 625 CurrentObjectType->isArrayType()? 0 : 626 CurrentObjectType->isVectorType()? 1 : 627 CurrentObjectType->isScalarType()? 2 : 628 CurrentObjectType->isUnionType()? 3 : 629 4; 630 631 unsigned DK = diag::warn_excess_initializers; 632 if (SemaRef.getLangOptions().CPlusPlus) { 633 DK = diag::err_excess_initializers; 634 hadError = true; 635 } 636 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 637 DK = diag::err_excess_initializers; 638 hadError = true; 639 } 640 641 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 642 << initKind << IList->getInit(Index)->getSourceRange(); 643 } 644 } 645 646 if (T->isScalarType() && !TopLevelObject) 647 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 648 << IList->getSourceRange() 649 << CodeModificationHint::CreateRemoval(IList->getLocStart()) 650 << CodeModificationHint::CreateRemoval(IList->getLocEnd()); 651} 652 653void InitListChecker::CheckListElementTypes(InitListExpr *IList, 654 QualType &DeclType, 655 bool SubobjectIsDesignatorContext, 656 unsigned &Index, 657 InitListExpr *StructuredList, 658 unsigned &StructuredIndex, 659 bool TopLevelObject) { 660 if (DeclType->isScalarType()) { 661 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex); 662 } else if (DeclType->isVectorType()) { 663 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex); 664 } else if (DeclType->isAggregateType()) { 665 if (DeclType->isRecordType()) { 666 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 667 CheckStructUnionTypes(IList, DeclType, RD->field_begin(), 668 SubobjectIsDesignatorContext, Index, 669 StructuredList, StructuredIndex, 670 TopLevelObject); 671 } else if (DeclType->isArrayType()) { 672 llvm::APSInt Zero( 673 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 674 false); 675 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index, 676 StructuredList, StructuredIndex); 677 } else 678 assert(0 && "Aggregate that isn't a structure or array?!"); 679 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 680 // This type is invalid, issue a diagnostic. 681 ++Index; 682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 683 << DeclType; 684 hadError = true; 685 } else if (DeclType->isRecordType()) { 686 // C++ [dcl.init]p14: 687 // [...] If the class is an aggregate (8.5.1), and the initializer 688 // is a brace-enclosed list, see 8.5.1. 689 // 690 // Note: 8.5.1 is handled below; here, we diagnose the case where 691 // we have an initializer list and a destination type that is not 692 // an aggregate. 693 // FIXME: In C++0x, this is yet another form of initialization. 694 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 695 << DeclType << IList->getSourceRange(); 696 hadError = true; 697 } else if (DeclType->isReferenceType()) { 698 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex); 699 } else { 700 // In C, all types are either scalars or aggregates, but 701 // additional handling is needed here for C++ (and possibly others?). 702 assert(0 && "Unsupported initializer type"); 703 } 704} 705 706void InitListChecker::CheckSubElementType(InitListExpr *IList, 707 QualType ElemType, 708 unsigned &Index, 709 InitListExpr *StructuredList, 710 unsigned &StructuredIndex) { 711 Expr *expr = IList->getInit(Index); 712 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 713 unsigned newIndex = 0; 714 unsigned newStructuredIndex = 0; 715 InitListExpr *newStructuredList 716 = getStructuredSubobjectInit(IList, Index, ElemType, 717 StructuredList, StructuredIndex, 718 SubInitList->getSourceRange()); 719 CheckExplicitInitList(SubInitList, ElemType, newIndex, 720 newStructuredList, newStructuredIndex); 721 ++StructuredIndex; 722 ++Index; 723 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) { 724 CheckStringInit(Str, ElemType, SemaRef); 725 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 726 ++Index; 727 } else if (ElemType->isScalarType()) { 728 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex); 729 } else if (ElemType->isReferenceType()) { 730 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex); 731 } else { 732 if (SemaRef.getLangOptions().CPlusPlus) { 733 // C++ [dcl.init.aggr]p12: 734 // All implicit type conversions (clause 4) are considered when 735 // initializing the aggregate member with an ini- tializer from 736 // an initializer-list. If the initializer can initialize a 737 // member, the member is initialized. [...] 738 ImplicitConversionSequence ICS 739 = SemaRef.TryCopyInitialization(expr, ElemType, 740 /*SuppressUserConversions=*/false, 741 /*ForceRValue=*/false, 742 /*InOverloadResolution=*/false); 743 744 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) { 745 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS, 746 "initializing")) 747 hadError = true; 748 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 749 ++Index; 750 return; 751 } 752 753 // Fall through for subaggregate initialization 754 } else { 755 // C99 6.7.8p13: 756 // 757 // The initializer for a structure or union object that has 758 // automatic storage duration shall be either an initializer 759 // list as described below, or a single expression that has 760 // compatible structure or union type. In the latter case, the 761 // initial value of the object, including unnamed members, is 762 // that of the expression. 763 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 764 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) { 765 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 766 ++Index; 767 return; 768 } 769 770 // Fall through for subaggregate initialization 771 } 772 773 // C++ [dcl.init.aggr]p12: 774 // 775 // [...] Otherwise, if the member is itself a non-empty 776 // subaggregate, brace elision is assumed and the initializer is 777 // considered for the initialization of the first member of 778 // the subaggregate. 779 if (ElemType->isAggregateType() || ElemType->isVectorType()) { 780 CheckImplicitInitList(IList, ElemType, Index, StructuredList, 781 StructuredIndex); 782 ++StructuredIndex; 783 } else { 784 // We cannot initialize this element, so let 785 // PerformCopyInitialization produce the appropriate diagnostic. 786 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing"); 787 hadError = true; 788 ++Index; 789 ++StructuredIndex; 790 } 791 } 792} 793 794void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType, 795 unsigned &Index, 796 InitListExpr *StructuredList, 797 unsigned &StructuredIndex) { 798 if (Index < IList->getNumInits()) { 799 Expr *expr = IList->getInit(Index); 800 if (isa<InitListExpr>(expr)) { 801 SemaRef.Diag(IList->getLocStart(), 802 diag::err_many_braces_around_scalar_init) 803 << IList->getSourceRange(); 804 hadError = true; 805 ++Index; 806 ++StructuredIndex; 807 return; 808 } else if (isa<DesignatedInitExpr>(expr)) { 809 SemaRef.Diag(expr->getSourceRange().getBegin(), 810 diag::err_designator_for_scalar_init) 811 << DeclType << expr->getSourceRange(); 812 hadError = true; 813 ++Index; 814 ++StructuredIndex; 815 return; 816 } 817 818 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 819 if (CheckSingleInitializer(expr, DeclType, false, SemaRef)) 820 hadError = true; // types weren't compatible. 821 else if (savExpr != expr) { 822 // The type was promoted, update initializer list. 823 IList->setInit(Index, expr); 824 } 825 if (hadError) 826 ++StructuredIndex; 827 else 828 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 829 ++Index; 830 } else { 831 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) 832 << IList->getSourceRange(); 833 hadError = true; 834 ++Index; 835 ++StructuredIndex; 836 return; 837 } 838} 839 840void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType, 841 unsigned &Index, 842 InitListExpr *StructuredList, 843 unsigned &StructuredIndex) { 844 if (Index < IList->getNumInits()) { 845 Expr *expr = IList->getInit(Index); 846 if (isa<InitListExpr>(expr)) { 847 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 848 << DeclType << IList->getSourceRange(); 849 hadError = true; 850 ++Index; 851 ++StructuredIndex; 852 return; 853 } 854 855 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 856 if (SemaRef.CheckReferenceInit(expr, DeclType, 857 /*FIXME:*/expr->getLocStart(), 858 /*SuppressUserConversions=*/false, 859 /*AllowExplicit=*/false, 860 /*ForceRValue=*/false)) 861 hadError = true; 862 else if (savExpr != expr) { 863 // The type was promoted, update initializer list. 864 IList->setInit(Index, expr); 865 } 866 if (hadError) 867 ++StructuredIndex; 868 else 869 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 870 ++Index; 871 } else { 872 // FIXME: It would be wonderful if we could point at the actual member. In 873 // general, it would be useful to pass location information down the stack, 874 // so that we know the location (or decl) of the "current object" being 875 // initialized. 876 SemaRef.Diag(IList->getLocStart(), 877 diag::err_init_reference_member_uninitialized) 878 << DeclType 879 << IList->getSourceRange(); 880 hadError = true; 881 ++Index; 882 ++StructuredIndex; 883 return; 884 } 885} 886 887void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType, 888 unsigned &Index, 889 InitListExpr *StructuredList, 890 unsigned &StructuredIndex) { 891 if (Index < IList->getNumInits()) { 892 const VectorType *VT = DeclType->getAs<VectorType>(); 893 unsigned maxElements = VT->getNumElements(); 894 unsigned numEltsInit = 0; 895 QualType elementType = VT->getElementType(); 896 897 if (!SemaRef.getLangOptions().OpenCL) { 898 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 899 // Don't attempt to go past the end of the init list 900 if (Index >= IList->getNumInits()) 901 break; 902 CheckSubElementType(IList, elementType, Index, 903 StructuredList, StructuredIndex); 904 } 905 } else { 906 // OpenCL initializers allows vectors to be constructed from vectors. 907 for (unsigned i = 0; i < maxElements; ++i) { 908 // Don't attempt to go past the end of the init list 909 if (Index >= IList->getNumInits()) 910 break; 911 QualType IType = IList->getInit(Index)->getType(); 912 if (!IType->isVectorType()) { 913 CheckSubElementType(IList, elementType, Index, 914 StructuredList, StructuredIndex); 915 ++numEltsInit; 916 } else { 917 const VectorType *IVT = IType->getAs<VectorType>(); 918 unsigned numIElts = IVT->getNumElements(); 919 QualType VecType = SemaRef.Context.getExtVectorType(elementType, 920 numIElts); 921 CheckSubElementType(IList, VecType, Index, 922 StructuredList, StructuredIndex); 923 numEltsInit += numIElts; 924 } 925 } 926 } 927 928 // OpenCL & AltiVec require all elements to be initialized. 929 if (numEltsInit != maxElements) 930 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec) 931 SemaRef.Diag(IList->getSourceRange().getBegin(), 932 diag::err_vector_incorrect_num_initializers) 933 << (numEltsInit < maxElements) << maxElements << numEltsInit; 934 } 935} 936 937void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType, 938 llvm::APSInt elementIndex, 939 bool SubobjectIsDesignatorContext, 940 unsigned &Index, 941 InitListExpr *StructuredList, 942 unsigned &StructuredIndex) { 943 // Check for the special-case of initializing an array with a string. 944 if (Index < IList->getNumInits()) { 945 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType, 946 SemaRef.Context)) { 947 CheckStringInit(Str, DeclType, SemaRef); 948 // We place the string literal directly into the resulting 949 // initializer list. This is the only place where the structure 950 // of the structured initializer list doesn't match exactly, 951 // because doing so would involve allocating one character 952 // constant for each string. 953 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 954 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 955 ++Index; 956 return; 957 } 958 } 959 if (const VariableArrayType *VAT = 960 SemaRef.Context.getAsVariableArrayType(DeclType)) { 961 // Check for VLAs; in standard C it would be possible to check this 962 // earlier, but I don't know where clang accepts VLAs (gcc accepts 963 // them in all sorts of strange places). 964 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 965 diag::err_variable_object_no_init) 966 << VAT->getSizeExpr()->getSourceRange(); 967 hadError = true; 968 ++Index; 969 ++StructuredIndex; 970 return; 971 } 972 973 // We might know the maximum number of elements in advance. 974 llvm::APSInt maxElements(elementIndex.getBitWidth(), 975 elementIndex.isUnsigned()); 976 bool maxElementsKnown = false; 977 if (const ConstantArrayType *CAT = 978 SemaRef.Context.getAsConstantArrayType(DeclType)) { 979 maxElements = CAT->getSize(); 980 elementIndex.extOrTrunc(maxElements.getBitWidth()); 981 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 982 maxElementsKnown = true; 983 } 984 985 QualType elementType = SemaRef.Context.getAsArrayType(DeclType) 986 ->getElementType(); 987 while (Index < IList->getNumInits()) { 988 Expr *Init = IList->getInit(Index); 989 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 990 // If we're not the subobject that matches up with the '{' for 991 // the designator, we shouldn't be handling the 992 // designator. Return immediately. 993 if (!SubobjectIsDesignatorContext) 994 return; 995 996 // Handle this designated initializer. elementIndex will be 997 // updated to be the next array element we'll initialize. 998 if (CheckDesignatedInitializer(IList, DIE, 0, 999 DeclType, 0, &elementIndex, Index, 1000 StructuredList, StructuredIndex, true, 1001 false)) { 1002 hadError = true; 1003 continue; 1004 } 1005 1006 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1007 maxElements.extend(elementIndex.getBitWidth()); 1008 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1009 elementIndex.extend(maxElements.getBitWidth()); 1010 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1011 1012 // If the array is of incomplete type, keep track of the number of 1013 // elements in the initializer. 1014 if (!maxElementsKnown && elementIndex > maxElements) 1015 maxElements = elementIndex; 1016 1017 continue; 1018 } 1019 1020 // If we know the maximum number of elements, and we've already 1021 // hit it, stop consuming elements in the initializer list. 1022 if (maxElementsKnown && elementIndex == maxElements) 1023 break; 1024 1025 // Check this element. 1026 CheckSubElementType(IList, elementType, Index, 1027 StructuredList, StructuredIndex); 1028 ++elementIndex; 1029 1030 // If the array is of incomplete type, keep track of the number of 1031 // elements in the initializer. 1032 if (!maxElementsKnown && elementIndex > maxElements) 1033 maxElements = elementIndex; 1034 } 1035 if (!hadError && DeclType->isIncompleteArrayType()) { 1036 // If this is an incomplete array type, the actual type needs to 1037 // be calculated here. 1038 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1039 if (maxElements == Zero) { 1040 // Sizing an array implicitly to zero is not allowed by ISO C, 1041 // but is supported by GNU. 1042 SemaRef.Diag(IList->getLocStart(), 1043 diag::ext_typecheck_zero_array_size); 1044 } 1045 1046 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1047 ArrayType::Normal, 0); 1048 } 1049} 1050 1051void InitListChecker::CheckStructUnionTypes(InitListExpr *IList, 1052 QualType DeclType, 1053 RecordDecl::field_iterator Field, 1054 bool SubobjectIsDesignatorContext, 1055 unsigned &Index, 1056 InitListExpr *StructuredList, 1057 unsigned &StructuredIndex, 1058 bool TopLevelObject) { 1059 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 1060 1061 // If the record is invalid, some of it's members are invalid. To avoid 1062 // confusion, we forgo checking the intializer for the entire record. 1063 if (structDecl->isInvalidDecl()) { 1064 hadError = true; 1065 return; 1066 } 1067 1068 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1069 // Value-initialize the first named member of the union. 1070 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1071 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1072 Field != FieldEnd; ++Field) { 1073 if (Field->getDeclName()) { 1074 StructuredList->setInitializedFieldInUnion(*Field); 1075 break; 1076 } 1077 } 1078 return; 1079 } 1080 1081 // If structDecl is a forward declaration, this loop won't do 1082 // anything except look at designated initializers; That's okay, 1083 // because an error should get printed out elsewhere. It might be 1084 // worthwhile to skip over the rest of the initializer, though. 1085 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1086 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1087 bool InitializedSomething = false; 1088 while (Index < IList->getNumInits()) { 1089 Expr *Init = IList->getInit(Index); 1090 1091 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1092 // If we're not the subobject that matches up with the '{' for 1093 // the designator, we shouldn't be handling the 1094 // designator. Return immediately. 1095 if (!SubobjectIsDesignatorContext) 1096 return; 1097 1098 // Handle this designated initializer. Field will be updated to 1099 // the next field that we'll be initializing. 1100 if (CheckDesignatedInitializer(IList, DIE, 0, 1101 DeclType, &Field, 0, Index, 1102 StructuredList, StructuredIndex, 1103 true, TopLevelObject)) 1104 hadError = true; 1105 1106 InitializedSomething = true; 1107 continue; 1108 } 1109 1110 if (Field == FieldEnd) { 1111 // We've run out of fields. We're done. 1112 break; 1113 } 1114 1115 // We've already initialized a member of a union. We're done. 1116 if (InitializedSomething && DeclType->isUnionType()) 1117 break; 1118 1119 // If we've hit the flexible array member at the end, we're done. 1120 if (Field->getType()->isIncompleteArrayType()) 1121 break; 1122 1123 if (Field->isUnnamedBitfield()) { 1124 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1125 ++Field; 1126 continue; 1127 } 1128 1129 CheckSubElementType(IList, Field->getType(), Index, 1130 StructuredList, StructuredIndex); 1131 InitializedSomething = true; 1132 1133 if (DeclType->isUnionType()) { 1134 // Initialize the first field within the union. 1135 StructuredList->setInitializedFieldInUnion(*Field); 1136 } 1137 1138 ++Field; 1139 } 1140 1141 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1142 Index >= IList->getNumInits()) 1143 return; 1144 1145 // Handle GNU flexible array initializers. 1146 if (!TopLevelObject && 1147 (!isa<InitListExpr>(IList->getInit(Index)) || 1148 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1149 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1150 diag::err_flexible_array_init_nonempty) 1151 << IList->getInit(Index)->getSourceRange().getBegin(); 1152 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1153 << *Field; 1154 hadError = true; 1155 ++Index; 1156 return; 1157 } else { 1158 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1159 diag::ext_flexible_array_init) 1160 << IList->getInit(Index)->getSourceRange().getBegin(); 1161 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1162 << *Field; 1163 } 1164 1165 if (isa<InitListExpr>(IList->getInit(Index))) 1166 CheckSubElementType(IList, Field->getType(), Index, StructuredList, 1167 StructuredIndex); 1168 else 1169 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList, 1170 StructuredIndex); 1171} 1172 1173/// \brief Expand a field designator that refers to a member of an 1174/// anonymous struct or union into a series of field designators that 1175/// refers to the field within the appropriate subobject. 1176/// 1177/// Field/FieldIndex will be updated to point to the (new) 1178/// currently-designated field. 1179static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1180 DesignatedInitExpr *DIE, 1181 unsigned DesigIdx, 1182 FieldDecl *Field, 1183 RecordDecl::field_iterator &FieldIter, 1184 unsigned &FieldIndex) { 1185 typedef DesignatedInitExpr::Designator Designator; 1186 1187 // Build the path from the current object to the member of the 1188 // anonymous struct/union (backwards). 1189 llvm::SmallVector<FieldDecl *, 4> Path; 1190 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path); 1191 1192 // Build the replacement designators. 1193 llvm::SmallVector<Designator, 4> Replacements; 1194 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 1195 FI = Path.rbegin(), FIEnd = Path.rend(); 1196 FI != FIEnd; ++FI) { 1197 if (FI + 1 == FIEnd) 1198 Replacements.push_back(Designator((IdentifierInfo *)0, 1199 DIE->getDesignator(DesigIdx)->getDotLoc(), 1200 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1201 else 1202 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1203 SourceLocation())); 1204 Replacements.back().setField(*FI); 1205 } 1206 1207 // Expand the current designator into the set of replacement 1208 // designators, so we have a full subobject path down to where the 1209 // member of the anonymous struct/union is actually stored. 1210 DIE->ExpandDesignator(DesigIdx, &Replacements[0], 1211 &Replacements[0] + Replacements.size()); 1212 1213 // Update FieldIter/FieldIndex; 1214 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext()); 1215 FieldIter = Record->field_begin(); 1216 FieldIndex = 0; 1217 for (RecordDecl::field_iterator FEnd = Record->field_end(); 1218 FieldIter != FEnd; ++FieldIter) { 1219 if (FieldIter->isUnnamedBitfield()) 1220 continue; 1221 1222 if (*FieldIter == Path.back()) 1223 return; 1224 1225 ++FieldIndex; 1226 } 1227 1228 assert(false && "Unable to find anonymous struct/union field"); 1229} 1230 1231/// @brief Check the well-formedness of a C99 designated initializer. 1232/// 1233/// Determines whether the designated initializer @p DIE, which 1234/// resides at the given @p Index within the initializer list @p 1235/// IList, is well-formed for a current object of type @p DeclType 1236/// (C99 6.7.8). The actual subobject that this designator refers to 1237/// within the current subobject is returned in either 1238/// @p NextField or @p NextElementIndex (whichever is appropriate). 1239/// 1240/// @param IList The initializer list in which this designated 1241/// initializer occurs. 1242/// 1243/// @param DIE The designated initializer expression. 1244/// 1245/// @param DesigIdx The index of the current designator. 1246/// 1247/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1248/// into which the designation in @p DIE should refer. 1249/// 1250/// @param NextField If non-NULL and the first designator in @p DIE is 1251/// a field, this will be set to the field declaration corresponding 1252/// to the field named by the designator. 1253/// 1254/// @param NextElementIndex If non-NULL and the first designator in @p 1255/// DIE is an array designator or GNU array-range designator, this 1256/// will be set to the last index initialized by this designator. 1257/// 1258/// @param Index Index into @p IList where the designated initializer 1259/// @p DIE occurs. 1260/// 1261/// @param StructuredList The initializer list expression that 1262/// describes all of the subobject initializers in the order they'll 1263/// actually be initialized. 1264/// 1265/// @returns true if there was an error, false otherwise. 1266bool 1267InitListChecker::CheckDesignatedInitializer(InitListExpr *IList, 1268 DesignatedInitExpr *DIE, 1269 unsigned DesigIdx, 1270 QualType &CurrentObjectType, 1271 RecordDecl::field_iterator *NextField, 1272 llvm::APSInt *NextElementIndex, 1273 unsigned &Index, 1274 InitListExpr *StructuredList, 1275 unsigned &StructuredIndex, 1276 bool FinishSubobjectInit, 1277 bool TopLevelObject) { 1278 if (DesigIdx == DIE->size()) { 1279 // Check the actual initialization for the designated object type. 1280 bool prevHadError = hadError; 1281 1282 // Temporarily remove the designator expression from the 1283 // initializer list that the child calls see, so that we don't try 1284 // to re-process the designator. 1285 unsigned OldIndex = Index; 1286 IList->setInit(OldIndex, DIE->getInit()); 1287 1288 CheckSubElementType(IList, CurrentObjectType, Index, 1289 StructuredList, StructuredIndex); 1290 1291 // Restore the designated initializer expression in the syntactic 1292 // form of the initializer list. 1293 if (IList->getInit(OldIndex) != DIE->getInit()) 1294 DIE->setInit(IList->getInit(OldIndex)); 1295 IList->setInit(OldIndex, DIE); 1296 1297 return hadError && !prevHadError; 1298 } 1299 1300 bool IsFirstDesignator = (DesigIdx == 0); 1301 assert((IsFirstDesignator || StructuredList) && 1302 "Need a non-designated initializer list to start from"); 1303 1304 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1305 // Determine the structural initializer list that corresponds to the 1306 // current subobject. 1307 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1308 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1309 StructuredList, StructuredIndex, 1310 SourceRange(D->getStartLocation(), 1311 DIE->getSourceRange().getEnd())); 1312 assert(StructuredList && "Expected a structured initializer list"); 1313 1314 if (D->isFieldDesignator()) { 1315 // C99 6.7.8p7: 1316 // 1317 // If a designator has the form 1318 // 1319 // . identifier 1320 // 1321 // then the current object (defined below) shall have 1322 // structure or union type and the identifier shall be the 1323 // name of a member of that type. 1324 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1325 if (!RT) { 1326 SourceLocation Loc = D->getDotLoc(); 1327 if (Loc.isInvalid()) 1328 Loc = D->getFieldLoc(); 1329 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1330 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1331 ++Index; 1332 return true; 1333 } 1334 1335 // Note: we perform a linear search of the fields here, despite 1336 // the fact that we have a faster lookup method, because we always 1337 // need to compute the field's index. 1338 FieldDecl *KnownField = D->getField(); 1339 IdentifierInfo *FieldName = D->getFieldName(); 1340 unsigned FieldIndex = 0; 1341 RecordDecl::field_iterator 1342 Field = RT->getDecl()->field_begin(), 1343 FieldEnd = RT->getDecl()->field_end(); 1344 for (; Field != FieldEnd; ++Field) { 1345 if (Field->isUnnamedBitfield()) 1346 continue; 1347 1348 if (KnownField == *Field || Field->getIdentifier() == FieldName) 1349 break; 1350 1351 ++FieldIndex; 1352 } 1353 1354 if (Field == FieldEnd) { 1355 // There was no normal field in the struct with the designated 1356 // name. Perform another lookup for this name, which may find 1357 // something that we can't designate (e.g., a member function), 1358 // may find nothing, or may find a member of an anonymous 1359 // struct/union. 1360 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1361 if (Lookup.first == Lookup.second) { 1362 // Name lookup didn't find anything. 1363 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1364 << FieldName << CurrentObjectType; 1365 ++Index; 1366 return true; 1367 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) && 1368 cast<RecordDecl>((*Lookup.first)->getDeclContext()) 1369 ->isAnonymousStructOrUnion()) { 1370 // Handle an field designator that refers to a member of an 1371 // anonymous struct or union. 1372 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, 1373 cast<FieldDecl>(*Lookup.first), 1374 Field, FieldIndex); 1375 D = DIE->getDesignator(DesigIdx); 1376 } else { 1377 // Name lookup found something, but it wasn't a field. 1378 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1379 << FieldName; 1380 SemaRef.Diag((*Lookup.first)->getLocation(), 1381 diag::note_field_designator_found); 1382 ++Index; 1383 return true; 1384 } 1385 } else if (!KnownField && 1386 cast<RecordDecl>((*Field)->getDeclContext()) 1387 ->isAnonymousStructOrUnion()) { 1388 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field, 1389 Field, FieldIndex); 1390 D = DIE->getDesignator(DesigIdx); 1391 } 1392 1393 // All of the fields of a union are located at the same place in 1394 // the initializer list. 1395 if (RT->getDecl()->isUnion()) { 1396 FieldIndex = 0; 1397 StructuredList->setInitializedFieldInUnion(*Field); 1398 } 1399 1400 // Update the designator with the field declaration. 1401 D->setField(*Field); 1402 1403 // Make sure that our non-designated initializer list has space 1404 // for a subobject corresponding to this field. 1405 if (FieldIndex >= StructuredList->getNumInits()) 1406 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1407 1408 // This designator names a flexible array member. 1409 if (Field->getType()->isIncompleteArrayType()) { 1410 bool Invalid = false; 1411 if ((DesigIdx + 1) != DIE->size()) { 1412 // We can't designate an object within the flexible array 1413 // member (because GCC doesn't allow it). 1414 DesignatedInitExpr::Designator *NextD 1415 = DIE->getDesignator(DesigIdx + 1); 1416 SemaRef.Diag(NextD->getStartLocation(), 1417 diag::err_designator_into_flexible_array_member) 1418 << SourceRange(NextD->getStartLocation(), 1419 DIE->getSourceRange().getEnd()); 1420 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1421 << *Field; 1422 Invalid = true; 1423 } 1424 1425 if (!hadError && !isa<InitListExpr>(DIE->getInit())) { 1426 // The initializer is not an initializer list. 1427 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1428 diag::err_flexible_array_init_needs_braces) 1429 << DIE->getInit()->getSourceRange(); 1430 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1431 << *Field; 1432 Invalid = true; 1433 } 1434 1435 // Handle GNU flexible array initializers. 1436 if (!Invalid && !TopLevelObject && 1437 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1438 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1439 diag::err_flexible_array_init_nonempty) 1440 << DIE->getSourceRange().getBegin(); 1441 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1442 << *Field; 1443 Invalid = true; 1444 } 1445 1446 if (Invalid) { 1447 ++Index; 1448 return true; 1449 } 1450 1451 // Initialize the array. 1452 bool prevHadError = hadError; 1453 unsigned newStructuredIndex = FieldIndex; 1454 unsigned OldIndex = Index; 1455 IList->setInit(Index, DIE->getInit()); 1456 CheckSubElementType(IList, Field->getType(), Index, 1457 StructuredList, newStructuredIndex); 1458 IList->setInit(OldIndex, DIE); 1459 if (hadError && !prevHadError) { 1460 ++Field; 1461 ++FieldIndex; 1462 if (NextField) 1463 *NextField = Field; 1464 StructuredIndex = FieldIndex; 1465 return true; 1466 } 1467 } else { 1468 // Recurse to check later designated subobjects. 1469 QualType FieldType = (*Field)->getType(); 1470 unsigned newStructuredIndex = FieldIndex; 1471 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0, 1472 Index, StructuredList, newStructuredIndex, 1473 true, false)) 1474 return true; 1475 } 1476 1477 // Find the position of the next field to be initialized in this 1478 // subobject. 1479 ++Field; 1480 ++FieldIndex; 1481 1482 // If this the first designator, our caller will continue checking 1483 // the rest of this struct/class/union subobject. 1484 if (IsFirstDesignator) { 1485 if (NextField) 1486 *NextField = Field; 1487 StructuredIndex = FieldIndex; 1488 return false; 1489 } 1490 1491 if (!FinishSubobjectInit) 1492 return false; 1493 1494 // We've already initialized something in the union; we're done. 1495 if (RT->getDecl()->isUnion()) 1496 return hadError; 1497 1498 // Check the remaining fields within this class/struct/union subobject. 1499 bool prevHadError = hadError; 1500 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index, 1501 StructuredList, FieldIndex); 1502 return hadError && !prevHadError; 1503 } 1504 1505 // C99 6.7.8p6: 1506 // 1507 // If a designator has the form 1508 // 1509 // [ constant-expression ] 1510 // 1511 // then the current object (defined below) shall have array 1512 // type and the expression shall be an integer constant 1513 // expression. If the array is of unknown size, any 1514 // nonnegative value is valid. 1515 // 1516 // Additionally, cope with the GNU extension that permits 1517 // designators of the form 1518 // 1519 // [ constant-expression ... constant-expression ] 1520 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1521 if (!AT) { 1522 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1523 << CurrentObjectType; 1524 ++Index; 1525 return true; 1526 } 1527 1528 Expr *IndexExpr = 0; 1529 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1530 if (D->isArrayDesignator()) { 1531 IndexExpr = DIE->getArrayIndex(*D); 1532 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1533 DesignatedEndIndex = DesignatedStartIndex; 1534 } else { 1535 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1536 1537 1538 DesignatedStartIndex = 1539 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1540 DesignatedEndIndex = 1541 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1542 IndexExpr = DIE->getArrayRangeEnd(*D); 1543 1544 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue()) 1545 FullyStructuredList->sawArrayRangeDesignator(); 1546 } 1547 1548 if (isa<ConstantArrayType>(AT)) { 1549 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1550 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1551 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1552 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1553 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1554 if (DesignatedEndIndex >= MaxElements) { 1555 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1556 diag::err_array_designator_too_large) 1557 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1558 << IndexExpr->getSourceRange(); 1559 ++Index; 1560 return true; 1561 } 1562 } else { 1563 // Make sure the bit-widths and signedness match. 1564 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1565 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1566 else if (DesignatedStartIndex.getBitWidth() < 1567 DesignatedEndIndex.getBitWidth()) 1568 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1569 DesignatedStartIndex.setIsUnsigned(true); 1570 DesignatedEndIndex.setIsUnsigned(true); 1571 } 1572 1573 // Make sure that our non-designated initializer list has space 1574 // for a subobject corresponding to this array element. 1575 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1576 StructuredList->resizeInits(SemaRef.Context, 1577 DesignatedEndIndex.getZExtValue() + 1); 1578 1579 // Repeatedly perform subobject initializations in the range 1580 // [DesignatedStartIndex, DesignatedEndIndex]. 1581 1582 // Move to the next designator 1583 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1584 unsigned OldIndex = Index; 1585 while (DesignatedStartIndex <= DesignatedEndIndex) { 1586 // Recurse to check later designated subobjects. 1587 QualType ElementType = AT->getElementType(); 1588 Index = OldIndex; 1589 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0, 1590 Index, StructuredList, ElementIndex, 1591 (DesignatedStartIndex == DesignatedEndIndex), 1592 false)) 1593 return true; 1594 1595 // Move to the next index in the array that we'll be initializing. 1596 ++DesignatedStartIndex; 1597 ElementIndex = DesignatedStartIndex.getZExtValue(); 1598 } 1599 1600 // If this the first designator, our caller will continue checking 1601 // the rest of this array subobject. 1602 if (IsFirstDesignator) { 1603 if (NextElementIndex) 1604 *NextElementIndex = DesignatedStartIndex; 1605 StructuredIndex = ElementIndex; 1606 return false; 1607 } 1608 1609 if (!FinishSubobjectInit) 1610 return false; 1611 1612 // Check the remaining elements within this array subobject. 1613 bool prevHadError = hadError; 1614 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index, 1615 StructuredList, ElementIndex); 1616 return hadError && !prevHadError; 1617} 1618 1619// Get the structured initializer list for a subobject of type 1620// @p CurrentObjectType. 1621InitListExpr * 1622InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1623 QualType CurrentObjectType, 1624 InitListExpr *StructuredList, 1625 unsigned StructuredIndex, 1626 SourceRange InitRange) { 1627 Expr *ExistingInit = 0; 1628 if (!StructuredList) 1629 ExistingInit = SyntacticToSemantic[IList]; 1630 else if (StructuredIndex < StructuredList->getNumInits()) 1631 ExistingInit = StructuredList->getInit(StructuredIndex); 1632 1633 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1634 return Result; 1635 1636 if (ExistingInit) { 1637 // We are creating an initializer list that initializes the 1638 // subobjects of the current object, but there was already an 1639 // initialization that completely initialized the current 1640 // subobject, e.g., by a compound literal: 1641 // 1642 // struct X { int a, b; }; 1643 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1644 // 1645 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1646 // designated initializer re-initializes the whole 1647 // subobject [0], overwriting previous initializers. 1648 SemaRef.Diag(InitRange.getBegin(), 1649 diag::warn_subobject_initializer_overrides) 1650 << InitRange; 1651 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1652 diag::note_previous_initializer) 1653 << /*FIXME:has side effects=*/0 1654 << ExistingInit->getSourceRange(); 1655 } 1656 1657 InitListExpr *Result 1658 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0, 1659 InitRange.getEnd()); 1660 1661 Result->setType(CurrentObjectType); 1662 1663 // Pre-allocate storage for the structured initializer list. 1664 unsigned NumElements = 0; 1665 unsigned NumInits = 0; 1666 if (!StructuredList) 1667 NumInits = IList->getNumInits(); 1668 else if (Index < IList->getNumInits()) { 1669 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) 1670 NumInits = SubList->getNumInits(); 1671 } 1672 1673 if (const ArrayType *AType 1674 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1675 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1676 NumElements = CAType->getSize().getZExtValue(); 1677 // Simple heuristic so that we don't allocate a very large 1678 // initializer with many empty entries at the end. 1679 if (NumInits && NumElements > NumInits) 1680 NumElements = 0; 1681 } 1682 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 1683 NumElements = VType->getNumElements(); 1684 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1685 RecordDecl *RDecl = RType->getDecl(); 1686 if (RDecl->isUnion()) 1687 NumElements = 1; 1688 else 1689 NumElements = std::distance(RDecl->field_begin(), 1690 RDecl->field_end()); 1691 } 1692 1693 if (NumElements < NumInits) 1694 NumElements = IList->getNumInits(); 1695 1696 Result->reserveInits(NumElements); 1697 1698 // Link this new initializer list into the structured initializer 1699 // lists. 1700 if (StructuredList) 1701 StructuredList->updateInit(StructuredIndex, Result); 1702 else { 1703 Result->setSyntacticForm(IList); 1704 SyntacticToSemantic[IList] = Result; 1705 } 1706 1707 return Result; 1708} 1709 1710/// Update the initializer at index @p StructuredIndex within the 1711/// structured initializer list to the value @p expr. 1712void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1713 unsigned &StructuredIndex, 1714 Expr *expr) { 1715 // No structured initializer list to update 1716 if (!StructuredList) 1717 return; 1718 1719 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) { 1720 // This initializer overwrites a previous initializer. Warn. 1721 SemaRef.Diag(expr->getSourceRange().getBegin(), 1722 diag::warn_initializer_overrides) 1723 << expr->getSourceRange(); 1724 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1725 diag::note_previous_initializer) 1726 << /*FIXME:has side effects=*/0 1727 << PrevInit->getSourceRange(); 1728 } 1729 1730 ++StructuredIndex; 1731} 1732 1733/// Check that the given Index expression is a valid array designator 1734/// value. This is essentailly just a wrapper around 1735/// VerifyIntegerConstantExpression that also checks for negative values 1736/// and produces a reasonable diagnostic if there is a 1737/// failure. Returns true if there was an error, false otherwise. If 1738/// everything went okay, Value will receive the value of the constant 1739/// expression. 1740static bool 1741CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1742 SourceLocation Loc = Index->getSourceRange().getBegin(); 1743 1744 // Make sure this is an integer constant expression. 1745 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1746 return true; 1747 1748 if (Value.isSigned() && Value.isNegative()) 1749 return S.Diag(Loc, diag::err_array_designator_negative) 1750 << Value.toString(10) << Index->getSourceRange(); 1751 1752 Value.setIsUnsigned(true); 1753 return false; 1754} 1755 1756Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1757 SourceLocation Loc, 1758 bool GNUSyntax, 1759 OwningExprResult Init) { 1760 typedef DesignatedInitExpr::Designator ASTDesignator; 1761 1762 bool Invalid = false; 1763 llvm::SmallVector<ASTDesignator, 32> Designators; 1764 llvm::SmallVector<Expr *, 32> InitExpressions; 1765 1766 // Build designators and check array designator expressions. 1767 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1768 const Designator &D = Desig.getDesignator(Idx); 1769 switch (D.getKind()) { 1770 case Designator::FieldDesignator: 1771 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1772 D.getFieldLoc())); 1773 break; 1774 1775 case Designator::ArrayDesignator: { 1776 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1777 llvm::APSInt IndexValue; 1778 if (!Index->isTypeDependent() && 1779 !Index->isValueDependent() && 1780 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1781 Invalid = true; 1782 else { 1783 Designators.push_back(ASTDesignator(InitExpressions.size(), 1784 D.getLBracketLoc(), 1785 D.getRBracketLoc())); 1786 InitExpressions.push_back(Index); 1787 } 1788 break; 1789 } 1790 1791 case Designator::ArrayRangeDesignator: { 1792 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1793 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1794 llvm::APSInt StartValue; 1795 llvm::APSInt EndValue; 1796 bool StartDependent = StartIndex->isTypeDependent() || 1797 StartIndex->isValueDependent(); 1798 bool EndDependent = EndIndex->isTypeDependent() || 1799 EndIndex->isValueDependent(); 1800 if ((!StartDependent && 1801 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1802 (!EndDependent && 1803 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1804 Invalid = true; 1805 else { 1806 // Make sure we're comparing values with the same bit width. 1807 if (StartDependent || EndDependent) { 1808 // Nothing to compute. 1809 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1810 EndValue.extend(StartValue.getBitWidth()); 1811 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1812 StartValue.extend(EndValue.getBitWidth()); 1813 1814 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1815 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1816 << StartValue.toString(10) << EndValue.toString(10) 1817 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1818 Invalid = true; 1819 } else { 1820 Designators.push_back(ASTDesignator(InitExpressions.size(), 1821 D.getLBracketLoc(), 1822 D.getEllipsisLoc(), 1823 D.getRBracketLoc())); 1824 InitExpressions.push_back(StartIndex); 1825 InitExpressions.push_back(EndIndex); 1826 } 1827 } 1828 break; 1829 } 1830 } 1831 } 1832 1833 if (Invalid || Init.isInvalid()) 1834 return ExprError(); 1835 1836 // Clear out the expressions within the designation. 1837 Desig.ClearExprs(*this); 1838 1839 DesignatedInitExpr *DIE 1840 = DesignatedInitExpr::Create(Context, 1841 Designators.data(), Designators.size(), 1842 InitExpressions.data(), InitExpressions.size(), 1843 Loc, GNUSyntax, Init.takeAs<Expr>()); 1844 return Owned(DIE); 1845} 1846 1847bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) { 1848 InitListChecker CheckInitList(*this, InitList, DeclType); 1849 if (!CheckInitList.HadError()) 1850 InitList = CheckInitList.getFullyStructuredList(); 1851 1852 return CheckInitList.HadError(); 1853} 1854 1855/// \brief Diagnose any semantic errors with value-initialization of 1856/// the given type. 1857/// 1858/// Value-initialization effectively zero-initializes any types 1859/// without user-declared constructors, and calls the default 1860/// constructor for a for any type that has a user-declared 1861/// constructor (C++ [dcl.init]p5). Value-initialization can fail when 1862/// a type with a user-declared constructor does not have an 1863/// accessible, non-deleted default constructor. In C, everything can 1864/// be value-initialized, which corresponds to C's notion of 1865/// initializing objects with static storage duration when no 1866/// initializer is provided for that object. 1867/// 1868/// \returns true if there was an error, false otherwise. 1869bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) { 1870 // C++ [dcl.init]p5: 1871 // 1872 // To value-initialize an object of type T means: 1873 1874 // -- if T is an array type, then each element is value-initialized; 1875 if (const ArrayType *AT = Context.getAsArrayType(Type)) 1876 return CheckValueInitialization(AT->getElementType(), Loc); 1877 1878 if (const RecordType *RT = Type->getAs<RecordType>()) { 1879 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1880 // -- if T is a class type (clause 9) with a user-declared 1881 // constructor (12.1), then the default constructor for T is 1882 // called (and the initialization is ill-formed if T has no 1883 // accessible default constructor); 1884 if (ClassDecl->hasUserDeclaredConstructor()) { 1885 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1886 1887 // FIXME: Poor location information 1888 CXXConstructorDecl *Constructor 1889 = PerformInitializationByConstructor(Type, 1890 MultiExprArg(*this, 0, 0), 1891 Loc, SourceRange(Loc), 1892 DeclarationName(), 1893 InitializationKind::CreateValue(Loc, Loc, Loc), 1894 ConstructorArgs); 1895 if (!Constructor) 1896 return true; 1897 1898 OwningExprResult Init 1899 = BuildCXXConstructExpr(Loc, Type, Constructor, 1900 move_arg(ConstructorArgs)); 1901 if (Init.isInvalid()) 1902 return true; 1903 1904 // FIXME: Actually perform the value-initialization! 1905 return false; 1906 } 1907 } 1908 } 1909 1910 if (Type->isReferenceType()) { 1911 // C++ [dcl.init]p5: 1912 // [...] A program that calls for default-initialization or 1913 // value-initialization of an entity of reference type is 1914 // ill-formed. [...] 1915 // FIXME: Once we have code that goes through this path, add an actual 1916 // diagnostic :) 1917 } 1918 1919 return false; 1920} 1921 1922//===----------------------------------------------------------------------===// 1923// Initialization entity 1924//===----------------------------------------------------------------------===// 1925 1926void InitializedEntity::InitDeclLoc() { 1927 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) && 1928 "InitDeclLoc cannot be used with non-declaration entities."); 1929 1930 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) { 1931 TL = DI->getTypeLoc(); 1932 return; 1933 } 1934 1935 // FIXME: Once we've gone through the effort to create the fake 1936 // TypeSourceInfo, should we cache it in the declaration? 1937 // (If not, we "leak" it). 1938 TypeSourceInfo *DI = VariableOrMember->getASTContext() 1939 .CreateTypeSourceInfo(VariableOrMember->getType()); 1940 DI->getTypeLoc().initialize(VariableOrMember->getLocation()); 1941 TL = DI->getTypeLoc(); 1942} 1943 1944InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 1945 CXXBaseSpecifier *Base) 1946{ 1947 InitializedEntity Result; 1948 Result.Kind = EK_Base; 1949 Result.Base = Base; 1950 // FIXME: CXXBaseSpecifier should store a TypeLoc. 1951 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType()); 1952 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin()); 1953 Result.TL = DI->getTypeLoc(); 1954 return Result; 1955} 1956 1957//===----------------------------------------------------------------------===// 1958// Initialization sequence 1959//===----------------------------------------------------------------------===// 1960 1961void InitializationSequence::Step::Destroy() { 1962 switch (Kind) { 1963 case SK_ResolveAddressOfOverloadedFunction: 1964 case SK_CastDerivedToBaseRValue: 1965 case SK_CastDerivedToBaseLValue: 1966 case SK_BindReference: 1967 case SK_BindReferenceToTemporary: 1968 case SK_UserConversion: 1969 case SK_QualificationConversionRValue: 1970 case SK_QualificationConversionLValue: 1971 case SK_ListInitialization: 1972 break; 1973 1974 case SK_ConversionSequence: 1975 delete ICS; 1976 } 1977} 1978 1979void InitializationSequence::AddAddressOverloadResolutionStep( 1980 FunctionDecl *Function) { 1981 Step S; 1982 S.Kind = SK_ResolveAddressOfOverloadedFunction; 1983 S.Type = Function->getType(); 1984 S.Function = Function; 1985 Steps.push_back(S); 1986} 1987 1988void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 1989 bool IsLValue) { 1990 Step S; 1991 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue; 1992 S.Type = BaseType; 1993 Steps.push_back(S); 1994} 1995 1996void InitializationSequence::AddReferenceBindingStep(QualType T, 1997 bool BindingTemporary) { 1998 Step S; 1999 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2000 S.Type = T; 2001 Steps.push_back(S); 2002} 2003 2004void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2005 QualType T) { 2006 Step S; 2007 S.Kind = SK_UserConversion; 2008 S.Type = T; 2009 S.Function = Function; 2010 Steps.push_back(S); 2011} 2012 2013void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2014 bool IsLValue) { 2015 Step S; 2016 S.Kind = IsLValue? SK_QualificationConversionLValue 2017 : SK_QualificationConversionRValue; 2018 S.Type = Ty; 2019 Steps.push_back(S); 2020} 2021 2022void InitializationSequence::AddConversionSequenceStep( 2023 const ImplicitConversionSequence &ICS, 2024 QualType T) { 2025 Step S; 2026 S.Kind = SK_ConversionSequence; 2027 S.Type = T; 2028 S.ICS = new ImplicitConversionSequence(ICS); 2029 Steps.push_back(S); 2030} 2031 2032void InitializationSequence::AddListInitializationStep(QualType T) { 2033 Step S; 2034 S.Kind = SK_ListInitialization; 2035 S.Type = T; 2036 Steps.push_back(S); 2037} 2038 2039void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2040 OverloadingResult Result) { 2041 SequenceKind = FailedSequence; 2042 this->Failure = Failure; 2043 this->FailedOverloadResult = Result; 2044} 2045 2046//===----------------------------------------------------------------------===// 2047// Attempt initialization 2048//===----------------------------------------------------------------------===// 2049 2050/// \brief Attempt list initialization (C++0x [dcl.init.list]) 2051static void TryListInitialization(Sema &S, 2052 const InitializedEntity &Entity, 2053 const InitializationKind &Kind, 2054 InitListExpr *InitList, 2055 InitializationSequence &Sequence) { 2056 // FIXME: We only perform rudimentary checking of list 2057 // initializations at this point, then assume that any list 2058 // initialization of an array, aggregate, or scalar will be 2059 // well-formed. We we actually "perform" list initialization, we'll 2060 // do all of the necessary checking. C++0x initializer lists will 2061 // force us to perform more checking here. 2062 Sequence.setSequenceKind(InitializationSequence::ListInitialization); 2063 2064 QualType DestType = Entity.getType().getType(); 2065 2066 // C++ [dcl.init]p13: 2067 // If T is a scalar type, then a declaration of the form 2068 // 2069 // T x = { a }; 2070 // 2071 // is equivalent to 2072 // 2073 // T x = a; 2074 if (DestType->isScalarType()) { 2075 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) { 2076 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 2077 return; 2078 } 2079 2080 // Assume scalar initialization from a single value works. 2081 } else if (DestType->isAggregateType()) { 2082 // Assume aggregate initialization works. 2083 } else if (DestType->isVectorType()) { 2084 // Assume vector initialization works. 2085 } else if (DestType->isReferenceType()) { 2086 // FIXME: C++0x defines behavior for this. 2087 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 2088 return; 2089 } else if (DestType->isRecordType()) { 2090 // FIXME: C++0x defines behavior for this 2091 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 2092 } 2093 2094 // Add a general "list initialization" step. 2095 Sequence.AddListInitializationStep(DestType); 2096} 2097 2098/// \brief Try a reference initialization that involves calling a conversion 2099/// function. 2100/// 2101/// FIXME: look intos DRs 656, 896 2102static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 2103 const InitializedEntity &Entity, 2104 const InitializationKind &Kind, 2105 Expr *Initializer, 2106 bool AllowRValues, 2107 InitializationSequence &Sequence) { 2108 QualType DestType = Entity.getType().getType(); 2109 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2110 QualType T1 = cv1T1.getUnqualifiedType(); 2111 QualType cv2T2 = Initializer->getType(); 2112 QualType T2 = cv2T2.getUnqualifiedType(); 2113 2114 bool DerivedToBase; 2115 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 2116 T1, T2, DerivedToBase) && 2117 "Must have incompatible references when binding via conversion"); 2118 (void)DerivedToBase; 2119 2120 // Build the candidate set directly in the initialization sequence 2121 // structure, so that it will persist if we fail. 2122 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2123 CandidateSet.clear(); 2124 2125 // Determine whether we are allowed to call explicit constructors or 2126 // explicit conversion operators. 2127 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2128 2129 const RecordType *T1RecordType = 0; 2130 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) { 2131 // The type we're converting to is a class type. Enumerate its constructors 2132 // to see if there is a suitable conversion. 2133 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 2134 2135 DeclarationName ConstructorName 2136 = S.Context.DeclarationNames.getCXXConstructorName( 2137 S.Context.getCanonicalType(T1).getUnqualifiedType()); 2138 DeclContext::lookup_iterator Con, ConEnd; 2139 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName); 2140 Con != ConEnd; ++Con) { 2141 // Find the constructor (which may be a template). 2142 CXXConstructorDecl *Constructor = 0; 2143 FunctionTemplateDecl *ConstructorTmpl 2144 = dyn_cast<FunctionTemplateDecl>(*Con); 2145 if (ConstructorTmpl) 2146 Constructor = cast<CXXConstructorDecl>( 2147 ConstructorTmpl->getTemplatedDecl()); 2148 else 2149 Constructor = cast<CXXConstructorDecl>(*Con); 2150 2151 if (!Constructor->isInvalidDecl() && 2152 Constructor->isConvertingConstructor(AllowExplicit)) { 2153 if (ConstructorTmpl) 2154 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2155 &Initializer, 1, CandidateSet); 2156 else 2157 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet); 2158 } 2159 } 2160 } 2161 2162 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) { 2163 // The type we're converting from is a class type, enumerate its conversion 2164 // functions. 2165 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 2166 2167 // Determine the type we are converting to. If we are allowed to 2168 // convert to an rvalue, take the type that the destination type 2169 // refers to. 2170 QualType ToType = AllowRValues? cv1T1 : DestType; 2171 2172 const UnresolvedSet *Conversions 2173 = T2RecordDecl->getVisibleConversionFunctions(); 2174 for (UnresolvedSet::iterator I = Conversions->begin(), 2175 E = Conversions->end(); 2176 I != E; ++I) { 2177 NamedDecl *D = *I; 2178 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2179 if (isa<UsingShadowDecl>(D)) 2180 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2181 2182 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2183 CXXConversionDecl *Conv; 2184 if (ConvTemplate) 2185 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2186 else 2187 Conv = cast<CXXConversionDecl>(*I); 2188 2189 // If the conversion function doesn't return a reference type, 2190 // it can't be considered for this conversion unless we're allowed to 2191 // consider rvalues. 2192 // FIXME: Do we need to make sure that we only consider conversion 2193 // candidates with reference-compatible results? That might be needed to 2194 // break recursion. 2195 if ((AllowExplicit || !Conv->isExplicit()) && 2196 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 2197 if (ConvTemplate) 2198 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer, 2199 ToType, CandidateSet); 2200 else 2201 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1, 2202 CandidateSet); 2203 } 2204 } 2205 } 2206 2207 SourceLocation DeclLoc = Initializer->getLocStart(); 2208 2209 // Perform overload resolution. If it fails, return the failed result. 2210 OverloadCandidateSet::iterator Best; 2211 if (OverloadingResult Result 2212 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) 2213 return Result; 2214 2215 FunctionDecl *Function = Best->Function; 2216 2217 // Compute the returned type of the conversion. 2218 if (isa<CXXConversionDecl>(Function)) 2219 T2 = Function->getResultType(); 2220 else 2221 T2 = cv1T1; 2222 2223 // Add the user-defined conversion step. 2224 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType()); 2225 2226 // Determine whether we need to perform derived-to-base or 2227 // cv-qualification adjustments. 2228 bool NewDerivedToBase = false; 2229 Sema::ReferenceCompareResult NewRefRelationship 2230 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(), 2231 NewDerivedToBase); 2232 assert(NewRefRelationship != Sema::Ref_Incompatible && 2233 "Overload resolution picked a bad conversion function"); 2234 (void)NewRefRelationship; 2235 if (NewDerivedToBase) 2236 Sequence.AddDerivedToBaseCastStep( 2237 S.Context.getQualifiedType(T1, 2238 T2.getNonReferenceType().getQualifiers()), 2239 /*isLValue=*/true); 2240 2241 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 2242 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType()); 2243 2244 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 2245 return OR_Success; 2246} 2247 2248/// \brief Attempt reference initialization (C++0x [dcl.init.list]) 2249static void TryReferenceInitialization(Sema &S, 2250 const InitializedEntity &Entity, 2251 const InitializationKind &Kind, 2252 Expr *Initializer, 2253 InitializationSequence &Sequence) { 2254 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding); 2255 2256 QualType DestType = Entity.getType().getType(); 2257 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2258 QualType T1 = cv1T1.getUnqualifiedType(); 2259 QualType cv2T2 = Initializer->getType(); 2260 QualType T2 = cv2T2.getUnqualifiedType(); 2261 SourceLocation DeclLoc = Initializer->getLocStart(); 2262 2263 // If the initializer is the address of an overloaded function, try 2264 // to resolve the overloaded function. If all goes well, T2 is the 2265 // type of the resulting function. 2266 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2267 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, 2268 T1, 2269 false); 2270 if (!Fn) { 2271 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2272 return; 2273 } 2274 2275 Sequence.AddAddressOverloadResolutionStep(Fn); 2276 cv2T2 = Fn->getType(); 2277 T2 = cv2T2.getUnqualifiedType(); 2278 } 2279 2280 // FIXME: Rvalue references 2281 bool ForceRValue = false; 2282 2283 // Compute some basic properties of the types and the initializer. 2284 bool isLValueRef = DestType->isLValueReferenceType(); 2285 bool isRValueRef = !isLValueRef; 2286 bool DerivedToBase = false; 2287 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 2288 Initializer->isLvalue(S.Context); 2289 Sema::ReferenceCompareResult RefRelationship 2290 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase); 2291 2292 // C++0x [dcl.init.ref]p5: 2293 // A reference to type "cv1 T1" is initialized by an expression of type 2294 // "cv2 T2" as follows: 2295 // 2296 // - If the reference is an lvalue reference and the initializer 2297 // expression 2298 OverloadingResult ConvOvlResult = OR_Success; 2299 if (isLValueRef) { 2300 if (InitLvalue == Expr::LV_Valid && 2301 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2302 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 2303 // reference-compatible with "cv2 T2," or 2304 // 2305 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a 2306 // bit-field when we're determining whether the reference initialization 2307 // can occur. This property will be checked by PerformInitialization. 2308 if (DerivedToBase) 2309 Sequence.AddDerivedToBaseCastStep( 2310 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()), 2311 /*isLValue=*/true); 2312 if (cv1T1.getQualifiers() != cv2T2.getQualifiers()) 2313 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true); 2314 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false); 2315 return; 2316 } 2317 2318 // - has a class type (i.e., T2 is a class type), where T1 is not 2319 // reference-related to T2, and can be implicitly converted to an 2320 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 2321 // with "cv3 T3" (this conversion is selected by enumerating the 2322 // applicable conversion functions (13.3.1.6) and choosing the best 2323 // one through overload resolution (13.3)), 2324 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) { 2325 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 2326 Initializer, 2327 /*AllowRValues=*/false, 2328 Sequence); 2329 if (ConvOvlResult == OR_Success) 2330 return; 2331 } 2332 } 2333 2334 // - Otherwise, the reference shall be an lvalue reference to a 2335 // non-volatile const type (i.e., cv1 shall be const), or the reference 2336 // shall be an rvalue reference and the initializer expression shall 2337 // be an rvalue. 2338 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) || 2339 (isRValueRef && InitLvalue != Expr::LV_Valid))) { 2340 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2341 Sequence.SetOverloadFailure( 2342 InitializationSequence::FK_ReferenceInitOverloadFailed, 2343 ConvOvlResult); 2344 else if (isLValueRef) 2345 Sequence.SetFailed(InitLvalue == Expr::LV_Valid 2346 ? (RefRelationship == Sema::Ref_Related 2347 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 2348 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 2349 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 2350 else 2351 Sequence.SetFailed( 2352 InitializationSequence::FK_RValueReferenceBindingToLValue); 2353 2354 return; 2355 } 2356 2357 // - If T1 and T2 are class types and 2358 if (T1->isRecordType() && T2->isRecordType()) { 2359 // - the initializer expression is an rvalue and "cv1 T1" is 2360 // reference-compatible with "cv2 T2", or 2361 if (InitLvalue != Expr::LV_Valid && 2362 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2363 if (DerivedToBase) 2364 Sequence.AddDerivedToBaseCastStep( 2365 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()), 2366 /*isLValue=*/false); 2367 if (cv1T1.getQualifiers() != cv2T2.getQualifiers()) 2368 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false); 2369 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2370 return; 2371 } 2372 2373 // - T1 is not reference-related to T2 and the initializer expression 2374 // can be implicitly converted to an rvalue of type "cv3 T3" (this 2375 // conversion is selected by enumerating the applicable conversion 2376 // functions (13.3.1.6) and choosing the best one through overload 2377 // resolution (13.3)), 2378 if (RefRelationship == Sema::Ref_Incompatible) { 2379 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 2380 Kind, Initializer, 2381 /*AllowRValues=*/true, 2382 Sequence); 2383 if (ConvOvlResult) 2384 Sequence.SetOverloadFailure( 2385 InitializationSequence::FK_ReferenceInitOverloadFailed, 2386 ConvOvlResult); 2387 2388 return; 2389 } 2390 2391 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2392 return; 2393 } 2394 2395 // - If the initializer expression is an rvalue, with T2 an array type, 2396 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference 2397 // is bound to the object represented by the rvalue (see 3.10). 2398 // FIXME: How can an array type be reference-compatible with anything? 2399 // Don't we mean the element types of T1 and T2? 2400 2401 // - Otherwise, a temporary of type “cv1 T1” is created and initialized 2402 // from the initializer expression using the rules for a non-reference 2403 // copy initialization (8.5). The reference is then bound to the 2404 // temporary. [...] 2405 // Determine whether we are allowed to call explicit constructors or 2406 // explicit conversion operators. 2407 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 2408 ImplicitConversionSequence ICS 2409 = S.TryImplicitConversion(Initializer, cv1T1, 2410 /*SuppressUserConversions=*/false, AllowExplicit, 2411 /*ForceRValue=*/false, 2412 /*FIXME:InOverloadResolution=*/false, 2413 /*UserCast=*/Kind.isExplicitCast()); 2414 2415 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 2416 // FIXME: Use the conversion function set stored in ICS to turn 2417 // this into an overloading ambiguity diagnostic. However, we need 2418 // to keep that set as an OverloadCandidateSet rather than as some 2419 // other kind of set. 2420 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 2421 return; 2422 } 2423 2424 // [...] If T1 is reference-related to T2, cv1 must be the 2425 // same cv-qualification as, or greater cv-qualification 2426 // than, cv2; otherwise, the program is ill-formed. 2427 if (RefRelationship == Sema::Ref_Related && 2428 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) { 2429 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2430 return; 2431 } 2432 2433 // Perform the actual conversion. 2434 Sequence.AddConversionSequenceStep(ICS, cv1T1); 2435 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2436 return; 2437} 2438 2439/// \brief Attempt character array initialization from a string literal 2440/// (C++ [dcl.init.string], C99 6.7.8). 2441static void TryStringLiteralInitialization(Sema &S, 2442 const InitializedEntity &Entity, 2443 const InitializationKind &Kind, 2444 Expr *Initializer, 2445 InitializationSequence &Sequence) { 2446 // FIXME: Implement! 2447} 2448 2449/// \brief Attempt value initialization (C++ [dcl.init]p7). 2450static void TryValueInitialization(Sema &S, 2451 const InitializedEntity &Entity, 2452 const InitializationKind &Kind, 2453 InitializationSequence &Sequence) { 2454 // FIXME: Implement! 2455} 2456 2457/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2458/// enumerates the constructors of the initialized entity and performs overload 2459/// resolution to select the best. 2460static void TryConstructorInitialization(Sema &S, 2461 const InitializedEntity &Entity, 2462 const InitializationKind &Kind, 2463 Expr **Args, unsigned NumArgs, 2464 InitializationSequence &Sequence) { 2465 // FIXME: Implement! 2466} 2467 2468/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 2469/// which enumerates all conversion functions and performs overload resolution 2470/// to select the best. 2471static void TryUserDefinedConversion(Sema &S, 2472 const InitializedEntity &Entity, 2473 const InitializationKind &Kind, 2474 Expr *Initializer, 2475 InitializationSequence &Sequence) { 2476 // FIXME: Implement! 2477} 2478 2479/// \brief Attempt an implicit conversion (C++ [conv]) converting from one 2480/// non-class type to another. 2481static void TryImplicitConversion(Sema &S, 2482 const InitializedEntity &Entity, 2483 const InitializationKind &Kind, 2484 Expr *Initializer, 2485 InitializationSequence &Sequence) { 2486 ImplicitConversionSequence ICS 2487 = S.TryImplicitConversion(Initializer, Entity.getType().getType(), 2488 /*SuppressUserConversions=*/true, 2489 /*AllowExplicit=*/false, 2490 /*ForceRValue=*/false, 2491 /*FIXME:InOverloadResolution=*/false, 2492 /*UserCast=*/Kind.isExplicitCast()); 2493 2494 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 2495 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed); 2496 return; 2497 } 2498 2499 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType()); 2500} 2501 2502InitializationSequence::InitializationSequence(Sema &S, 2503 const InitializedEntity &Entity, 2504 const InitializationKind &Kind, 2505 Expr **Args, 2506 unsigned NumArgs) { 2507 ASTContext &Context = S.Context; 2508 2509 // C++0x [dcl.init]p16: 2510 // The semantics of initializers are as follows. The destination type is 2511 // the type of the object or reference being initialized and the source 2512 // type is the type of the initializer expression. The source type is not 2513 // defined when the initializer is a braced-init-list or when it is a 2514 // parenthesized list of expressions. 2515 QualType DestType = Entity.getType().getType(); 2516 2517 if (DestType->isDependentType() || 2518 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 2519 SequenceKind = DependentSequence; 2520 return; 2521 } 2522 2523 QualType SourceType; 2524 Expr *Initializer = 0; 2525 if (Kind.getKind() == InitializationKind::IK_Copy) { 2526 Initializer = Args[0]; 2527 if (!isa<InitListExpr>(Initializer)) 2528 SourceType = Initializer->getType(); 2529 } 2530 2531 // - If the initializer is a braced-init-list, the object is 2532 // list-initialized (8.5.4). 2533 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 2534 TryListInitialization(S, Entity, Kind, InitList, *this); 2535 return; 2536 } 2537 2538 // - If the destination type is a reference type, see 8.5.3. 2539 if (DestType->isReferenceType()) { 2540 // C++0x [dcl.init.ref]p1: 2541 // A variable declared to be a T& or T&&, that is, "reference to type T" 2542 // (8.3.2), shall be initialized by an object, or function, of type T or 2543 // by an object that can be converted into a T. 2544 // (Therefore, multiple arguments are not permitted.) 2545 if (NumArgs != 1) 2546 SetFailed(FK_TooManyInitsForReference); 2547 else 2548 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 2549 return; 2550 } 2551 2552 // - If the destination type is an array of characters, an array of 2553 // char16_t, an array of char32_t, or an array of wchar_t, and the 2554 // initializer is a string literal, see 8.5.2. 2555 if (Initializer && IsStringInit(Initializer, DestType, Context)) { 2556 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 2557 return; 2558 } 2559 2560 // - If the initializer is (), the object is value-initialized. 2561 if (Kind.getKind() == InitializationKind::IK_Value) { 2562 TryValueInitialization(S, Entity, Kind, *this); 2563 return; 2564 } 2565 2566 // - Otherwise, if the destination type is an array, the program is 2567 // ill-formed. 2568 if (const ArrayType *AT = Context.getAsArrayType(DestType)) { 2569 if (AT->getElementType()->isAnyCharacterType()) 2570 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 2571 else 2572 SetFailed(FK_ArrayNeedsInitList); 2573 2574 return; 2575 } 2576 2577 // - If the destination type is a (possibly cv-qualified) class type: 2578 if (DestType->isRecordType()) { 2579 // - If the initialization is direct-initialization, or if it is 2580 // copy-initialization where the cv-unqualified version of the 2581 // source type is the same class as, or a derived class of, the 2582 // class of the destination, constructors are considered. [...] 2583 if (Kind.getKind() == InitializationKind::IK_Direct || 2584 (Kind.getKind() == InitializationKind::IK_Copy && 2585 (Context.hasSameUnqualifiedType(SourceType, DestType) || 2586 S.IsDerivedFrom(SourceType, DestType)))) 2587 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, *this); 2588 // - Otherwise (i.e., for the remaining copy-initialization cases), 2589 // user-defined conversion sequences that can convert from the source 2590 // type to the destination type or (when a conversion function is 2591 // used) to a derived class thereof are enumerated as described in 2592 // 13.3.1.4, and the best one is chosen through overload resolution 2593 // (13.3). 2594 else 2595 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 2596 return; 2597 } 2598 2599 // - Otherwise, if the source type is a (possibly cv-qualified) class 2600 // type, conversion functions are considered. 2601 if (SourceType->isRecordType()) { 2602 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 2603 return; 2604 } 2605 2606 // - Otherwise, the initial value of the object being initialized is the 2607 // (possibly converted) value of the ini- tializer expression. Standard 2608 // conversions (Clause 4) will be used, if necessary, to convert the 2609 // initializer expression to the cv-unqualified version of the 2610 // destination type; no user-defined conversions are considered. 2611 TryImplicitConversion(S, Entity, Kind, Initializer, *this); 2612} 2613 2614InitializationSequence::~InitializationSequence() { 2615 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(), 2616 StepEnd = Steps.end(); 2617 Step != StepEnd; ++Step) 2618 Step->Destroy(); 2619} 2620 2621//===----------------------------------------------------------------------===// 2622// Perform initialization 2623//===----------------------------------------------------------------------===// 2624 2625Action::OwningExprResult 2626InitializationSequence::Perform(Sema &S, 2627 const InitializedEntity &Entity, 2628 const InitializationKind &Kind, 2629 Action::MultiExprArg Args, 2630 QualType *ResultType) { 2631 if (SequenceKind == FailedSequence) { 2632 unsigned NumArgs = Args.size(); 2633 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 2634 return S.ExprError(); 2635 } 2636 2637 if (SequenceKind == DependentSequence) { 2638 // If the declaration is a non-dependent, incomplete array type 2639 // that has an initializer, then its type will be completed once 2640 // the initializer is instantiated. 2641 if (ResultType && !Entity.getType().getType()->isDependentType() && 2642 Args.size() == 1) { 2643 QualType DeclType = Entity.getType().getType(); 2644 if (const IncompleteArrayType *ArrayT 2645 = S.Context.getAsIncompleteArrayType(DeclType)) { 2646 // FIXME: We don't currently have the ability to accurately 2647 // compute the length of an initializer list without 2648 // performing full type-checking of the initializer list 2649 // (since we have to determine where braces are implicitly 2650 // introduced and such). So, we fall back to making the array 2651 // type a dependently-sized array type with no specified 2652 // bound. 2653 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 2654 SourceRange Brackets; 2655 // Scavange the location of the brackets from the entity, if we can. 2656 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) { 2657 IncompleteArrayTypeLoc ArrayLoc 2658 = cast<IncompleteArrayTypeLoc>(Entity.getType()); 2659 Brackets = ArrayLoc.getBracketsRange(); 2660 } 2661 2662 *ResultType 2663 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 2664 /*NumElts=*/0, 2665 ArrayT->getSizeModifier(), 2666 ArrayT->getIndexTypeCVRQualifiers(), 2667 Brackets); 2668 } 2669 2670 } 2671 } 2672 2673 if (Kind.getKind() == InitializationKind::IK_Copy) 2674 return Sema::OwningExprResult(S, Args.release()[0]); 2675 2676 unsigned NumArgs = Args.size(); 2677 return S.Owned(new (S.Context) ParenListExpr(S.Context, 2678 SourceLocation(), 2679 (Expr **)Args.release(), 2680 NumArgs, 2681 SourceLocation())); 2682 } 2683 2684 QualType DestType = Entity.getType().getType().getNonReferenceType(); 2685 if (ResultType) 2686 *ResultType = Entity.getType().getType(); 2687 2688 Sema::OwningExprResult CurInit(S); 2689 // For copy initialization and any other initialization forms that 2690 // only have a single initializer, we start with the (only) 2691 // initializer we have. 2692 // FIXME: DPG is not happy about this. There's confusion regarding whether 2693 // we're supposed to start the conversion from the solitary initializer or 2694 // from the set of arguments. 2695 if (Kind.getKind() == InitializationKind::IK_Copy || 2696 SequenceKind == ReferenceBinding) { 2697 assert(Args.size() == 1); 2698 CurInit = Sema::OwningExprResult(S, Args.release()[0]); 2699 if (CurInit.isInvalid()) 2700 return S.ExprError(); 2701 } 2702 2703 // Walk through the computed steps for the initialization sequence, 2704 // performing the specified conversions along the way. 2705 for (step_iterator Step = step_begin(), StepEnd = step_end(); 2706 Step != StepEnd; ++Step) { 2707 if (CurInit.isInvalid()) 2708 return S.ExprError(); 2709 2710 Expr *CurInitExpr = (Expr *)CurInit.get(); 2711 QualType SourceType = CurInitExpr->getType(); 2712 2713 switch (Step->Kind) { 2714 case SK_ResolveAddressOfOverloadedFunction: 2715 // Overload resolution determined which function invoke; update the 2716 // initializer to reflect that choice. 2717 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function); 2718 break; 2719 2720 case SK_CastDerivedToBaseRValue: 2721 case SK_CastDerivedToBaseLValue: { 2722 // We have a derived-to-base cast that produces either an rvalue or an 2723 // lvalue. Perform that cast. 2724 2725 // Casts to inaccessible base classes are allowed with C-style casts. 2726 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 2727 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 2728 CurInitExpr->getLocStart(), 2729 CurInitExpr->getSourceRange(), 2730 IgnoreBaseAccess)) 2731 return S.ExprError(); 2732 2733 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type, 2734 CastExpr::CK_DerivedToBase, 2735 (Expr*)CurInit.release(), 2736 Step->Kind == SK_CastDerivedToBaseLValue)); 2737 break; 2738 } 2739 2740 case SK_BindReference: 2741 if (FieldDecl *BitField = CurInitExpr->getBitField()) { 2742 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 2743 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 2744 << Entity.getType().getType().isVolatileQualified() 2745 << BitField->getDeclName() 2746 << CurInitExpr->getSourceRange(); 2747 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 2748 return S.ExprError(); 2749 } 2750 2751 // Reference binding does not have any corresponding ASTs. 2752 2753 // Check exception specifications 2754 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 2755 return S.ExprError(); 2756 break; 2757 2758 case SK_BindReferenceToTemporary: 2759 // Check exception specifications 2760 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 2761 return S.ExprError(); 2762 2763 // FIXME: At present, we have no AST to describe when we need to make a 2764 // temporary to bind a reference to. We should. 2765 break; 2766 2767 case SK_UserConversion: { 2768 // We have a user-defined conversion that invokes either a constructor 2769 // or a conversion function. 2770 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 2771 if (CXXConstructorDecl *Constructor 2772 = dyn_cast<CXXConstructorDecl>(Step->Function)) { 2773 // Build a call to the selected constructor. 2774 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S); 2775 SourceLocation Loc = CurInitExpr->getLocStart(); 2776 CurInit.release(); // Ownership transferred into MultiExprArg, below. 2777 2778 // Determine the arguments required to actually perform the constructor 2779 // call. 2780 if (S.CompleteConstructorCall(Constructor, 2781 Sema::MultiExprArg(S, 2782 (void **)&CurInitExpr, 2783 1), 2784 Loc, ConstructorArgs)) 2785 return S.ExprError(); 2786 2787 // Build the an expression that constructs a temporary. 2788 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 2789 move_arg(ConstructorArgs)); 2790 if (CurInit.isInvalid()) 2791 return S.ExprError(); 2792 2793 CastKind = CastExpr::CK_ConstructorConversion; 2794 } else { 2795 // Build a call to the conversion function. 2796 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function); 2797 2798 // FIXME: Should we move this initialization into a separate 2799 // derived-to-base conversion? I believe the answer is "no", because 2800 // we don't want to turn off access control here for c-style casts. 2801 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion)) 2802 return S.ExprError(); 2803 2804 // Do a little dance to make sure that CurInit has the proper 2805 // pointer. 2806 CurInit.release(); 2807 2808 // Build the actual call to the conversion function. 2809 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion)); 2810 if (CurInit.isInvalid() || !CurInit.get()) 2811 return S.ExprError(); 2812 2813 CastKind = CastExpr::CK_UserDefinedConversion; 2814 } 2815 2816 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 2817 CurInitExpr = CurInit.takeAs<Expr>(); 2818 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(), 2819 CastKind, 2820 CurInitExpr, 2821 false)); 2822 break; 2823 } 2824 2825 case SK_QualificationConversionLValue: 2826 case SK_QualificationConversionRValue: 2827 // Perform a qualification conversion; these can never go wrong. 2828 S.ImpCastExprToType(CurInitExpr, Step->Type, 2829 CastExpr::CK_NoOp, 2830 Step->Kind == SK_QualificationConversionLValue); 2831 CurInit.release(); 2832 CurInit = S.Owned(CurInitExpr); 2833 break; 2834 2835 case SK_ConversionSequence: 2836 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, "converting", 2837 false, false, *Step->ICS)) 2838 return S.ExprError(); 2839 2840 CurInit.release(); 2841 CurInit = S.Owned(CurInitExpr); 2842 break; 2843 2844 case SK_ListInitialization: { 2845 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr); 2846 QualType Ty = Step->Type; 2847 if (S.CheckInitList(InitList, ResultType? *ResultType : Ty)) 2848 return S.ExprError(); 2849 2850 CurInit.release(); 2851 CurInit = S.Owned(InitList); 2852 break; 2853 } 2854 } 2855 } 2856 2857 return move(CurInit); 2858} 2859 2860//===----------------------------------------------------------------------===// 2861// Diagnose initialization failures 2862//===----------------------------------------------------------------------===// 2863bool InitializationSequence::Diagnose(Sema &S, 2864 const InitializedEntity &Entity, 2865 const InitializationKind &Kind, 2866 Expr **Args, unsigned NumArgs) { 2867 if (SequenceKind != FailedSequence) 2868 return false; 2869 2870 QualType DestType = Entity.getType().getType(); 2871 switch (Failure) { 2872 case FK_TooManyInitsForReference: 2873 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 2874 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 2875 break; 2876 2877 case FK_ArrayNeedsInitList: 2878 case FK_ArrayNeedsInitListOrStringLiteral: 2879 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 2880 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 2881 break; 2882 2883 case FK_AddressOfOverloadFailed: 2884 S.ResolveAddressOfOverloadedFunction(Args[0], 2885 DestType.getNonReferenceType(), 2886 true); 2887 break; 2888 2889 case FK_ReferenceInitOverloadFailed: 2890 switch (FailedOverloadResult) { 2891 case OR_Ambiguous: 2892 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 2893 << Args[0]->getType() << DestType.getNonReferenceType() 2894 << Args[0]->getSourceRange(); 2895 S.PrintOverloadCandidates(FailedCandidateSet, true); 2896 break; 2897 2898 case OR_No_Viable_Function: 2899 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 2900 << Args[0]->getType() << DestType.getNonReferenceType() 2901 << Args[0]->getSourceRange(); 2902 S.PrintOverloadCandidates(FailedCandidateSet, false); 2903 break; 2904 2905 case OR_Deleted: { 2906 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 2907 << Args[0]->getType() << DestType.getNonReferenceType() 2908 << Args[0]->getSourceRange(); 2909 OverloadCandidateSet::iterator Best; 2910 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet, 2911 Kind.getLocation(), 2912 Best); 2913 if (Ovl == OR_Deleted) { 2914 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 2915 << Best->Function->isDeleted(); 2916 } else { 2917 llvm_unreachable("Inconsistent overload resolution?"); 2918 } 2919 break; 2920 } 2921 2922 case OR_Success: 2923 llvm_unreachable("Conversion did not fail!"); 2924 break; 2925 } 2926 break; 2927 2928 case FK_NonConstLValueReferenceBindingToTemporary: 2929 case FK_NonConstLValueReferenceBindingToUnrelated: 2930 S.Diag(Kind.getLocation(), 2931 Failure == FK_NonConstLValueReferenceBindingToTemporary 2932 ? diag::err_lvalue_reference_bind_to_temporary 2933 : diag::err_lvalue_reference_bind_to_unrelated) 2934 << DestType.getNonReferenceType() 2935 << Args[0]->getType() 2936 << Args[0]->getSourceRange(); 2937 break; 2938 2939 case FK_RValueReferenceBindingToLValue: 2940 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 2941 << Args[0]->getSourceRange(); 2942 break; 2943 2944 case FK_ReferenceInitDropsQualifiers: 2945 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 2946 << DestType.getNonReferenceType() 2947 << Args[0]->getType() 2948 << Args[0]->getSourceRange(); 2949 break; 2950 2951 case FK_ReferenceInitFailed: 2952 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 2953 << DestType.getNonReferenceType() 2954 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 2955 << Args[0]->getType() 2956 << Args[0]->getSourceRange(); 2957 break; 2958 2959 case FK_ConversionFailed: 2960 S.Diag(Kind.getLocation(), diag::err_cannot_initialize_decl_noname) 2961 << DestType 2962 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 2963 << Args[0]->getType() 2964 << Args[0]->getSourceRange(); 2965 break; 2966 2967 case FK_TooManyInitsForScalar: { 2968 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 2969 2970 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 2971 << /*scalar=*/2 2972 << SourceRange(InitList->getInit(1)->getLocStart(), 2973 InitList->getLocEnd()); 2974 break; 2975 } 2976 2977 case FK_ReferenceBindingToInitList: 2978 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 2979 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 2980 break; 2981 2982 case FK_InitListBadDestinationType: 2983 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 2984 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 2985 break; 2986 } 2987 2988 return true; 2989} 2990