SemaInit.cpp revision f312b1ea179f1c44371f9ee0cd0bc006f612de11
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 "clang/Sema/Designator.h" 19#include "clang/Sema/Initialization.h" 20#include "clang/Sema/Lookup.h" 21#include "clang/Sema/SemaInternal.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/TypeLoc.h" 28#include "llvm/Support/ErrorHandling.h" 29#include <map> 30using namespace clang; 31 32//===----------------------------------------------------------------------===// 33// Sema Initialization Checking 34//===----------------------------------------------------------------------===// 35 36static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) { 37 const ArrayType *AT = Context.getAsArrayType(DeclType); 38 if (!AT) return 0; 39 40 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 41 return 0; 42 43 // See if this is a string literal or @encode. 44 Init = Init->IgnoreParens(); 45 46 // Handle @encode, which is a narrow string. 47 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 48 return Init; 49 50 // Otherwise we can only handle string literals. 51 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 52 if (SL == 0) return 0; 53 54 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 55 // char array can be initialized with a narrow string. 56 // Only allow char x[] = "foo"; not char x[] = L"foo"; 57 if (!SL->isWide()) 58 return ElemTy->isCharType() ? Init : 0; 59 60 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 61 // correction from DR343): "An array with element type compatible with a 62 // qualified or unqualified version of wchar_t may be initialized by a wide 63 // string literal, optionally enclosed in braces." 64 if (Context.typesAreCompatible(Context.getWCharType(), 65 ElemTy.getUnqualifiedType())) 66 return Init; 67 68 return 0; 69} 70 71static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) { 72 // Get the length of the string as parsed. 73 uint64_t StrLength = 74 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 75 76 77 const ArrayType *AT = S.Context.getAsArrayType(DeclT); 78 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 79 // C99 6.7.8p14. We have an array of character type with unknown size 80 // being initialized to a string literal. 81 llvm::APSInt ConstVal(32); 82 ConstVal = StrLength; 83 // Return a new array type (C99 6.7.8p22). 84 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 85 ConstVal, 86 ArrayType::Normal, 0); 87 return; 88 } 89 90 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 91 92 // C99 6.7.8p14. We have an array of character type with known size. However, 93 // the size may be smaller or larger than the string we are initializing. 94 // FIXME: Avoid truncation for 64-bit length strings. 95 if (StrLength-1 > CAT->getSize().getZExtValue()) 96 S.Diag(Str->getSourceRange().getBegin(), 97 diag::warn_initializer_string_for_char_array_too_long) 98 << Str->getSourceRange(); 99 100 // Set the type to the actual size that we are initializing. If we have 101 // something like: 102 // char x[1] = "foo"; 103 // then this will set the string literal's type to char[1]. 104 Str->setType(DeclT); 105} 106 107//===----------------------------------------------------------------------===// 108// Semantic checking for initializer lists. 109//===----------------------------------------------------------------------===// 110 111/// @brief Semantic checking for initializer lists. 112/// 113/// The InitListChecker class contains a set of routines that each 114/// handle the initialization of a certain kind of entity, e.g., 115/// arrays, vectors, struct/union types, scalars, etc. The 116/// InitListChecker itself performs a recursive walk of the subobject 117/// structure of the type to be initialized, while stepping through 118/// the initializer list one element at a time. The IList and Index 119/// parameters to each of the Check* routines contain the active 120/// (syntactic) initializer list and the index into that initializer 121/// list that represents the current initializer. Each routine is 122/// responsible for moving that Index forward as it consumes elements. 123/// 124/// Each Check* routine also has a StructuredList/StructuredIndex 125/// arguments, which contains the current the "structured" (semantic) 126/// initializer list and the index into that initializer list where we 127/// are copying initializers as we map them over to the semantic 128/// list. Once we have completed our recursive walk of the subobject 129/// structure, we will have constructed a full semantic initializer 130/// list. 131/// 132/// C99 designators cause changes in the initializer list traversal, 133/// because they make the initialization "jump" into a specific 134/// subobject and then continue the initialization from that 135/// point. CheckDesignatedInitializer() recursively steps into the 136/// designated subobject and manages backing out the recursion to 137/// initialize the subobjects after the one designated. 138namespace { 139class InitListChecker { 140 Sema &SemaRef; 141 bool hadError; 142 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 143 InitListExpr *FullyStructuredList; 144 145 void CheckImplicitInitList(const InitializedEntity &Entity, 146 InitListExpr *ParentIList, QualType T, 147 unsigned &Index, InitListExpr *StructuredList, 148 unsigned &StructuredIndex, 149 bool TopLevelObject = false); 150 void CheckExplicitInitList(const InitializedEntity &Entity, 151 InitListExpr *IList, QualType &T, 152 unsigned &Index, InitListExpr *StructuredList, 153 unsigned &StructuredIndex, 154 bool TopLevelObject = false); 155 void CheckListElementTypes(const InitializedEntity &Entity, 156 InitListExpr *IList, QualType &DeclType, 157 bool SubobjectIsDesignatorContext, 158 unsigned &Index, 159 InitListExpr *StructuredList, 160 unsigned &StructuredIndex, 161 bool TopLevelObject = false); 162 void CheckSubElementType(const InitializedEntity &Entity, 163 InitListExpr *IList, QualType ElemType, 164 unsigned &Index, 165 InitListExpr *StructuredList, 166 unsigned &StructuredIndex); 167 void CheckScalarType(const InitializedEntity &Entity, 168 InitListExpr *IList, QualType DeclType, 169 unsigned &Index, 170 InitListExpr *StructuredList, 171 unsigned &StructuredIndex); 172 void CheckReferenceType(const InitializedEntity &Entity, 173 InitListExpr *IList, QualType DeclType, 174 unsigned &Index, 175 InitListExpr *StructuredList, 176 unsigned &StructuredIndex); 177 void CheckVectorType(const InitializedEntity &Entity, 178 InitListExpr *IList, QualType DeclType, unsigned &Index, 179 InitListExpr *StructuredList, 180 unsigned &StructuredIndex); 181 void CheckStructUnionTypes(const InitializedEntity &Entity, 182 InitListExpr *IList, QualType DeclType, 183 RecordDecl::field_iterator Field, 184 bool SubobjectIsDesignatorContext, unsigned &Index, 185 InitListExpr *StructuredList, 186 unsigned &StructuredIndex, 187 bool TopLevelObject = false); 188 void CheckArrayType(const InitializedEntity &Entity, 189 InitListExpr *IList, QualType &DeclType, 190 llvm::APSInt elementIndex, 191 bool SubobjectIsDesignatorContext, unsigned &Index, 192 InitListExpr *StructuredList, 193 unsigned &StructuredIndex); 194 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 195 InitListExpr *IList, DesignatedInitExpr *DIE, 196 unsigned DesigIdx, 197 QualType &CurrentObjectType, 198 RecordDecl::field_iterator *NextField, 199 llvm::APSInt *NextElementIndex, 200 unsigned &Index, 201 InitListExpr *StructuredList, 202 unsigned &StructuredIndex, 203 bool FinishSubobjectInit, 204 bool TopLevelObject); 205 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 206 QualType CurrentObjectType, 207 InitListExpr *StructuredList, 208 unsigned StructuredIndex, 209 SourceRange InitRange); 210 void UpdateStructuredListElement(InitListExpr *StructuredList, 211 unsigned &StructuredIndex, 212 Expr *expr); 213 int numArrayElements(QualType DeclType); 214 int numStructUnionElements(QualType DeclType); 215 216 void FillInValueInitForField(unsigned Init, FieldDecl *Field, 217 const InitializedEntity &ParentEntity, 218 InitListExpr *ILE, bool &RequiresSecondPass); 219 void FillInValueInitializations(const InitializedEntity &Entity, 220 InitListExpr *ILE, bool &RequiresSecondPass); 221public: 222 InitListChecker(Sema &S, const InitializedEntity &Entity, 223 InitListExpr *IL, QualType &T); 224 bool HadError() { return hadError; } 225 226 // @brief Retrieves the fully-structured initializer list used for 227 // semantic analysis and code generation. 228 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 229}; 230} // end anonymous namespace 231 232void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field, 233 const InitializedEntity &ParentEntity, 234 InitListExpr *ILE, 235 bool &RequiresSecondPass) { 236 SourceLocation Loc = ILE->getSourceRange().getBegin(); 237 unsigned NumInits = ILE->getNumInits(); 238 InitializedEntity MemberEntity 239 = InitializedEntity::InitializeMember(Field, &ParentEntity); 240 if (Init >= NumInits || !ILE->getInit(Init)) { 241 // FIXME: We probably don't need to handle references 242 // specially here, since value-initialization of references is 243 // handled in InitializationSequence. 244 if (Field->getType()->isReferenceType()) { 245 // C++ [dcl.init.aggr]p9: 246 // If an incomplete or empty initializer-list leaves a 247 // member of reference type uninitialized, the program is 248 // ill-formed. 249 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 250 << Field->getType() 251 << ILE->getSyntacticForm()->getSourceRange(); 252 SemaRef.Diag(Field->getLocation(), 253 diag::note_uninit_reference_member); 254 hadError = true; 255 return; 256 } 257 258 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 259 true); 260 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0); 261 if (!InitSeq) { 262 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0); 263 hadError = true; 264 return; 265 } 266 267 ExprResult MemberInit 268 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg()); 269 if (MemberInit.isInvalid()) { 270 hadError = true; 271 return; 272 } 273 274 if (hadError) { 275 // Do nothing 276 } else if (Init < NumInits) { 277 ILE->setInit(Init, MemberInit.takeAs<Expr>()); 278 } else if (InitSeq.getKind() 279 == InitializationSequence::ConstructorInitialization) { 280 // Value-initialization requires a constructor call, so 281 // extend the initializer list to include the constructor 282 // call and make a note that we'll need to take another pass 283 // through the initializer list. 284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>()); 285 RequiresSecondPass = true; 286 } 287 } else if (InitListExpr *InnerILE 288 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 289 FillInValueInitializations(MemberEntity, InnerILE, 290 RequiresSecondPass); 291} 292 293/// Recursively replaces NULL values within the given initializer list 294/// with expressions that perform value-initialization of the 295/// appropriate type. 296void 297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity, 298 InitListExpr *ILE, 299 bool &RequiresSecondPass) { 300 assert((ILE->getType() != SemaRef.Context.VoidTy) && 301 "Should not have void type"); 302 SourceLocation Loc = ILE->getSourceRange().getBegin(); 303 if (ILE->getSyntacticForm()) 304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 305 306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 307 if (RType->getDecl()->isUnion() && 308 ILE->getInitializedFieldInUnion()) 309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(), 310 Entity, ILE, RequiresSecondPass); 311 else { 312 unsigned Init = 0; 313 for (RecordDecl::field_iterator 314 Field = RType->getDecl()->field_begin(), 315 FieldEnd = RType->getDecl()->field_end(); 316 Field != FieldEnd; ++Field) { 317 if (Field->isUnnamedBitfield()) 318 continue; 319 320 if (hadError) 321 return; 322 323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass); 324 if (hadError) 325 return; 326 327 ++Init; 328 329 // Only look at the first initialization of a union. 330 if (RType->getDecl()->isUnion()) 331 break; 332 } 333 } 334 335 return; 336 } 337 338 QualType ElementType; 339 340 InitializedEntity ElementEntity = Entity; 341 unsigned NumInits = ILE->getNumInits(); 342 unsigned NumElements = NumInits; 343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 344 ElementType = AType->getElementType(); 345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 346 NumElements = CAType->getSize().getZExtValue(); 347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 348 0, Entity); 349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 350 ElementType = VType->getElementType(); 351 NumElements = VType->getNumElements(); 352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 353 0, Entity); 354 } else 355 ElementType = ILE->getType(); 356 357 358 for (unsigned Init = 0; Init != NumElements; ++Init) { 359 if (hadError) 360 return; 361 362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 364 ElementEntity.setElementIndex(Init); 365 366 if (Init >= NumInits || !ILE->getInit(Init)) { 367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 368 true); 369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0); 370 if (!InitSeq) { 371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0); 372 hadError = true; 373 return; 374 } 375 376 ExprResult ElementInit 377 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg()); 378 if (ElementInit.isInvalid()) { 379 hadError = true; 380 return; 381 } 382 383 if (hadError) { 384 // Do nothing 385 } else if (Init < NumInits) { 386 ILE->setInit(Init, ElementInit.takeAs<Expr>()); 387 } else if (InitSeq.getKind() 388 == InitializationSequence::ConstructorInitialization) { 389 // Value-initialization requires a constructor call, so 390 // extend the initializer list to include the constructor 391 // call and make a note that we'll need to take another pass 392 // through the initializer list. 393 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>()); 394 RequiresSecondPass = true; 395 } 396 } else if (InitListExpr *InnerILE 397 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass); 399 } 400} 401 402 403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 404 InitListExpr *IL, QualType &T) 405 : SemaRef(S) { 406 hadError = false; 407 408 unsigned newIndex = 0; 409 unsigned newStructuredIndex = 0; 410 FullyStructuredList 411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 412 CheckExplicitInitList(Entity, IL, T, newIndex, 413 FullyStructuredList, newStructuredIndex, 414 /*TopLevelObject=*/true); 415 416 if (!hadError) { 417 bool RequiresSecondPass = false; 418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass); 419 if (RequiresSecondPass && !hadError) 420 FillInValueInitializations(Entity, FullyStructuredList, 421 RequiresSecondPass); 422 } 423} 424 425int InitListChecker::numArrayElements(QualType DeclType) { 426 // FIXME: use a proper constant 427 int maxElements = 0x7FFFFFFF; 428 if (const ConstantArrayType *CAT = 429 SemaRef.Context.getAsConstantArrayType(DeclType)) { 430 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 431 } 432 return maxElements; 433} 434 435int InitListChecker::numStructUnionElements(QualType DeclType) { 436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 437 int InitializableMembers = 0; 438 for (RecordDecl::field_iterator 439 Field = structDecl->field_begin(), 440 FieldEnd = structDecl->field_end(); 441 Field != FieldEnd; ++Field) { 442 if ((*Field)->getIdentifier() || !(*Field)->isBitField()) 443 ++InitializableMembers; 444 } 445 if (structDecl->isUnion()) 446 return std::min(InitializableMembers, 1); 447 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 448} 449 450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 451 InitListExpr *ParentIList, 452 QualType T, unsigned &Index, 453 InitListExpr *StructuredList, 454 unsigned &StructuredIndex, 455 bool TopLevelObject) { 456 int maxElements = 0; 457 458 if (T->isArrayType()) 459 maxElements = numArrayElements(T); 460 else if (T->isRecordType()) 461 maxElements = numStructUnionElements(T); 462 else if (T->isVectorType()) 463 maxElements = T->getAs<VectorType>()->getNumElements(); 464 else 465 assert(0 && "CheckImplicitInitList(): Illegal type"); 466 467 if (maxElements == 0) { 468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 469 diag::err_implicit_empty_initializer); 470 ++Index; 471 hadError = true; 472 return; 473 } 474 475 // Build a structured initializer list corresponding to this subobject. 476 InitListExpr *StructuredSubobjectInitList 477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 478 StructuredIndex, 479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 480 ParentIList->getSourceRange().getEnd())); 481 unsigned StructuredSubobjectInitIndex = 0; 482 483 // Check the element types and build the structural subobject. 484 unsigned StartIndex = Index; 485 CheckListElementTypes(Entity, ParentIList, T, 486 /*SubobjectIsDesignatorContext=*/false, Index, 487 StructuredSubobjectInitList, 488 StructuredSubobjectInitIndex, 489 TopLevelObject); 490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 491 StructuredSubobjectInitList->setType(T); 492 493 // Update the structured sub-object initializer so that it's ending 494 // range corresponds with the end of the last initializer it used. 495 if (EndIndex < ParentIList->getNumInits()) { 496 SourceLocation EndLoc 497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 498 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 499 } 500 501 // Warn about missing braces. 502 if (T->isArrayType() || T->isRecordType()) { 503 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), 504 diag::warn_missing_braces) 505 << StructuredSubobjectInitList->getSourceRange() 506 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(), 507 "{") 508 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken( 509 StructuredSubobjectInitList->getLocEnd()), 510 "}"); 511 } 512} 513 514void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 515 InitListExpr *IList, QualType &T, 516 unsigned &Index, 517 InitListExpr *StructuredList, 518 unsigned &StructuredIndex, 519 bool TopLevelObject) { 520 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 521 SyntacticToSemantic[IList] = StructuredList; 522 StructuredList->setSyntacticForm(IList); 523 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 524 Index, StructuredList, StructuredIndex, TopLevelObject); 525 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context); 526 IList->setType(ExprTy); 527 StructuredList->setType(ExprTy); 528 if (hadError) 529 return; 530 531 if (Index < IList->getNumInits()) { 532 // We have leftover initializers 533 if (StructuredIndex == 1 && 534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 536 if (SemaRef.getLangOptions().CPlusPlus) { 537 DK = diag::err_excess_initializers_in_char_array_initializer; 538 hadError = true; 539 } 540 // Special-case 541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 542 << IList->getInit(Index)->getSourceRange(); 543 } else if (!T->isIncompleteType()) { 544 // Don't complain for incomplete types, since we'll get an error 545 // elsewhere 546 QualType CurrentObjectType = StructuredList->getType(); 547 int initKind = 548 CurrentObjectType->isArrayType()? 0 : 549 CurrentObjectType->isVectorType()? 1 : 550 CurrentObjectType->isScalarType()? 2 : 551 CurrentObjectType->isUnionType()? 3 : 552 4; 553 554 unsigned DK = diag::warn_excess_initializers; 555 if (SemaRef.getLangOptions().CPlusPlus) { 556 DK = diag::err_excess_initializers; 557 hadError = true; 558 } 559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 560 DK = diag::err_excess_initializers; 561 hadError = true; 562 } 563 564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 565 << initKind << IList->getInit(Index)->getSourceRange(); 566 } 567 } 568 569 if (T->isScalarType() && !TopLevelObject) 570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 571 << IList->getSourceRange() 572 << FixItHint::CreateRemoval(IList->getLocStart()) 573 << FixItHint::CreateRemoval(IList->getLocEnd()); 574} 575 576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 577 InitListExpr *IList, 578 QualType &DeclType, 579 bool SubobjectIsDesignatorContext, 580 unsigned &Index, 581 InitListExpr *StructuredList, 582 unsigned &StructuredIndex, 583 bool TopLevelObject) { 584 if (DeclType->isScalarType()) { 585 CheckScalarType(Entity, IList, DeclType, Index, 586 StructuredList, StructuredIndex); 587 } else if (DeclType->isVectorType()) { 588 CheckVectorType(Entity, IList, DeclType, Index, 589 StructuredList, StructuredIndex); 590 } else if (DeclType->isAggregateType()) { 591 if (DeclType->isRecordType()) { 592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(), 594 SubobjectIsDesignatorContext, Index, 595 StructuredList, StructuredIndex, 596 TopLevelObject); 597 } else if (DeclType->isArrayType()) { 598 llvm::APSInt Zero( 599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 600 false); 601 CheckArrayType(Entity, IList, DeclType, Zero, 602 SubobjectIsDesignatorContext, Index, 603 StructuredList, StructuredIndex); 604 } else 605 assert(0 && "Aggregate that isn't a structure or array?!"); 606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 607 // This type is invalid, issue a diagnostic. 608 ++Index; 609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 610 << DeclType; 611 hadError = true; 612 } else if (DeclType->isRecordType()) { 613 // C++ [dcl.init]p14: 614 // [...] If the class is an aggregate (8.5.1), and the initializer 615 // is a brace-enclosed list, see 8.5.1. 616 // 617 // Note: 8.5.1 is handled below; here, we diagnose the case where 618 // we have an initializer list and a destination type that is not 619 // an aggregate. 620 // FIXME: In C++0x, this is yet another form of initialization. 621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 622 << DeclType << IList->getSourceRange(); 623 hadError = true; 624 } else if (DeclType->isReferenceType()) { 625 CheckReferenceType(Entity, IList, DeclType, Index, 626 StructuredList, StructuredIndex); 627 } else if (DeclType->isObjCObjectType()) { 628 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class) 629 << DeclType; 630 hadError = true; 631 } else { 632 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 633 << DeclType; 634 hadError = true; 635 } 636} 637 638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 639 InitListExpr *IList, 640 QualType ElemType, 641 unsigned &Index, 642 InitListExpr *StructuredList, 643 unsigned &StructuredIndex) { 644 Expr *expr = IList->getInit(Index); 645 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 646 unsigned newIndex = 0; 647 unsigned newStructuredIndex = 0; 648 InitListExpr *newStructuredList 649 = getStructuredSubobjectInit(IList, Index, ElemType, 650 StructuredList, StructuredIndex, 651 SubInitList->getSourceRange()); 652 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex, 653 newStructuredList, newStructuredIndex); 654 ++StructuredIndex; 655 ++Index; 656 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) { 657 CheckStringInit(Str, ElemType, SemaRef); 658 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 659 ++Index; 660 } else if (ElemType->isScalarType()) { 661 CheckScalarType(Entity, IList, ElemType, Index, 662 StructuredList, StructuredIndex); 663 } else if (ElemType->isReferenceType()) { 664 CheckReferenceType(Entity, IList, ElemType, Index, 665 StructuredList, StructuredIndex); 666 } else { 667 if (SemaRef.getLangOptions().CPlusPlus) { 668 // C++ [dcl.init.aggr]p12: 669 // All implicit type conversions (clause 4) are considered when 670 // initializing the aggregate member with an ini- tializer from 671 // an initializer-list. If the initializer can initialize a 672 // member, the member is initialized. [...] 673 674 // FIXME: Better EqualLoc? 675 InitializationKind Kind = 676 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation()); 677 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1); 678 679 if (Seq) { 680 ExprResult Result = 681 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1)); 682 if (Result.isInvalid()) 683 hadError = true; 684 685 UpdateStructuredListElement(StructuredList, StructuredIndex, 686 Result.takeAs<Expr>()); 687 ++Index; 688 return; 689 } 690 691 // Fall through for subaggregate initialization 692 } else { 693 // C99 6.7.8p13: 694 // 695 // The initializer for a structure or union object that has 696 // automatic storage duration shall be either an initializer 697 // list as described below, or a single expression that has 698 // compatible structure or union type. In the latter case, the 699 // initial value of the object, including unnamed members, is 700 // that of the expression. 701 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 702 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) { 703 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 704 ++Index; 705 return; 706 } 707 708 // Fall through for subaggregate initialization 709 } 710 711 // C++ [dcl.init.aggr]p12: 712 // 713 // [...] Otherwise, if the member is itself a non-empty 714 // subaggregate, brace elision is assumed and the initializer is 715 // considered for the initialization of the first member of 716 // the subaggregate. 717 if (ElemType->isAggregateType() || ElemType->isVectorType()) { 718 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 719 StructuredIndex); 720 ++StructuredIndex; 721 } else { 722 // We cannot initialize this element, so let 723 // PerformCopyInitialization produce the appropriate diagnostic. 724 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), 725 SemaRef.Owned(expr)); 726 IList->setInit(Index, 0); 727 hadError = true; 728 ++Index; 729 ++StructuredIndex; 730 } 731 } 732} 733 734void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 735 InitListExpr *IList, QualType DeclType, 736 unsigned &Index, 737 InitListExpr *StructuredList, 738 unsigned &StructuredIndex) { 739 if (Index < IList->getNumInits()) { 740 Expr *expr = IList->getInit(Index); 741 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 742 SemaRef.Diag(SubIList->getLocStart(), 743 diag::warn_many_braces_around_scalar_init) 744 << SubIList->getSourceRange(); 745 746 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 747 StructuredIndex); 748 return; 749 } else if (isa<DesignatedInitExpr>(expr)) { 750 SemaRef.Diag(expr->getSourceRange().getBegin(), 751 diag::err_designator_for_scalar_init) 752 << DeclType << expr->getSourceRange(); 753 hadError = true; 754 ++Index; 755 ++StructuredIndex; 756 return; 757 } 758 759 ExprResult Result = 760 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 761 SemaRef.Owned(expr)); 762 763 Expr *ResultExpr = 0; 764 765 if (Result.isInvalid()) 766 hadError = true; // types weren't compatible. 767 else { 768 ResultExpr = Result.takeAs<Expr>(); 769 770 if (ResultExpr != expr) { 771 // The type was promoted, update initializer list. 772 IList->setInit(Index, ResultExpr); 773 } 774 } 775 if (hadError) 776 ++StructuredIndex; 777 else 778 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 779 ++Index; 780 } else { 781 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) 782 << IList->getSourceRange(); 783 hadError = true; 784 ++Index; 785 ++StructuredIndex; 786 return; 787 } 788} 789 790void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 791 InitListExpr *IList, QualType DeclType, 792 unsigned &Index, 793 InitListExpr *StructuredList, 794 unsigned &StructuredIndex) { 795 if (Index < IList->getNumInits()) { 796 Expr *expr = IList->getInit(Index); 797 if (isa<InitListExpr>(expr)) { 798 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 799 << DeclType << IList->getSourceRange(); 800 hadError = true; 801 ++Index; 802 ++StructuredIndex; 803 return; 804 } 805 806 ExprResult Result = 807 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 808 SemaRef.Owned(expr)); 809 810 if (Result.isInvalid()) 811 hadError = true; 812 813 expr = Result.takeAs<Expr>(); 814 IList->setInit(Index, expr); 815 816 if (hadError) 817 ++StructuredIndex; 818 else 819 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 820 ++Index; 821 } else { 822 // FIXME: It would be wonderful if we could point at the actual member. In 823 // general, it would be useful to pass location information down the stack, 824 // so that we know the location (or decl) of the "current object" being 825 // initialized. 826 SemaRef.Diag(IList->getLocStart(), 827 diag::err_init_reference_member_uninitialized) 828 << DeclType 829 << IList->getSourceRange(); 830 hadError = true; 831 ++Index; 832 ++StructuredIndex; 833 return; 834 } 835} 836 837void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 838 InitListExpr *IList, QualType DeclType, 839 unsigned &Index, 840 InitListExpr *StructuredList, 841 unsigned &StructuredIndex) { 842 if (Index < IList->getNumInits()) { 843 const VectorType *VT = DeclType->getAs<VectorType>(); 844 unsigned maxElements = VT->getNumElements(); 845 unsigned numEltsInit = 0; 846 QualType elementType = VT->getElementType(); 847 848 if (!SemaRef.getLangOptions().OpenCL) { 849 InitializedEntity ElementEntity = 850 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 851 852 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 853 // Don't attempt to go past the end of the init list 854 if (Index >= IList->getNumInits()) 855 break; 856 857 ElementEntity.setElementIndex(Index); 858 CheckSubElementType(ElementEntity, IList, elementType, Index, 859 StructuredList, StructuredIndex); 860 } 861 } else { 862 InitializedEntity ElementEntity = 863 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 864 865 // OpenCL initializers allows vectors to be constructed from vectors. 866 for (unsigned i = 0; i < maxElements; ++i) { 867 // Don't attempt to go past the end of the init list 868 if (Index >= IList->getNumInits()) 869 break; 870 871 ElementEntity.setElementIndex(Index); 872 873 QualType IType = IList->getInit(Index)->getType(); 874 if (!IType->isVectorType()) { 875 CheckSubElementType(ElementEntity, IList, elementType, Index, 876 StructuredList, StructuredIndex); 877 ++numEltsInit; 878 } else { 879 QualType VecType; 880 const VectorType *IVT = IType->getAs<VectorType>(); 881 unsigned numIElts = IVT->getNumElements(); 882 883 if (IType->isExtVectorType()) 884 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 885 else 886 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 887 IVT->getAltiVecSpecific()); 888 CheckSubElementType(ElementEntity, IList, VecType, Index, 889 StructuredList, StructuredIndex); 890 numEltsInit += numIElts; 891 } 892 } 893 } 894 895 // OpenCL requires all elements to be initialized. 896 if (numEltsInit != maxElements) 897 if (SemaRef.getLangOptions().OpenCL) 898 SemaRef.Diag(IList->getSourceRange().getBegin(), 899 diag::err_vector_incorrect_num_initializers) 900 << (numEltsInit < maxElements) << maxElements << numEltsInit; 901 } 902} 903 904void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 905 InitListExpr *IList, QualType &DeclType, 906 llvm::APSInt elementIndex, 907 bool SubobjectIsDesignatorContext, 908 unsigned &Index, 909 InitListExpr *StructuredList, 910 unsigned &StructuredIndex) { 911 // Check for the special-case of initializing an array with a string. 912 if (Index < IList->getNumInits()) { 913 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType, 914 SemaRef.Context)) { 915 CheckStringInit(Str, DeclType, SemaRef); 916 // We place the string literal directly into the resulting 917 // initializer list. This is the only place where the structure 918 // of the structured initializer list doesn't match exactly, 919 // because doing so would involve allocating one character 920 // constant for each string. 921 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 922 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 923 ++Index; 924 return; 925 } 926 } 927 if (const VariableArrayType *VAT = 928 SemaRef.Context.getAsVariableArrayType(DeclType)) { 929 // Check for VLAs; in standard C it would be possible to check this 930 // earlier, but I don't know where clang accepts VLAs (gcc accepts 931 // them in all sorts of strange places). 932 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 933 diag::err_variable_object_no_init) 934 << VAT->getSizeExpr()->getSourceRange(); 935 hadError = true; 936 ++Index; 937 ++StructuredIndex; 938 return; 939 } 940 941 // We might know the maximum number of elements in advance. 942 llvm::APSInt maxElements(elementIndex.getBitWidth(), 943 elementIndex.isUnsigned()); 944 bool maxElementsKnown = false; 945 if (const ConstantArrayType *CAT = 946 SemaRef.Context.getAsConstantArrayType(DeclType)) { 947 maxElements = CAT->getSize(); 948 elementIndex.extOrTrunc(maxElements.getBitWidth()); 949 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 950 maxElementsKnown = true; 951 } 952 953 QualType elementType = SemaRef.Context.getAsArrayType(DeclType) 954 ->getElementType(); 955 while (Index < IList->getNumInits()) { 956 Expr *Init = IList->getInit(Index); 957 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 958 // If we're not the subobject that matches up with the '{' for 959 // the designator, we shouldn't be handling the 960 // designator. Return immediately. 961 if (!SubobjectIsDesignatorContext) 962 return; 963 964 // Handle this designated initializer. elementIndex will be 965 // updated to be the next array element we'll initialize. 966 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 967 DeclType, 0, &elementIndex, Index, 968 StructuredList, StructuredIndex, true, 969 false)) { 970 hadError = true; 971 continue; 972 } 973 974 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 975 maxElements.extend(elementIndex.getBitWidth()); 976 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 977 elementIndex.extend(maxElements.getBitWidth()); 978 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 979 980 // If the array is of incomplete type, keep track of the number of 981 // elements in the initializer. 982 if (!maxElementsKnown && elementIndex > maxElements) 983 maxElements = elementIndex; 984 985 continue; 986 } 987 988 // If we know the maximum number of elements, and we've already 989 // hit it, stop consuming elements in the initializer list. 990 if (maxElementsKnown && elementIndex == maxElements) 991 break; 992 993 InitializedEntity ElementEntity = 994 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 995 Entity); 996 // Check this element. 997 CheckSubElementType(ElementEntity, IList, elementType, Index, 998 StructuredList, StructuredIndex); 999 ++elementIndex; 1000 1001 // If the array is of incomplete type, keep track of the number of 1002 // elements in the initializer. 1003 if (!maxElementsKnown && elementIndex > maxElements) 1004 maxElements = elementIndex; 1005 } 1006 if (!hadError && DeclType->isIncompleteArrayType()) { 1007 // If this is an incomplete array type, the actual type needs to 1008 // be calculated here. 1009 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1010 if (maxElements == Zero) { 1011 // Sizing an array implicitly to zero is not allowed by ISO C, 1012 // but is supported by GNU. 1013 SemaRef.Diag(IList->getLocStart(), 1014 diag::ext_typecheck_zero_array_size); 1015 } 1016 1017 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1018 ArrayType::Normal, 0); 1019 } 1020} 1021 1022void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity, 1023 InitListExpr *IList, 1024 QualType DeclType, 1025 RecordDecl::field_iterator Field, 1026 bool SubobjectIsDesignatorContext, 1027 unsigned &Index, 1028 InitListExpr *StructuredList, 1029 unsigned &StructuredIndex, 1030 bool TopLevelObject) { 1031 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 1032 1033 // If the record is invalid, some of it's members are invalid. To avoid 1034 // confusion, we forgo checking the intializer for the entire record. 1035 if (structDecl->isInvalidDecl()) { 1036 hadError = true; 1037 return; 1038 } 1039 1040 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1041 // Value-initialize the first named member of the union. 1042 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1043 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1044 Field != FieldEnd; ++Field) { 1045 if (Field->getDeclName()) { 1046 StructuredList->setInitializedFieldInUnion(*Field); 1047 break; 1048 } 1049 } 1050 return; 1051 } 1052 1053 // If structDecl is a forward declaration, this loop won't do 1054 // anything except look at designated initializers; That's okay, 1055 // because an error should get printed out elsewhere. It might be 1056 // worthwhile to skip over the rest of the initializer, though. 1057 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1058 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1059 bool InitializedSomething = false; 1060 bool CheckForMissingFields = true; 1061 while (Index < IList->getNumInits()) { 1062 Expr *Init = IList->getInit(Index); 1063 1064 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1065 // If we're not the subobject that matches up with the '{' for 1066 // the designator, we shouldn't be handling the 1067 // designator. Return immediately. 1068 if (!SubobjectIsDesignatorContext) 1069 return; 1070 1071 // Handle this designated initializer. Field will be updated to 1072 // the next field that we'll be initializing. 1073 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1074 DeclType, &Field, 0, Index, 1075 StructuredList, StructuredIndex, 1076 true, TopLevelObject)) 1077 hadError = true; 1078 1079 InitializedSomething = true; 1080 1081 // Disable check for missing fields when designators are used. 1082 // This matches gcc behaviour. 1083 CheckForMissingFields = false; 1084 continue; 1085 } 1086 1087 if (Field == FieldEnd) { 1088 // We've run out of fields. We're done. 1089 break; 1090 } 1091 1092 // We've already initialized a member of a union. We're done. 1093 if (InitializedSomething && DeclType->isUnionType()) 1094 break; 1095 1096 // If we've hit the flexible array member at the end, we're done. 1097 if (Field->getType()->isIncompleteArrayType()) 1098 break; 1099 1100 if (Field->isUnnamedBitfield()) { 1101 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1102 ++Field; 1103 continue; 1104 } 1105 1106 InitializedEntity MemberEntity = 1107 InitializedEntity::InitializeMember(*Field, &Entity); 1108 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1109 StructuredList, StructuredIndex); 1110 InitializedSomething = true; 1111 1112 if (DeclType->isUnionType()) { 1113 // Initialize the first field within the union. 1114 StructuredList->setInitializedFieldInUnion(*Field); 1115 } 1116 1117 ++Field; 1118 } 1119 1120 // Emit warnings for missing struct field initializers. 1121 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd && 1122 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) { 1123 // It is possible we have one or more unnamed bitfields remaining. 1124 // Find first (if any) named field and emit warning. 1125 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 1126 it != end; ++it) { 1127 if (!it->isUnnamedBitfield()) { 1128 SemaRef.Diag(IList->getSourceRange().getEnd(), 1129 diag::warn_missing_field_initializers) << it->getName(); 1130 break; 1131 } 1132 } 1133 } 1134 1135 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1136 Index >= IList->getNumInits()) 1137 return; 1138 1139 // Handle GNU flexible array initializers. 1140 if (!TopLevelObject && 1141 (!isa<InitListExpr>(IList->getInit(Index)) || 1142 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1143 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1144 diag::err_flexible_array_init_nonempty) 1145 << IList->getInit(Index)->getSourceRange().getBegin(); 1146 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1147 << *Field; 1148 hadError = true; 1149 ++Index; 1150 return; 1151 } else { 1152 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1153 diag::ext_flexible_array_init) 1154 << IList->getInit(Index)->getSourceRange().getBegin(); 1155 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1156 << *Field; 1157 } 1158 1159 InitializedEntity MemberEntity = 1160 InitializedEntity::InitializeMember(*Field, &Entity); 1161 1162 if (isa<InitListExpr>(IList->getInit(Index))) 1163 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1164 StructuredList, StructuredIndex); 1165 else 1166 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 1167 StructuredList, StructuredIndex); 1168} 1169 1170/// \brief Expand a field designator that refers to a member of an 1171/// anonymous struct or union into a series of field designators that 1172/// refers to the field within the appropriate subobject. 1173/// 1174/// Field/FieldIndex will be updated to point to the (new) 1175/// currently-designated field. 1176static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1177 DesignatedInitExpr *DIE, 1178 unsigned DesigIdx, 1179 FieldDecl *Field, 1180 RecordDecl::field_iterator &FieldIter, 1181 unsigned &FieldIndex) { 1182 typedef DesignatedInitExpr::Designator Designator; 1183 1184 // Build the path from the current object to the member of the 1185 // anonymous struct/union (backwards). 1186 llvm::SmallVector<FieldDecl *, 4> Path; 1187 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path); 1188 1189 // Build the replacement designators. 1190 llvm::SmallVector<Designator, 4> Replacements; 1191 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 1192 FI = Path.rbegin(), FIEnd = Path.rend(); 1193 FI != FIEnd; ++FI) { 1194 if (FI + 1 == FIEnd) 1195 Replacements.push_back(Designator((IdentifierInfo *)0, 1196 DIE->getDesignator(DesigIdx)->getDotLoc(), 1197 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1198 else 1199 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1200 SourceLocation())); 1201 Replacements.back().setField(*FI); 1202 } 1203 1204 // Expand the current designator into the set of replacement 1205 // designators, so we have a full subobject path down to where the 1206 // member of the anonymous struct/union is actually stored. 1207 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 1208 &Replacements[0] + Replacements.size()); 1209 1210 // Update FieldIter/FieldIndex; 1211 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext()); 1212 FieldIter = Record->field_begin(); 1213 FieldIndex = 0; 1214 for (RecordDecl::field_iterator FEnd = Record->field_end(); 1215 FieldIter != FEnd; ++FieldIter) { 1216 if (FieldIter->isUnnamedBitfield()) 1217 continue; 1218 1219 if (*FieldIter == Path.back()) 1220 return; 1221 1222 ++FieldIndex; 1223 } 1224 1225 assert(false && "Unable to find anonymous struct/union field"); 1226} 1227 1228/// @brief Check the well-formedness of a C99 designated initializer. 1229/// 1230/// Determines whether the designated initializer @p DIE, which 1231/// resides at the given @p Index within the initializer list @p 1232/// IList, is well-formed for a current object of type @p DeclType 1233/// (C99 6.7.8). The actual subobject that this designator refers to 1234/// within the current subobject is returned in either 1235/// @p NextField or @p NextElementIndex (whichever is appropriate). 1236/// 1237/// @param IList The initializer list in which this designated 1238/// initializer occurs. 1239/// 1240/// @param DIE The designated initializer expression. 1241/// 1242/// @param DesigIdx The index of the current designator. 1243/// 1244/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1245/// into which the designation in @p DIE should refer. 1246/// 1247/// @param NextField If non-NULL and the first designator in @p DIE is 1248/// a field, this will be set to the field declaration corresponding 1249/// to the field named by the designator. 1250/// 1251/// @param NextElementIndex If non-NULL and the first designator in @p 1252/// DIE is an array designator or GNU array-range designator, this 1253/// will be set to the last index initialized by this designator. 1254/// 1255/// @param Index Index into @p IList where the designated initializer 1256/// @p DIE occurs. 1257/// 1258/// @param StructuredList The initializer list expression that 1259/// describes all of the subobject initializers in the order they'll 1260/// actually be initialized. 1261/// 1262/// @returns true if there was an error, false otherwise. 1263bool 1264InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 1265 InitListExpr *IList, 1266 DesignatedInitExpr *DIE, 1267 unsigned DesigIdx, 1268 QualType &CurrentObjectType, 1269 RecordDecl::field_iterator *NextField, 1270 llvm::APSInt *NextElementIndex, 1271 unsigned &Index, 1272 InitListExpr *StructuredList, 1273 unsigned &StructuredIndex, 1274 bool FinishSubobjectInit, 1275 bool TopLevelObject) { 1276 if (DesigIdx == DIE->size()) { 1277 // Check the actual initialization for the designated object type. 1278 bool prevHadError = hadError; 1279 1280 // Temporarily remove the designator expression from the 1281 // initializer list that the child calls see, so that we don't try 1282 // to re-process the designator. 1283 unsigned OldIndex = Index; 1284 IList->setInit(OldIndex, DIE->getInit()); 1285 1286 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 1287 StructuredList, StructuredIndex); 1288 1289 // Restore the designated initializer expression in the syntactic 1290 // form of the initializer list. 1291 if (IList->getInit(OldIndex) != DIE->getInit()) 1292 DIE->setInit(IList->getInit(OldIndex)); 1293 IList->setInit(OldIndex, DIE); 1294 1295 return hadError && !prevHadError; 1296 } 1297 1298 bool IsFirstDesignator = (DesigIdx == 0); 1299 assert((IsFirstDesignator || StructuredList) && 1300 "Need a non-designated initializer list to start from"); 1301 1302 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1303 // Determine the structural initializer list that corresponds to the 1304 // current subobject. 1305 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1306 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1307 StructuredList, StructuredIndex, 1308 SourceRange(D->getStartLocation(), 1309 DIE->getSourceRange().getEnd())); 1310 assert(StructuredList && "Expected a structured initializer list"); 1311 1312 if (D->isFieldDesignator()) { 1313 // C99 6.7.8p7: 1314 // 1315 // If a designator has the form 1316 // 1317 // . identifier 1318 // 1319 // then the current object (defined below) shall have 1320 // structure or union type and the identifier shall be the 1321 // name of a member of that type. 1322 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1323 if (!RT) { 1324 SourceLocation Loc = D->getDotLoc(); 1325 if (Loc.isInvalid()) 1326 Loc = D->getFieldLoc(); 1327 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1328 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1329 ++Index; 1330 return true; 1331 } 1332 1333 // Note: we perform a linear search of the fields here, despite 1334 // the fact that we have a faster lookup method, because we always 1335 // need to compute the field's index. 1336 FieldDecl *KnownField = D->getField(); 1337 IdentifierInfo *FieldName = D->getFieldName(); 1338 unsigned FieldIndex = 0; 1339 RecordDecl::field_iterator 1340 Field = RT->getDecl()->field_begin(), 1341 FieldEnd = RT->getDecl()->field_end(); 1342 for (; Field != FieldEnd; ++Field) { 1343 if (Field->isUnnamedBitfield()) 1344 continue; 1345 1346 if (KnownField == *Field || Field->getIdentifier() == FieldName) 1347 break; 1348 1349 ++FieldIndex; 1350 } 1351 1352 if (Field == FieldEnd) { 1353 // There was no normal field in the struct with the designated 1354 // name. Perform another lookup for this name, which may find 1355 // something that we can't designate (e.g., a member function), 1356 // may find nothing, or may find a member of an anonymous 1357 // struct/union. 1358 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1359 FieldDecl *ReplacementField = 0; 1360 if (Lookup.first == Lookup.second) { 1361 // Name lookup didn't find anything. Determine whether this 1362 // was a typo for another field name. 1363 LookupResult R(SemaRef, FieldName, D->getFieldLoc(), 1364 Sema::LookupMemberName); 1365 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false, 1366 Sema::CTC_NoKeywords) && 1367 (ReplacementField = R.getAsSingle<FieldDecl>()) && 1368 ReplacementField->getDeclContext()->getLookupContext() 1369 ->Equals(RT->getDecl())) { 1370 SemaRef.Diag(D->getFieldLoc(), 1371 diag::err_field_designator_unknown_suggest) 1372 << FieldName << CurrentObjectType << R.getLookupName() 1373 << FixItHint::CreateReplacement(D->getFieldLoc(), 1374 R.getLookupName().getAsString()); 1375 SemaRef.Diag(ReplacementField->getLocation(), 1376 diag::note_previous_decl) 1377 << ReplacementField->getDeclName(); 1378 } else { 1379 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1380 << FieldName << CurrentObjectType; 1381 ++Index; 1382 return true; 1383 } 1384 } else if (!KnownField) { 1385 // Determine whether we found a field at all. 1386 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first); 1387 } 1388 1389 if (!ReplacementField) { 1390 // Name lookup found something, but it wasn't a field. 1391 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1392 << FieldName; 1393 SemaRef.Diag((*Lookup.first)->getLocation(), 1394 diag::note_field_designator_found); 1395 ++Index; 1396 return true; 1397 } 1398 1399 if (!KnownField && 1400 cast<RecordDecl>((ReplacementField)->getDeclContext()) 1401 ->isAnonymousStructOrUnion()) { 1402 // Handle an field designator that refers to a member of an 1403 // anonymous struct or union. 1404 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, 1405 ReplacementField, 1406 Field, FieldIndex); 1407 D = DIE->getDesignator(DesigIdx); 1408 } else if (!KnownField) { 1409 // The replacement field comes from typo correction; find it 1410 // in the list of fields. 1411 FieldIndex = 0; 1412 Field = RT->getDecl()->field_begin(); 1413 for (; Field != FieldEnd; ++Field) { 1414 if (Field->isUnnamedBitfield()) 1415 continue; 1416 1417 if (ReplacementField == *Field || 1418 Field->getIdentifier() == ReplacementField->getIdentifier()) 1419 break; 1420 1421 ++FieldIndex; 1422 } 1423 } 1424 } else if (!KnownField && 1425 cast<RecordDecl>((*Field)->getDeclContext()) 1426 ->isAnonymousStructOrUnion()) { 1427 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field, 1428 Field, FieldIndex); 1429 D = DIE->getDesignator(DesigIdx); 1430 } 1431 1432 // All of the fields of a union are located at the same place in 1433 // the initializer list. 1434 if (RT->getDecl()->isUnion()) { 1435 FieldIndex = 0; 1436 StructuredList->setInitializedFieldInUnion(*Field); 1437 } 1438 1439 // Update the designator with the field declaration. 1440 D->setField(*Field); 1441 1442 // Make sure that our non-designated initializer list has space 1443 // for a subobject corresponding to this field. 1444 if (FieldIndex >= StructuredList->getNumInits()) 1445 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1446 1447 // This designator names a flexible array member. 1448 if (Field->getType()->isIncompleteArrayType()) { 1449 bool Invalid = false; 1450 if ((DesigIdx + 1) != DIE->size()) { 1451 // We can't designate an object within the flexible array 1452 // member (because GCC doesn't allow it). 1453 DesignatedInitExpr::Designator *NextD 1454 = DIE->getDesignator(DesigIdx + 1); 1455 SemaRef.Diag(NextD->getStartLocation(), 1456 diag::err_designator_into_flexible_array_member) 1457 << SourceRange(NextD->getStartLocation(), 1458 DIE->getSourceRange().getEnd()); 1459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1460 << *Field; 1461 Invalid = true; 1462 } 1463 1464 if (!hadError && !isa<InitListExpr>(DIE->getInit())) { 1465 // The initializer is not an initializer list. 1466 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1467 diag::err_flexible_array_init_needs_braces) 1468 << DIE->getInit()->getSourceRange(); 1469 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1470 << *Field; 1471 Invalid = true; 1472 } 1473 1474 // Handle GNU flexible array initializers. 1475 if (!Invalid && !TopLevelObject && 1476 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1477 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1478 diag::err_flexible_array_init_nonempty) 1479 << DIE->getSourceRange().getBegin(); 1480 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1481 << *Field; 1482 Invalid = true; 1483 } 1484 1485 if (Invalid) { 1486 ++Index; 1487 return true; 1488 } 1489 1490 // Initialize the array. 1491 bool prevHadError = hadError; 1492 unsigned newStructuredIndex = FieldIndex; 1493 unsigned OldIndex = Index; 1494 IList->setInit(Index, DIE->getInit()); 1495 1496 InitializedEntity MemberEntity = 1497 InitializedEntity::InitializeMember(*Field, &Entity); 1498 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1499 StructuredList, newStructuredIndex); 1500 1501 IList->setInit(OldIndex, DIE); 1502 if (hadError && !prevHadError) { 1503 ++Field; 1504 ++FieldIndex; 1505 if (NextField) 1506 *NextField = Field; 1507 StructuredIndex = FieldIndex; 1508 return true; 1509 } 1510 } else { 1511 // Recurse to check later designated subobjects. 1512 QualType FieldType = (*Field)->getType(); 1513 unsigned newStructuredIndex = FieldIndex; 1514 1515 InitializedEntity MemberEntity = 1516 InitializedEntity::InitializeMember(*Field, &Entity); 1517 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 1518 FieldType, 0, 0, Index, 1519 StructuredList, newStructuredIndex, 1520 true, false)) 1521 return true; 1522 } 1523 1524 // Find the position of the next field to be initialized in this 1525 // subobject. 1526 ++Field; 1527 ++FieldIndex; 1528 1529 // If this the first designator, our caller will continue checking 1530 // the rest of this struct/class/union subobject. 1531 if (IsFirstDesignator) { 1532 if (NextField) 1533 *NextField = Field; 1534 StructuredIndex = FieldIndex; 1535 return false; 1536 } 1537 1538 if (!FinishSubobjectInit) 1539 return false; 1540 1541 // We've already initialized something in the union; we're done. 1542 if (RT->getDecl()->isUnion()) 1543 return hadError; 1544 1545 // Check the remaining fields within this class/struct/union subobject. 1546 bool prevHadError = hadError; 1547 1548 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index, 1549 StructuredList, FieldIndex); 1550 return hadError && !prevHadError; 1551 } 1552 1553 // C99 6.7.8p6: 1554 // 1555 // If a designator has the form 1556 // 1557 // [ constant-expression ] 1558 // 1559 // then the current object (defined below) shall have array 1560 // type and the expression shall be an integer constant 1561 // expression. If the array is of unknown size, any 1562 // nonnegative value is valid. 1563 // 1564 // Additionally, cope with the GNU extension that permits 1565 // designators of the form 1566 // 1567 // [ constant-expression ... constant-expression ] 1568 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1569 if (!AT) { 1570 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1571 << CurrentObjectType; 1572 ++Index; 1573 return true; 1574 } 1575 1576 Expr *IndexExpr = 0; 1577 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1578 if (D->isArrayDesignator()) { 1579 IndexExpr = DIE->getArrayIndex(*D); 1580 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1581 DesignatedEndIndex = DesignatedStartIndex; 1582 } else { 1583 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1584 1585 1586 DesignatedStartIndex = 1587 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1588 DesignatedEndIndex = 1589 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1590 IndexExpr = DIE->getArrayRangeEnd(*D); 1591 1592 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue()) 1593 FullyStructuredList->sawArrayRangeDesignator(); 1594 } 1595 1596 if (isa<ConstantArrayType>(AT)) { 1597 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1598 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1599 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1600 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1601 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1602 if (DesignatedEndIndex >= MaxElements) { 1603 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1604 diag::err_array_designator_too_large) 1605 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1606 << IndexExpr->getSourceRange(); 1607 ++Index; 1608 return true; 1609 } 1610 } else { 1611 // Make sure the bit-widths and signedness match. 1612 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1613 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1614 else if (DesignatedStartIndex.getBitWidth() < 1615 DesignatedEndIndex.getBitWidth()) 1616 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1617 DesignatedStartIndex.setIsUnsigned(true); 1618 DesignatedEndIndex.setIsUnsigned(true); 1619 } 1620 1621 // Make sure that our non-designated initializer list has space 1622 // for a subobject corresponding to this array element. 1623 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1624 StructuredList->resizeInits(SemaRef.Context, 1625 DesignatedEndIndex.getZExtValue() + 1); 1626 1627 // Repeatedly perform subobject initializations in the range 1628 // [DesignatedStartIndex, DesignatedEndIndex]. 1629 1630 // Move to the next designator 1631 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1632 unsigned OldIndex = Index; 1633 1634 InitializedEntity ElementEntity = 1635 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1636 1637 while (DesignatedStartIndex <= DesignatedEndIndex) { 1638 // Recurse to check later designated subobjects. 1639 QualType ElementType = AT->getElementType(); 1640 Index = OldIndex; 1641 1642 ElementEntity.setElementIndex(ElementIndex); 1643 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1, 1644 ElementType, 0, 0, Index, 1645 StructuredList, ElementIndex, 1646 (DesignatedStartIndex == DesignatedEndIndex), 1647 false)) 1648 return true; 1649 1650 // Move to the next index in the array that we'll be initializing. 1651 ++DesignatedStartIndex; 1652 ElementIndex = DesignatedStartIndex.getZExtValue(); 1653 } 1654 1655 // If this the first designator, our caller will continue checking 1656 // the rest of this array subobject. 1657 if (IsFirstDesignator) { 1658 if (NextElementIndex) 1659 *NextElementIndex = DesignatedStartIndex; 1660 StructuredIndex = ElementIndex; 1661 return false; 1662 } 1663 1664 if (!FinishSubobjectInit) 1665 return false; 1666 1667 // Check the remaining elements within this array subobject. 1668 bool prevHadError = hadError; 1669 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 1670 /*SubobjectIsDesignatorContext=*/false, Index, 1671 StructuredList, ElementIndex); 1672 return hadError && !prevHadError; 1673} 1674 1675// Get the structured initializer list for a subobject of type 1676// @p CurrentObjectType. 1677InitListExpr * 1678InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1679 QualType CurrentObjectType, 1680 InitListExpr *StructuredList, 1681 unsigned StructuredIndex, 1682 SourceRange InitRange) { 1683 Expr *ExistingInit = 0; 1684 if (!StructuredList) 1685 ExistingInit = SyntacticToSemantic[IList]; 1686 else if (StructuredIndex < StructuredList->getNumInits()) 1687 ExistingInit = StructuredList->getInit(StructuredIndex); 1688 1689 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1690 return Result; 1691 1692 if (ExistingInit) { 1693 // We are creating an initializer list that initializes the 1694 // subobjects of the current object, but there was already an 1695 // initialization that completely initialized the current 1696 // subobject, e.g., by a compound literal: 1697 // 1698 // struct X { int a, b; }; 1699 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1700 // 1701 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1702 // designated initializer re-initializes the whole 1703 // subobject [0], overwriting previous initializers. 1704 SemaRef.Diag(InitRange.getBegin(), 1705 diag::warn_subobject_initializer_overrides) 1706 << InitRange; 1707 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1708 diag::note_previous_initializer) 1709 << /*FIXME:has side effects=*/0 1710 << ExistingInit->getSourceRange(); 1711 } 1712 1713 InitListExpr *Result 1714 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 1715 InitRange.getBegin(), 0, 0, 1716 InitRange.getEnd()); 1717 1718 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context)); 1719 1720 // Pre-allocate storage for the structured initializer list. 1721 unsigned NumElements = 0; 1722 unsigned NumInits = 0; 1723 if (!StructuredList) 1724 NumInits = IList->getNumInits(); 1725 else if (Index < IList->getNumInits()) { 1726 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) 1727 NumInits = SubList->getNumInits(); 1728 } 1729 1730 if (const ArrayType *AType 1731 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1732 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1733 NumElements = CAType->getSize().getZExtValue(); 1734 // Simple heuristic so that we don't allocate a very large 1735 // initializer with many empty entries at the end. 1736 if (NumInits && NumElements > NumInits) 1737 NumElements = 0; 1738 } 1739 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 1740 NumElements = VType->getNumElements(); 1741 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1742 RecordDecl *RDecl = RType->getDecl(); 1743 if (RDecl->isUnion()) 1744 NumElements = 1; 1745 else 1746 NumElements = std::distance(RDecl->field_begin(), 1747 RDecl->field_end()); 1748 } 1749 1750 if (NumElements < NumInits) 1751 NumElements = IList->getNumInits(); 1752 1753 Result->reserveInits(SemaRef.Context, NumElements); 1754 1755 // Link this new initializer list into the structured initializer 1756 // lists. 1757 if (StructuredList) 1758 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 1759 else { 1760 Result->setSyntacticForm(IList); 1761 SyntacticToSemantic[IList] = Result; 1762 } 1763 1764 return Result; 1765} 1766 1767/// Update the initializer at index @p StructuredIndex within the 1768/// structured initializer list to the value @p expr. 1769void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1770 unsigned &StructuredIndex, 1771 Expr *expr) { 1772 // No structured initializer list to update 1773 if (!StructuredList) 1774 return; 1775 1776 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 1777 StructuredIndex, expr)) { 1778 // This initializer overwrites a previous initializer. Warn. 1779 SemaRef.Diag(expr->getSourceRange().getBegin(), 1780 diag::warn_initializer_overrides) 1781 << expr->getSourceRange(); 1782 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1783 diag::note_previous_initializer) 1784 << /*FIXME:has side effects=*/0 1785 << PrevInit->getSourceRange(); 1786 } 1787 1788 ++StructuredIndex; 1789} 1790 1791/// Check that the given Index expression is a valid array designator 1792/// value. This is essentailly just a wrapper around 1793/// VerifyIntegerConstantExpression that also checks for negative values 1794/// and produces a reasonable diagnostic if there is a 1795/// failure. Returns true if there was an error, false otherwise. If 1796/// everything went okay, Value will receive the value of the constant 1797/// expression. 1798static bool 1799CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1800 SourceLocation Loc = Index->getSourceRange().getBegin(); 1801 1802 // Make sure this is an integer constant expression. 1803 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1804 return true; 1805 1806 if (Value.isSigned() && Value.isNegative()) 1807 return S.Diag(Loc, diag::err_array_designator_negative) 1808 << Value.toString(10) << Index->getSourceRange(); 1809 1810 Value.setIsUnsigned(true); 1811 return false; 1812} 1813 1814ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1815 SourceLocation Loc, 1816 bool GNUSyntax, 1817 ExprResult Init) { 1818 typedef DesignatedInitExpr::Designator ASTDesignator; 1819 1820 bool Invalid = false; 1821 llvm::SmallVector<ASTDesignator, 32> Designators; 1822 llvm::SmallVector<Expr *, 32> InitExpressions; 1823 1824 // Build designators and check array designator expressions. 1825 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1826 const Designator &D = Desig.getDesignator(Idx); 1827 switch (D.getKind()) { 1828 case Designator::FieldDesignator: 1829 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1830 D.getFieldLoc())); 1831 break; 1832 1833 case Designator::ArrayDesignator: { 1834 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1835 llvm::APSInt IndexValue; 1836 if (!Index->isTypeDependent() && 1837 !Index->isValueDependent() && 1838 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1839 Invalid = true; 1840 else { 1841 Designators.push_back(ASTDesignator(InitExpressions.size(), 1842 D.getLBracketLoc(), 1843 D.getRBracketLoc())); 1844 InitExpressions.push_back(Index); 1845 } 1846 break; 1847 } 1848 1849 case Designator::ArrayRangeDesignator: { 1850 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1851 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1852 llvm::APSInt StartValue; 1853 llvm::APSInt EndValue; 1854 bool StartDependent = StartIndex->isTypeDependent() || 1855 StartIndex->isValueDependent(); 1856 bool EndDependent = EndIndex->isTypeDependent() || 1857 EndIndex->isValueDependent(); 1858 if ((!StartDependent && 1859 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1860 (!EndDependent && 1861 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1862 Invalid = true; 1863 else { 1864 // Make sure we're comparing values with the same bit width. 1865 if (StartDependent || EndDependent) { 1866 // Nothing to compute. 1867 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1868 EndValue.extend(StartValue.getBitWidth()); 1869 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1870 StartValue.extend(EndValue.getBitWidth()); 1871 1872 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1873 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1874 << StartValue.toString(10) << EndValue.toString(10) 1875 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1876 Invalid = true; 1877 } else { 1878 Designators.push_back(ASTDesignator(InitExpressions.size(), 1879 D.getLBracketLoc(), 1880 D.getEllipsisLoc(), 1881 D.getRBracketLoc())); 1882 InitExpressions.push_back(StartIndex); 1883 InitExpressions.push_back(EndIndex); 1884 } 1885 } 1886 break; 1887 } 1888 } 1889 } 1890 1891 if (Invalid || Init.isInvalid()) 1892 return ExprError(); 1893 1894 // Clear out the expressions within the designation. 1895 Desig.ClearExprs(*this); 1896 1897 DesignatedInitExpr *DIE 1898 = DesignatedInitExpr::Create(Context, 1899 Designators.data(), Designators.size(), 1900 InitExpressions.data(), InitExpressions.size(), 1901 Loc, GNUSyntax, Init.takeAs<Expr>()); 1902 return Owned(DIE); 1903} 1904 1905bool Sema::CheckInitList(const InitializedEntity &Entity, 1906 InitListExpr *&InitList, QualType &DeclType) { 1907 InitListChecker CheckInitList(*this, Entity, InitList, DeclType); 1908 if (!CheckInitList.HadError()) 1909 InitList = CheckInitList.getFullyStructuredList(); 1910 1911 return CheckInitList.HadError(); 1912} 1913 1914//===----------------------------------------------------------------------===// 1915// Initialization entity 1916//===----------------------------------------------------------------------===// 1917 1918InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 1919 const InitializedEntity &Parent) 1920 : Parent(&Parent), Index(Index) 1921{ 1922 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 1923 Kind = EK_ArrayElement; 1924 Type = AT->getElementType(); 1925 } else { 1926 Kind = EK_VectorElement; 1927 Type = Parent.getType()->getAs<VectorType>()->getElementType(); 1928 } 1929} 1930 1931InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 1932 CXXBaseSpecifier *Base, 1933 bool IsInheritedVirtualBase) 1934{ 1935 InitializedEntity Result; 1936 Result.Kind = EK_Base; 1937 Result.Base = reinterpret_cast<uintptr_t>(Base); 1938 if (IsInheritedVirtualBase) 1939 Result.Base |= 0x01; 1940 1941 Result.Type = Base->getType(); 1942 return Result; 1943} 1944 1945DeclarationName InitializedEntity::getName() const { 1946 switch (getKind()) { 1947 case EK_Parameter: 1948 if (!VariableOrMember) 1949 return DeclarationName(); 1950 // Fall through 1951 1952 case EK_Variable: 1953 case EK_Member: 1954 return VariableOrMember->getDeclName(); 1955 1956 case EK_Result: 1957 case EK_Exception: 1958 case EK_New: 1959 case EK_Temporary: 1960 case EK_Base: 1961 case EK_ArrayElement: 1962 case EK_VectorElement: 1963 case EK_BlockElement: 1964 return DeclarationName(); 1965 } 1966 1967 // Silence GCC warning 1968 return DeclarationName(); 1969} 1970 1971DeclaratorDecl *InitializedEntity::getDecl() const { 1972 switch (getKind()) { 1973 case EK_Variable: 1974 case EK_Parameter: 1975 case EK_Member: 1976 return VariableOrMember; 1977 1978 case EK_Result: 1979 case EK_Exception: 1980 case EK_New: 1981 case EK_Temporary: 1982 case EK_Base: 1983 case EK_ArrayElement: 1984 case EK_VectorElement: 1985 case EK_BlockElement: 1986 return 0; 1987 } 1988 1989 // Silence GCC warning 1990 return 0; 1991} 1992 1993bool InitializedEntity::allowsNRVO() const { 1994 switch (getKind()) { 1995 case EK_Result: 1996 case EK_Exception: 1997 return LocAndNRVO.NRVO; 1998 1999 case EK_Variable: 2000 case EK_Parameter: 2001 case EK_Member: 2002 case EK_New: 2003 case EK_Temporary: 2004 case EK_Base: 2005 case EK_ArrayElement: 2006 case EK_VectorElement: 2007 case EK_BlockElement: 2008 break; 2009 } 2010 2011 return false; 2012} 2013 2014//===----------------------------------------------------------------------===// 2015// Initialization sequence 2016//===----------------------------------------------------------------------===// 2017 2018void InitializationSequence::Step::Destroy() { 2019 switch (Kind) { 2020 case SK_ResolveAddressOfOverloadedFunction: 2021 case SK_CastDerivedToBaseRValue: 2022 case SK_CastDerivedToBaseXValue: 2023 case SK_CastDerivedToBaseLValue: 2024 case SK_BindReference: 2025 case SK_BindReferenceToTemporary: 2026 case SK_ExtraneousCopyToTemporary: 2027 case SK_UserConversion: 2028 case SK_QualificationConversionRValue: 2029 case SK_QualificationConversionXValue: 2030 case SK_QualificationConversionLValue: 2031 case SK_ListInitialization: 2032 case SK_ConstructorInitialization: 2033 case SK_ZeroInitialization: 2034 case SK_CAssignment: 2035 case SK_StringInit: 2036 case SK_ObjCObjectConversion: 2037 break; 2038 2039 case SK_ConversionSequence: 2040 delete ICS; 2041 } 2042} 2043 2044bool InitializationSequence::isDirectReferenceBinding() const { 2045 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference; 2046} 2047 2048bool InitializationSequence::isAmbiguous() const { 2049 if (getKind() != FailedSequence) 2050 return false; 2051 2052 switch (getFailureKind()) { 2053 case FK_TooManyInitsForReference: 2054 case FK_ArrayNeedsInitList: 2055 case FK_ArrayNeedsInitListOrStringLiteral: 2056 case FK_AddressOfOverloadFailed: // FIXME: Could do better 2057 case FK_NonConstLValueReferenceBindingToTemporary: 2058 case FK_NonConstLValueReferenceBindingToUnrelated: 2059 case FK_RValueReferenceBindingToLValue: 2060 case FK_ReferenceInitDropsQualifiers: 2061 case FK_ReferenceInitFailed: 2062 case FK_ConversionFailed: 2063 case FK_TooManyInitsForScalar: 2064 case FK_ReferenceBindingToInitList: 2065 case FK_InitListBadDestinationType: 2066 case FK_DefaultInitOfConst: 2067 case FK_Incomplete: 2068 return false; 2069 2070 case FK_ReferenceInitOverloadFailed: 2071 case FK_UserConversionOverloadFailed: 2072 case FK_ConstructorOverloadFailed: 2073 return FailedOverloadResult == OR_Ambiguous; 2074 } 2075 2076 return false; 2077} 2078 2079bool InitializationSequence::isConstructorInitialization() const { 2080 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 2081} 2082 2083void InitializationSequence::AddAddressOverloadResolutionStep( 2084 FunctionDecl *Function, 2085 DeclAccessPair Found) { 2086 Step S; 2087 S.Kind = SK_ResolveAddressOfOverloadedFunction; 2088 S.Type = Function->getType(); 2089 S.Function.Function = Function; 2090 S.Function.FoundDecl = Found; 2091 Steps.push_back(S); 2092} 2093 2094void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 2095 ExprValueKind VK) { 2096 Step S; 2097 switch (VK) { 2098 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 2099 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 2100 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 2101 default: llvm_unreachable("No such category"); 2102 } 2103 S.Type = BaseType; 2104 Steps.push_back(S); 2105} 2106 2107void InitializationSequence::AddReferenceBindingStep(QualType T, 2108 bool BindingTemporary) { 2109 Step S; 2110 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2111 S.Type = T; 2112 Steps.push_back(S); 2113} 2114 2115void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 2116 Step S; 2117 S.Kind = SK_ExtraneousCopyToTemporary; 2118 S.Type = T; 2119 Steps.push_back(S); 2120} 2121 2122void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2123 DeclAccessPair FoundDecl, 2124 QualType T) { 2125 Step S; 2126 S.Kind = SK_UserConversion; 2127 S.Type = T; 2128 S.Function.Function = Function; 2129 S.Function.FoundDecl = FoundDecl; 2130 Steps.push_back(S); 2131} 2132 2133void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2134 ExprValueKind VK) { 2135 Step S; 2136 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 2137 switch (VK) { 2138 case VK_RValue: 2139 S.Kind = SK_QualificationConversionRValue; 2140 break; 2141 case VK_XValue: 2142 S.Kind = SK_QualificationConversionXValue; 2143 break; 2144 case VK_LValue: 2145 S.Kind = SK_QualificationConversionLValue; 2146 break; 2147 } 2148 S.Type = Ty; 2149 Steps.push_back(S); 2150} 2151 2152void InitializationSequence::AddConversionSequenceStep( 2153 const ImplicitConversionSequence &ICS, 2154 QualType T) { 2155 Step S; 2156 S.Kind = SK_ConversionSequence; 2157 S.Type = T; 2158 S.ICS = new ImplicitConversionSequence(ICS); 2159 Steps.push_back(S); 2160} 2161 2162void InitializationSequence::AddListInitializationStep(QualType T) { 2163 Step S; 2164 S.Kind = SK_ListInitialization; 2165 S.Type = T; 2166 Steps.push_back(S); 2167} 2168 2169void 2170InitializationSequence::AddConstructorInitializationStep( 2171 CXXConstructorDecl *Constructor, 2172 AccessSpecifier Access, 2173 QualType T) { 2174 Step S; 2175 S.Kind = SK_ConstructorInitialization; 2176 S.Type = T; 2177 S.Function.Function = Constructor; 2178 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access); 2179 Steps.push_back(S); 2180} 2181 2182void InitializationSequence::AddZeroInitializationStep(QualType T) { 2183 Step S; 2184 S.Kind = SK_ZeroInitialization; 2185 S.Type = T; 2186 Steps.push_back(S); 2187} 2188 2189void InitializationSequence::AddCAssignmentStep(QualType T) { 2190 Step S; 2191 S.Kind = SK_CAssignment; 2192 S.Type = T; 2193 Steps.push_back(S); 2194} 2195 2196void InitializationSequence::AddStringInitStep(QualType T) { 2197 Step S; 2198 S.Kind = SK_StringInit; 2199 S.Type = T; 2200 Steps.push_back(S); 2201} 2202 2203void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 2204 Step S; 2205 S.Kind = SK_ObjCObjectConversion; 2206 S.Type = T; 2207 Steps.push_back(S); 2208} 2209 2210void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2211 OverloadingResult Result) { 2212 SequenceKind = FailedSequence; 2213 this->Failure = Failure; 2214 this->FailedOverloadResult = Result; 2215} 2216 2217//===----------------------------------------------------------------------===// 2218// Attempt initialization 2219//===----------------------------------------------------------------------===// 2220 2221/// \brief Attempt list initialization (C++0x [dcl.init.list]) 2222static void TryListInitialization(Sema &S, 2223 const InitializedEntity &Entity, 2224 const InitializationKind &Kind, 2225 InitListExpr *InitList, 2226 InitializationSequence &Sequence) { 2227 // FIXME: We only perform rudimentary checking of list 2228 // initializations at this point, then assume that any list 2229 // initialization of an array, aggregate, or scalar will be 2230 // well-formed. When we actually "perform" list initialization, we'll 2231 // do all of the necessary checking. C++0x initializer lists will 2232 // force us to perform more checking here. 2233 Sequence.setSequenceKind(InitializationSequence::ListInitialization); 2234 2235 QualType DestType = Entity.getType(); 2236 2237 // C++ [dcl.init]p13: 2238 // If T is a scalar type, then a declaration of the form 2239 // 2240 // T x = { a }; 2241 // 2242 // is equivalent to 2243 // 2244 // T x = a; 2245 if (DestType->isScalarType()) { 2246 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) { 2247 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 2248 return; 2249 } 2250 2251 // Assume scalar initialization from a single value works. 2252 } else if (DestType->isAggregateType()) { 2253 // Assume aggregate initialization works. 2254 } else if (DestType->isVectorType()) { 2255 // Assume vector initialization works. 2256 } else if (DestType->isReferenceType()) { 2257 // FIXME: C++0x defines behavior for this. 2258 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 2259 return; 2260 } else if (DestType->isRecordType()) { 2261 // FIXME: C++0x defines behavior for this 2262 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 2263 } 2264 2265 // Add a general "list initialization" step. 2266 Sequence.AddListInitializationStep(DestType); 2267} 2268 2269/// \brief Try a reference initialization that involves calling a conversion 2270/// function. 2271static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 2272 const InitializedEntity &Entity, 2273 const InitializationKind &Kind, 2274 Expr *Initializer, 2275 bool AllowRValues, 2276 InitializationSequence &Sequence) { 2277 QualType DestType = Entity.getType(); 2278 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2279 QualType T1 = cv1T1.getUnqualifiedType(); 2280 QualType cv2T2 = Initializer->getType(); 2281 QualType T2 = cv2T2.getUnqualifiedType(); 2282 2283 bool DerivedToBase; 2284 bool ObjCConversion; 2285 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 2286 T1, T2, DerivedToBase, 2287 ObjCConversion) && 2288 "Must have incompatible references when binding via conversion"); 2289 (void)DerivedToBase; 2290 (void)ObjCConversion; 2291 2292 // Build the candidate set directly in the initialization sequence 2293 // structure, so that it will persist if we fail. 2294 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2295 CandidateSet.clear(); 2296 2297 // Determine whether we are allowed to call explicit constructors or 2298 // explicit conversion operators. 2299 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2300 2301 const RecordType *T1RecordType = 0; 2302 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 2303 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) { 2304 // The type we're converting to is a class type. Enumerate its constructors 2305 // to see if there is a suitable conversion. 2306 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 2307 2308 DeclContext::lookup_iterator Con, ConEnd; 2309 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl); 2310 Con != ConEnd; ++Con) { 2311 NamedDecl *D = *Con; 2312 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2313 2314 // Find the constructor (which may be a template). 2315 CXXConstructorDecl *Constructor = 0; 2316 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2317 if (ConstructorTmpl) 2318 Constructor = cast<CXXConstructorDecl>( 2319 ConstructorTmpl->getTemplatedDecl()); 2320 else 2321 Constructor = cast<CXXConstructorDecl>(D); 2322 2323 if (!Constructor->isInvalidDecl() && 2324 Constructor->isConvertingConstructor(AllowExplicit)) { 2325 if (ConstructorTmpl) 2326 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2327 /*ExplicitArgs*/ 0, 2328 &Initializer, 1, CandidateSet); 2329 else 2330 S.AddOverloadCandidate(Constructor, FoundDecl, 2331 &Initializer, 1, CandidateSet); 2332 } 2333 } 2334 } 2335 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 2336 return OR_No_Viable_Function; 2337 2338 const RecordType *T2RecordType = 0; 2339 if ((T2RecordType = T2->getAs<RecordType>()) && 2340 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) { 2341 // The type we're converting from is a class type, enumerate its conversion 2342 // functions. 2343 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 2344 2345 // Determine the type we are converting to. If we are allowed to 2346 // convert to an rvalue, take the type that the destination type 2347 // refers to. 2348 QualType ToType = AllowRValues? cv1T1 : DestType; 2349 2350 const UnresolvedSetImpl *Conversions 2351 = T2RecordDecl->getVisibleConversionFunctions(); 2352 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 2353 E = Conversions->end(); I != E; ++I) { 2354 NamedDecl *D = *I; 2355 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2356 if (isa<UsingShadowDecl>(D)) 2357 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2358 2359 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2360 CXXConversionDecl *Conv; 2361 if (ConvTemplate) 2362 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2363 else 2364 Conv = cast<CXXConversionDecl>(D); 2365 2366 // If the conversion function doesn't return a reference type, 2367 // it can't be considered for this conversion unless we're allowed to 2368 // consider rvalues. 2369 // FIXME: Do we need to make sure that we only consider conversion 2370 // candidates with reference-compatible results? That might be needed to 2371 // break recursion. 2372 if ((AllowExplicit || !Conv->isExplicit()) && 2373 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 2374 if (ConvTemplate) 2375 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 2376 ActingDC, Initializer, 2377 ToType, CandidateSet); 2378 else 2379 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 2380 Initializer, ToType, CandidateSet); 2381 } 2382 } 2383 } 2384 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 2385 return OR_No_Viable_Function; 2386 2387 SourceLocation DeclLoc = Initializer->getLocStart(); 2388 2389 // Perform overload resolution. If it fails, return the failed result. 2390 OverloadCandidateSet::iterator Best; 2391 if (OverloadingResult Result 2392 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) 2393 return Result; 2394 2395 FunctionDecl *Function = Best->Function; 2396 2397 // Compute the returned type of the conversion. 2398 if (isa<CXXConversionDecl>(Function)) 2399 T2 = Function->getResultType(); 2400 else 2401 T2 = cv1T1; 2402 2403 // Add the user-defined conversion step. 2404 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 2405 T2.getNonLValueExprType(S.Context)); 2406 2407 // Determine whether we need to perform derived-to-base or 2408 // cv-qualification adjustments. 2409 ExprValueKind VK = VK_RValue; 2410 if (T2->isLValueReferenceType()) 2411 VK = VK_LValue; 2412 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>()) 2413 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 2414 2415 bool NewDerivedToBase = false; 2416 bool NewObjCConversion = false; 2417 Sema::ReferenceCompareResult NewRefRelationship 2418 = S.CompareReferenceRelationship(DeclLoc, T1, 2419 T2.getNonLValueExprType(S.Context), 2420 NewDerivedToBase, NewObjCConversion); 2421 if (NewRefRelationship == Sema::Ref_Incompatible) { 2422 // If the type we've converted to is not reference-related to the 2423 // type we're looking for, then there is another conversion step 2424 // we need to perform to produce a temporary of the right type 2425 // that we'll be binding to. 2426 ImplicitConversionSequence ICS; 2427 ICS.setStandard(); 2428 ICS.Standard = Best->FinalConversion; 2429 T2 = ICS.Standard.getToType(2); 2430 Sequence.AddConversionSequenceStep(ICS, T2); 2431 } else if (NewDerivedToBase) 2432 Sequence.AddDerivedToBaseCastStep( 2433 S.Context.getQualifiedType(T1, 2434 T2.getNonReferenceType().getQualifiers()), 2435 VK); 2436 else if (NewObjCConversion) 2437 Sequence.AddObjCObjectConversionStep( 2438 S.Context.getQualifiedType(T1, 2439 T2.getNonReferenceType().getQualifiers())); 2440 2441 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 2442 Sequence.AddQualificationConversionStep(cv1T1, VK); 2443 2444 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 2445 return OR_Success; 2446} 2447 2448/// \brief Attempt reference initialization (C++0x [dcl.init.ref]) 2449static void TryReferenceInitialization(Sema &S, 2450 const InitializedEntity &Entity, 2451 const InitializationKind &Kind, 2452 Expr *Initializer, 2453 InitializationSequence &Sequence) { 2454 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding); 2455 2456 QualType DestType = Entity.getType(); 2457 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2458 Qualifiers T1Quals; 2459 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 2460 QualType cv2T2 = Initializer->getType(); 2461 Qualifiers T2Quals; 2462 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 2463 SourceLocation DeclLoc = Initializer->getLocStart(); 2464 2465 // If the initializer is the address of an overloaded function, try 2466 // to resolve the overloaded function. If all goes well, T2 is the 2467 // type of the resulting function. 2468 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2469 DeclAccessPair Found; 2470 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, 2471 T1, 2472 false, 2473 Found); 2474 if (!Fn) { 2475 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2476 return; 2477 } 2478 2479 Sequence.AddAddressOverloadResolutionStep(Fn, Found); 2480 cv2T2 = Fn->getType(); 2481 T2 = cv2T2.getUnqualifiedType(); 2482 } 2483 2484 // Compute some basic properties of the types and the initializer. 2485 bool isLValueRef = DestType->isLValueReferenceType(); 2486 bool isRValueRef = !isLValueRef; 2487 bool DerivedToBase = false; 2488 bool ObjCConversion = false; 2489 Expr::Classification InitCategory = Initializer->Classify(S.Context); 2490 Sema::ReferenceCompareResult RefRelationship 2491 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, 2492 ObjCConversion); 2493 2494 // C++0x [dcl.init.ref]p5: 2495 // A reference to type "cv1 T1" is initialized by an expression of type 2496 // "cv2 T2" as follows: 2497 // 2498 // - If the reference is an lvalue reference and the initializer 2499 // expression 2500 // Note the analogous bullet points for rvlaue refs to functions. Because 2501 // there are no function rvalues in C++, rvalue refs to functions are treated 2502 // like lvalue refs. 2503 OverloadingResult ConvOvlResult = OR_Success; 2504 bool T1Function = T1->isFunctionType(); 2505 if (isLValueRef || T1Function) { 2506 if (InitCategory.isLValue() && 2507 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2508 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 2509 // reference-compatible with "cv2 T2," or 2510 // 2511 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a 2512 // bit-field when we're determining whether the reference initialization 2513 // can occur. However, we do pay attention to whether it is a bit-field 2514 // to decide whether we're actually binding to a temporary created from 2515 // the bit-field. 2516 if (DerivedToBase) 2517 Sequence.AddDerivedToBaseCastStep( 2518 S.Context.getQualifiedType(T1, T2Quals), 2519 VK_LValue); 2520 else if (ObjCConversion) 2521 Sequence.AddObjCObjectConversionStep( 2522 S.Context.getQualifiedType(T1, T2Quals)); 2523 2524 if (T1Quals != T2Quals) 2525 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue); 2526 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() && 2527 (Initializer->getBitField() || Initializer->refersToVectorElement()); 2528 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary); 2529 return; 2530 } 2531 2532 // - has a class type (i.e., T2 is a class type), where T1 is not 2533 // reference-related to T2, and can be implicitly converted to an 2534 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 2535 // with "cv3 T3" (this conversion is selected by enumerating the 2536 // applicable conversion functions (13.3.1.6) and choosing the best 2537 // one through overload resolution (13.3)), 2538 // If we have an rvalue ref to function type here, the rhs must be 2539 // an rvalue. 2540 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 2541 (isLValueRef || InitCategory.isRValue())) { 2542 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 2543 Initializer, 2544 /*AllowRValues=*/isRValueRef, 2545 Sequence); 2546 if (ConvOvlResult == OR_Success) 2547 return; 2548 if (ConvOvlResult != OR_No_Viable_Function) { 2549 Sequence.SetOverloadFailure( 2550 InitializationSequence::FK_ReferenceInitOverloadFailed, 2551 ConvOvlResult); 2552 } 2553 } 2554 } 2555 2556 // - Otherwise, the reference shall be an lvalue reference to a 2557 // non-volatile const type (i.e., cv1 shall be const), or the reference 2558 // shall be an rvalue reference and the initializer expression shall 2559 // be an rvalue or have a function type. 2560 // We handled the function type stuff above. 2561 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) || 2562 (isRValueRef && InitCategory.isRValue()))) { 2563 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2564 Sequence.SetOverloadFailure( 2565 InitializationSequence::FK_ReferenceInitOverloadFailed, 2566 ConvOvlResult); 2567 else if (isLValueRef) 2568 Sequence.SetFailed(InitCategory.isLValue() 2569 ? (RefRelationship == Sema::Ref_Related 2570 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 2571 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 2572 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 2573 else 2574 Sequence.SetFailed( 2575 InitializationSequence::FK_RValueReferenceBindingToLValue); 2576 2577 return; 2578 } 2579 2580 // - [If T1 is not a function type], if T2 is a class type and 2581 if (!T1Function && T2->isRecordType()) { 2582 bool isXValue = InitCategory.isXValue(); 2583 // - the initializer expression is an rvalue and "cv1 T1" is 2584 // reference-compatible with "cv2 T2", or 2585 if (InitCategory.isRValue() && 2586 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2587 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 2588 // compiler the freedom to perform a copy here or bind to the 2589 // object, while C++0x requires that we bind directly to the 2590 // object. Hence, we always bind to the object without making an 2591 // extra copy. However, in C++03 requires that we check for the 2592 // presence of a suitable copy constructor: 2593 // 2594 // The constructor that would be used to make the copy shall 2595 // be callable whether or not the copy is actually done. 2596 if (!S.getLangOptions().CPlusPlus0x) 2597 Sequence.AddExtraneousCopyToTemporary(cv2T2); 2598 2599 if (DerivedToBase) 2600 Sequence.AddDerivedToBaseCastStep( 2601 S.Context.getQualifiedType(T1, T2Quals), 2602 isXValue ? VK_XValue : VK_RValue); 2603 else if (ObjCConversion) 2604 Sequence.AddObjCObjectConversionStep( 2605 S.Context.getQualifiedType(T1, T2Quals)); 2606 2607 if (T1Quals != T2Quals) 2608 Sequence.AddQualificationConversionStep(cv1T1, 2609 isXValue ? VK_XValue : VK_RValue); 2610 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue); 2611 return; 2612 } 2613 2614 // - T1 is not reference-related to T2 and the initializer expression 2615 // can be implicitly converted to an rvalue of type "cv3 T3" (this 2616 // conversion is selected by enumerating the applicable conversion 2617 // functions (13.3.1.6) and choosing the best one through overload 2618 // resolution (13.3)), 2619 if (RefRelationship == Sema::Ref_Incompatible) { 2620 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 2621 Kind, Initializer, 2622 /*AllowRValues=*/true, 2623 Sequence); 2624 if (ConvOvlResult) 2625 Sequence.SetOverloadFailure( 2626 InitializationSequence::FK_ReferenceInitOverloadFailed, 2627 ConvOvlResult); 2628 2629 return; 2630 } 2631 2632 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2633 return; 2634 } 2635 2636 // - If the initializer expression is an rvalue, with T2 an array type, 2637 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference 2638 // is bound to the object represented by the rvalue (see 3.10). 2639 // FIXME: How can an array type be reference-compatible with anything? 2640 // Don't we mean the element types of T1 and T2? 2641 2642 // - Otherwise, a temporary of type “cv1 T1” is created and initialized 2643 // from the initializer expression using the rules for a non-reference 2644 // copy initialization (8.5). The reference is then bound to the 2645 // temporary. [...] 2646 2647 // Determine whether we are allowed to call explicit constructors or 2648 // explicit conversion operators. 2649 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 2650 2651 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 2652 2653 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer, 2654 /*SuppressUserConversions*/ false, 2655 AllowExplicit, 2656 /*FIXME:InOverloadResolution=*/false)) { 2657 // FIXME: Use the conversion function set stored in ICS to turn 2658 // this into an overloading ambiguity diagnostic. However, we need 2659 // to keep that set as an OverloadCandidateSet rather than as some 2660 // other kind of set. 2661 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2662 Sequence.SetOverloadFailure( 2663 InitializationSequence::FK_ReferenceInitOverloadFailed, 2664 ConvOvlResult); 2665 else 2666 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 2667 return; 2668 } 2669 2670 // [...] If T1 is reference-related to T2, cv1 must be the 2671 // same cv-qualification as, or greater cv-qualification 2672 // than, cv2; otherwise, the program is ill-formed. 2673 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 2674 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 2675 if (RefRelationship == Sema::Ref_Related && 2676 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { 2677 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2678 return; 2679 } 2680 2681 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2682 return; 2683} 2684 2685/// \brief Attempt character array initialization from a string literal 2686/// (C++ [dcl.init.string], C99 6.7.8). 2687static void TryStringLiteralInitialization(Sema &S, 2688 const InitializedEntity &Entity, 2689 const InitializationKind &Kind, 2690 Expr *Initializer, 2691 InitializationSequence &Sequence) { 2692 Sequence.setSequenceKind(InitializationSequence::StringInit); 2693 Sequence.AddStringInitStep(Entity.getType()); 2694} 2695 2696/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2697/// enumerates the constructors of the initialized entity and performs overload 2698/// resolution to select the best. 2699static void TryConstructorInitialization(Sema &S, 2700 const InitializedEntity &Entity, 2701 const InitializationKind &Kind, 2702 Expr **Args, unsigned NumArgs, 2703 QualType DestType, 2704 InitializationSequence &Sequence) { 2705 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization); 2706 2707 // Build the candidate set directly in the initialization sequence 2708 // structure, so that it will persist if we fail. 2709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2710 CandidateSet.clear(); 2711 2712 // Determine whether we are allowed to call explicit constructors or 2713 // explicit conversion operators. 2714 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct || 2715 Kind.getKind() == InitializationKind::IK_Value || 2716 Kind.getKind() == InitializationKind::IK_Default); 2717 2718 // The type we're constructing needs to be complete. 2719 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 2720 Sequence.SetFailed(InitializationSequence::FK_Incomplete); 2721 return; 2722 } 2723 2724 // The type we're converting to is a class type. Enumerate its constructors 2725 // to see if one is suitable. 2726 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2727 assert(DestRecordType && "Constructor initialization requires record type"); 2728 CXXRecordDecl *DestRecordDecl 2729 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2730 2731 DeclContext::lookup_iterator Con, ConEnd; 2732 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 2733 Con != ConEnd; ++Con) { 2734 NamedDecl *D = *Con; 2735 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2736 bool SuppressUserConversions = false; 2737 2738 // Find the constructor (which may be a template). 2739 CXXConstructorDecl *Constructor = 0; 2740 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2741 if (ConstructorTmpl) 2742 Constructor = cast<CXXConstructorDecl>( 2743 ConstructorTmpl->getTemplatedDecl()); 2744 else { 2745 Constructor = cast<CXXConstructorDecl>(D); 2746 2747 // If we're performing copy initialization using a copy constructor, we 2748 // suppress user-defined conversions on the arguments. 2749 // FIXME: Move constructors? 2750 if (Kind.getKind() == InitializationKind::IK_Copy && 2751 Constructor->isCopyConstructor()) 2752 SuppressUserConversions = true; 2753 } 2754 2755 if (!Constructor->isInvalidDecl() && 2756 (AllowExplicit || !Constructor->isExplicit())) { 2757 if (ConstructorTmpl) 2758 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2759 /*ExplicitArgs*/ 0, 2760 Args, NumArgs, CandidateSet, 2761 SuppressUserConversions); 2762 else 2763 S.AddOverloadCandidate(Constructor, FoundDecl, 2764 Args, NumArgs, CandidateSet, 2765 SuppressUserConversions); 2766 } 2767 } 2768 2769 SourceLocation DeclLoc = Kind.getLocation(); 2770 2771 // Perform overload resolution. If it fails, return the failed result. 2772 OverloadCandidateSet::iterator Best; 2773 if (OverloadingResult Result 2774 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 2775 Sequence.SetOverloadFailure( 2776 InitializationSequence::FK_ConstructorOverloadFailed, 2777 Result); 2778 return; 2779 } 2780 2781 // C++0x [dcl.init]p6: 2782 // If a program calls for the default initialization of an object 2783 // of a const-qualified type T, T shall be a class type with a 2784 // user-provided default constructor. 2785 if (Kind.getKind() == InitializationKind::IK_Default && 2786 Entity.getType().isConstQualified() && 2787 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) { 2788 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2789 return; 2790 } 2791 2792 // Add the constructor initialization step. Any cv-qualification conversion is 2793 // subsumed by the initialization. 2794 Sequence.AddConstructorInitializationStep( 2795 cast<CXXConstructorDecl>(Best->Function), 2796 Best->FoundDecl.getAccess(), 2797 DestType); 2798} 2799 2800/// \brief Attempt value initialization (C++ [dcl.init]p7). 2801static void TryValueInitialization(Sema &S, 2802 const InitializedEntity &Entity, 2803 const InitializationKind &Kind, 2804 InitializationSequence &Sequence) { 2805 // C++ [dcl.init]p5: 2806 // 2807 // To value-initialize an object of type T means: 2808 QualType T = Entity.getType(); 2809 2810 // -- if T is an array type, then each element is value-initialized; 2811 while (const ArrayType *AT = S.Context.getAsArrayType(T)) 2812 T = AT->getElementType(); 2813 2814 if (const RecordType *RT = T->getAs<RecordType>()) { 2815 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2816 // -- if T is a class type (clause 9) with a user-declared 2817 // constructor (12.1), then the default constructor for T is 2818 // called (and the initialization is ill-formed if T has no 2819 // accessible default constructor); 2820 // 2821 // FIXME: we really want to refer to a single subobject of the array, 2822 // but Entity doesn't have a way to capture that (yet). 2823 if (ClassDecl->hasUserDeclaredConstructor()) 2824 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2825 2826 // -- if T is a (possibly cv-qualified) non-union class type 2827 // without a user-provided constructor, then the object is 2828 // zero-initialized and, if T’s implicitly-declared default 2829 // constructor is non-trivial, that constructor is called. 2830 if ((ClassDecl->getTagKind() == TTK_Class || 2831 ClassDecl->getTagKind() == TTK_Struct)) { 2832 Sequence.AddZeroInitializationStep(Entity.getType()); 2833 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2834 } 2835 } 2836 } 2837 2838 Sequence.AddZeroInitializationStep(Entity.getType()); 2839 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization); 2840} 2841 2842/// \brief Attempt default initialization (C++ [dcl.init]p6). 2843static void TryDefaultInitialization(Sema &S, 2844 const InitializedEntity &Entity, 2845 const InitializationKind &Kind, 2846 InitializationSequence &Sequence) { 2847 assert(Kind.getKind() == InitializationKind::IK_Default); 2848 2849 // C++ [dcl.init]p6: 2850 // To default-initialize an object of type T means: 2851 // - if T is an array type, each element is default-initialized; 2852 QualType DestType = Entity.getType(); 2853 while (const ArrayType *Array = S.Context.getAsArrayType(DestType)) 2854 DestType = Array->getElementType(); 2855 2856 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 2857 // constructor for T is called (and the initialization is ill-formed if 2858 // T has no accessible default constructor); 2859 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) { 2860 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence); 2861 return; 2862 } 2863 2864 // - otherwise, no initialization is performed. 2865 Sequence.setSequenceKind(InitializationSequence::NoInitialization); 2866 2867 // If a program calls for the default initialization of an object of 2868 // a const-qualified type T, T shall be a class type with a user-provided 2869 // default constructor. 2870 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) 2871 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2872} 2873 2874/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 2875/// which enumerates all conversion functions and performs overload resolution 2876/// to select the best. 2877static void TryUserDefinedConversion(Sema &S, 2878 const InitializedEntity &Entity, 2879 const InitializationKind &Kind, 2880 Expr *Initializer, 2881 InitializationSequence &Sequence) { 2882 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion); 2883 2884 QualType DestType = Entity.getType(); 2885 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 2886 QualType SourceType = Initializer->getType(); 2887 assert((DestType->isRecordType() || SourceType->isRecordType()) && 2888 "Must have a class type to perform a user-defined conversion"); 2889 2890 // Build the candidate set directly in the initialization sequence 2891 // structure, so that it will persist if we fail. 2892 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2893 CandidateSet.clear(); 2894 2895 // Determine whether we are allowed to call explicit constructors or 2896 // explicit conversion operators. 2897 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2898 2899 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 2900 // The type we're converting to is a class type. Enumerate its constructors 2901 // to see if there is a suitable conversion. 2902 CXXRecordDecl *DestRecordDecl 2903 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2904 2905 // Try to complete the type we're converting to. 2906 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 2907 DeclContext::lookup_iterator Con, ConEnd; 2908 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 2909 Con != ConEnd; ++Con) { 2910 NamedDecl *D = *Con; 2911 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2912 2913 // Find the constructor (which may be a template). 2914 CXXConstructorDecl *Constructor = 0; 2915 FunctionTemplateDecl *ConstructorTmpl 2916 = dyn_cast<FunctionTemplateDecl>(D); 2917 if (ConstructorTmpl) 2918 Constructor = cast<CXXConstructorDecl>( 2919 ConstructorTmpl->getTemplatedDecl()); 2920 else 2921 Constructor = cast<CXXConstructorDecl>(D); 2922 2923 if (!Constructor->isInvalidDecl() && 2924 Constructor->isConvertingConstructor(AllowExplicit)) { 2925 if (ConstructorTmpl) 2926 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2927 /*ExplicitArgs*/ 0, 2928 &Initializer, 1, CandidateSet, 2929 /*SuppressUserConversions=*/true); 2930 else 2931 S.AddOverloadCandidate(Constructor, FoundDecl, 2932 &Initializer, 1, CandidateSet, 2933 /*SuppressUserConversions=*/true); 2934 } 2935 } 2936 } 2937 } 2938 2939 SourceLocation DeclLoc = Initializer->getLocStart(); 2940 2941 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 2942 // The type we're converting from is a class type, enumerate its conversion 2943 // functions. 2944 2945 // We can only enumerate the conversion functions for a complete type; if 2946 // the type isn't complete, simply skip this step. 2947 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) { 2948 CXXRecordDecl *SourceRecordDecl 2949 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 2950 2951 const UnresolvedSetImpl *Conversions 2952 = SourceRecordDecl->getVisibleConversionFunctions(); 2953 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 2954 E = Conversions->end(); 2955 I != E; ++I) { 2956 NamedDecl *D = *I; 2957 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2958 if (isa<UsingShadowDecl>(D)) 2959 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2960 2961 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2962 CXXConversionDecl *Conv; 2963 if (ConvTemplate) 2964 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2965 else 2966 Conv = cast<CXXConversionDecl>(D); 2967 2968 if (AllowExplicit || !Conv->isExplicit()) { 2969 if (ConvTemplate) 2970 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 2971 ActingDC, Initializer, DestType, 2972 CandidateSet); 2973 else 2974 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 2975 Initializer, DestType, CandidateSet); 2976 } 2977 } 2978 } 2979 } 2980 2981 // Perform overload resolution. If it fails, return the failed result. 2982 OverloadCandidateSet::iterator Best; 2983 if (OverloadingResult Result 2984 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 2985 Sequence.SetOverloadFailure( 2986 InitializationSequence::FK_UserConversionOverloadFailed, 2987 Result); 2988 return; 2989 } 2990 2991 FunctionDecl *Function = Best->Function; 2992 2993 if (isa<CXXConstructorDecl>(Function)) { 2994 // Add the user-defined conversion step. Any cv-qualification conversion is 2995 // subsumed by the initialization. 2996 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType); 2997 return; 2998 } 2999 3000 // Add the user-defined conversion step that calls the conversion function. 3001 QualType ConvType = Function->getCallResultType(); 3002 if (ConvType->getAs<RecordType>()) { 3003 // If we're converting to a class type, there may be an copy if 3004 // the resulting temporary object (possible to create an object of 3005 // a base class type). That copy is not a separate conversion, so 3006 // we just make a note of the actual destination type (possibly a 3007 // base class of the type returned by the conversion function) and 3008 // let the user-defined conversion step handle the conversion. 3009 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType); 3010 return; 3011 } 3012 3013 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType); 3014 3015 // If the conversion following the call to the conversion function 3016 // is interesting, add it as a separate step. 3017 if (Best->FinalConversion.First || Best->FinalConversion.Second || 3018 Best->FinalConversion.Third) { 3019 ImplicitConversionSequence ICS; 3020 ICS.setStandard(); 3021 ICS.Standard = Best->FinalConversion; 3022 Sequence.AddConversionSequenceStep(ICS, DestType); 3023 } 3024} 3025 3026InitializationSequence::InitializationSequence(Sema &S, 3027 const InitializedEntity &Entity, 3028 const InitializationKind &Kind, 3029 Expr **Args, 3030 unsigned NumArgs) 3031 : FailedCandidateSet(Kind.getLocation()) { 3032 ASTContext &Context = S.Context; 3033 3034 // C++0x [dcl.init]p16: 3035 // The semantics of initializers are as follows. The destination type is 3036 // the type of the object or reference being initialized and the source 3037 // type is the type of the initializer expression. The source type is not 3038 // defined when the initializer is a braced-init-list or when it is a 3039 // parenthesized list of expressions. 3040 QualType DestType = Entity.getType(); 3041 3042 if (DestType->isDependentType() || 3043 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 3044 SequenceKind = DependentSequence; 3045 return; 3046 } 3047 3048 QualType SourceType; 3049 Expr *Initializer = 0; 3050 if (NumArgs == 1) { 3051 Initializer = Args[0]; 3052 if (!isa<InitListExpr>(Initializer)) 3053 SourceType = Initializer->getType(); 3054 } 3055 3056 // - If the initializer is a braced-init-list, the object is 3057 // list-initialized (8.5.4). 3058 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 3059 TryListInitialization(S, Entity, Kind, InitList, *this); 3060 return; 3061 } 3062 3063 // - If the destination type is a reference type, see 8.5.3. 3064 if (DestType->isReferenceType()) { 3065 // C++0x [dcl.init.ref]p1: 3066 // A variable declared to be a T& or T&&, that is, "reference to type T" 3067 // (8.3.2), shall be initialized by an object, or function, of type T or 3068 // by an object that can be converted into a T. 3069 // (Therefore, multiple arguments are not permitted.) 3070 if (NumArgs != 1) 3071 SetFailed(FK_TooManyInitsForReference); 3072 else 3073 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 3074 return; 3075 } 3076 3077 // - If the destination type is an array of characters, an array of 3078 // char16_t, an array of char32_t, or an array of wchar_t, and the 3079 // initializer is a string literal, see 8.5.2. 3080 if (Initializer && IsStringInit(Initializer, DestType, Context)) { 3081 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 3082 return; 3083 } 3084 3085 // - If the initializer is (), the object is value-initialized. 3086 if (Kind.getKind() == InitializationKind::IK_Value || 3087 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) { 3088 TryValueInitialization(S, Entity, Kind, *this); 3089 return; 3090 } 3091 3092 // Handle default initialization. 3093 if (Kind.getKind() == InitializationKind::IK_Default){ 3094 TryDefaultInitialization(S, Entity, Kind, *this); 3095 return; 3096 } 3097 3098 // - Otherwise, if the destination type is an array, the program is 3099 // ill-formed. 3100 if (const ArrayType *AT = Context.getAsArrayType(DestType)) { 3101 if (AT->getElementType()->isAnyCharacterType()) 3102 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 3103 else 3104 SetFailed(FK_ArrayNeedsInitList); 3105 3106 return; 3107 } 3108 3109 // Handle initialization in C 3110 if (!S.getLangOptions().CPlusPlus) { 3111 setSequenceKind(CAssignment); 3112 AddCAssignmentStep(DestType); 3113 return; 3114 } 3115 3116 // - If the destination type is a (possibly cv-qualified) class type: 3117 if (DestType->isRecordType()) { 3118 // - If the initialization is direct-initialization, or if it is 3119 // copy-initialization where the cv-unqualified version of the 3120 // source type is the same class as, or a derived class of, the 3121 // class of the destination, constructors are considered. [...] 3122 if (Kind.getKind() == InitializationKind::IK_Direct || 3123 (Kind.getKind() == InitializationKind::IK_Copy && 3124 (Context.hasSameUnqualifiedType(SourceType, DestType) || 3125 S.IsDerivedFrom(SourceType, DestType)))) 3126 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, 3127 Entity.getType(), *this); 3128 // - Otherwise (i.e., for the remaining copy-initialization cases), 3129 // user-defined conversion sequences that can convert from the source 3130 // type to the destination type or (when a conversion function is 3131 // used) to a derived class thereof are enumerated as described in 3132 // 13.3.1.4, and the best one is chosen through overload resolution 3133 // (13.3). 3134 else 3135 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 3136 return; 3137 } 3138 3139 if (NumArgs > 1) { 3140 SetFailed(FK_TooManyInitsForScalar); 3141 return; 3142 } 3143 assert(NumArgs == 1 && "Zero-argument case handled above"); 3144 3145 // - Otherwise, if the source type is a (possibly cv-qualified) class 3146 // type, conversion functions are considered. 3147 if (!SourceType.isNull() && SourceType->isRecordType()) { 3148 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 3149 return; 3150 } 3151 3152 // - Otherwise, the initial value of the object being initialized is the 3153 // (possibly converted) value of the initializer expression. Standard 3154 // conversions (Clause 4) will be used, if necessary, to convert the 3155 // initializer expression to the cv-unqualified version of the 3156 // destination type; no user-defined conversions are considered. 3157 if (S.TryImplicitConversion(*this, Entity, Initializer, 3158 /*SuppressUserConversions*/ true, 3159 /*AllowExplicitConversions*/ false, 3160 /*InOverloadResolution*/ false)) 3161 SetFailed(InitializationSequence::FK_ConversionFailed); 3162 else 3163 setSequenceKind(StandardConversion); 3164} 3165 3166InitializationSequence::~InitializationSequence() { 3167 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(), 3168 StepEnd = Steps.end(); 3169 Step != StepEnd; ++Step) 3170 Step->Destroy(); 3171} 3172 3173//===----------------------------------------------------------------------===// 3174// Perform initialization 3175//===----------------------------------------------------------------------===// 3176static Sema::AssignmentAction 3177getAssignmentAction(const InitializedEntity &Entity) { 3178 switch(Entity.getKind()) { 3179 case InitializedEntity::EK_Variable: 3180 case InitializedEntity::EK_New: 3181 return Sema::AA_Initializing; 3182 3183 case InitializedEntity::EK_Parameter: 3184 if (Entity.getDecl() && 3185 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 3186 return Sema::AA_Sending; 3187 3188 return Sema::AA_Passing; 3189 3190 case InitializedEntity::EK_Result: 3191 return Sema::AA_Returning; 3192 3193 case InitializedEntity::EK_Exception: 3194 case InitializedEntity::EK_Base: 3195 llvm_unreachable("No assignment action for C++-specific initialization"); 3196 break; 3197 3198 case InitializedEntity::EK_Temporary: 3199 // FIXME: Can we tell apart casting vs. converting? 3200 return Sema::AA_Casting; 3201 3202 case InitializedEntity::EK_Member: 3203 case InitializedEntity::EK_ArrayElement: 3204 case InitializedEntity::EK_VectorElement: 3205 case InitializedEntity::EK_BlockElement: 3206 return Sema::AA_Initializing; 3207 } 3208 3209 return Sema::AA_Converting; 3210} 3211 3212/// \brief Whether we should binding a created object as a temporary when 3213/// initializing the given entity. 3214static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 3215 switch (Entity.getKind()) { 3216 case InitializedEntity::EK_ArrayElement: 3217 case InitializedEntity::EK_Member: 3218 case InitializedEntity::EK_Result: 3219 case InitializedEntity::EK_New: 3220 case InitializedEntity::EK_Variable: 3221 case InitializedEntity::EK_Base: 3222 case InitializedEntity::EK_VectorElement: 3223 case InitializedEntity::EK_Exception: 3224 case InitializedEntity::EK_BlockElement: 3225 return false; 3226 3227 case InitializedEntity::EK_Parameter: 3228 case InitializedEntity::EK_Temporary: 3229 return true; 3230 } 3231 3232 llvm_unreachable("missed an InitializedEntity kind?"); 3233} 3234 3235/// \brief Whether the given entity, when initialized with an object 3236/// created for that initialization, requires destruction. 3237static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 3238 switch (Entity.getKind()) { 3239 case InitializedEntity::EK_Member: 3240 case InitializedEntity::EK_Result: 3241 case InitializedEntity::EK_New: 3242 case InitializedEntity::EK_Base: 3243 case InitializedEntity::EK_VectorElement: 3244 case InitializedEntity::EK_BlockElement: 3245 return false; 3246 3247 case InitializedEntity::EK_Variable: 3248 case InitializedEntity::EK_Parameter: 3249 case InitializedEntity::EK_Temporary: 3250 case InitializedEntity::EK_ArrayElement: 3251 case InitializedEntity::EK_Exception: 3252 return true; 3253 } 3254 3255 llvm_unreachable("missed an InitializedEntity kind?"); 3256} 3257 3258/// \brief Make a (potentially elidable) temporary copy of the object 3259/// provided by the given initializer by calling the appropriate copy 3260/// constructor. 3261/// 3262/// \param S The Sema object used for type-checking. 3263/// 3264/// \param T The type of the temporary object, which must either by 3265/// the type of the initializer expression or a superclass thereof. 3266/// 3267/// \param Enter The entity being initialized. 3268/// 3269/// \param CurInit The initializer expression. 3270/// 3271/// \param IsExtraneousCopy Whether this is an "extraneous" copy that 3272/// is permitted in C++03 (but not C++0x) when binding a reference to 3273/// an rvalue. 3274/// 3275/// \returns An expression that copies the initializer expression into 3276/// a temporary object, or an error expression if a copy could not be 3277/// created. 3278static ExprResult CopyObject(Sema &S, 3279 QualType T, 3280 const InitializedEntity &Entity, 3281 ExprResult CurInit, 3282 bool IsExtraneousCopy) { 3283 // Determine which class type we're copying to. 3284 Expr *CurInitExpr = (Expr *)CurInit.get(); 3285 CXXRecordDecl *Class = 0; 3286 if (const RecordType *Record = T->getAs<RecordType>()) 3287 Class = cast<CXXRecordDecl>(Record->getDecl()); 3288 if (!Class) 3289 return move(CurInit); 3290 3291 // C++0x [class.copy]p34: 3292 // When certain criteria are met, an implementation is allowed to 3293 // omit the copy/move construction of a class object, even if the 3294 // copy/move constructor and/or destructor for the object have 3295 // side effects. [...] 3296 // - when a temporary class object that has not been bound to a 3297 // reference (12.2) would be copied/moved to a class object 3298 // with the same cv-unqualified type, the copy/move operation 3299 // can be omitted by constructing the temporary object 3300 // directly into the target of the omitted copy/move 3301 // 3302 // Note that the other three bullets are handled elsewhere. Copy 3303 // elision for return statements and throw expressions are handled as part 3304 // of constructor initialization, while copy elision for exception handlers 3305 // is handled by the run-time. 3306 bool Elidable = CurInitExpr->isTemporaryObject() && 3307 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType()); 3308 SourceLocation Loc; 3309 switch (Entity.getKind()) { 3310 case InitializedEntity::EK_Result: 3311 Loc = Entity.getReturnLoc(); 3312 break; 3313 3314 case InitializedEntity::EK_Exception: 3315 Loc = Entity.getThrowLoc(); 3316 break; 3317 3318 case InitializedEntity::EK_Variable: 3319 Loc = Entity.getDecl()->getLocation(); 3320 break; 3321 3322 case InitializedEntity::EK_ArrayElement: 3323 case InitializedEntity::EK_Member: 3324 case InitializedEntity::EK_Parameter: 3325 case InitializedEntity::EK_Temporary: 3326 case InitializedEntity::EK_New: 3327 case InitializedEntity::EK_Base: 3328 case InitializedEntity::EK_VectorElement: 3329 case InitializedEntity::EK_BlockElement: 3330 Loc = CurInitExpr->getLocStart(); 3331 break; 3332 } 3333 3334 // Make sure that the type we are copying is complete. 3335 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete))) 3336 return move(CurInit); 3337 3338 // Perform overload resolution using the class's copy constructors. 3339 DeclContext::lookup_iterator Con, ConEnd; 3340 OverloadCandidateSet CandidateSet(Loc); 3341 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class); 3342 Con != ConEnd; ++Con) { 3343 // Only consider copy constructors. 3344 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con); 3345 if (!Constructor || Constructor->isInvalidDecl() || 3346 !Constructor->isCopyConstructor() || 3347 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) 3348 continue; 3349 3350 DeclAccessPair FoundDecl 3351 = DeclAccessPair::make(Constructor, Constructor->getAccess()); 3352 S.AddOverloadCandidate(Constructor, FoundDecl, 3353 &CurInitExpr, 1, CandidateSet); 3354 } 3355 3356 OverloadCandidateSet::iterator Best; 3357 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 3358 case OR_Success: 3359 break; 3360 3361 case OR_No_Viable_Function: 3362 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 3363 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 3364 : diag::err_temp_copy_no_viable) 3365 << (int)Entity.getKind() << CurInitExpr->getType() 3366 << CurInitExpr->getSourceRange(); 3367 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1); 3368 if (!IsExtraneousCopy || S.isSFINAEContext()) 3369 return ExprError(); 3370 return move(CurInit); 3371 3372 case OR_Ambiguous: 3373 S.Diag(Loc, diag::err_temp_copy_ambiguous) 3374 << (int)Entity.getKind() << CurInitExpr->getType() 3375 << CurInitExpr->getSourceRange(); 3376 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1); 3377 return ExprError(); 3378 3379 case OR_Deleted: 3380 S.Diag(Loc, diag::err_temp_copy_deleted) 3381 << (int)Entity.getKind() << CurInitExpr->getType() 3382 << CurInitExpr->getSourceRange(); 3383 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3384 << Best->Function->isDeleted(); 3385 return ExprError(); 3386 } 3387 3388 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3389 ASTOwningVector<Expr*> ConstructorArgs(S); 3390 CurInit.release(); // Ownership transferred into MultiExprArg, below. 3391 3392 S.CheckConstructorAccess(Loc, Constructor, Entity, 3393 Best->FoundDecl.getAccess(), IsExtraneousCopy); 3394 3395 if (IsExtraneousCopy) { 3396 // If this is a totally extraneous copy for C++03 reference 3397 // binding purposes, just return the original initialization 3398 // expression. We don't generate an (elided) copy operation here 3399 // because doing so would require us to pass down a flag to avoid 3400 // infinite recursion, where each step adds another extraneous, 3401 // elidable copy. 3402 3403 // Instantiate the default arguments of any extra parameters in 3404 // the selected copy constructor, as if we were going to create a 3405 // proper call to the copy constructor. 3406 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 3407 ParmVarDecl *Parm = Constructor->getParamDecl(I); 3408 if (S.RequireCompleteType(Loc, Parm->getType(), 3409 S.PDiag(diag::err_call_incomplete_argument))) 3410 break; 3411 3412 // Build the default argument expression; we don't actually care 3413 // if this succeeds or not, because this routine will complain 3414 // if there was a problem. 3415 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 3416 } 3417 3418 return S.Owned(CurInitExpr); 3419 } 3420 3421 // Determine the arguments required to actually perform the 3422 // constructor call (we might have derived-to-base conversions, or 3423 // the copy constructor may have default arguments). 3424 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1), 3425 Loc, ConstructorArgs)) 3426 return ExprError(); 3427 3428 // Actually perform the constructor call. 3429 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable, 3430 move_arg(ConstructorArgs), 3431 /*ZeroInit*/ false, 3432 CXXConstructExpr::CK_Complete); 3433 3434 // If we're supposed to bind temporaries, do so. 3435 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 3436 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3437 return move(CurInit); 3438} 3439 3440void InitializationSequence::PrintInitLocationNote(Sema &S, 3441 const InitializedEntity &Entity) { 3442 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) { 3443 if (Entity.getDecl()->getLocation().isInvalid()) 3444 return; 3445 3446 if (Entity.getDecl()->getDeclName()) 3447 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 3448 << Entity.getDecl()->getDeclName(); 3449 else 3450 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 3451 } 3452} 3453 3454ExprResult 3455InitializationSequence::Perform(Sema &S, 3456 const InitializedEntity &Entity, 3457 const InitializationKind &Kind, 3458 MultiExprArg Args, 3459 QualType *ResultType) { 3460 if (SequenceKind == FailedSequence) { 3461 unsigned NumArgs = Args.size(); 3462 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 3463 return ExprError(); 3464 } 3465 3466 if (SequenceKind == DependentSequence) { 3467 // If the declaration is a non-dependent, incomplete array type 3468 // that has an initializer, then its type will be completed once 3469 // the initializer is instantiated. 3470 if (ResultType && !Entity.getType()->isDependentType() && 3471 Args.size() == 1) { 3472 QualType DeclType = Entity.getType(); 3473 if (const IncompleteArrayType *ArrayT 3474 = S.Context.getAsIncompleteArrayType(DeclType)) { 3475 // FIXME: We don't currently have the ability to accurately 3476 // compute the length of an initializer list without 3477 // performing full type-checking of the initializer list 3478 // (since we have to determine where braces are implicitly 3479 // introduced and such). So, we fall back to making the array 3480 // type a dependently-sized array type with no specified 3481 // bound. 3482 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 3483 SourceRange Brackets; 3484 3485 // Scavange the location of the brackets from the entity, if we can. 3486 if (DeclaratorDecl *DD = Entity.getDecl()) { 3487 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 3488 TypeLoc TL = TInfo->getTypeLoc(); 3489 if (IncompleteArrayTypeLoc *ArrayLoc 3490 = dyn_cast<IncompleteArrayTypeLoc>(&TL)) 3491 Brackets = ArrayLoc->getBracketsRange(); 3492 } 3493 } 3494 3495 *ResultType 3496 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 3497 /*NumElts=*/0, 3498 ArrayT->getSizeModifier(), 3499 ArrayT->getIndexTypeCVRQualifiers(), 3500 Brackets); 3501 } 3502 3503 } 3504 } 3505 3506 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast()) 3507 return ExprResult(Args.release()[0]); 3508 3509 if (Args.size() == 0) 3510 return S.Owned((Expr *)0); 3511 3512 unsigned NumArgs = Args.size(); 3513 return S.Owned(new (S.Context) ParenListExpr(S.Context, 3514 SourceLocation(), 3515 (Expr **)Args.release(), 3516 NumArgs, 3517 SourceLocation())); 3518 } 3519 3520 if (SequenceKind == NoInitialization) 3521 return S.Owned((Expr *)0); 3522 3523 QualType DestType = Entity.getType().getNonReferenceType(); 3524 // FIXME: Ugly hack around the fact that Entity.getType() is not 3525 // the same as Entity.getDecl()->getType() in cases involving type merging, 3526 // and we want latter when it makes sense. 3527 if (ResultType) 3528 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 3529 Entity.getType(); 3530 3531 ExprResult CurInit = S.Owned((Expr *)0); 3532 3533 assert(!Steps.empty() && "Cannot have an empty initialization sequence"); 3534 3535 // For initialization steps that start with a single initializer, 3536 // grab the only argument out the Args and place it into the "current" 3537 // initializer. 3538 switch (Steps.front().Kind) { 3539 case SK_ResolveAddressOfOverloadedFunction: 3540 case SK_CastDerivedToBaseRValue: 3541 case SK_CastDerivedToBaseXValue: 3542 case SK_CastDerivedToBaseLValue: 3543 case SK_BindReference: 3544 case SK_BindReferenceToTemporary: 3545 case SK_ExtraneousCopyToTemporary: 3546 case SK_UserConversion: 3547 case SK_QualificationConversionLValue: 3548 case SK_QualificationConversionXValue: 3549 case SK_QualificationConversionRValue: 3550 case SK_ConversionSequence: 3551 case SK_ListInitialization: 3552 case SK_CAssignment: 3553 case SK_StringInit: 3554 case SK_ObjCObjectConversion: 3555 assert(Args.size() == 1); 3556 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain()); 3557 if (CurInit.isInvalid()) 3558 return ExprError(); 3559 break; 3560 3561 case SK_ConstructorInitialization: 3562 case SK_ZeroInitialization: 3563 break; 3564 } 3565 3566 // Walk through the computed steps for the initialization sequence, 3567 // performing the specified conversions along the way. 3568 bool ConstructorInitRequiresZeroInit = false; 3569 for (step_iterator Step = step_begin(), StepEnd = step_end(); 3570 Step != StepEnd; ++Step) { 3571 if (CurInit.isInvalid()) 3572 return ExprError(); 3573 3574 Expr *CurInitExpr = (Expr *)CurInit.get(); 3575 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType(); 3576 3577 switch (Step->Kind) { 3578 case SK_ResolveAddressOfOverloadedFunction: 3579 // Overload resolution determined which function invoke; update the 3580 // initializer to reflect that choice. 3581 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl); 3582 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()); 3583 CurInit = S.FixOverloadedFunctionReference(move(CurInit), 3584 Step->Function.FoundDecl, 3585 Step->Function.Function); 3586 break; 3587 3588 case SK_CastDerivedToBaseRValue: 3589 case SK_CastDerivedToBaseXValue: 3590 case SK_CastDerivedToBaseLValue: { 3591 // We have a derived-to-base cast that produces either an rvalue or an 3592 // lvalue. Perform that cast. 3593 3594 CXXCastPath BasePath; 3595 3596 // Casts to inaccessible base classes are allowed with C-style casts. 3597 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 3598 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 3599 CurInitExpr->getLocStart(), 3600 CurInitExpr->getSourceRange(), 3601 &BasePath, IgnoreBaseAccess)) 3602 return ExprError(); 3603 3604 if (S.BasePathInvolvesVirtualBase(BasePath)) { 3605 QualType T = SourceType; 3606 if (const PointerType *Pointer = T->getAs<PointerType>()) 3607 T = Pointer->getPointeeType(); 3608 if (const RecordType *RecordTy = T->getAs<RecordType>()) 3609 S.MarkVTableUsed(CurInitExpr->getLocStart(), 3610 cast<CXXRecordDecl>(RecordTy->getDecl())); 3611 } 3612 3613 ExprValueKind VK = 3614 Step->Kind == SK_CastDerivedToBaseLValue ? 3615 VK_LValue : 3616 (Step->Kind == SK_CastDerivedToBaseXValue ? 3617 VK_XValue : 3618 VK_RValue); 3619 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 3620 Step->Type, 3621 CK_DerivedToBase, 3622 CurInit.get(), 3623 &BasePath, VK)); 3624 break; 3625 } 3626 3627 case SK_BindReference: 3628 if (FieldDecl *BitField = CurInitExpr->getBitField()) { 3629 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 3630 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 3631 << Entity.getType().isVolatileQualified() 3632 << BitField->getDeclName() 3633 << CurInitExpr->getSourceRange(); 3634 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 3635 return ExprError(); 3636 } 3637 3638 if (CurInitExpr->refersToVectorElement()) { 3639 // References cannot bind to vector elements. 3640 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 3641 << Entity.getType().isVolatileQualified() 3642 << CurInitExpr->getSourceRange(); 3643 PrintInitLocationNote(S, Entity); 3644 return ExprError(); 3645 } 3646 3647 // Reference binding does not have any corresponding ASTs. 3648 3649 // Check exception specifications 3650 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 3651 return ExprError(); 3652 3653 break; 3654 3655 case SK_BindReferenceToTemporary: 3656 // Reference binding does not have any corresponding ASTs. 3657 3658 // Check exception specifications 3659 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 3660 return ExprError(); 3661 3662 break; 3663 3664 case SK_ExtraneousCopyToTemporary: 3665 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit), 3666 /*IsExtraneousCopy=*/true); 3667 break; 3668 3669 case SK_UserConversion: { 3670 // We have a user-defined conversion that invokes either a constructor 3671 // or a conversion function. 3672 CastKind CastKind = CK_Unknown; 3673 bool IsCopy = false; 3674 FunctionDecl *Fn = Step->Function.Function; 3675 DeclAccessPair FoundFn = Step->Function.FoundDecl; 3676 bool CreatedObject = false; 3677 bool IsLvalue = false; 3678 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 3679 // Build a call to the selected constructor. 3680 ASTOwningVector<Expr*> ConstructorArgs(S); 3681 SourceLocation Loc = CurInitExpr->getLocStart(); 3682 CurInit.release(); // Ownership transferred into MultiExprArg, below. 3683 3684 // Determine the arguments required to actually perform the constructor 3685 // call. 3686 if (S.CompleteConstructorCall(Constructor, 3687 MultiExprArg(&CurInitExpr, 1), 3688 Loc, ConstructorArgs)) 3689 return ExprError(); 3690 3691 // Build the an expression that constructs a temporary. 3692 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 3693 move_arg(ConstructorArgs), 3694 /*ZeroInit*/ false, 3695 CXXConstructExpr::CK_Complete); 3696 if (CurInit.isInvalid()) 3697 return ExprError(); 3698 3699 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity, 3700 FoundFn.getAccess()); 3701 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 3702 3703 CastKind = CK_ConstructorConversion; 3704 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 3705 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 3706 S.IsDerivedFrom(SourceType, Class)) 3707 IsCopy = true; 3708 3709 CreatedObject = true; 3710 } else { 3711 // Build a call to the conversion function. 3712 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 3713 IsLvalue = Conversion->getResultType()->isLValueReferenceType(); 3714 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0, 3715 FoundFn); 3716 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 3717 3718 // FIXME: Should we move this initialization into a separate 3719 // derived-to-base conversion? I believe the answer is "no", because 3720 // we don't want to turn off access control here for c-style casts. 3721 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0, 3722 FoundFn, Conversion)) 3723 return ExprError(); 3724 3725 // Do a little dance to make sure that CurInit has the proper 3726 // pointer. 3727 CurInit.release(); 3728 3729 // Build the actual call to the conversion function. 3730 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, 3731 Conversion)); 3732 if (CurInit.isInvalid() || !CurInit.get()) 3733 return ExprError(); 3734 3735 CastKind = CK_UserDefinedConversion; 3736 3737 CreatedObject = Conversion->getResultType()->isRecordType(); 3738 } 3739 3740 bool RequiresCopy = !IsCopy && 3741 getKind() != InitializationSequence::ReferenceBinding; 3742 if (RequiresCopy || shouldBindAsTemporary(Entity)) 3743 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3744 else if (CreatedObject && shouldDestroyTemporary(Entity)) { 3745 CurInitExpr = static_cast<Expr *>(CurInit.get()); 3746 QualType T = CurInitExpr->getType(); 3747 if (const RecordType *Record = T->getAs<RecordType>()) { 3748 CXXDestructorDecl *Destructor 3749 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 3750 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor, 3751 S.PDiag(diag::err_access_dtor_temp) << T); 3752 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor); 3753 } 3754 } 3755 3756 CurInitExpr = CurInit.takeAs<Expr>(); 3757 // FIXME: xvalues 3758 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 3759 CurInitExpr->getType(), 3760 CastKind, CurInitExpr, 0, 3761 IsLvalue ? VK_LValue : VK_RValue)); 3762 3763 if (RequiresCopy) 3764 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 3765 move(CurInit), /*IsExtraneousCopy=*/false); 3766 3767 break; 3768 } 3769 3770 case SK_QualificationConversionLValue: 3771 case SK_QualificationConversionXValue: 3772 case SK_QualificationConversionRValue: { 3773 // Perform a qualification conversion; these can never go wrong. 3774 ExprValueKind VK = 3775 Step->Kind == SK_QualificationConversionLValue ? 3776 VK_LValue : 3777 (Step->Kind == SK_QualificationConversionXValue ? 3778 VK_XValue : 3779 VK_RValue); 3780 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK); 3781 CurInit.release(); 3782 CurInit = S.Owned(CurInitExpr); 3783 break; 3784 } 3785 3786 case SK_ConversionSequence: { 3787 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 3788 3789 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS, 3790 Sema::AA_Converting, IgnoreBaseAccess)) 3791 return ExprError(); 3792 3793 CurInit.release(); 3794 CurInit = S.Owned(CurInitExpr); 3795 break; 3796 } 3797 3798 case SK_ListInitialization: { 3799 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr); 3800 QualType Ty = Step->Type; 3801 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty)) 3802 return ExprError(); 3803 3804 CurInit.release(); 3805 CurInit = S.Owned(InitList); 3806 break; 3807 } 3808 3809 case SK_ConstructorInitialization: { 3810 unsigned NumArgs = Args.size(); 3811 CXXConstructorDecl *Constructor 3812 = cast<CXXConstructorDecl>(Step->Function.Function); 3813 3814 // Build a call to the selected constructor. 3815 ASTOwningVector<Expr*> ConstructorArgs(S); 3816 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 3817 ? Kind.getEqualLoc() 3818 : Kind.getLocation(); 3819 3820 if (Kind.getKind() == InitializationKind::IK_Default) { 3821 // Force even a trivial, implicit default constructor to be 3822 // semantically checked. We do this explicitly because we don't build 3823 // the definition for completely trivial constructors. 3824 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3825 assert(ClassDecl && "No parent class for constructor."); 3826 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() && 3827 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false)) 3828 S.DefineImplicitDefaultConstructor(Loc, Constructor); 3829 } 3830 3831 // Determine the arguments required to actually perform the constructor 3832 // call. 3833 if (S.CompleteConstructorCall(Constructor, move(Args), 3834 Loc, ConstructorArgs)) 3835 return ExprError(); 3836 3837 3838 if (Entity.getKind() == InitializedEntity::EK_Temporary && 3839 NumArgs != 1 && // FIXME: Hack to work around cast weirdness 3840 (Kind.getKind() == InitializationKind::IK_Direct || 3841 Kind.getKind() == InitializationKind::IK_Value)) { 3842 // An explicitly-constructed temporary, e.g., X(1, 2). 3843 unsigned NumExprs = ConstructorArgs.size(); 3844 Expr **Exprs = (Expr **)ConstructorArgs.take(); 3845 S.MarkDeclarationReferenced(Loc, Constructor); 3846 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context, 3847 Constructor, 3848 Entity.getType(), 3849 Loc, 3850 Exprs, 3851 NumExprs, 3852 Kind.getParenRange().getEnd(), 3853 ConstructorInitRequiresZeroInit)); 3854 } else { 3855 CXXConstructExpr::ConstructionKind ConstructKind = 3856 CXXConstructExpr::CK_Complete; 3857 3858 if (Entity.getKind() == InitializedEntity::EK_Base) { 3859 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 3860 CXXConstructExpr::CK_VirtualBase : 3861 CXXConstructExpr::CK_NonVirtualBase; 3862 } 3863 3864 // If the entity allows NRVO, mark the construction as elidable 3865 // unconditionally. 3866 if (Entity.allowsNRVO()) 3867 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 3868 Constructor, /*Elidable=*/true, 3869 move_arg(ConstructorArgs), 3870 ConstructorInitRequiresZeroInit, 3871 ConstructKind); 3872 else 3873 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 3874 Constructor, 3875 move_arg(ConstructorArgs), 3876 ConstructorInitRequiresZeroInit, 3877 ConstructKind); 3878 } 3879 if (CurInit.isInvalid()) 3880 return ExprError(); 3881 3882 // Only check access if all of that succeeded. 3883 S.CheckConstructorAccess(Loc, Constructor, Entity, 3884 Step->Function.FoundDecl.getAccess()); 3885 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc); 3886 3887 if (shouldBindAsTemporary(Entity)) 3888 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3889 3890 break; 3891 } 3892 3893 case SK_ZeroInitialization: { 3894 step_iterator NextStep = Step; 3895 ++NextStep; 3896 if (NextStep != StepEnd && 3897 NextStep->Kind == SK_ConstructorInitialization) { 3898 // The need for zero-initialization is recorded directly into 3899 // the call to the object's constructor within the next step. 3900 ConstructorInitRequiresZeroInit = true; 3901 } else if (Kind.getKind() == InitializationKind::IK_Value && 3902 S.getLangOptions().CPlusPlus && 3903 !Kind.isImplicitValueInit()) { 3904 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type, 3905 Kind.getRange().getBegin(), 3906 Kind.getRange().getEnd())); 3907 } else { 3908 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 3909 } 3910 break; 3911 } 3912 3913 case SK_CAssignment: { 3914 QualType SourceType = CurInitExpr->getType(); 3915 Sema::AssignConvertType ConvTy = 3916 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr); 3917 3918 // If this is a call, allow conversion to a transparent union. 3919 if (ConvTy != Sema::Compatible && 3920 Entity.getKind() == InitializedEntity::EK_Parameter && 3921 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr) 3922 == Sema::Compatible) 3923 ConvTy = Sema::Compatible; 3924 3925 bool Complained; 3926 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 3927 Step->Type, SourceType, 3928 CurInitExpr, 3929 getAssignmentAction(Entity), 3930 &Complained)) { 3931 PrintInitLocationNote(S, Entity); 3932 return ExprError(); 3933 } else if (Complained) 3934 PrintInitLocationNote(S, Entity); 3935 3936 CurInit.release(); 3937 CurInit = S.Owned(CurInitExpr); 3938 break; 3939 } 3940 3941 case SK_StringInit: { 3942 QualType Ty = Step->Type; 3943 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S); 3944 break; 3945 } 3946 3947 case SK_ObjCObjectConversion: 3948 S.ImpCastExprToType(CurInitExpr, Step->Type, 3949 CK_ObjCObjectLValueCast, 3950 S.CastCategory(CurInitExpr)); 3951 CurInit.release(); 3952 CurInit = S.Owned(CurInitExpr); 3953 break; 3954 } 3955 } 3956 3957 return move(CurInit); 3958} 3959 3960//===----------------------------------------------------------------------===// 3961// Diagnose initialization failures 3962//===----------------------------------------------------------------------===// 3963bool InitializationSequence::Diagnose(Sema &S, 3964 const InitializedEntity &Entity, 3965 const InitializationKind &Kind, 3966 Expr **Args, unsigned NumArgs) { 3967 if (SequenceKind != FailedSequence) 3968 return false; 3969 3970 QualType DestType = Entity.getType(); 3971 switch (Failure) { 3972 case FK_TooManyInitsForReference: 3973 // FIXME: Customize for the initialized entity? 3974 if (NumArgs == 0) 3975 S.Diag(Kind.getLocation(), diag::err_reference_without_init) 3976 << DestType.getNonReferenceType(); 3977 else // FIXME: diagnostic below could be better! 3978 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 3979 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 3980 break; 3981 3982 case FK_ArrayNeedsInitList: 3983 case FK_ArrayNeedsInitListOrStringLiteral: 3984 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 3985 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 3986 break; 3987 3988 case FK_AddressOfOverloadFailed: { 3989 DeclAccessPair Found; 3990 S.ResolveAddressOfOverloadedFunction(Args[0], 3991 DestType.getNonReferenceType(), 3992 true, 3993 Found); 3994 break; 3995 } 3996 3997 case FK_ReferenceInitOverloadFailed: 3998 case FK_UserConversionOverloadFailed: 3999 switch (FailedOverloadResult) { 4000 case OR_Ambiguous: 4001 if (Failure == FK_UserConversionOverloadFailed) 4002 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 4003 << Args[0]->getType() << DestType 4004 << Args[0]->getSourceRange(); 4005 else 4006 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 4007 << DestType << Args[0]->getType() 4008 << Args[0]->getSourceRange(); 4009 4010 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs); 4011 break; 4012 4013 case OR_No_Viable_Function: 4014 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 4015 << Args[0]->getType() << DestType.getNonReferenceType() 4016 << Args[0]->getSourceRange(); 4017 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 4018 break; 4019 4020 case OR_Deleted: { 4021 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 4022 << Args[0]->getType() << DestType.getNonReferenceType() 4023 << Args[0]->getSourceRange(); 4024 OverloadCandidateSet::iterator Best; 4025 OverloadingResult Ovl 4026 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 4027 if (Ovl == OR_Deleted) { 4028 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4029 << Best->Function->isDeleted(); 4030 } else { 4031 llvm_unreachable("Inconsistent overload resolution?"); 4032 } 4033 break; 4034 } 4035 4036 case OR_Success: 4037 llvm_unreachable("Conversion did not fail!"); 4038 break; 4039 } 4040 break; 4041 4042 case FK_NonConstLValueReferenceBindingToTemporary: 4043 case FK_NonConstLValueReferenceBindingToUnrelated: 4044 S.Diag(Kind.getLocation(), 4045 Failure == FK_NonConstLValueReferenceBindingToTemporary 4046 ? diag::err_lvalue_reference_bind_to_temporary 4047 : diag::err_lvalue_reference_bind_to_unrelated) 4048 << DestType.getNonReferenceType().isVolatileQualified() 4049 << DestType.getNonReferenceType() 4050 << Args[0]->getType() 4051 << Args[0]->getSourceRange(); 4052 break; 4053 4054 case FK_RValueReferenceBindingToLValue: 4055 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 4056 << Args[0]->getSourceRange(); 4057 break; 4058 4059 case FK_ReferenceInitDropsQualifiers: 4060 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 4061 << DestType.getNonReferenceType() 4062 << Args[0]->getType() 4063 << Args[0]->getSourceRange(); 4064 break; 4065 4066 case FK_ReferenceInitFailed: 4067 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 4068 << DestType.getNonReferenceType() 4069 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 4070 << Args[0]->getType() 4071 << Args[0]->getSourceRange(); 4072 break; 4073 4074 case FK_ConversionFailed: 4075 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed) 4076 << (int)Entity.getKind() 4077 << DestType 4078 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 4079 << Args[0]->getType() 4080 << Args[0]->getSourceRange(); 4081 break; 4082 4083 case FK_TooManyInitsForScalar: { 4084 SourceRange R; 4085 4086 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 4087 R = SourceRange(InitList->getInit(1)->getLocStart(), 4088 InitList->getLocEnd()); 4089 else 4090 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 4091 4092 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 4093 << /*scalar=*/2 << R; 4094 break; 4095 } 4096 4097 case FK_ReferenceBindingToInitList: 4098 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 4099 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 4100 break; 4101 4102 case FK_InitListBadDestinationType: 4103 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 4104 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 4105 break; 4106 4107 case FK_ConstructorOverloadFailed: { 4108 SourceRange ArgsRange; 4109 if (NumArgs) 4110 ArgsRange = SourceRange(Args[0]->getLocStart(), 4111 Args[NumArgs - 1]->getLocEnd()); 4112 4113 // FIXME: Using "DestType" for the entity we're printing is probably 4114 // bad. 4115 switch (FailedOverloadResult) { 4116 case OR_Ambiguous: 4117 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 4118 << DestType << ArgsRange; 4119 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, 4120 Args, NumArgs); 4121 break; 4122 4123 case OR_No_Viable_Function: 4124 if (Kind.getKind() == InitializationKind::IK_Default && 4125 (Entity.getKind() == InitializedEntity::EK_Base || 4126 Entity.getKind() == InitializedEntity::EK_Member) && 4127 isa<CXXConstructorDecl>(S.CurContext)) { 4128 // This is implicit default initialization of a member or 4129 // base within a constructor. If no viable function was 4130 // found, notify the user that she needs to explicitly 4131 // initialize this base/member. 4132 CXXConstructorDecl *Constructor 4133 = cast<CXXConstructorDecl>(S.CurContext); 4134 if (Entity.getKind() == InitializedEntity::EK_Base) { 4135 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 4136 << Constructor->isImplicit() 4137 << S.Context.getTypeDeclType(Constructor->getParent()) 4138 << /*base=*/0 4139 << Entity.getType(); 4140 4141 RecordDecl *BaseDecl 4142 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 4143 ->getDecl(); 4144 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 4145 << S.Context.getTagDeclType(BaseDecl); 4146 } else { 4147 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 4148 << Constructor->isImplicit() 4149 << S.Context.getTypeDeclType(Constructor->getParent()) 4150 << /*member=*/1 4151 << Entity.getName(); 4152 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl); 4153 4154 if (const RecordType *Record 4155 = Entity.getType()->getAs<RecordType>()) 4156 S.Diag(Record->getDecl()->getLocation(), 4157 diag::note_previous_decl) 4158 << S.Context.getTagDeclType(Record->getDecl()); 4159 } 4160 break; 4161 } 4162 4163 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 4164 << DestType << ArgsRange; 4165 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 4166 break; 4167 4168 case OR_Deleted: { 4169 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 4170 << true << DestType << ArgsRange; 4171 OverloadCandidateSet::iterator Best; 4172 OverloadingResult Ovl 4173 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 4174 if (Ovl == OR_Deleted) { 4175 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4176 << Best->Function->isDeleted(); 4177 } else { 4178 llvm_unreachable("Inconsistent overload resolution?"); 4179 } 4180 break; 4181 } 4182 4183 case OR_Success: 4184 llvm_unreachable("Conversion did not fail!"); 4185 break; 4186 } 4187 break; 4188 } 4189 4190 case FK_DefaultInitOfConst: 4191 if (Entity.getKind() == InitializedEntity::EK_Member && 4192 isa<CXXConstructorDecl>(S.CurContext)) { 4193 // This is implicit default-initialization of a const member in 4194 // a constructor. Complain that it needs to be explicitly 4195 // initialized. 4196 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 4197 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 4198 << Constructor->isImplicit() 4199 << S.Context.getTypeDeclType(Constructor->getParent()) 4200 << /*const=*/1 4201 << Entity.getName(); 4202 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 4203 << Entity.getName(); 4204 } else { 4205 S.Diag(Kind.getLocation(), diag::err_default_init_const) 4206 << DestType << (bool)DestType->getAs<RecordType>(); 4207 } 4208 break; 4209 4210 case FK_Incomplete: 4211 S.RequireCompleteType(Kind.getLocation(), DestType, 4212 diag::err_init_incomplete_type); 4213 break; 4214 } 4215 4216 PrintInitLocationNote(S, Entity); 4217 return true; 4218} 4219 4220void InitializationSequence::dump(llvm::raw_ostream &OS) const { 4221 switch (SequenceKind) { 4222 case FailedSequence: { 4223 OS << "Failed sequence: "; 4224 switch (Failure) { 4225 case FK_TooManyInitsForReference: 4226 OS << "too many initializers for reference"; 4227 break; 4228 4229 case FK_ArrayNeedsInitList: 4230 OS << "array requires initializer list"; 4231 break; 4232 4233 case FK_ArrayNeedsInitListOrStringLiteral: 4234 OS << "array requires initializer list or string literal"; 4235 break; 4236 4237 case FK_AddressOfOverloadFailed: 4238 OS << "address of overloaded function failed"; 4239 break; 4240 4241 case FK_ReferenceInitOverloadFailed: 4242 OS << "overload resolution for reference initialization failed"; 4243 break; 4244 4245 case FK_NonConstLValueReferenceBindingToTemporary: 4246 OS << "non-const lvalue reference bound to temporary"; 4247 break; 4248 4249 case FK_NonConstLValueReferenceBindingToUnrelated: 4250 OS << "non-const lvalue reference bound to unrelated type"; 4251 break; 4252 4253 case FK_RValueReferenceBindingToLValue: 4254 OS << "rvalue reference bound to an lvalue"; 4255 break; 4256 4257 case FK_ReferenceInitDropsQualifiers: 4258 OS << "reference initialization drops qualifiers"; 4259 break; 4260 4261 case FK_ReferenceInitFailed: 4262 OS << "reference initialization failed"; 4263 break; 4264 4265 case FK_ConversionFailed: 4266 OS << "conversion failed"; 4267 break; 4268 4269 case FK_TooManyInitsForScalar: 4270 OS << "too many initializers for scalar"; 4271 break; 4272 4273 case FK_ReferenceBindingToInitList: 4274 OS << "referencing binding to initializer list"; 4275 break; 4276 4277 case FK_InitListBadDestinationType: 4278 OS << "initializer list for non-aggregate, non-scalar type"; 4279 break; 4280 4281 case FK_UserConversionOverloadFailed: 4282 OS << "overloading failed for user-defined conversion"; 4283 break; 4284 4285 case FK_ConstructorOverloadFailed: 4286 OS << "constructor overloading failed"; 4287 break; 4288 4289 case FK_DefaultInitOfConst: 4290 OS << "default initialization of a const variable"; 4291 break; 4292 4293 case FK_Incomplete: 4294 OS << "initialization of incomplete type"; 4295 break; 4296 } 4297 OS << '\n'; 4298 return; 4299 } 4300 4301 case DependentSequence: 4302 OS << "Dependent sequence: "; 4303 return; 4304 4305 case UserDefinedConversion: 4306 OS << "User-defined conversion sequence: "; 4307 break; 4308 4309 case ConstructorInitialization: 4310 OS << "Constructor initialization sequence: "; 4311 break; 4312 4313 case ReferenceBinding: 4314 OS << "Reference binding: "; 4315 break; 4316 4317 case ListInitialization: 4318 OS << "List initialization: "; 4319 break; 4320 4321 case ZeroInitialization: 4322 OS << "Zero initialization\n"; 4323 return; 4324 4325 case NoInitialization: 4326 OS << "No initialization\n"; 4327 return; 4328 4329 case StandardConversion: 4330 OS << "Standard conversion: "; 4331 break; 4332 4333 case CAssignment: 4334 OS << "C assignment: "; 4335 break; 4336 4337 case StringInit: 4338 OS << "String initialization: "; 4339 break; 4340 } 4341 4342 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 4343 if (S != step_begin()) { 4344 OS << " -> "; 4345 } 4346 4347 switch (S->Kind) { 4348 case SK_ResolveAddressOfOverloadedFunction: 4349 OS << "resolve address of overloaded function"; 4350 break; 4351 4352 case SK_CastDerivedToBaseRValue: 4353 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 4354 break; 4355 4356 case SK_CastDerivedToBaseXValue: 4357 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 4358 break; 4359 4360 case SK_CastDerivedToBaseLValue: 4361 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 4362 break; 4363 4364 case SK_BindReference: 4365 OS << "bind reference to lvalue"; 4366 break; 4367 4368 case SK_BindReferenceToTemporary: 4369 OS << "bind reference to a temporary"; 4370 break; 4371 4372 case SK_ExtraneousCopyToTemporary: 4373 OS << "extraneous C++03 copy to temporary"; 4374 break; 4375 4376 case SK_UserConversion: 4377 OS << "user-defined conversion via " << S->Function.Function; 4378 break; 4379 4380 case SK_QualificationConversionRValue: 4381 OS << "qualification conversion (rvalue)"; 4382 4383 case SK_QualificationConversionXValue: 4384 OS << "qualification conversion (xvalue)"; 4385 4386 case SK_QualificationConversionLValue: 4387 OS << "qualification conversion (lvalue)"; 4388 break; 4389 4390 case SK_ConversionSequence: 4391 OS << "implicit conversion sequence ("; 4392 S->ICS->DebugPrint(); // FIXME: use OS 4393 OS << ")"; 4394 break; 4395 4396 case SK_ListInitialization: 4397 OS << "list initialization"; 4398 break; 4399 4400 case SK_ConstructorInitialization: 4401 OS << "constructor initialization"; 4402 break; 4403 4404 case SK_ZeroInitialization: 4405 OS << "zero initialization"; 4406 break; 4407 4408 case SK_CAssignment: 4409 OS << "C assignment"; 4410 break; 4411 4412 case SK_StringInit: 4413 OS << "string initialization"; 4414 break; 4415 4416 case SK_ObjCObjectConversion: 4417 OS << "Objective-C object conversion"; 4418 break; 4419 } 4420 } 4421} 4422 4423void InitializationSequence::dump() const { 4424 dump(llvm::errs()); 4425} 4426 4427//===----------------------------------------------------------------------===// 4428// Initialization helper functions 4429//===----------------------------------------------------------------------===// 4430ExprResult 4431Sema::PerformCopyInitialization(const InitializedEntity &Entity, 4432 SourceLocation EqualLoc, 4433 ExprResult Init) { 4434 if (Init.isInvalid()) 4435 return ExprError(); 4436 4437 Expr *InitE = (Expr *)Init.get(); 4438 assert(InitE && "No initialization expression?"); 4439 4440 if (EqualLoc.isInvalid()) 4441 EqualLoc = InitE->getLocStart(); 4442 4443 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 4444 EqualLoc); 4445 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 4446 Init.release(); 4447 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1)); 4448} 4449