SemaInit.cpp revision 993f43f24d7a45a5cd4678a3316b0852261fc5d4
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. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/Initialization.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/ExprCXX.h" 18#include "clang/AST/ExprObjC.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Sema/Designator.h" 22#include "clang/Sema/Lookup.h" 23#include "clang/Sema/SemaInternal.h" 24#include "llvm/ADT/APInt.h" 25#include "llvm/ADT/SmallString.h" 26#include "llvm/Support/ErrorHandling.h" 27#include "llvm/Support/raw_ostream.h" 28#include <map> 29using namespace clang; 30 31//===----------------------------------------------------------------------===// 32// Sema Initialization Checking 33//===----------------------------------------------------------------------===// 34 35static Expr *IsStringInit(Expr *Init, const ArrayType *AT, 36 ASTContext &Context) { 37 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 38 return 0; 39 40 // See if this is a string literal or @encode. 41 Init = Init->IgnoreParens(); 42 43 // Handle @encode, which is a narrow string. 44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 45 return Init; 46 47 // Otherwise we can only handle string literals. 48 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 49 if (SL == 0) return 0; 50 51 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 52 53 switch (SL->getKind()) { 54 case StringLiteral::Ascii: 55 case StringLiteral::UTF8: 56 // char array can be initialized with a narrow string. 57 // Only allow char x[] = "foo"; not char x[] = L"foo"; 58 return ElemTy->isCharType() ? Init : 0; 59 case StringLiteral::UTF16: 60 return ElemTy->isChar16Type() ? Init : 0; 61 case StringLiteral::UTF32: 62 return ElemTy->isChar32Type() ? Init : 0; 63 case StringLiteral::Wide: 64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 65 // correction from DR343): "An array with element type compatible with a 66 // qualified or unqualified version of wchar_t may be initialized by a wide 67 // string literal, optionally enclosed in braces." 68 if (Context.typesAreCompatible(Context.getWCharType(), 69 ElemTy.getUnqualifiedType())) 70 return Init; 71 72 return 0; 73 } 74 75 llvm_unreachable("missed a StringLiteral kind?"); 76} 77 78static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) { 79 const ArrayType *arrayType = Context.getAsArrayType(declType); 80 if (!arrayType) return 0; 81 82 return IsStringInit(init, arrayType, Context); 83} 84 85/// Update the type of a string literal, including any surrounding parentheses, 86/// to match the type of the object which it is initializing. 87static void updateStringLiteralType(Expr *E, QualType Ty) { 88 while (true) { 89 E->setType(Ty); 90 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) 91 break; 92 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) 93 E = PE->getSubExpr(); 94 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 95 E = UO->getSubExpr(); 96 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) 97 E = GSE->getResultExpr(); 98 else 99 llvm_unreachable("unexpected expr in string literal init"); 100 } 101} 102 103static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 104 Sema &S) { 105 // Get the length of the string as parsed. 106 uint64_t StrLength = 107 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 108 109 110 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 111 // C99 6.7.8p14. We have an array of character type with unknown size 112 // being initialized to a string literal. 113 llvm::APInt ConstVal(32, StrLength); 114 // Return a new array type (C99 6.7.8p22). 115 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 116 ConstVal, 117 ArrayType::Normal, 0); 118 updateStringLiteralType(Str, DeclT); 119 return; 120 } 121 122 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 123 124 // We have an array of character type with known size. However, 125 // the size may be smaller or larger than the string we are initializing. 126 // FIXME: Avoid truncation for 64-bit length strings. 127 if (S.getLangOpts().CPlusPlus) { 128 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { 129 // For Pascal strings it's OK to strip off the terminating null character, 130 // so the example below is valid: 131 // 132 // unsigned char a[2] = "\pa"; 133 if (SL->isPascal()) 134 StrLength--; 135 } 136 137 // [dcl.init.string]p2 138 if (StrLength > CAT->getSize().getZExtValue()) 139 S.Diag(Str->getLocStart(), 140 diag::err_initializer_string_for_char_array_too_long) 141 << Str->getSourceRange(); 142 } else { 143 // C99 6.7.8p14. 144 if (StrLength-1 > CAT->getSize().getZExtValue()) 145 S.Diag(Str->getLocStart(), 146 diag::warn_initializer_string_for_char_array_too_long) 147 << Str->getSourceRange(); 148 } 149 150 // Set the type to the actual size that we are initializing. If we have 151 // something like: 152 // char x[1] = "foo"; 153 // then this will set the string literal's type to char[1]. 154 updateStringLiteralType(Str, DeclT); 155} 156 157//===----------------------------------------------------------------------===// 158// Semantic checking for initializer lists. 159//===----------------------------------------------------------------------===// 160 161/// @brief Semantic checking for initializer lists. 162/// 163/// The InitListChecker class contains a set of routines that each 164/// handle the initialization of a certain kind of entity, e.g., 165/// arrays, vectors, struct/union types, scalars, etc. The 166/// InitListChecker itself performs a recursive walk of the subobject 167/// structure of the type to be initialized, while stepping through 168/// the initializer list one element at a time. The IList and Index 169/// parameters to each of the Check* routines contain the active 170/// (syntactic) initializer list and the index into that initializer 171/// list that represents the current initializer. Each routine is 172/// responsible for moving that Index forward as it consumes elements. 173/// 174/// Each Check* routine also has a StructuredList/StructuredIndex 175/// arguments, which contains the current "structured" (semantic) 176/// initializer list and the index into that initializer list where we 177/// are copying initializers as we map them over to the semantic 178/// list. Once we have completed our recursive walk of the subobject 179/// structure, we will have constructed a full semantic initializer 180/// list. 181/// 182/// C99 designators cause changes in the initializer list traversal, 183/// because they make the initialization "jump" into a specific 184/// subobject and then continue the initialization from that 185/// point. CheckDesignatedInitializer() recursively steps into the 186/// designated subobject and manages backing out the recursion to 187/// initialize the subobjects after the one designated. 188namespace { 189class InitListChecker { 190 Sema &SemaRef; 191 bool hadError; 192 bool VerifyOnly; // no diagnostics, no structure building 193 bool AllowBraceElision; 194 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic; 195 InitListExpr *FullyStructuredList; 196 197 void CheckImplicitInitList(const InitializedEntity &Entity, 198 InitListExpr *ParentIList, QualType T, 199 unsigned &Index, InitListExpr *StructuredList, 200 unsigned &StructuredIndex); 201 void CheckExplicitInitList(const InitializedEntity &Entity, 202 InitListExpr *IList, QualType &T, 203 unsigned &Index, InitListExpr *StructuredList, 204 unsigned &StructuredIndex, 205 bool TopLevelObject = false); 206 void CheckListElementTypes(const InitializedEntity &Entity, 207 InitListExpr *IList, QualType &DeclType, 208 bool SubobjectIsDesignatorContext, 209 unsigned &Index, 210 InitListExpr *StructuredList, 211 unsigned &StructuredIndex, 212 bool TopLevelObject = false); 213 void CheckSubElementType(const InitializedEntity &Entity, 214 InitListExpr *IList, QualType ElemType, 215 unsigned &Index, 216 InitListExpr *StructuredList, 217 unsigned &StructuredIndex); 218 void CheckComplexType(const InitializedEntity &Entity, 219 InitListExpr *IList, QualType DeclType, 220 unsigned &Index, 221 InitListExpr *StructuredList, 222 unsigned &StructuredIndex); 223 void CheckScalarType(const InitializedEntity &Entity, 224 InitListExpr *IList, QualType DeclType, 225 unsigned &Index, 226 InitListExpr *StructuredList, 227 unsigned &StructuredIndex); 228 void CheckReferenceType(const InitializedEntity &Entity, 229 InitListExpr *IList, QualType DeclType, 230 unsigned &Index, 231 InitListExpr *StructuredList, 232 unsigned &StructuredIndex); 233 void CheckVectorType(const InitializedEntity &Entity, 234 InitListExpr *IList, QualType DeclType, unsigned &Index, 235 InitListExpr *StructuredList, 236 unsigned &StructuredIndex); 237 void CheckStructUnionTypes(const InitializedEntity &Entity, 238 InitListExpr *IList, QualType DeclType, 239 RecordDecl::field_iterator Field, 240 bool SubobjectIsDesignatorContext, unsigned &Index, 241 InitListExpr *StructuredList, 242 unsigned &StructuredIndex, 243 bool TopLevelObject = false); 244 void CheckArrayType(const InitializedEntity &Entity, 245 InitListExpr *IList, QualType &DeclType, 246 llvm::APSInt elementIndex, 247 bool SubobjectIsDesignatorContext, unsigned &Index, 248 InitListExpr *StructuredList, 249 unsigned &StructuredIndex); 250 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 251 InitListExpr *IList, DesignatedInitExpr *DIE, 252 unsigned DesigIdx, 253 QualType &CurrentObjectType, 254 RecordDecl::field_iterator *NextField, 255 llvm::APSInt *NextElementIndex, 256 unsigned &Index, 257 InitListExpr *StructuredList, 258 unsigned &StructuredIndex, 259 bool FinishSubobjectInit, 260 bool TopLevelObject); 261 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 262 QualType CurrentObjectType, 263 InitListExpr *StructuredList, 264 unsigned StructuredIndex, 265 SourceRange InitRange); 266 void UpdateStructuredListElement(InitListExpr *StructuredList, 267 unsigned &StructuredIndex, 268 Expr *expr); 269 int numArrayElements(QualType DeclType); 270 int numStructUnionElements(QualType DeclType); 271 272 void FillInValueInitForField(unsigned Init, FieldDecl *Field, 273 const InitializedEntity &ParentEntity, 274 InitListExpr *ILE, bool &RequiresSecondPass); 275 void FillInValueInitializations(const InitializedEntity &Entity, 276 InitListExpr *ILE, bool &RequiresSecondPass); 277 bool CheckFlexibleArrayInit(const InitializedEntity &Entity, 278 Expr *InitExpr, FieldDecl *Field, 279 bool TopLevelObject); 280 void CheckValueInitializable(const InitializedEntity &Entity); 281 282public: 283 InitListChecker(Sema &S, const InitializedEntity &Entity, 284 InitListExpr *IL, QualType &T, bool VerifyOnly, 285 bool AllowBraceElision); 286 bool HadError() { return hadError; } 287 288 // @brief Retrieves the fully-structured initializer list used for 289 // semantic analysis and code generation. 290 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 291}; 292} // end anonymous namespace 293 294void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) { 295 assert(VerifyOnly && 296 "CheckValueInitializable is only inteded for verification mode."); 297 298 SourceLocation Loc; 299 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 300 true); 301 InitializationSequence InitSeq(SemaRef, Entity, Kind, None); 302 if (InitSeq.Failed()) 303 hadError = true; 304} 305 306void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field, 307 const InitializedEntity &ParentEntity, 308 InitListExpr *ILE, 309 bool &RequiresSecondPass) { 310 SourceLocation Loc = ILE->getLocStart(); 311 unsigned NumInits = ILE->getNumInits(); 312 InitializedEntity MemberEntity 313 = InitializedEntity::InitializeMember(Field, &ParentEntity); 314 if (Init >= NumInits || !ILE->getInit(Init)) { 315 // If there's no explicit initializer but we have a default initializer, use 316 // that. This only happens in C++1y, since classes with default 317 // initializers are not aggregates in C++11. 318 if (Field->hasInClassInitializer()) { 319 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 320 ILE->getRBraceLoc(), Field); 321 if (Init < NumInits) 322 ILE->setInit(Init, DIE); 323 else { 324 ILE->updateInit(SemaRef.Context, Init, DIE); 325 RequiresSecondPass = true; 326 } 327 return; 328 } 329 330 // FIXME: We probably don't need to handle references 331 // specially here, since value-initialization of references is 332 // handled in InitializationSequence. 333 if (Field->getType()->isReferenceType()) { 334 // C++ [dcl.init.aggr]p9: 335 // If an incomplete or empty initializer-list leaves a 336 // member of reference type uninitialized, the program is 337 // ill-formed. 338 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 339 << Field->getType() 340 << ILE->getSyntacticForm()->getSourceRange(); 341 SemaRef.Diag(Field->getLocation(), 342 diag::note_uninit_reference_member); 343 hadError = true; 344 return; 345 } 346 347 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 348 true); 349 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None); 350 if (!InitSeq) { 351 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None); 352 hadError = true; 353 return; 354 } 355 356 ExprResult MemberInit 357 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None); 358 if (MemberInit.isInvalid()) { 359 hadError = true; 360 return; 361 } 362 363 if (hadError) { 364 // Do nothing 365 } else if (Init < NumInits) { 366 ILE->setInit(Init, MemberInit.takeAs<Expr>()); 367 } else if (InitSeq.isConstructorInitialization()) { 368 // Value-initialization requires a constructor call, so 369 // extend the initializer list to include the constructor 370 // call and make a note that we'll need to take another pass 371 // through the initializer list. 372 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>()); 373 RequiresSecondPass = true; 374 } 375 } else if (InitListExpr *InnerILE 376 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 377 FillInValueInitializations(MemberEntity, InnerILE, 378 RequiresSecondPass); 379} 380 381/// Recursively replaces NULL values within the given initializer list 382/// with expressions that perform value-initialization of the 383/// appropriate type. 384void 385InitListChecker::FillInValueInitializations(const InitializedEntity &Entity, 386 InitListExpr *ILE, 387 bool &RequiresSecondPass) { 388 assert((ILE->getType() != SemaRef.Context.VoidTy) && 389 "Should not have void type"); 390 SourceLocation Loc = ILE->getLocStart(); 391 if (ILE->getSyntacticForm()) 392 Loc = ILE->getSyntacticForm()->getLocStart(); 393 394 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 395 const RecordDecl *RDecl = RType->getDecl(); 396 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) 397 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(), 398 Entity, ILE, RequiresSecondPass); 399 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && 400 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { 401 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 402 FieldEnd = RDecl->field_end(); 403 Field != FieldEnd; ++Field) { 404 if (Field->hasInClassInitializer()) { 405 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass); 406 break; 407 } 408 } 409 } else { 410 unsigned Init = 0; 411 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 412 FieldEnd = RDecl->field_end(); 413 Field != FieldEnd; ++Field) { 414 if (Field->isUnnamedBitfield()) 415 continue; 416 417 if (hadError) 418 return; 419 420 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass); 421 if (hadError) 422 return; 423 424 ++Init; 425 426 // Only look at the first initialization of a union. 427 if (RDecl->isUnion()) 428 break; 429 } 430 } 431 432 return; 433 } 434 435 QualType ElementType; 436 437 InitializedEntity ElementEntity = Entity; 438 unsigned NumInits = ILE->getNumInits(); 439 unsigned NumElements = NumInits; 440 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 441 ElementType = AType->getElementType(); 442 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 443 NumElements = CAType->getSize().getZExtValue(); 444 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 445 0, Entity); 446 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 447 ElementType = VType->getElementType(); 448 NumElements = VType->getNumElements(); 449 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 450 0, Entity); 451 } else 452 ElementType = ILE->getType(); 453 454 455 for (unsigned Init = 0; Init != NumElements; ++Init) { 456 if (hadError) 457 return; 458 459 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 460 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 461 ElementEntity.setElementIndex(Init); 462 463 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0); 464 if (!InitExpr && !ILE->hasArrayFiller()) { 465 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 466 true); 467 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None); 468 if (!InitSeq) { 469 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None); 470 hadError = true; 471 return; 472 } 473 474 ExprResult ElementInit 475 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None); 476 if (ElementInit.isInvalid()) { 477 hadError = true; 478 return; 479 } 480 481 if (hadError) { 482 // Do nothing 483 } else if (Init < NumInits) { 484 // For arrays, just set the expression used for value-initialization 485 // of the "holes" in the array. 486 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 487 ILE->setArrayFiller(ElementInit.takeAs<Expr>()); 488 else 489 ILE->setInit(Init, ElementInit.takeAs<Expr>()); 490 } else { 491 // For arrays, just set the expression used for value-initialization 492 // of the rest of elements and exit. 493 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 494 ILE->setArrayFiller(ElementInit.takeAs<Expr>()); 495 return; 496 } 497 498 if (InitSeq.isConstructorInitialization()) { 499 // Value-initialization requires a constructor call, so 500 // extend the initializer list to include the constructor 501 // call and make a note that we'll need to take another pass 502 // through the initializer list. 503 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>()); 504 RequiresSecondPass = true; 505 } 506 } 507 } else if (InitListExpr *InnerILE 508 = dyn_cast_or_null<InitListExpr>(InitExpr)) 509 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass); 510 } 511} 512 513 514InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 515 InitListExpr *IL, QualType &T, 516 bool VerifyOnly, bool AllowBraceElision) 517 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) { 518 hadError = false; 519 520 unsigned newIndex = 0; 521 unsigned newStructuredIndex = 0; 522 FullyStructuredList 523 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 524 CheckExplicitInitList(Entity, IL, T, newIndex, 525 FullyStructuredList, newStructuredIndex, 526 /*TopLevelObject=*/true); 527 528 if (!hadError && !VerifyOnly) { 529 bool RequiresSecondPass = false; 530 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass); 531 if (RequiresSecondPass && !hadError) 532 FillInValueInitializations(Entity, FullyStructuredList, 533 RequiresSecondPass); 534 } 535} 536 537int InitListChecker::numArrayElements(QualType DeclType) { 538 // FIXME: use a proper constant 539 int maxElements = 0x7FFFFFFF; 540 if (const ConstantArrayType *CAT = 541 SemaRef.Context.getAsConstantArrayType(DeclType)) { 542 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 543 } 544 return maxElements; 545} 546 547int InitListChecker::numStructUnionElements(QualType DeclType) { 548 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 549 int InitializableMembers = 0; 550 for (RecordDecl::field_iterator 551 Field = structDecl->field_begin(), 552 FieldEnd = structDecl->field_end(); 553 Field != FieldEnd; ++Field) { 554 if (!Field->isUnnamedBitfield()) 555 ++InitializableMembers; 556 } 557 if (structDecl->isUnion()) 558 return std::min(InitializableMembers, 1); 559 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 560} 561 562void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 563 InitListExpr *ParentIList, 564 QualType T, unsigned &Index, 565 InitListExpr *StructuredList, 566 unsigned &StructuredIndex) { 567 int maxElements = 0; 568 569 if (T->isArrayType()) 570 maxElements = numArrayElements(T); 571 else if (T->isRecordType()) 572 maxElements = numStructUnionElements(T); 573 else if (T->isVectorType()) 574 maxElements = T->getAs<VectorType>()->getNumElements(); 575 else 576 llvm_unreachable("CheckImplicitInitList(): Illegal type"); 577 578 if (maxElements == 0) { 579 if (!VerifyOnly) 580 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 581 diag::err_implicit_empty_initializer); 582 ++Index; 583 hadError = true; 584 return; 585 } 586 587 // Build a structured initializer list corresponding to this subobject. 588 InitListExpr *StructuredSubobjectInitList 589 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 590 StructuredIndex, 591 SourceRange(ParentIList->getInit(Index)->getLocStart(), 592 ParentIList->getSourceRange().getEnd())); 593 unsigned StructuredSubobjectInitIndex = 0; 594 595 // Check the element types and build the structural subobject. 596 unsigned StartIndex = Index; 597 CheckListElementTypes(Entity, ParentIList, T, 598 /*SubobjectIsDesignatorContext=*/false, Index, 599 StructuredSubobjectInitList, 600 StructuredSubobjectInitIndex); 601 602 if (VerifyOnly) { 603 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType())) 604 hadError = true; 605 } else { 606 StructuredSubobjectInitList->setType(T); 607 608 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 609 // Update the structured sub-object initializer so that it's ending 610 // range corresponds with the end of the last initializer it used. 611 if (EndIndex < ParentIList->getNumInits()) { 612 SourceLocation EndLoc 613 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 614 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 615 } 616 617 // Complain about missing braces. 618 if (T->isArrayType() || T->isRecordType()) { 619 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), 620 AllowBraceElision ? diag::warn_missing_braces : 621 diag::err_missing_braces) 622 << StructuredSubobjectInitList->getSourceRange() 623 << FixItHint::CreateInsertion( 624 StructuredSubobjectInitList->getLocStart(), "{") 625 << FixItHint::CreateInsertion( 626 SemaRef.PP.getLocForEndOfToken( 627 StructuredSubobjectInitList->getLocEnd()), 628 "}"); 629 if (!AllowBraceElision) 630 hadError = true; 631 } 632 } 633} 634 635void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 636 InitListExpr *IList, QualType &T, 637 unsigned &Index, 638 InitListExpr *StructuredList, 639 unsigned &StructuredIndex, 640 bool TopLevelObject) { 641 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 642 if (!VerifyOnly) { 643 SyntacticToSemantic[IList] = StructuredList; 644 StructuredList->setSyntacticForm(IList); 645 } 646 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 647 Index, StructuredList, StructuredIndex, TopLevelObject); 648 if (!VerifyOnly) { 649 QualType ExprTy = T; 650 if (!ExprTy->isArrayType()) 651 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); 652 IList->setType(ExprTy); 653 StructuredList->setType(ExprTy); 654 } 655 if (hadError) 656 return; 657 658 if (Index < IList->getNumInits()) { 659 // We have leftover initializers 660 if (VerifyOnly) { 661 if (SemaRef.getLangOpts().CPlusPlus || 662 (SemaRef.getLangOpts().OpenCL && 663 IList->getType()->isVectorType())) { 664 hadError = true; 665 } 666 return; 667 } 668 669 if (StructuredIndex == 1 && 670 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 671 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 672 if (SemaRef.getLangOpts().CPlusPlus) { 673 DK = diag::err_excess_initializers_in_char_array_initializer; 674 hadError = true; 675 } 676 // Special-case 677 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 678 << IList->getInit(Index)->getSourceRange(); 679 } else if (!T->isIncompleteType()) { 680 // Don't complain for incomplete types, since we'll get an error 681 // elsewhere 682 QualType CurrentObjectType = StructuredList->getType(); 683 int initKind = 684 CurrentObjectType->isArrayType()? 0 : 685 CurrentObjectType->isVectorType()? 1 : 686 CurrentObjectType->isScalarType()? 2 : 687 CurrentObjectType->isUnionType()? 3 : 688 4; 689 690 unsigned DK = diag::warn_excess_initializers; 691 if (SemaRef.getLangOpts().CPlusPlus) { 692 DK = diag::err_excess_initializers; 693 hadError = true; 694 } 695 if (SemaRef.getLangOpts().OpenCL && initKind == 1) { 696 DK = diag::err_excess_initializers; 697 hadError = true; 698 } 699 700 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 701 << initKind << IList->getInit(Index)->getSourceRange(); 702 } 703 } 704 705 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 && 706 !TopLevelObject) 707 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 708 << IList->getSourceRange() 709 << FixItHint::CreateRemoval(IList->getLocStart()) 710 << FixItHint::CreateRemoval(IList->getLocEnd()); 711} 712 713void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 714 InitListExpr *IList, 715 QualType &DeclType, 716 bool SubobjectIsDesignatorContext, 717 unsigned &Index, 718 InitListExpr *StructuredList, 719 unsigned &StructuredIndex, 720 bool TopLevelObject) { 721 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { 722 // Explicitly braced initializer for complex type can be real+imaginary 723 // parts. 724 CheckComplexType(Entity, IList, DeclType, Index, 725 StructuredList, StructuredIndex); 726 } else if (DeclType->isScalarType()) { 727 CheckScalarType(Entity, IList, DeclType, Index, 728 StructuredList, StructuredIndex); 729 } else if (DeclType->isVectorType()) { 730 CheckVectorType(Entity, IList, DeclType, Index, 731 StructuredList, StructuredIndex); 732 } else if (DeclType->isRecordType()) { 733 assert(DeclType->isAggregateType() && 734 "non-aggregate records should be handed in CheckSubElementType"); 735 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 736 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(), 737 SubobjectIsDesignatorContext, Index, 738 StructuredList, StructuredIndex, 739 TopLevelObject); 740 } else if (DeclType->isArrayType()) { 741 llvm::APSInt Zero( 742 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 743 false); 744 CheckArrayType(Entity, IList, DeclType, Zero, 745 SubobjectIsDesignatorContext, Index, 746 StructuredList, StructuredIndex); 747 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 748 // This type is invalid, issue a diagnostic. 749 ++Index; 750 if (!VerifyOnly) 751 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 752 << DeclType; 753 hadError = true; 754 } else if (DeclType->isReferenceType()) { 755 CheckReferenceType(Entity, IList, DeclType, Index, 756 StructuredList, StructuredIndex); 757 } else if (DeclType->isObjCObjectType()) { 758 if (!VerifyOnly) 759 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class) 760 << DeclType; 761 hadError = true; 762 } else { 763 if (!VerifyOnly) 764 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 765 << DeclType; 766 hadError = true; 767 } 768} 769 770void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 771 InitListExpr *IList, 772 QualType ElemType, 773 unsigned &Index, 774 InitListExpr *StructuredList, 775 unsigned &StructuredIndex) { 776 Expr *expr = IList->getInit(Index); 777 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 778 if (!ElemType->isRecordType() || ElemType->isAggregateType()) { 779 unsigned newIndex = 0; 780 unsigned newStructuredIndex = 0; 781 InitListExpr *newStructuredList 782 = getStructuredSubobjectInit(IList, Index, ElemType, 783 StructuredList, StructuredIndex, 784 SubInitList->getSourceRange()); 785 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex, 786 newStructuredList, newStructuredIndex); 787 ++StructuredIndex; 788 ++Index; 789 return; 790 } 791 assert(SemaRef.getLangOpts().CPlusPlus && 792 "non-aggregate records are only possible in C++"); 793 // C++ initialization is handled later. 794 } 795 796 if (ElemType->isScalarType()) { 797 return CheckScalarType(Entity, IList, ElemType, Index, 798 StructuredList, StructuredIndex); 799 } else if (ElemType->isReferenceType()) { 800 return CheckReferenceType(Entity, IList, ElemType, Index, 801 StructuredList, StructuredIndex); 802 } 803 804 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) { 805 // arrayType can be incomplete if we're initializing a flexible 806 // array member. There's nothing we can do with the completed 807 // type here, though. 808 809 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) { 810 if (!VerifyOnly) { 811 CheckStringInit(Str, ElemType, arrayType, SemaRef); 812 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 813 } 814 ++Index; 815 return; 816 } 817 818 // Fall through for subaggregate initialization. 819 820 } else if (SemaRef.getLangOpts().CPlusPlus) { 821 // C++ [dcl.init.aggr]p12: 822 // All implicit type conversions (clause 4) are considered when 823 // initializing the aggregate member with an initializer from 824 // an initializer-list. If the initializer can initialize a 825 // member, the member is initialized. [...] 826 827 // FIXME: Better EqualLoc? 828 InitializationKind Kind = 829 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation()); 830 InitializationSequence Seq(SemaRef, Entity, Kind, expr); 831 832 if (Seq) { 833 if (!VerifyOnly) { 834 ExprResult Result = 835 Seq.Perform(SemaRef, Entity, Kind, expr); 836 if (Result.isInvalid()) 837 hadError = true; 838 839 UpdateStructuredListElement(StructuredList, StructuredIndex, 840 Result.takeAs<Expr>()); 841 } 842 ++Index; 843 return; 844 } 845 846 // Fall through for subaggregate initialization 847 } else { 848 // C99 6.7.8p13: 849 // 850 // The initializer for a structure or union object that has 851 // automatic storage duration shall be either an initializer 852 // list as described below, or a single expression that has 853 // compatible structure or union type. In the latter case, the 854 // initial value of the object, including unnamed members, is 855 // that of the expression. 856 ExprResult ExprRes = SemaRef.Owned(expr); 857 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 858 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes, 859 !VerifyOnly) 860 == Sema::Compatible) { 861 if (ExprRes.isInvalid()) 862 hadError = true; 863 else { 864 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take()); 865 if (ExprRes.isInvalid()) 866 hadError = true; 867 } 868 UpdateStructuredListElement(StructuredList, StructuredIndex, 869 ExprRes.takeAs<Expr>()); 870 ++Index; 871 return; 872 } 873 ExprRes.release(); 874 // Fall through for subaggregate initialization 875 } 876 877 // C++ [dcl.init.aggr]p12: 878 // 879 // [...] Otherwise, if the member is itself a non-empty 880 // subaggregate, brace elision is assumed and the initializer is 881 // considered for the initialization of the first member of 882 // the subaggregate. 883 if (!SemaRef.getLangOpts().OpenCL && 884 (ElemType->isAggregateType() || ElemType->isVectorType())) { 885 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 886 StructuredIndex); 887 ++StructuredIndex; 888 } else { 889 if (!VerifyOnly) { 890 // We cannot initialize this element, so let 891 // PerformCopyInitialization produce the appropriate diagnostic. 892 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), 893 SemaRef.Owned(expr), 894 /*TopLevelOfInitList=*/true); 895 } 896 hadError = true; 897 ++Index; 898 ++StructuredIndex; 899 } 900} 901 902void InitListChecker::CheckComplexType(const InitializedEntity &Entity, 903 InitListExpr *IList, QualType DeclType, 904 unsigned &Index, 905 InitListExpr *StructuredList, 906 unsigned &StructuredIndex) { 907 assert(Index == 0 && "Index in explicit init list must be zero"); 908 909 // As an extension, clang supports complex initializers, which initialize 910 // a complex number component-wise. When an explicit initializer list for 911 // a complex number contains two two initializers, this extension kicks in: 912 // it exepcts the initializer list to contain two elements convertible to 913 // the element type of the complex type. The first element initializes 914 // the real part, and the second element intitializes the imaginary part. 915 916 if (IList->getNumInits() != 2) 917 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 918 StructuredIndex); 919 920 // This is an extension in C. (The builtin _Complex type does not exist 921 // in the C++ standard.) 922 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) 923 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init) 924 << IList->getSourceRange(); 925 926 // Initialize the complex number. 927 QualType elementType = DeclType->getAs<ComplexType>()->getElementType(); 928 InitializedEntity ElementEntity = 929 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 930 931 for (unsigned i = 0; i < 2; ++i) { 932 ElementEntity.setElementIndex(Index); 933 CheckSubElementType(ElementEntity, IList, elementType, Index, 934 StructuredList, StructuredIndex); 935 } 936} 937 938 939void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 940 InitListExpr *IList, QualType DeclType, 941 unsigned &Index, 942 InitListExpr *StructuredList, 943 unsigned &StructuredIndex) { 944 if (Index >= IList->getNumInits()) { 945 if (!VerifyOnly) 946 SemaRef.Diag(IList->getLocStart(), 947 SemaRef.getLangOpts().CPlusPlus11 ? 948 diag::warn_cxx98_compat_empty_scalar_initializer : 949 diag::err_empty_scalar_initializer) 950 << IList->getSourceRange(); 951 hadError = !SemaRef.getLangOpts().CPlusPlus11; 952 ++Index; 953 ++StructuredIndex; 954 return; 955 } 956 957 Expr *expr = IList->getInit(Index); 958 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 959 if (!VerifyOnly) 960 SemaRef.Diag(SubIList->getLocStart(), 961 diag::warn_many_braces_around_scalar_init) 962 << SubIList->getSourceRange(); 963 964 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 965 StructuredIndex); 966 return; 967 } else if (isa<DesignatedInitExpr>(expr)) { 968 if (!VerifyOnly) 969 SemaRef.Diag(expr->getLocStart(), 970 diag::err_designator_for_scalar_init) 971 << DeclType << expr->getSourceRange(); 972 hadError = true; 973 ++Index; 974 ++StructuredIndex; 975 return; 976 } 977 978 if (VerifyOnly) { 979 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr))) 980 hadError = true; 981 ++Index; 982 return; 983 } 984 985 ExprResult Result = 986 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 987 SemaRef.Owned(expr), 988 /*TopLevelOfInitList=*/true); 989 990 Expr *ResultExpr = 0; 991 992 if (Result.isInvalid()) 993 hadError = true; // types weren't compatible. 994 else { 995 ResultExpr = Result.takeAs<Expr>(); 996 997 if (ResultExpr != expr) { 998 // The type was promoted, update initializer list. 999 IList->setInit(Index, ResultExpr); 1000 } 1001 } 1002 if (hadError) 1003 ++StructuredIndex; 1004 else 1005 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1006 ++Index; 1007} 1008 1009void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 1010 InitListExpr *IList, QualType DeclType, 1011 unsigned &Index, 1012 InitListExpr *StructuredList, 1013 unsigned &StructuredIndex) { 1014 if (Index >= IList->getNumInits()) { 1015 // FIXME: It would be wonderful if we could point at the actual member. In 1016 // general, it would be useful to pass location information down the stack, 1017 // so that we know the location (or decl) of the "current object" being 1018 // initialized. 1019 if (!VerifyOnly) 1020 SemaRef.Diag(IList->getLocStart(), 1021 diag::err_init_reference_member_uninitialized) 1022 << DeclType 1023 << IList->getSourceRange(); 1024 hadError = true; 1025 ++Index; 1026 ++StructuredIndex; 1027 return; 1028 } 1029 1030 Expr *expr = IList->getInit(Index); 1031 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { 1032 if (!VerifyOnly) 1033 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 1034 << DeclType << IList->getSourceRange(); 1035 hadError = true; 1036 ++Index; 1037 ++StructuredIndex; 1038 return; 1039 } 1040 1041 if (VerifyOnly) { 1042 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr))) 1043 hadError = true; 1044 ++Index; 1045 return; 1046 } 1047 1048 ExprResult Result = 1049 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 1050 SemaRef.Owned(expr), 1051 /*TopLevelOfInitList=*/true); 1052 1053 if (Result.isInvalid()) 1054 hadError = true; 1055 1056 expr = Result.takeAs<Expr>(); 1057 IList->setInit(Index, expr); 1058 1059 if (hadError) 1060 ++StructuredIndex; 1061 else 1062 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1063 ++Index; 1064} 1065 1066void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 1067 InitListExpr *IList, QualType DeclType, 1068 unsigned &Index, 1069 InitListExpr *StructuredList, 1070 unsigned &StructuredIndex) { 1071 const VectorType *VT = DeclType->getAs<VectorType>(); 1072 unsigned maxElements = VT->getNumElements(); 1073 unsigned numEltsInit = 0; 1074 QualType elementType = VT->getElementType(); 1075 1076 if (Index >= IList->getNumInits()) { 1077 // Make sure the element type can be value-initialized. 1078 if (VerifyOnly) 1079 CheckValueInitializable( 1080 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity)); 1081 return; 1082 } 1083 1084 if (!SemaRef.getLangOpts().OpenCL) { 1085 // If the initializing element is a vector, try to copy-initialize 1086 // instead of breaking it apart (which is doomed to failure anyway). 1087 Expr *Init = IList->getInit(Index); 1088 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 1089 if (VerifyOnly) { 1090 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init))) 1091 hadError = true; 1092 ++Index; 1093 return; 1094 } 1095 1096 ExprResult Result = 1097 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), 1098 SemaRef.Owned(Init), 1099 /*TopLevelOfInitList=*/true); 1100 1101 Expr *ResultExpr = 0; 1102 if (Result.isInvalid()) 1103 hadError = true; // types weren't compatible. 1104 else { 1105 ResultExpr = Result.takeAs<Expr>(); 1106 1107 if (ResultExpr != Init) { 1108 // The type was promoted, update initializer list. 1109 IList->setInit(Index, ResultExpr); 1110 } 1111 } 1112 if (hadError) 1113 ++StructuredIndex; 1114 else 1115 UpdateStructuredListElement(StructuredList, StructuredIndex, 1116 ResultExpr); 1117 ++Index; 1118 return; 1119 } 1120 1121 InitializedEntity ElementEntity = 1122 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1123 1124 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 1125 // Don't attempt to go past the end of the init list 1126 if (Index >= IList->getNumInits()) { 1127 if (VerifyOnly) 1128 CheckValueInitializable(ElementEntity); 1129 break; 1130 } 1131 1132 ElementEntity.setElementIndex(Index); 1133 CheckSubElementType(ElementEntity, IList, elementType, Index, 1134 StructuredList, StructuredIndex); 1135 } 1136 return; 1137 } 1138 1139 InitializedEntity ElementEntity = 1140 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1141 1142 // OpenCL initializers allows vectors to be constructed from vectors. 1143 for (unsigned i = 0; i < maxElements; ++i) { 1144 // Don't attempt to go past the end of the init list 1145 if (Index >= IList->getNumInits()) 1146 break; 1147 1148 ElementEntity.setElementIndex(Index); 1149 1150 QualType IType = IList->getInit(Index)->getType(); 1151 if (!IType->isVectorType()) { 1152 CheckSubElementType(ElementEntity, IList, elementType, Index, 1153 StructuredList, StructuredIndex); 1154 ++numEltsInit; 1155 } else { 1156 QualType VecType; 1157 const VectorType *IVT = IType->getAs<VectorType>(); 1158 unsigned numIElts = IVT->getNumElements(); 1159 1160 if (IType->isExtVectorType()) 1161 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 1162 else 1163 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 1164 IVT->getVectorKind()); 1165 CheckSubElementType(ElementEntity, IList, VecType, Index, 1166 StructuredList, StructuredIndex); 1167 numEltsInit += numIElts; 1168 } 1169 } 1170 1171 // OpenCL requires all elements to be initialized. 1172 if (numEltsInit != maxElements) { 1173 if (!VerifyOnly) 1174 SemaRef.Diag(IList->getLocStart(), 1175 diag::err_vector_incorrect_num_initializers) 1176 << (numEltsInit < maxElements) << maxElements << numEltsInit; 1177 hadError = true; 1178 } 1179} 1180 1181void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 1182 InitListExpr *IList, QualType &DeclType, 1183 llvm::APSInt elementIndex, 1184 bool SubobjectIsDesignatorContext, 1185 unsigned &Index, 1186 InitListExpr *StructuredList, 1187 unsigned &StructuredIndex) { 1188 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 1189 1190 // Check for the special-case of initializing an array with a string. 1191 if (Index < IList->getNumInits()) { 1192 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType, 1193 SemaRef.Context)) { 1194 // We place the string literal directly into the resulting 1195 // initializer list. This is the only place where the structure 1196 // of the structured initializer list doesn't match exactly, 1197 // because doing so would involve allocating one character 1198 // constant for each string. 1199 if (!VerifyOnly) { 1200 CheckStringInit(Str, DeclType, arrayType, SemaRef); 1201 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 1202 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1203 } 1204 ++Index; 1205 return; 1206 } 1207 } 1208 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1209 // Check for VLAs; in standard C it would be possible to check this 1210 // earlier, but I don't know where clang accepts VLAs (gcc accepts 1211 // them in all sorts of strange places). 1212 if (!VerifyOnly) 1213 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 1214 diag::err_variable_object_no_init) 1215 << VAT->getSizeExpr()->getSourceRange(); 1216 hadError = true; 1217 ++Index; 1218 ++StructuredIndex; 1219 return; 1220 } 1221 1222 // We might know the maximum number of elements in advance. 1223 llvm::APSInt maxElements(elementIndex.getBitWidth(), 1224 elementIndex.isUnsigned()); 1225 bool maxElementsKnown = false; 1226 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1227 maxElements = CAT->getSize(); 1228 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1229 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1230 maxElementsKnown = true; 1231 } 1232 1233 QualType elementType = arrayType->getElementType(); 1234 while (Index < IList->getNumInits()) { 1235 Expr *Init = IList->getInit(Index); 1236 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1237 // If we're not the subobject that matches up with the '{' for 1238 // the designator, we shouldn't be handling the 1239 // designator. Return immediately. 1240 if (!SubobjectIsDesignatorContext) 1241 return; 1242 1243 // Handle this designated initializer. elementIndex will be 1244 // updated to be the next array element we'll initialize. 1245 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1246 DeclType, 0, &elementIndex, Index, 1247 StructuredList, StructuredIndex, true, 1248 false)) { 1249 hadError = true; 1250 continue; 1251 } 1252 1253 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1254 maxElements = maxElements.extend(elementIndex.getBitWidth()); 1255 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1256 elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1257 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1258 1259 // If the array is of incomplete type, keep track of the number of 1260 // elements in the initializer. 1261 if (!maxElementsKnown && elementIndex > maxElements) 1262 maxElements = elementIndex; 1263 1264 continue; 1265 } 1266 1267 // If we know the maximum number of elements, and we've already 1268 // hit it, stop consuming elements in the initializer list. 1269 if (maxElementsKnown && elementIndex == maxElements) 1270 break; 1271 1272 InitializedEntity ElementEntity = 1273 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1274 Entity); 1275 // Check this element. 1276 CheckSubElementType(ElementEntity, IList, elementType, Index, 1277 StructuredList, StructuredIndex); 1278 ++elementIndex; 1279 1280 // If the array is of incomplete type, keep track of the number of 1281 // elements in the initializer. 1282 if (!maxElementsKnown && elementIndex > maxElements) 1283 maxElements = elementIndex; 1284 } 1285 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { 1286 // If this is an incomplete array type, the actual type needs to 1287 // be calculated here. 1288 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1289 if (maxElements == Zero) { 1290 // Sizing an array implicitly to zero is not allowed by ISO C, 1291 // but is supported by GNU. 1292 SemaRef.Diag(IList->getLocStart(), 1293 diag::ext_typecheck_zero_array_size); 1294 } 1295 1296 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1297 ArrayType::Normal, 0); 1298 } 1299 if (!hadError && VerifyOnly) { 1300 // Check if there are any members of the array that get value-initialized. 1301 // If so, check if doing that is possible. 1302 // FIXME: This needs to detect holes left by designated initializers too. 1303 if (maxElementsKnown && elementIndex < maxElements) 1304 CheckValueInitializable(InitializedEntity::InitializeElement( 1305 SemaRef.Context, 0, Entity)); 1306 } 1307} 1308 1309bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, 1310 Expr *InitExpr, 1311 FieldDecl *Field, 1312 bool TopLevelObject) { 1313 // Handle GNU flexible array initializers. 1314 unsigned FlexArrayDiag; 1315 if (isa<InitListExpr>(InitExpr) && 1316 cast<InitListExpr>(InitExpr)->getNumInits() == 0) { 1317 // Empty flexible array init always allowed as an extension 1318 FlexArrayDiag = diag::ext_flexible_array_init; 1319 } else if (SemaRef.getLangOpts().CPlusPlus) { 1320 // Disallow flexible array init in C++; it is not required for gcc 1321 // compatibility, and it needs work to IRGen correctly in general. 1322 FlexArrayDiag = diag::err_flexible_array_init; 1323 } else if (!TopLevelObject) { 1324 // Disallow flexible array init on non-top-level object 1325 FlexArrayDiag = diag::err_flexible_array_init; 1326 } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 1327 // Disallow flexible array init on anything which is not a variable. 1328 FlexArrayDiag = diag::err_flexible_array_init; 1329 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { 1330 // Disallow flexible array init on local variables. 1331 FlexArrayDiag = diag::err_flexible_array_init; 1332 } else { 1333 // Allow other cases. 1334 FlexArrayDiag = diag::ext_flexible_array_init; 1335 } 1336 1337 if (!VerifyOnly) { 1338 SemaRef.Diag(InitExpr->getLocStart(), 1339 FlexArrayDiag) 1340 << InitExpr->getLocStart(); 1341 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1342 << Field; 1343 } 1344 1345 return FlexArrayDiag != diag::ext_flexible_array_init; 1346} 1347 1348void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity, 1349 InitListExpr *IList, 1350 QualType DeclType, 1351 RecordDecl::field_iterator Field, 1352 bool SubobjectIsDesignatorContext, 1353 unsigned &Index, 1354 InitListExpr *StructuredList, 1355 unsigned &StructuredIndex, 1356 bool TopLevelObject) { 1357 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 1358 1359 // If the record is invalid, some of it's members are invalid. To avoid 1360 // confusion, we forgo checking the intializer for the entire record. 1361 if (structDecl->isInvalidDecl()) { 1362 // Assume it was supposed to consume a single initializer. 1363 ++Index; 1364 hadError = true; 1365 return; 1366 } 1367 1368 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1369 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1370 1371 // If there's a default initializer, use it. 1372 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { 1373 if (VerifyOnly) 1374 return; 1375 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1376 Field != FieldEnd; ++Field) { 1377 if (Field->hasInClassInitializer()) { 1378 StructuredList->setInitializedFieldInUnion(*Field); 1379 // FIXME: Actually build a CXXDefaultInitExpr? 1380 return; 1381 } 1382 } 1383 } 1384 1385 // Value-initialize the first named member of the union. 1386 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1387 Field != FieldEnd; ++Field) { 1388 if (Field->getDeclName()) { 1389 if (VerifyOnly) 1390 CheckValueInitializable( 1391 InitializedEntity::InitializeMember(*Field, &Entity)); 1392 else 1393 StructuredList->setInitializedFieldInUnion(*Field); 1394 break; 1395 } 1396 } 1397 return; 1398 } 1399 1400 // If structDecl is a forward declaration, this loop won't do 1401 // anything except look at designated initializers; That's okay, 1402 // because an error should get printed out elsewhere. It might be 1403 // worthwhile to skip over the rest of the initializer, though. 1404 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1405 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1406 bool InitializedSomething = false; 1407 bool CheckForMissingFields = true; 1408 while (Index < IList->getNumInits()) { 1409 Expr *Init = IList->getInit(Index); 1410 1411 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1412 // If we're not the subobject that matches up with the '{' for 1413 // the designator, we shouldn't be handling the 1414 // designator. Return immediately. 1415 if (!SubobjectIsDesignatorContext) 1416 return; 1417 1418 // Handle this designated initializer. Field will be updated to 1419 // the next field that we'll be initializing. 1420 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1421 DeclType, &Field, 0, Index, 1422 StructuredList, StructuredIndex, 1423 true, TopLevelObject)) 1424 hadError = true; 1425 1426 InitializedSomething = true; 1427 1428 // Disable check for missing fields when designators are used. 1429 // This matches gcc behaviour. 1430 CheckForMissingFields = false; 1431 continue; 1432 } 1433 1434 if (Field == FieldEnd) { 1435 // We've run out of fields. We're done. 1436 break; 1437 } 1438 1439 // We've already initialized a member of a union. We're done. 1440 if (InitializedSomething && DeclType->isUnionType()) 1441 break; 1442 1443 // If we've hit the flexible array member at the end, we're done. 1444 if (Field->getType()->isIncompleteArrayType()) 1445 break; 1446 1447 if (Field->isUnnamedBitfield()) { 1448 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1449 ++Field; 1450 continue; 1451 } 1452 1453 // Make sure we can use this declaration. 1454 bool InvalidUse; 1455 if (VerifyOnly) 1456 InvalidUse = !SemaRef.CanUseDecl(*Field); 1457 else 1458 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, 1459 IList->getInit(Index)->getLocStart()); 1460 if (InvalidUse) { 1461 ++Index; 1462 ++Field; 1463 hadError = true; 1464 continue; 1465 } 1466 1467 InitializedEntity MemberEntity = 1468 InitializedEntity::InitializeMember(*Field, &Entity); 1469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1470 StructuredList, StructuredIndex); 1471 InitializedSomething = true; 1472 1473 if (DeclType->isUnionType() && !VerifyOnly) { 1474 // Initialize the first field within the union. 1475 StructuredList->setInitializedFieldInUnion(*Field); 1476 } 1477 1478 ++Field; 1479 } 1480 1481 // Emit warnings for missing struct field initializers. 1482 if (!VerifyOnly && InitializedSomething && CheckForMissingFields && 1483 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && 1484 !DeclType->isUnionType()) { 1485 // It is possible we have one or more unnamed bitfields remaining. 1486 // Find first (if any) named field and emit warning. 1487 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 1488 it != end; ++it) { 1489 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { 1490 SemaRef.Diag(IList->getSourceRange().getEnd(), 1491 diag::warn_missing_field_initializers) << it->getName(); 1492 break; 1493 } 1494 } 1495 } 1496 1497 // Check that any remaining fields can be value-initialized. 1498 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() && 1499 !Field->getType()->isIncompleteArrayType()) { 1500 // FIXME: Should check for holes left by designated initializers too. 1501 for (; Field != FieldEnd && !hadError; ++Field) { 1502 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) 1503 CheckValueInitializable( 1504 InitializedEntity::InitializeMember(*Field, &Entity)); 1505 } 1506 } 1507 1508 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1509 Index >= IList->getNumInits()) 1510 return; 1511 1512 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, 1513 TopLevelObject)) { 1514 hadError = true; 1515 ++Index; 1516 return; 1517 } 1518 1519 InitializedEntity MemberEntity = 1520 InitializedEntity::InitializeMember(*Field, &Entity); 1521 1522 if (isa<InitListExpr>(IList->getInit(Index))) 1523 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1524 StructuredList, StructuredIndex); 1525 else 1526 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 1527 StructuredList, StructuredIndex); 1528} 1529 1530/// \brief Expand a field designator that refers to a member of an 1531/// anonymous struct or union into a series of field designators that 1532/// refers to the field within the appropriate subobject. 1533/// 1534static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1535 DesignatedInitExpr *DIE, 1536 unsigned DesigIdx, 1537 IndirectFieldDecl *IndirectField) { 1538 typedef DesignatedInitExpr::Designator Designator; 1539 1540 // Build the replacement designators. 1541 SmallVector<Designator, 4> Replacements; 1542 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 1543 PE = IndirectField->chain_end(); PI != PE; ++PI) { 1544 if (PI + 1 == PE) 1545 Replacements.push_back(Designator((IdentifierInfo *)0, 1546 DIE->getDesignator(DesigIdx)->getDotLoc(), 1547 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1548 else 1549 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1550 SourceLocation())); 1551 assert(isa<FieldDecl>(*PI)); 1552 Replacements.back().setField(cast<FieldDecl>(*PI)); 1553 } 1554 1555 // Expand the current designator into the set of replacement 1556 // designators, so we have a full subobject path down to where the 1557 // member of the anonymous struct/union is actually stored. 1558 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 1559 &Replacements[0] + Replacements.size()); 1560} 1561 1562/// \brief Given an implicit anonymous field, search the IndirectField that 1563/// corresponds to FieldName. 1564static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField, 1565 IdentifierInfo *FieldName) { 1566 if (!FieldName) 1567 return 0; 1568 1569 assert(AnonField->isAnonymousStructOrUnion()); 1570 Decl *NextDecl = AnonField->getNextDeclInContext(); 1571 while (IndirectFieldDecl *IF = 1572 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) { 1573 if (FieldName == IF->getAnonField()->getIdentifier()) 1574 return IF; 1575 NextDecl = NextDecl->getNextDeclInContext(); 1576 } 1577 return 0; 1578} 1579 1580static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, 1581 DesignatedInitExpr *DIE) { 1582 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; 1583 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); 1584 for (unsigned I = 0; I < NumIndexExprs; ++I) 1585 IndexExprs[I] = DIE->getSubExpr(I + 1); 1586 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(), 1587 DIE->size(), IndexExprs, 1588 DIE->getEqualOrColonLoc(), 1589 DIE->usesGNUSyntax(), DIE->getInit()); 1590} 1591 1592namespace { 1593 1594// Callback to only accept typo corrections that are for field members of 1595// the given struct or union. 1596class FieldInitializerValidatorCCC : public CorrectionCandidateCallback { 1597 public: 1598 explicit FieldInitializerValidatorCCC(RecordDecl *RD) 1599 : Record(RD) {} 1600 1601 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1602 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); 1603 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); 1604 } 1605 1606 private: 1607 RecordDecl *Record; 1608}; 1609 1610} 1611 1612/// @brief Check the well-formedness of a C99 designated initializer. 1613/// 1614/// Determines whether the designated initializer @p DIE, which 1615/// resides at the given @p Index within the initializer list @p 1616/// IList, is well-formed for a current object of type @p DeclType 1617/// (C99 6.7.8). The actual subobject that this designator refers to 1618/// within the current subobject is returned in either 1619/// @p NextField or @p NextElementIndex (whichever is appropriate). 1620/// 1621/// @param IList The initializer list in which this designated 1622/// initializer occurs. 1623/// 1624/// @param DIE The designated initializer expression. 1625/// 1626/// @param DesigIdx The index of the current designator. 1627/// 1628/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), 1629/// into which the designation in @p DIE should refer. 1630/// 1631/// @param NextField If non-NULL and the first designator in @p DIE is 1632/// a field, this will be set to the field declaration corresponding 1633/// to the field named by the designator. 1634/// 1635/// @param NextElementIndex If non-NULL and the first designator in @p 1636/// DIE is an array designator or GNU array-range designator, this 1637/// will be set to the last index initialized by this designator. 1638/// 1639/// @param Index Index into @p IList where the designated initializer 1640/// @p DIE occurs. 1641/// 1642/// @param StructuredList The initializer list expression that 1643/// describes all of the subobject initializers in the order they'll 1644/// actually be initialized. 1645/// 1646/// @returns true if there was an error, false otherwise. 1647bool 1648InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 1649 InitListExpr *IList, 1650 DesignatedInitExpr *DIE, 1651 unsigned DesigIdx, 1652 QualType &CurrentObjectType, 1653 RecordDecl::field_iterator *NextField, 1654 llvm::APSInt *NextElementIndex, 1655 unsigned &Index, 1656 InitListExpr *StructuredList, 1657 unsigned &StructuredIndex, 1658 bool FinishSubobjectInit, 1659 bool TopLevelObject) { 1660 if (DesigIdx == DIE->size()) { 1661 // Check the actual initialization for the designated object type. 1662 bool prevHadError = hadError; 1663 1664 // Temporarily remove the designator expression from the 1665 // initializer list that the child calls see, so that we don't try 1666 // to re-process the designator. 1667 unsigned OldIndex = Index; 1668 IList->setInit(OldIndex, DIE->getInit()); 1669 1670 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 1671 StructuredList, StructuredIndex); 1672 1673 // Restore the designated initializer expression in the syntactic 1674 // form of the initializer list. 1675 if (IList->getInit(OldIndex) != DIE->getInit()) 1676 DIE->setInit(IList->getInit(OldIndex)); 1677 IList->setInit(OldIndex, DIE); 1678 1679 return hadError && !prevHadError; 1680 } 1681 1682 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1683 bool IsFirstDesignator = (DesigIdx == 0); 1684 if (!VerifyOnly) { 1685 assert((IsFirstDesignator || StructuredList) && 1686 "Need a non-designated initializer list to start from"); 1687 1688 // Determine the structural initializer list that corresponds to the 1689 // current subobject. 1690 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList) 1691 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1692 StructuredList, StructuredIndex, 1693 SourceRange(D->getLocStart(), 1694 DIE->getLocEnd())); 1695 assert(StructuredList && "Expected a structured initializer list"); 1696 } 1697 1698 if (D->isFieldDesignator()) { 1699 // C99 6.7.8p7: 1700 // 1701 // If a designator has the form 1702 // 1703 // . identifier 1704 // 1705 // then the current object (defined below) shall have 1706 // structure or union type and the identifier shall be the 1707 // name of a member of that type. 1708 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1709 if (!RT) { 1710 SourceLocation Loc = D->getDotLoc(); 1711 if (Loc.isInvalid()) 1712 Loc = D->getFieldLoc(); 1713 if (!VerifyOnly) 1714 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1715 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; 1716 ++Index; 1717 return true; 1718 } 1719 1720 // Note: we perform a linear search of the fields here, despite 1721 // the fact that we have a faster lookup method, because we always 1722 // need to compute the field's index. 1723 FieldDecl *KnownField = D->getField(); 1724 IdentifierInfo *FieldName = D->getFieldName(); 1725 unsigned FieldIndex = 0; 1726 RecordDecl::field_iterator 1727 Field = RT->getDecl()->field_begin(), 1728 FieldEnd = RT->getDecl()->field_end(); 1729 for (; Field != FieldEnd; ++Field) { 1730 if (Field->isUnnamedBitfield()) 1731 continue; 1732 1733 // If we find a field representing an anonymous field, look in the 1734 // IndirectFieldDecl that follow for the designated initializer. 1735 if (!KnownField && Field->isAnonymousStructOrUnion()) { 1736 if (IndirectFieldDecl *IF = 1737 FindIndirectFieldDesignator(*Field, FieldName)) { 1738 // In verify mode, don't modify the original. 1739 if (VerifyOnly) 1740 DIE = CloneDesignatedInitExpr(SemaRef, DIE); 1741 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF); 1742 D = DIE->getDesignator(DesigIdx); 1743 break; 1744 } 1745 } 1746 if (KnownField && KnownField == *Field) 1747 break; 1748 if (FieldName && FieldName == Field->getIdentifier()) 1749 break; 1750 1751 ++FieldIndex; 1752 } 1753 1754 if (Field == FieldEnd) { 1755 if (VerifyOnly) { 1756 ++Index; 1757 return true; // No typo correction when just trying this out. 1758 } 1759 1760 // There was no normal field in the struct with the designated 1761 // name. Perform another lookup for this name, which may find 1762 // something that we can't designate (e.g., a member function), 1763 // may find nothing, or may find a member of an anonymous 1764 // struct/union. 1765 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1766 FieldDecl *ReplacementField = 0; 1767 if (Lookup.empty()) { 1768 // Name lookup didn't find anything. Determine whether this 1769 // was a typo for another field name. 1770 FieldInitializerValidatorCCC Validator(RT->getDecl()); 1771 TypoCorrection Corrected = SemaRef.CorrectTypo( 1772 DeclarationNameInfo(FieldName, D->getFieldLoc()), 1773 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator, 1774 RT->getDecl()); 1775 if (Corrected) { 1776 std::string CorrectedStr( 1777 Corrected.getAsString(SemaRef.getLangOpts())); 1778 std::string CorrectedQuotedStr( 1779 Corrected.getQuoted(SemaRef.getLangOpts())); 1780 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>(); 1781 SemaRef.Diag(D->getFieldLoc(), 1782 diag::err_field_designator_unknown_suggest) 1783 << FieldName << CurrentObjectType << CorrectedQuotedStr 1784 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr); 1785 SemaRef.Diag(ReplacementField->getLocation(), 1786 diag::note_previous_decl) << CorrectedQuotedStr; 1787 hadError = true; 1788 } else { 1789 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1790 << FieldName << CurrentObjectType; 1791 ++Index; 1792 return true; 1793 } 1794 } 1795 1796 if (!ReplacementField) { 1797 // Name lookup found something, but it wasn't a field. 1798 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1799 << FieldName; 1800 SemaRef.Diag(Lookup.front()->getLocation(), 1801 diag::note_field_designator_found); 1802 ++Index; 1803 return true; 1804 } 1805 1806 if (!KnownField) { 1807 // The replacement field comes from typo correction; find it 1808 // in the list of fields. 1809 FieldIndex = 0; 1810 Field = RT->getDecl()->field_begin(); 1811 for (; Field != FieldEnd; ++Field) { 1812 if (Field->isUnnamedBitfield()) 1813 continue; 1814 1815 if (ReplacementField == *Field || 1816 Field->getIdentifier() == ReplacementField->getIdentifier()) 1817 break; 1818 1819 ++FieldIndex; 1820 } 1821 } 1822 } 1823 1824 // All of the fields of a union are located at the same place in 1825 // the initializer list. 1826 if (RT->getDecl()->isUnion()) { 1827 FieldIndex = 0; 1828 if (!VerifyOnly) 1829 StructuredList->setInitializedFieldInUnion(*Field); 1830 } 1831 1832 // Make sure we can use this declaration. 1833 bool InvalidUse; 1834 if (VerifyOnly) 1835 InvalidUse = !SemaRef.CanUseDecl(*Field); 1836 else 1837 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); 1838 if (InvalidUse) { 1839 ++Index; 1840 return true; 1841 } 1842 1843 if (!VerifyOnly) { 1844 // Update the designator with the field declaration. 1845 D->setField(*Field); 1846 1847 // Make sure that our non-designated initializer list has space 1848 // for a subobject corresponding to this field. 1849 if (FieldIndex >= StructuredList->getNumInits()) 1850 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1851 } 1852 1853 // This designator names a flexible array member. 1854 if (Field->getType()->isIncompleteArrayType()) { 1855 bool Invalid = false; 1856 if ((DesigIdx + 1) != DIE->size()) { 1857 // We can't designate an object within the flexible array 1858 // member (because GCC doesn't allow it). 1859 if (!VerifyOnly) { 1860 DesignatedInitExpr::Designator *NextD 1861 = DIE->getDesignator(DesigIdx + 1); 1862 SemaRef.Diag(NextD->getLocStart(), 1863 diag::err_designator_into_flexible_array_member) 1864 << SourceRange(NextD->getLocStart(), 1865 DIE->getLocEnd()); 1866 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1867 << *Field; 1868 } 1869 Invalid = true; 1870 } 1871 1872 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 1873 !isa<StringLiteral>(DIE->getInit())) { 1874 // The initializer is not an initializer list. 1875 if (!VerifyOnly) { 1876 SemaRef.Diag(DIE->getInit()->getLocStart(), 1877 diag::err_flexible_array_init_needs_braces) 1878 << DIE->getInit()->getSourceRange(); 1879 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1880 << *Field; 1881 } 1882 Invalid = true; 1883 } 1884 1885 // Check GNU flexible array initializer. 1886 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, 1887 TopLevelObject)) 1888 Invalid = true; 1889 1890 if (Invalid) { 1891 ++Index; 1892 return true; 1893 } 1894 1895 // Initialize the array. 1896 bool prevHadError = hadError; 1897 unsigned newStructuredIndex = FieldIndex; 1898 unsigned OldIndex = Index; 1899 IList->setInit(Index, DIE->getInit()); 1900 1901 InitializedEntity MemberEntity = 1902 InitializedEntity::InitializeMember(*Field, &Entity); 1903 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1904 StructuredList, newStructuredIndex); 1905 1906 IList->setInit(OldIndex, DIE); 1907 if (hadError && !prevHadError) { 1908 ++Field; 1909 ++FieldIndex; 1910 if (NextField) 1911 *NextField = Field; 1912 StructuredIndex = FieldIndex; 1913 return true; 1914 } 1915 } else { 1916 // Recurse to check later designated subobjects. 1917 QualType FieldType = Field->getType(); 1918 unsigned newStructuredIndex = FieldIndex; 1919 1920 InitializedEntity MemberEntity = 1921 InitializedEntity::InitializeMember(*Field, &Entity); 1922 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 1923 FieldType, 0, 0, Index, 1924 StructuredList, newStructuredIndex, 1925 true, false)) 1926 return true; 1927 } 1928 1929 // Find the position of the next field to be initialized in this 1930 // subobject. 1931 ++Field; 1932 ++FieldIndex; 1933 1934 // If this the first designator, our caller will continue checking 1935 // the rest of this struct/class/union subobject. 1936 if (IsFirstDesignator) { 1937 if (NextField) 1938 *NextField = Field; 1939 StructuredIndex = FieldIndex; 1940 return false; 1941 } 1942 1943 if (!FinishSubobjectInit) 1944 return false; 1945 1946 // We've already initialized something in the union; we're done. 1947 if (RT->getDecl()->isUnion()) 1948 return hadError; 1949 1950 // Check the remaining fields within this class/struct/union subobject. 1951 bool prevHadError = hadError; 1952 1953 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index, 1954 StructuredList, FieldIndex); 1955 return hadError && !prevHadError; 1956 } 1957 1958 // C99 6.7.8p6: 1959 // 1960 // If a designator has the form 1961 // 1962 // [ constant-expression ] 1963 // 1964 // then the current object (defined below) shall have array 1965 // type and the expression shall be an integer constant 1966 // expression. If the array is of unknown size, any 1967 // nonnegative value is valid. 1968 // 1969 // Additionally, cope with the GNU extension that permits 1970 // designators of the form 1971 // 1972 // [ constant-expression ... constant-expression ] 1973 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1974 if (!AT) { 1975 if (!VerifyOnly) 1976 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1977 << CurrentObjectType; 1978 ++Index; 1979 return true; 1980 } 1981 1982 Expr *IndexExpr = 0; 1983 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1984 if (D->isArrayDesignator()) { 1985 IndexExpr = DIE->getArrayIndex(*D); 1986 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); 1987 DesignatedEndIndex = DesignatedStartIndex; 1988 } else { 1989 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1990 1991 DesignatedStartIndex = 1992 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); 1993 DesignatedEndIndex = 1994 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); 1995 IndexExpr = DIE->getArrayRangeEnd(*D); 1996 1997 // Codegen can't handle evaluating array range designators that have side 1998 // effects, because we replicate the AST value for each initialized element. 1999 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 2000 // elements with something that has a side effect, so codegen can emit an 2001 // "error unsupported" error instead of miscompiling the app. 2002 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 2003 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) 2004 FullyStructuredList->sawArrayRangeDesignator(); 2005 } 2006 2007 if (isa<ConstantArrayType>(AT)) { 2008 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 2009 DesignatedStartIndex 2010 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 2011 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 2012 DesignatedEndIndex 2013 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 2014 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 2015 if (DesignatedEndIndex >= MaxElements) { 2016 if (!VerifyOnly) 2017 SemaRef.Diag(IndexExpr->getLocStart(), 2018 diag::err_array_designator_too_large) 2019 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 2020 << IndexExpr->getSourceRange(); 2021 ++Index; 2022 return true; 2023 } 2024 } else { 2025 // Make sure the bit-widths and signedness match. 2026 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 2027 DesignatedEndIndex 2028 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 2029 else if (DesignatedStartIndex.getBitWidth() < 2030 DesignatedEndIndex.getBitWidth()) 2031 DesignatedStartIndex 2032 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 2033 DesignatedStartIndex.setIsUnsigned(true); 2034 DesignatedEndIndex.setIsUnsigned(true); 2035 } 2036 2037 // Make sure that our non-designated initializer list has space 2038 // for a subobject corresponding to this array element. 2039 if (!VerifyOnly && 2040 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 2041 StructuredList->resizeInits(SemaRef.Context, 2042 DesignatedEndIndex.getZExtValue() + 1); 2043 2044 // Repeatedly perform subobject initializations in the range 2045 // [DesignatedStartIndex, DesignatedEndIndex]. 2046 2047 // Move to the next designator 2048 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 2049 unsigned OldIndex = Index; 2050 2051 InitializedEntity ElementEntity = 2052 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 2053 2054 while (DesignatedStartIndex <= DesignatedEndIndex) { 2055 // Recurse to check later designated subobjects. 2056 QualType ElementType = AT->getElementType(); 2057 Index = OldIndex; 2058 2059 ElementEntity.setElementIndex(ElementIndex); 2060 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1, 2061 ElementType, 0, 0, Index, 2062 StructuredList, ElementIndex, 2063 (DesignatedStartIndex == DesignatedEndIndex), 2064 false)) 2065 return true; 2066 2067 // Move to the next index in the array that we'll be initializing. 2068 ++DesignatedStartIndex; 2069 ElementIndex = DesignatedStartIndex.getZExtValue(); 2070 } 2071 2072 // If this the first designator, our caller will continue checking 2073 // the rest of this array subobject. 2074 if (IsFirstDesignator) { 2075 if (NextElementIndex) 2076 *NextElementIndex = DesignatedStartIndex; 2077 StructuredIndex = ElementIndex; 2078 return false; 2079 } 2080 2081 if (!FinishSubobjectInit) 2082 return false; 2083 2084 // Check the remaining elements within this array subobject. 2085 bool prevHadError = hadError; 2086 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 2087 /*SubobjectIsDesignatorContext=*/false, Index, 2088 StructuredList, ElementIndex); 2089 return hadError && !prevHadError; 2090} 2091 2092// Get the structured initializer list for a subobject of type 2093// @p CurrentObjectType. 2094InitListExpr * 2095InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 2096 QualType CurrentObjectType, 2097 InitListExpr *StructuredList, 2098 unsigned StructuredIndex, 2099 SourceRange InitRange) { 2100 if (VerifyOnly) 2101 return 0; // No structured list in verification-only mode. 2102 Expr *ExistingInit = 0; 2103 if (!StructuredList) 2104 ExistingInit = SyntacticToSemantic.lookup(IList); 2105 else if (StructuredIndex < StructuredList->getNumInits()) 2106 ExistingInit = StructuredList->getInit(StructuredIndex); 2107 2108 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 2109 return Result; 2110 2111 if (ExistingInit) { 2112 // We are creating an initializer list that initializes the 2113 // subobjects of the current object, but there was already an 2114 // initialization that completely initialized the current 2115 // subobject, e.g., by a compound literal: 2116 // 2117 // struct X { int a, b; }; 2118 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2119 // 2120 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 2121 // designated initializer re-initializes the whole 2122 // subobject [0], overwriting previous initializers. 2123 SemaRef.Diag(InitRange.getBegin(), 2124 diag::warn_subobject_initializer_overrides) 2125 << InitRange; 2126 SemaRef.Diag(ExistingInit->getLocStart(), 2127 diag::note_previous_initializer) 2128 << /*FIXME:has side effects=*/0 2129 << ExistingInit->getSourceRange(); 2130 } 2131 2132 InitListExpr *Result 2133 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 2134 InitRange.getBegin(), None, 2135 InitRange.getEnd()); 2136 2137 QualType ResultType = CurrentObjectType; 2138 if (!ResultType->isArrayType()) 2139 ResultType = ResultType.getNonLValueExprType(SemaRef.Context); 2140 Result->setType(ResultType); 2141 2142 // Pre-allocate storage for the structured initializer list. 2143 unsigned NumElements = 0; 2144 unsigned NumInits = 0; 2145 bool GotNumInits = false; 2146 if (!StructuredList) { 2147 NumInits = IList->getNumInits(); 2148 GotNumInits = true; 2149 } else if (Index < IList->getNumInits()) { 2150 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) { 2151 NumInits = SubList->getNumInits(); 2152 GotNumInits = true; 2153 } 2154 } 2155 2156 if (const ArrayType *AType 2157 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 2158 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 2159 NumElements = CAType->getSize().getZExtValue(); 2160 // Simple heuristic so that we don't allocate a very large 2161 // initializer with many empty entries at the end. 2162 if (GotNumInits && NumElements > NumInits) 2163 NumElements = 0; 2164 } 2165 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 2166 NumElements = VType->getNumElements(); 2167 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 2168 RecordDecl *RDecl = RType->getDecl(); 2169 if (RDecl->isUnion()) 2170 NumElements = 1; 2171 else 2172 NumElements = std::distance(RDecl->field_begin(), 2173 RDecl->field_end()); 2174 } 2175 2176 Result->reserveInits(SemaRef.Context, NumElements); 2177 2178 // Link this new initializer list into the structured initializer 2179 // lists. 2180 if (StructuredList) 2181 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 2182 else { 2183 Result->setSyntacticForm(IList); 2184 SyntacticToSemantic[IList] = Result; 2185 } 2186 2187 return Result; 2188} 2189 2190/// Update the initializer at index @p StructuredIndex within the 2191/// structured initializer list to the value @p expr. 2192void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 2193 unsigned &StructuredIndex, 2194 Expr *expr) { 2195 // No structured initializer list to update 2196 if (!StructuredList) 2197 return; 2198 2199 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 2200 StructuredIndex, expr)) { 2201 // This initializer overwrites a previous initializer. Warn. 2202 SemaRef.Diag(expr->getLocStart(), 2203 diag::warn_initializer_overrides) 2204 << expr->getSourceRange(); 2205 SemaRef.Diag(PrevInit->getLocStart(), 2206 diag::note_previous_initializer) 2207 << /*FIXME:has side effects=*/0 2208 << PrevInit->getSourceRange(); 2209 } 2210 2211 ++StructuredIndex; 2212} 2213 2214/// Check that the given Index expression is a valid array designator 2215/// value. This is essentially just a wrapper around 2216/// VerifyIntegerConstantExpression that also checks for negative values 2217/// and produces a reasonable diagnostic if there is a 2218/// failure. Returns the index expression, possibly with an implicit cast 2219/// added, on success. If everything went okay, Value will receive the 2220/// value of the constant expression. 2221static ExprResult 2222CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 2223 SourceLocation Loc = Index->getLocStart(); 2224 2225 // Make sure this is an integer constant expression. 2226 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value); 2227 if (Result.isInvalid()) 2228 return Result; 2229 2230 if (Value.isSigned() && Value.isNegative()) 2231 return S.Diag(Loc, diag::err_array_designator_negative) 2232 << Value.toString(10) << Index->getSourceRange(); 2233 2234 Value.setIsUnsigned(true); 2235 return Result; 2236} 2237 2238ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 2239 SourceLocation Loc, 2240 bool GNUSyntax, 2241 ExprResult Init) { 2242 typedef DesignatedInitExpr::Designator ASTDesignator; 2243 2244 bool Invalid = false; 2245 SmallVector<ASTDesignator, 32> Designators; 2246 SmallVector<Expr *, 32> InitExpressions; 2247 2248 // Build designators and check array designator expressions. 2249 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 2250 const Designator &D = Desig.getDesignator(Idx); 2251 switch (D.getKind()) { 2252 case Designator::FieldDesignator: 2253 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 2254 D.getFieldLoc())); 2255 break; 2256 2257 case Designator::ArrayDesignator: { 2258 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 2259 llvm::APSInt IndexValue; 2260 if (!Index->isTypeDependent() && !Index->isValueDependent()) 2261 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take(); 2262 if (!Index) 2263 Invalid = true; 2264 else { 2265 Designators.push_back(ASTDesignator(InitExpressions.size(), 2266 D.getLBracketLoc(), 2267 D.getRBracketLoc())); 2268 InitExpressions.push_back(Index); 2269 } 2270 break; 2271 } 2272 2273 case Designator::ArrayRangeDesignator: { 2274 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 2275 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 2276 llvm::APSInt StartValue; 2277 llvm::APSInt EndValue; 2278 bool StartDependent = StartIndex->isTypeDependent() || 2279 StartIndex->isValueDependent(); 2280 bool EndDependent = EndIndex->isTypeDependent() || 2281 EndIndex->isValueDependent(); 2282 if (!StartDependent) 2283 StartIndex = 2284 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take(); 2285 if (!EndDependent) 2286 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take(); 2287 2288 if (!StartIndex || !EndIndex) 2289 Invalid = true; 2290 else { 2291 // Make sure we're comparing values with the same bit width. 2292 if (StartDependent || EndDependent) { 2293 // Nothing to compute. 2294 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 2295 EndValue = EndValue.extend(StartValue.getBitWidth()); 2296 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 2297 StartValue = StartValue.extend(EndValue.getBitWidth()); 2298 2299 if (!StartDependent && !EndDependent && EndValue < StartValue) { 2300 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 2301 << StartValue.toString(10) << EndValue.toString(10) 2302 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 2303 Invalid = true; 2304 } else { 2305 Designators.push_back(ASTDesignator(InitExpressions.size(), 2306 D.getLBracketLoc(), 2307 D.getEllipsisLoc(), 2308 D.getRBracketLoc())); 2309 InitExpressions.push_back(StartIndex); 2310 InitExpressions.push_back(EndIndex); 2311 } 2312 } 2313 break; 2314 } 2315 } 2316 } 2317 2318 if (Invalid || Init.isInvalid()) 2319 return ExprError(); 2320 2321 // Clear out the expressions within the designation. 2322 Desig.ClearExprs(*this); 2323 2324 DesignatedInitExpr *DIE 2325 = DesignatedInitExpr::Create(Context, 2326 Designators.data(), Designators.size(), 2327 InitExpressions, Loc, GNUSyntax, 2328 Init.takeAs<Expr>()); 2329 2330 if (!getLangOpts().C99) 2331 Diag(DIE->getLocStart(), diag::ext_designated_init) 2332 << DIE->getSourceRange(); 2333 2334 return Owned(DIE); 2335} 2336 2337//===----------------------------------------------------------------------===// 2338// Initialization entity 2339//===----------------------------------------------------------------------===// 2340 2341InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 2342 const InitializedEntity &Parent) 2343 : Parent(&Parent), Index(Index) 2344{ 2345 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 2346 Kind = EK_ArrayElement; 2347 Type = AT->getElementType(); 2348 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 2349 Kind = EK_VectorElement; 2350 Type = VT->getElementType(); 2351 } else { 2352 const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 2353 assert(CT && "Unexpected type"); 2354 Kind = EK_ComplexElement; 2355 Type = CT->getElementType(); 2356 } 2357} 2358 2359InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 2360 CXXBaseSpecifier *Base, 2361 bool IsInheritedVirtualBase) 2362{ 2363 InitializedEntity Result; 2364 Result.Kind = EK_Base; 2365 Result.Base = reinterpret_cast<uintptr_t>(Base); 2366 if (IsInheritedVirtualBase) 2367 Result.Base |= 0x01; 2368 2369 Result.Type = Base->getType(); 2370 return Result; 2371} 2372 2373DeclarationName InitializedEntity::getName() const { 2374 switch (getKind()) { 2375 case EK_Parameter: { 2376 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2377 return (D ? D->getDeclName() : DeclarationName()); 2378 } 2379 2380 case EK_Variable: 2381 case EK_Member: 2382 return VariableOrMember->getDeclName(); 2383 2384 case EK_LambdaCapture: 2385 return Capture.Var->getDeclName(); 2386 2387 case EK_Result: 2388 case EK_Exception: 2389 case EK_New: 2390 case EK_Temporary: 2391 case EK_Base: 2392 case EK_Delegating: 2393 case EK_ArrayElement: 2394 case EK_VectorElement: 2395 case EK_ComplexElement: 2396 case EK_BlockElement: 2397 case EK_CompoundLiteralInit: 2398 return DeclarationName(); 2399 } 2400 2401 llvm_unreachable("Invalid EntityKind!"); 2402} 2403 2404DeclaratorDecl *InitializedEntity::getDecl() const { 2405 switch (getKind()) { 2406 case EK_Variable: 2407 case EK_Member: 2408 return VariableOrMember; 2409 2410 case EK_Parameter: 2411 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2412 2413 case EK_Result: 2414 case EK_Exception: 2415 case EK_New: 2416 case EK_Temporary: 2417 case EK_Base: 2418 case EK_Delegating: 2419 case EK_ArrayElement: 2420 case EK_VectorElement: 2421 case EK_ComplexElement: 2422 case EK_BlockElement: 2423 case EK_LambdaCapture: 2424 case EK_CompoundLiteralInit: 2425 return 0; 2426 } 2427 2428 llvm_unreachable("Invalid EntityKind!"); 2429} 2430 2431bool InitializedEntity::allowsNRVO() const { 2432 switch (getKind()) { 2433 case EK_Result: 2434 case EK_Exception: 2435 return LocAndNRVO.NRVO; 2436 2437 case EK_Variable: 2438 case EK_Parameter: 2439 case EK_Member: 2440 case EK_New: 2441 case EK_Temporary: 2442 case EK_CompoundLiteralInit: 2443 case EK_Base: 2444 case EK_Delegating: 2445 case EK_ArrayElement: 2446 case EK_VectorElement: 2447 case EK_ComplexElement: 2448 case EK_BlockElement: 2449 case EK_LambdaCapture: 2450 break; 2451 } 2452 2453 return false; 2454} 2455 2456//===----------------------------------------------------------------------===// 2457// Initialization sequence 2458//===----------------------------------------------------------------------===// 2459 2460void InitializationSequence::Step::Destroy() { 2461 switch (Kind) { 2462 case SK_ResolveAddressOfOverloadedFunction: 2463 case SK_CastDerivedToBaseRValue: 2464 case SK_CastDerivedToBaseXValue: 2465 case SK_CastDerivedToBaseLValue: 2466 case SK_BindReference: 2467 case SK_BindReferenceToTemporary: 2468 case SK_ExtraneousCopyToTemporary: 2469 case SK_UserConversion: 2470 case SK_QualificationConversionRValue: 2471 case SK_QualificationConversionXValue: 2472 case SK_QualificationConversionLValue: 2473 case SK_LValueToRValue: 2474 case SK_ListInitialization: 2475 case SK_ListConstructorCall: 2476 case SK_UnwrapInitList: 2477 case SK_RewrapInitList: 2478 case SK_ConstructorInitialization: 2479 case SK_ZeroInitialization: 2480 case SK_CAssignment: 2481 case SK_StringInit: 2482 case SK_ObjCObjectConversion: 2483 case SK_ArrayInit: 2484 case SK_ParenthesizedArrayInit: 2485 case SK_PassByIndirectCopyRestore: 2486 case SK_PassByIndirectRestore: 2487 case SK_ProduceObjCObject: 2488 case SK_StdInitializerList: 2489 case SK_OCLSamplerInit: 2490 case SK_OCLZeroEvent: 2491 break; 2492 2493 case SK_ConversionSequence: 2494 delete ICS; 2495 } 2496} 2497 2498bool InitializationSequence::isDirectReferenceBinding() const { 2499 return !Steps.empty() && Steps.back().Kind == SK_BindReference; 2500} 2501 2502bool InitializationSequence::isAmbiguous() const { 2503 if (!Failed()) 2504 return false; 2505 2506 switch (getFailureKind()) { 2507 case FK_TooManyInitsForReference: 2508 case FK_ArrayNeedsInitList: 2509 case FK_ArrayNeedsInitListOrStringLiteral: 2510 case FK_AddressOfOverloadFailed: // FIXME: Could do better 2511 case FK_NonConstLValueReferenceBindingToTemporary: 2512 case FK_NonConstLValueReferenceBindingToUnrelated: 2513 case FK_RValueReferenceBindingToLValue: 2514 case FK_ReferenceInitDropsQualifiers: 2515 case FK_ReferenceInitFailed: 2516 case FK_ConversionFailed: 2517 case FK_ConversionFromPropertyFailed: 2518 case FK_TooManyInitsForScalar: 2519 case FK_ReferenceBindingToInitList: 2520 case FK_InitListBadDestinationType: 2521 case FK_DefaultInitOfConst: 2522 case FK_Incomplete: 2523 case FK_ArrayTypeMismatch: 2524 case FK_NonConstantArrayInit: 2525 case FK_ListInitializationFailed: 2526 case FK_VariableLengthArrayHasInitializer: 2527 case FK_PlaceholderType: 2528 case FK_InitListElementCopyFailure: 2529 case FK_ExplicitConstructor: 2530 return false; 2531 2532 case FK_ReferenceInitOverloadFailed: 2533 case FK_UserConversionOverloadFailed: 2534 case FK_ConstructorOverloadFailed: 2535 case FK_ListConstructorOverloadFailed: 2536 return FailedOverloadResult == OR_Ambiguous; 2537 } 2538 2539 llvm_unreachable("Invalid EntityKind!"); 2540} 2541 2542bool InitializationSequence::isConstructorInitialization() const { 2543 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 2544} 2545 2546void 2547InitializationSequence 2548::AddAddressOverloadResolutionStep(FunctionDecl *Function, 2549 DeclAccessPair Found, 2550 bool HadMultipleCandidates) { 2551 Step S; 2552 S.Kind = SK_ResolveAddressOfOverloadedFunction; 2553 S.Type = Function->getType(); 2554 S.Function.HadMultipleCandidates = HadMultipleCandidates; 2555 S.Function.Function = Function; 2556 S.Function.FoundDecl = Found; 2557 Steps.push_back(S); 2558} 2559 2560void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 2561 ExprValueKind VK) { 2562 Step S; 2563 switch (VK) { 2564 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 2565 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 2566 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 2567 } 2568 S.Type = BaseType; 2569 Steps.push_back(S); 2570} 2571 2572void InitializationSequence::AddReferenceBindingStep(QualType T, 2573 bool BindingTemporary) { 2574 Step S; 2575 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2576 S.Type = T; 2577 Steps.push_back(S); 2578} 2579 2580void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 2581 Step S; 2582 S.Kind = SK_ExtraneousCopyToTemporary; 2583 S.Type = T; 2584 Steps.push_back(S); 2585} 2586 2587void 2588InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2589 DeclAccessPair FoundDecl, 2590 QualType T, 2591 bool HadMultipleCandidates) { 2592 Step S; 2593 S.Kind = SK_UserConversion; 2594 S.Type = T; 2595 S.Function.HadMultipleCandidates = HadMultipleCandidates; 2596 S.Function.Function = Function; 2597 S.Function.FoundDecl = FoundDecl; 2598 Steps.push_back(S); 2599} 2600 2601void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2602 ExprValueKind VK) { 2603 Step S; 2604 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 2605 switch (VK) { 2606 case VK_RValue: 2607 S.Kind = SK_QualificationConversionRValue; 2608 break; 2609 case VK_XValue: 2610 S.Kind = SK_QualificationConversionXValue; 2611 break; 2612 case VK_LValue: 2613 S.Kind = SK_QualificationConversionLValue; 2614 break; 2615 } 2616 S.Type = Ty; 2617 Steps.push_back(S); 2618} 2619 2620void InitializationSequence::AddLValueToRValueStep(QualType Ty) { 2621 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers"); 2622 2623 Step S; 2624 S.Kind = SK_LValueToRValue; 2625 S.Type = Ty; 2626 Steps.push_back(S); 2627} 2628 2629void InitializationSequence::AddConversionSequenceStep( 2630 const ImplicitConversionSequence &ICS, 2631 QualType T) { 2632 Step S; 2633 S.Kind = SK_ConversionSequence; 2634 S.Type = T; 2635 S.ICS = new ImplicitConversionSequence(ICS); 2636 Steps.push_back(S); 2637} 2638 2639void InitializationSequence::AddListInitializationStep(QualType T) { 2640 Step S; 2641 S.Kind = SK_ListInitialization; 2642 S.Type = T; 2643 Steps.push_back(S); 2644} 2645 2646void 2647InitializationSequence 2648::AddConstructorInitializationStep(CXXConstructorDecl *Constructor, 2649 AccessSpecifier Access, 2650 QualType T, 2651 bool HadMultipleCandidates, 2652 bool FromInitList, bool AsInitList) { 2653 Step S; 2654 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall 2655 : SK_ConstructorInitialization; 2656 S.Type = T; 2657 S.Function.HadMultipleCandidates = HadMultipleCandidates; 2658 S.Function.Function = Constructor; 2659 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access); 2660 Steps.push_back(S); 2661} 2662 2663void InitializationSequence::AddZeroInitializationStep(QualType T) { 2664 Step S; 2665 S.Kind = SK_ZeroInitialization; 2666 S.Type = T; 2667 Steps.push_back(S); 2668} 2669 2670void InitializationSequence::AddCAssignmentStep(QualType T) { 2671 Step S; 2672 S.Kind = SK_CAssignment; 2673 S.Type = T; 2674 Steps.push_back(S); 2675} 2676 2677void InitializationSequence::AddStringInitStep(QualType T) { 2678 Step S; 2679 S.Kind = SK_StringInit; 2680 S.Type = T; 2681 Steps.push_back(S); 2682} 2683 2684void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 2685 Step S; 2686 S.Kind = SK_ObjCObjectConversion; 2687 S.Type = T; 2688 Steps.push_back(S); 2689} 2690 2691void InitializationSequence::AddArrayInitStep(QualType T) { 2692 Step S; 2693 S.Kind = SK_ArrayInit; 2694 S.Type = T; 2695 Steps.push_back(S); 2696} 2697 2698void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { 2699 Step S; 2700 S.Kind = SK_ParenthesizedArrayInit; 2701 S.Type = T; 2702 Steps.push_back(S); 2703} 2704 2705void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 2706 bool shouldCopy) { 2707 Step s; 2708 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 2709 : SK_PassByIndirectRestore); 2710 s.Type = type; 2711 Steps.push_back(s); 2712} 2713 2714void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 2715 Step S; 2716 S.Kind = SK_ProduceObjCObject; 2717 S.Type = T; 2718 Steps.push_back(S); 2719} 2720 2721void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { 2722 Step S; 2723 S.Kind = SK_StdInitializerList; 2724 S.Type = T; 2725 Steps.push_back(S); 2726} 2727 2728void InitializationSequence::AddOCLSamplerInitStep(QualType T) { 2729 Step S; 2730 S.Kind = SK_OCLSamplerInit; 2731 S.Type = T; 2732 Steps.push_back(S); 2733} 2734 2735void InitializationSequence::AddOCLZeroEventStep(QualType T) { 2736 Step S; 2737 S.Kind = SK_OCLZeroEvent; 2738 S.Type = T; 2739 Steps.push_back(S); 2740} 2741 2742void InitializationSequence::RewrapReferenceInitList(QualType T, 2743 InitListExpr *Syntactic) { 2744 assert(Syntactic->getNumInits() == 1 && 2745 "Can only rewrap trivial init lists."); 2746 Step S; 2747 S.Kind = SK_UnwrapInitList; 2748 S.Type = Syntactic->getInit(0)->getType(); 2749 Steps.insert(Steps.begin(), S); 2750 2751 S.Kind = SK_RewrapInitList; 2752 S.Type = T; 2753 S.WrappingSyntacticList = Syntactic; 2754 Steps.push_back(S); 2755} 2756 2757void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2758 OverloadingResult Result) { 2759 setSequenceKind(FailedSequence); 2760 this->Failure = Failure; 2761 this->FailedOverloadResult = Result; 2762} 2763 2764//===----------------------------------------------------------------------===// 2765// Attempt initialization 2766//===----------------------------------------------------------------------===// 2767 2768static void MaybeProduceObjCObject(Sema &S, 2769 InitializationSequence &Sequence, 2770 const InitializedEntity &Entity) { 2771 if (!S.getLangOpts().ObjCAutoRefCount) return; 2772 2773 /// When initializing a parameter, produce the value if it's marked 2774 /// __attribute__((ns_consumed)). 2775 if (Entity.getKind() == InitializedEntity::EK_Parameter) { 2776 if (!Entity.isParameterConsumed()) 2777 return; 2778 2779 assert(Entity.getType()->isObjCRetainableType() && 2780 "consuming an object of unretainable type?"); 2781 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2782 2783 /// When initializing a return value, if the return type is a 2784 /// retainable type, then returns need to immediately retain the 2785 /// object. If an autorelease is required, it will be done at the 2786 /// last instant. 2787 } else if (Entity.getKind() == InitializedEntity::EK_Result) { 2788 if (!Entity.getType()->isObjCRetainableType()) 2789 return; 2790 2791 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2792 } 2793} 2794 2795/// \brief When initializing from init list via constructor, handle 2796/// initialization of an object of type std::initializer_list<T>. 2797/// 2798/// \return true if we have handled initialization of an object of type 2799/// std::initializer_list<T>, false otherwise. 2800static bool TryInitializerListConstruction(Sema &S, 2801 InitListExpr *List, 2802 QualType DestType, 2803 InitializationSequence &Sequence) { 2804 QualType E; 2805 if (!S.isStdInitializerList(DestType, &E)) 2806 return false; 2807 2808 // Check that each individual element can be copy-constructed. But since we 2809 // have no place to store further information, we'll recalculate everything 2810 // later. 2811 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary( 2812 S.Context.getConstantArrayType(E, 2813 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 2814 List->getNumInits()), 2815 ArrayType::Normal, 0)); 2816 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context, 2817 0, HiddenArray); 2818 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) { 2819 Element.setElementIndex(i); 2820 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) { 2821 Sequence.SetFailed( 2822 InitializationSequence::FK_InitListElementCopyFailure); 2823 return true; 2824 } 2825 } 2826 Sequence.AddStdInitializerListConstructionStep(DestType); 2827 return true; 2828} 2829 2830static OverloadingResult 2831ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, 2832 MultiExprArg Args, 2833 OverloadCandidateSet &CandidateSet, 2834 ArrayRef<NamedDecl *> Ctors, 2835 OverloadCandidateSet::iterator &Best, 2836 bool CopyInitializing, bool AllowExplicit, 2837 bool OnlyListConstructors, bool InitListSyntax) { 2838 CandidateSet.clear(); 2839 2840 for (ArrayRef<NamedDecl *>::iterator 2841 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) { 2842 NamedDecl *D = *Con; 2843 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2844 bool SuppressUserConversions = false; 2845 2846 // Find the constructor (which may be a template). 2847 CXXConstructorDecl *Constructor = 0; 2848 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2849 if (ConstructorTmpl) 2850 Constructor = cast<CXXConstructorDecl>( 2851 ConstructorTmpl->getTemplatedDecl()); 2852 else { 2853 Constructor = cast<CXXConstructorDecl>(D); 2854 2855 // If we're performing copy initialization using a copy constructor, we 2856 // suppress user-defined conversions on the arguments. We do the same for 2857 // move constructors. 2858 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) && 2859 Constructor->isCopyOrMoveConstructor()) 2860 SuppressUserConversions = true; 2861 } 2862 2863 if (!Constructor->isInvalidDecl() && 2864 (AllowExplicit || !Constructor->isExplicit()) && 2865 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) { 2866 if (ConstructorTmpl) 2867 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2868 /*ExplicitArgs*/ 0, Args, 2869 CandidateSet, SuppressUserConversions); 2870 else { 2871 // C++ [over.match.copy]p1: 2872 // - When initializing a temporary to be bound to the first parameter 2873 // of a constructor that takes a reference to possibly cv-qualified 2874 // T as its first argument, called with a single argument in the 2875 // context of direct-initialization, explicit conversion functions 2876 // are also considered. 2877 bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 2878 Args.size() == 1 && 2879 Constructor->isCopyOrMoveConstructor(); 2880 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet, 2881 SuppressUserConversions, 2882 /*PartialOverloading=*/false, 2883 /*AllowExplicit=*/AllowExplicitConv); 2884 } 2885 } 2886 } 2887 2888 // Perform overload resolution and return the result. 2889 return CandidateSet.BestViableFunction(S, DeclLoc, Best); 2890} 2891 2892/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2893/// enumerates the constructors of the initialized entity and performs overload 2894/// resolution to select the best. 2895/// If InitListSyntax is true, this is list-initialization of a non-aggregate 2896/// class type. 2897static void TryConstructorInitialization(Sema &S, 2898 const InitializedEntity &Entity, 2899 const InitializationKind &Kind, 2900 MultiExprArg Args, QualType DestType, 2901 InitializationSequence &Sequence, 2902 bool InitListSyntax = false) { 2903 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 2904 "InitListSyntax must come with a single initializer list argument."); 2905 2906 // The type we're constructing needs to be complete. 2907 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 2908 Sequence.setIncompleteTypeFailure(DestType); 2909 return; 2910 } 2911 2912 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2913 assert(DestRecordType && "Constructor initialization requires record type"); 2914 CXXRecordDecl *DestRecordDecl 2915 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2916 2917 // Build the candidate set directly in the initialization sequence 2918 // structure, so that it will persist if we fail. 2919 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2920 2921 // Determine whether we are allowed to call explicit constructors or 2922 // explicit conversion operators. 2923 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax; 2924 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; 2925 2926 // - Otherwise, if T is a class type, constructors are considered. The 2927 // applicable constructors are enumerated, and the best one is chosen 2928 // through overload resolution. 2929 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl); 2930 // The container holding the constructors can under certain conditions 2931 // be changed while iterating (e.g. because of deserialization). 2932 // To be safe we copy the lookup results to a new container. 2933 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end()); 2934 2935 OverloadingResult Result = OR_No_Viable_Function; 2936 OverloadCandidateSet::iterator Best; 2937 bool AsInitializerList = false; 2938 2939 // C++11 [over.match.list]p1: 2940 // When objects of non-aggregate type T are list-initialized, overload 2941 // resolution selects the constructor in two phases: 2942 // - Initially, the candidate functions are the initializer-list 2943 // constructors of the class T and the argument list consists of the 2944 // initializer list as a single argument. 2945 if (InitListSyntax) { 2946 InitListExpr *ILE = cast<InitListExpr>(Args[0]); 2947 AsInitializerList = true; 2948 2949 // If the initializer list has no elements and T has a default constructor, 2950 // the first phase is omitted. 2951 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor()) 2952 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 2953 CandidateSet, Ctors, Best, 2954 CopyInitialization, AllowExplicit, 2955 /*OnlyListConstructor=*/true, 2956 InitListSyntax); 2957 2958 // Time to unwrap the init list. 2959 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits()); 2960 } 2961 2962 // C++11 [over.match.list]p1: 2963 // - If no viable initializer-list constructor is found, overload resolution 2964 // is performed again, where the candidate functions are all the 2965 // constructors of the class T and the argument list consists of the 2966 // elements of the initializer list. 2967 if (Result == OR_No_Viable_Function) { 2968 AsInitializerList = false; 2969 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 2970 CandidateSet, Ctors, Best, 2971 CopyInitialization, AllowExplicit, 2972 /*OnlyListConstructors=*/false, 2973 InitListSyntax); 2974 } 2975 if (Result) { 2976 Sequence.SetOverloadFailure(InitListSyntax ? 2977 InitializationSequence::FK_ListConstructorOverloadFailed : 2978 InitializationSequence::FK_ConstructorOverloadFailed, 2979 Result); 2980 return; 2981 } 2982 2983 // C++11 [dcl.init]p6: 2984 // If a program calls for the default initialization of an object 2985 // of a const-qualified type T, T shall be a class type with a 2986 // user-provided default constructor. 2987 if (Kind.getKind() == InitializationKind::IK_Default && 2988 Entity.getType().isConstQualified() && 2989 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) { 2990 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2991 return; 2992 } 2993 2994 // C++11 [over.match.list]p1: 2995 // In copy-list-initialization, if an explicit constructor is chosen, the 2996 // initializer is ill-formed. 2997 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 2998 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { 2999 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); 3000 return; 3001 } 3002 3003 // Add the constructor initialization step. Any cv-qualification conversion is 3004 // subsumed by the initialization. 3005 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3006 Sequence.AddConstructorInitializationStep(CtorDecl, 3007 Best->FoundDecl.getAccess(), 3008 DestType, HadMultipleCandidates, 3009 InitListSyntax, AsInitializerList); 3010} 3011 3012static bool 3013ResolveOverloadedFunctionForReferenceBinding(Sema &S, 3014 Expr *Initializer, 3015 QualType &SourceType, 3016 QualType &UnqualifiedSourceType, 3017 QualType UnqualifiedTargetType, 3018 InitializationSequence &Sequence) { 3019 if (S.Context.getCanonicalType(UnqualifiedSourceType) == 3020 S.Context.OverloadTy) { 3021 DeclAccessPair Found; 3022 bool HadMultipleCandidates = false; 3023 if (FunctionDecl *Fn 3024 = S.ResolveAddressOfOverloadedFunction(Initializer, 3025 UnqualifiedTargetType, 3026 false, Found, 3027 &HadMultipleCandidates)) { 3028 Sequence.AddAddressOverloadResolutionStep(Fn, Found, 3029 HadMultipleCandidates); 3030 SourceType = Fn->getType(); 3031 UnqualifiedSourceType = SourceType.getUnqualifiedType(); 3032 } else if (!UnqualifiedTargetType->isRecordType()) { 3033 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3034 return true; 3035 } 3036 } 3037 return false; 3038} 3039 3040static void TryReferenceInitializationCore(Sema &S, 3041 const InitializedEntity &Entity, 3042 const InitializationKind &Kind, 3043 Expr *Initializer, 3044 QualType cv1T1, QualType T1, 3045 Qualifiers T1Quals, 3046 QualType cv2T2, QualType T2, 3047 Qualifiers T2Quals, 3048 InitializationSequence &Sequence); 3049 3050static void TryValueInitialization(Sema &S, 3051 const InitializedEntity &Entity, 3052 const InitializationKind &Kind, 3053 InitializationSequence &Sequence, 3054 InitListExpr *InitList = 0); 3055 3056static void TryListInitialization(Sema &S, 3057 const InitializedEntity &Entity, 3058 const InitializationKind &Kind, 3059 InitListExpr *InitList, 3060 InitializationSequence &Sequence); 3061 3062/// \brief Attempt list initialization of a reference. 3063static void TryReferenceListInitialization(Sema &S, 3064 const InitializedEntity &Entity, 3065 const InitializationKind &Kind, 3066 InitListExpr *InitList, 3067 InitializationSequence &Sequence) 3068{ 3069 // First, catch C++03 where this isn't possible. 3070 if (!S.getLangOpts().CPlusPlus11) { 3071 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 3072 return; 3073 } 3074 3075 QualType DestType = Entity.getType(); 3076 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3077 Qualifiers T1Quals; 3078 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 3079 3080 // Reference initialization via an initializer list works thus: 3081 // If the initializer list consists of a single element that is 3082 // reference-related to the referenced type, bind directly to that element 3083 // (possibly creating temporaries). 3084 // Otherwise, initialize a temporary with the initializer list and 3085 // bind to that. 3086 if (InitList->getNumInits() == 1) { 3087 Expr *Initializer = InitList->getInit(0); 3088 QualType cv2T2 = Initializer->getType(); 3089 Qualifiers T2Quals; 3090 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 3091 3092 // If this fails, creating a temporary wouldn't work either. 3093 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 3094 T1, Sequence)) 3095 return; 3096 3097 SourceLocation DeclLoc = Initializer->getLocStart(); 3098 bool dummy1, dummy2, dummy3; 3099 Sema::ReferenceCompareResult RefRelationship 3100 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1, 3101 dummy2, dummy3); 3102 if (RefRelationship >= Sema::Ref_Related) { 3103 // Try to bind the reference here. 3104 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 3105 T1Quals, cv2T2, T2, T2Quals, Sequence); 3106 if (Sequence) 3107 Sequence.RewrapReferenceInitList(cv1T1, InitList); 3108 return; 3109 } 3110 3111 // Update the initializer if we've resolved an overloaded function. 3112 if (Sequence.step_begin() != Sequence.step_end()) 3113 Sequence.RewrapReferenceInitList(cv1T1, InitList); 3114 } 3115 3116 // Not reference-related. Create a temporary and bind to that. 3117 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 3118 3119 TryListInitialization(S, TempEntity, Kind, InitList, Sequence); 3120 if (Sequence) { 3121 if (DestType->isRValueReferenceType() || 3122 (T1Quals.hasConst() && !T1Quals.hasVolatile())) 3123 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 3124 else 3125 Sequence.SetFailed( 3126 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 3127 } 3128} 3129 3130/// \brief Attempt list initialization (C++0x [dcl.init.list]) 3131static void TryListInitialization(Sema &S, 3132 const InitializedEntity &Entity, 3133 const InitializationKind &Kind, 3134 InitListExpr *InitList, 3135 InitializationSequence &Sequence) { 3136 QualType DestType = Entity.getType(); 3137 3138 // C++ doesn't allow scalar initialization with more than one argument. 3139 // But C99 complex numbers are scalars and it makes sense there. 3140 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && 3141 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 3142 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 3143 return; 3144 } 3145 if (DestType->isReferenceType()) { 3146 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence); 3147 return; 3148 } 3149 if (DestType->isRecordType()) { 3150 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) { 3151 Sequence.setIncompleteTypeFailure(DestType); 3152 return; 3153 } 3154 3155 // C++11 [dcl.init.list]p3: 3156 // - If T is an aggregate, aggregate initialization is performed. 3157 if (!DestType->isAggregateType()) { 3158 if (S.getLangOpts().CPlusPlus11) { 3159 // - Otherwise, if the initializer list has no elements and T is a 3160 // class type with a default constructor, the object is 3161 // value-initialized. 3162 if (InitList->getNumInits() == 0) { 3163 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); 3164 if (RD->hasDefaultConstructor()) { 3165 TryValueInitialization(S, Entity, Kind, Sequence, InitList); 3166 return; 3167 } 3168 } 3169 3170 // - Otherwise, if T is a specialization of std::initializer_list<E>, 3171 // an initializer_list object constructed [...] 3172 if (TryInitializerListConstruction(S, InitList, DestType, Sequence)) 3173 return; 3174 3175 // - Otherwise, if T is a class type, constructors are considered. 3176 Expr *InitListAsExpr = InitList; 3177 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 3178 Sequence, /*InitListSyntax*/true); 3179 } else 3180 Sequence.SetFailed( 3181 InitializationSequence::FK_InitListBadDestinationType); 3182 return; 3183 } 3184 } 3185 3186 InitListChecker CheckInitList(S, Entity, InitList, 3187 DestType, /*VerifyOnly=*/true, 3188 Kind.getKind() != InitializationKind::IK_DirectList || 3189 !S.getLangOpts().CPlusPlus11); 3190 if (CheckInitList.HadError()) { 3191 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 3192 return; 3193 } 3194 3195 // Add the list initialization step with the built init list. 3196 Sequence.AddListInitializationStep(DestType); 3197} 3198 3199/// \brief Try a reference initialization that involves calling a conversion 3200/// function. 3201static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 3202 const InitializedEntity &Entity, 3203 const InitializationKind &Kind, 3204 Expr *Initializer, 3205 bool AllowRValues, 3206 InitializationSequence &Sequence) { 3207 QualType DestType = Entity.getType(); 3208 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3209 QualType T1 = cv1T1.getUnqualifiedType(); 3210 QualType cv2T2 = Initializer->getType(); 3211 QualType T2 = cv2T2.getUnqualifiedType(); 3212 3213 bool DerivedToBase; 3214 bool ObjCConversion; 3215 bool ObjCLifetimeConversion; 3216 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 3217 T1, T2, DerivedToBase, 3218 ObjCConversion, 3219 ObjCLifetimeConversion) && 3220 "Must have incompatible references when binding via conversion"); 3221 (void)DerivedToBase; 3222 (void)ObjCConversion; 3223 (void)ObjCLifetimeConversion; 3224 3225 // Build the candidate set directly in the initialization sequence 3226 // structure, so that it will persist if we fail. 3227 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3228 CandidateSet.clear(); 3229 3230 // Determine whether we are allowed to call explicit constructors or 3231 // explicit conversion operators. 3232 bool AllowExplicit = Kind.AllowExplicit(); 3233 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions(); 3234 3235 const RecordType *T1RecordType = 0; 3236 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 3237 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) { 3238 // The type we're converting to is a class type. Enumerate its constructors 3239 // to see if there is a suitable conversion. 3240 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 3241 3242 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl); 3243 // The container holding the constructors can under certain conditions 3244 // be changed while iterating (e.g. because of deserialization). 3245 // To be safe we copy the lookup results to a new container. 3246 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end()); 3247 for (SmallVector<NamedDecl*, 16>::iterator 3248 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) { 3249 NamedDecl *D = *CI; 3250 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3251 3252 // Find the constructor (which may be a template). 3253 CXXConstructorDecl *Constructor = 0; 3254 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 3255 if (ConstructorTmpl) 3256 Constructor = cast<CXXConstructorDecl>( 3257 ConstructorTmpl->getTemplatedDecl()); 3258 else 3259 Constructor = cast<CXXConstructorDecl>(D); 3260 3261 if (!Constructor->isInvalidDecl() && 3262 Constructor->isConvertingConstructor(AllowExplicit)) { 3263 if (ConstructorTmpl) 3264 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3265 /*ExplicitArgs*/ 0, 3266 Initializer, CandidateSet, 3267 /*SuppressUserConversions=*/true); 3268 else 3269 S.AddOverloadCandidate(Constructor, FoundDecl, 3270 Initializer, CandidateSet, 3271 /*SuppressUserConversions=*/true); 3272 } 3273 } 3274 } 3275 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 3276 return OR_No_Viable_Function; 3277 3278 const RecordType *T2RecordType = 0; 3279 if ((T2RecordType = T2->getAs<RecordType>()) && 3280 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) { 3281 // The type we're converting from is a class type, enumerate its conversion 3282 // functions. 3283 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 3284 3285 std::pair<CXXRecordDecl::conversion_iterator, 3286 CXXRecordDecl::conversion_iterator> 3287 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 3288 for (CXXRecordDecl::conversion_iterator 3289 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3290 NamedDecl *D = *I; 3291 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3292 if (isa<UsingShadowDecl>(D)) 3293 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3294 3295 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3296 CXXConversionDecl *Conv; 3297 if (ConvTemplate) 3298 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3299 else 3300 Conv = cast<CXXConversionDecl>(D); 3301 3302 // If the conversion function doesn't return a reference type, 3303 // it can't be considered for this conversion unless we're allowed to 3304 // consider rvalues. 3305 // FIXME: Do we need to make sure that we only consider conversion 3306 // candidates with reference-compatible results? That might be needed to 3307 // break recursion. 3308 if ((AllowExplicitConvs || !Conv->isExplicit()) && 3309 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 3310 if (ConvTemplate) 3311 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 3312 ActingDC, Initializer, 3313 DestType, CandidateSet); 3314 else 3315 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 3316 Initializer, DestType, CandidateSet); 3317 } 3318 } 3319 } 3320 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 3321 return OR_No_Viable_Function; 3322 3323 SourceLocation DeclLoc = Initializer->getLocStart(); 3324 3325 // Perform overload resolution. If it fails, return the failed result. 3326 OverloadCandidateSet::iterator Best; 3327 if (OverloadingResult Result 3328 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) 3329 return Result; 3330 3331 FunctionDecl *Function = Best->Function; 3332 // This is the overload that will be used for this initialization step if we 3333 // use this initialization. Mark it as referenced. 3334 Function->setReferenced(); 3335 3336 // Compute the returned type of the conversion. 3337 if (isa<CXXConversionDecl>(Function)) 3338 T2 = Function->getResultType(); 3339 else 3340 T2 = cv1T1; 3341 3342 // Add the user-defined conversion step. 3343 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3344 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 3345 T2.getNonLValueExprType(S.Context), 3346 HadMultipleCandidates); 3347 3348 // Determine whether we need to perform derived-to-base or 3349 // cv-qualification adjustments. 3350 ExprValueKind VK = VK_RValue; 3351 if (T2->isLValueReferenceType()) 3352 VK = VK_LValue; 3353 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>()) 3354 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 3355 3356 bool NewDerivedToBase = false; 3357 bool NewObjCConversion = false; 3358 bool NewObjCLifetimeConversion = false; 3359 Sema::ReferenceCompareResult NewRefRelationship 3360 = S.CompareReferenceRelationship(DeclLoc, T1, 3361 T2.getNonLValueExprType(S.Context), 3362 NewDerivedToBase, NewObjCConversion, 3363 NewObjCLifetimeConversion); 3364 if (NewRefRelationship == Sema::Ref_Incompatible) { 3365 // If the type we've converted to is not reference-related to the 3366 // type we're looking for, then there is another conversion step 3367 // we need to perform to produce a temporary of the right type 3368 // that we'll be binding to. 3369 ImplicitConversionSequence ICS; 3370 ICS.setStandard(); 3371 ICS.Standard = Best->FinalConversion; 3372 T2 = ICS.Standard.getToType(2); 3373 Sequence.AddConversionSequenceStep(ICS, T2); 3374 } else if (NewDerivedToBase) 3375 Sequence.AddDerivedToBaseCastStep( 3376 S.Context.getQualifiedType(T1, 3377 T2.getNonReferenceType().getQualifiers()), 3378 VK); 3379 else if (NewObjCConversion) 3380 Sequence.AddObjCObjectConversionStep( 3381 S.Context.getQualifiedType(T1, 3382 T2.getNonReferenceType().getQualifiers())); 3383 3384 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 3385 Sequence.AddQualificationConversionStep(cv1T1, VK); 3386 3387 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 3388 return OR_Success; 3389} 3390 3391static void CheckCXX98CompatAccessibleCopy(Sema &S, 3392 const InitializedEntity &Entity, 3393 Expr *CurInitExpr); 3394 3395/// \brief Attempt reference initialization (C++0x [dcl.init.ref]) 3396static void TryReferenceInitialization(Sema &S, 3397 const InitializedEntity &Entity, 3398 const InitializationKind &Kind, 3399 Expr *Initializer, 3400 InitializationSequence &Sequence) { 3401 QualType DestType = Entity.getType(); 3402 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3403 Qualifiers T1Quals; 3404 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 3405 QualType cv2T2 = Initializer->getType(); 3406 Qualifiers T2Quals; 3407 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 3408 3409 // If the initializer is the address of an overloaded function, try 3410 // to resolve the overloaded function. If all goes well, T2 is the 3411 // type of the resulting function. 3412 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 3413 T1, Sequence)) 3414 return; 3415 3416 // Delegate everything else to a subfunction. 3417 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 3418 T1Quals, cv2T2, T2, T2Quals, Sequence); 3419} 3420 3421/// Converts the target of reference initialization so that it has the 3422/// appropriate qualifiers and value kind. 3423/// 3424/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'. 3425/// \code 3426/// int x; 3427/// const int &r = x; 3428/// \endcode 3429/// 3430/// In this case the reference is binding to a bitfield lvalue, which isn't 3431/// valid. Perform a load to create a lifetime-extended temporary instead. 3432/// \code 3433/// const int &r = someStruct.bitfield; 3434/// \endcode 3435static ExprValueKind 3436convertQualifiersAndValueKindIfNecessary(Sema &S, 3437 InitializationSequence &Sequence, 3438 Expr *Initializer, 3439 QualType cv1T1, 3440 Qualifiers T1Quals, 3441 Qualifiers T2Quals, 3442 bool IsLValueRef) { 3443 bool IsNonAddressableType = Initializer->refersToBitField() || 3444 Initializer->refersToVectorElement(); 3445 3446 if (IsNonAddressableType) { 3447 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an 3448 // lvalue reference to a non-volatile const type, or the reference shall be 3449 // an rvalue reference. 3450 // 3451 // If not, we can't make a temporary and bind to that. Give up and allow the 3452 // error to be diagnosed later. 3453 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) { 3454 assert(Initializer->isGLValue()); 3455 return Initializer->getValueKind(); 3456 } 3457 3458 // Force a load so we can materialize a temporary. 3459 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType()); 3460 return VK_RValue; 3461 } 3462 3463 if (T1Quals != T2Quals) { 3464 Sequence.AddQualificationConversionStep(cv1T1, 3465 Initializer->getValueKind()); 3466 } 3467 3468 return Initializer->getValueKind(); 3469} 3470 3471 3472/// \brief Reference initialization without resolving overloaded functions. 3473static void TryReferenceInitializationCore(Sema &S, 3474 const InitializedEntity &Entity, 3475 const InitializationKind &Kind, 3476 Expr *Initializer, 3477 QualType cv1T1, QualType T1, 3478 Qualifiers T1Quals, 3479 QualType cv2T2, QualType T2, 3480 Qualifiers T2Quals, 3481 InitializationSequence &Sequence) { 3482 QualType DestType = Entity.getType(); 3483 SourceLocation DeclLoc = Initializer->getLocStart(); 3484 // Compute some basic properties of the types and the initializer. 3485 bool isLValueRef = DestType->isLValueReferenceType(); 3486 bool isRValueRef = !isLValueRef; 3487 bool DerivedToBase = false; 3488 bool ObjCConversion = false; 3489 bool ObjCLifetimeConversion = false; 3490 Expr::Classification InitCategory = Initializer->Classify(S.Context); 3491 Sema::ReferenceCompareResult RefRelationship 3492 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, 3493 ObjCConversion, ObjCLifetimeConversion); 3494 3495 // C++0x [dcl.init.ref]p5: 3496 // A reference to type "cv1 T1" is initialized by an expression of type 3497 // "cv2 T2" as follows: 3498 // 3499 // - If the reference is an lvalue reference and the initializer 3500 // expression 3501 // Note the analogous bullet points for rvlaue refs to functions. Because 3502 // there are no function rvalues in C++, rvalue refs to functions are treated 3503 // like lvalue refs. 3504 OverloadingResult ConvOvlResult = OR_Success; 3505 bool T1Function = T1->isFunctionType(); 3506 if (isLValueRef || T1Function) { 3507 if (InitCategory.isLValue() && 3508 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 3509 (Kind.isCStyleOrFunctionalCast() && 3510 RefRelationship == Sema::Ref_Related))) { 3511 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 3512 // reference-compatible with "cv2 T2," or 3513 // 3514 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a 3515 // bit-field when we're determining whether the reference initialization 3516 // can occur. However, we do pay attention to whether it is a bit-field 3517 // to decide whether we're actually binding to a temporary created from 3518 // the bit-field. 3519 if (DerivedToBase) 3520 Sequence.AddDerivedToBaseCastStep( 3521 S.Context.getQualifiedType(T1, T2Quals), 3522 VK_LValue); 3523 else if (ObjCConversion) 3524 Sequence.AddObjCObjectConversionStep( 3525 S.Context.getQualifiedType(T1, T2Quals)); 3526 3527 ExprValueKind ValueKind = 3528 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer, 3529 cv1T1, T1Quals, T2Quals, 3530 isLValueRef); 3531 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue); 3532 return; 3533 } 3534 3535 // - has a class type (i.e., T2 is a class type), where T1 is not 3536 // reference-related to T2, and can be implicitly converted to an 3537 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 3538 // with "cv3 T3" (this conversion is selected by enumerating the 3539 // applicable conversion functions (13.3.1.6) and choosing the best 3540 // one through overload resolution (13.3)), 3541 // If we have an rvalue ref to function type here, the rhs must be 3542 // an rvalue. 3543 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 3544 (isLValueRef || InitCategory.isRValue())) { 3545 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 3546 Initializer, 3547 /*AllowRValues=*/isRValueRef, 3548 Sequence); 3549 if (ConvOvlResult == OR_Success) 3550 return; 3551 if (ConvOvlResult != OR_No_Viable_Function) { 3552 Sequence.SetOverloadFailure( 3553 InitializationSequence::FK_ReferenceInitOverloadFailed, 3554 ConvOvlResult); 3555 } 3556 } 3557 } 3558 3559 // - Otherwise, the reference shall be an lvalue reference to a 3560 // non-volatile const type (i.e., cv1 shall be const), or the reference 3561 // shall be an rvalue reference. 3562 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) { 3563 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 3564 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3565 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 3566 Sequence.SetOverloadFailure( 3567 InitializationSequence::FK_ReferenceInitOverloadFailed, 3568 ConvOvlResult); 3569 else 3570 Sequence.SetFailed(InitCategory.isLValue() 3571 ? (RefRelationship == Sema::Ref_Related 3572 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 3573 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 3574 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 3575 3576 return; 3577 } 3578 3579 // - If the initializer expression 3580 // - is an xvalue, class prvalue, array prvalue, or function lvalue and 3581 // "cv1 T1" is reference-compatible with "cv2 T2" 3582 // Note: functions are handled below. 3583 if (!T1Function && 3584 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 3585 (Kind.isCStyleOrFunctionalCast() && 3586 RefRelationship == Sema::Ref_Related)) && 3587 (InitCategory.isXValue() || 3588 (InitCategory.isPRValue() && T2->isRecordType()) || 3589 (InitCategory.isPRValue() && T2->isArrayType()))) { 3590 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue; 3591 if (InitCategory.isPRValue() && T2->isRecordType()) { 3592 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 3593 // compiler the freedom to perform a copy here or bind to the 3594 // object, while C++0x requires that we bind directly to the 3595 // object. Hence, we always bind to the object without making an 3596 // extra copy. However, in C++03 requires that we check for the 3597 // presence of a suitable copy constructor: 3598 // 3599 // The constructor that would be used to make the copy shall 3600 // be callable whether or not the copy is actually done. 3601 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) 3602 Sequence.AddExtraneousCopyToTemporary(cv2T2); 3603 else if (S.getLangOpts().CPlusPlus11) 3604 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 3605 } 3606 3607 if (DerivedToBase) 3608 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals), 3609 ValueKind); 3610 else if (ObjCConversion) 3611 Sequence.AddObjCObjectConversionStep( 3612 S.Context.getQualifiedType(T1, T2Quals)); 3613 3614 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence, 3615 Initializer, cv1T1, 3616 T1Quals, T2Quals, 3617 isLValueRef); 3618 3619 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue); 3620 return; 3621 } 3622 3623 // - has a class type (i.e., T2 is a class type), where T1 is not 3624 // reference-related to T2, and can be implicitly converted to an 3625 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 3626 // where "cv1 T1" is reference-compatible with "cv3 T3", 3627 if (T2->isRecordType()) { 3628 if (RefRelationship == Sema::Ref_Incompatible) { 3629 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 3630 Kind, Initializer, 3631 /*AllowRValues=*/true, 3632 Sequence); 3633 if (ConvOvlResult) 3634 Sequence.SetOverloadFailure( 3635 InitializationSequence::FK_ReferenceInitOverloadFailed, 3636 ConvOvlResult); 3637 3638 return; 3639 } 3640 3641 if ((RefRelationship == Sema::Ref_Compatible || 3642 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) && 3643 isRValueRef && InitCategory.isLValue()) { 3644 Sequence.SetFailed( 3645 InitializationSequence::FK_RValueReferenceBindingToLValue); 3646 return; 3647 } 3648 3649 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 3650 return; 3651 } 3652 3653 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 3654 // from the initializer expression using the rules for a non-reference 3655 // copy initialization (8.5). The reference is then bound to the 3656 // temporary. [...] 3657 3658 // Determine whether we are allowed to call explicit constructors or 3659 // explicit conversion operators. 3660 bool AllowExplicit = Kind.AllowExplicit(); 3661 3662 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 3663 3664 ImplicitConversionSequence ICS 3665 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 3666 /*SuppressUserConversions*/ false, 3667 AllowExplicit, 3668 /*FIXME:InOverloadResolution=*/false, 3669 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 3670 /*AllowObjCWritebackConversion=*/false); 3671 3672 if (ICS.isBad()) { 3673 // FIXME: Use the conversion function set stored in ICS to turn 3674 // this into an overloading ambiguity diagnostic. However, we need 3675 // to keep that set as an OverloadCandidateSet rather than as some 3676 // other kind of set. 3677 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 3678 Sequence.SetOverloadFailure( 3679 InitializationSequence::FK_ReferenceInitOverloadFailed, 3680 ConvOvlResult); 3681 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 3682 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3683 else 3684 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 3685 return; 3686 } else { 3687 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 3688 } 3689 3690 // [...] If T1 is reference-related to T2, cv1 must be the 3691 // same cv-qualification as, or greater cv-qualification 3692 // than, cv2; otherwise, the program is ill-formed. 3693 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 3694 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 3695 if (RefRelationship == Sema::Ref_Related && 3696 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { 3697 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 3698 return; 3699 } 3700 3701 // [...] If T1 is reference-related to T2 and the reference is an rvalue 3702 // reference, the initializer expression shall not be an lvalue. 3703 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 3704 InitCategory.isLValue()) { 3705 Sequence.SetFailed( 3706 InitializationSequence::FK_RValueReferenceBindingToLValue); 3707 return; 3708 } 3709 3710 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 3711 return; 3712} 3713 3714/// \brief Attempt character array initialization from a string literal 3715/// (C++ [dcl.init.string], C99 6.7.8). 3716static void TryStringLiteralInitialization(Sema &S, 3717 const InitializedEntity &Entity, 3718 const InitializationKind &Kind, 3719 Expr *Initializer, 3720 InitializationSequence &Sequence) { 3721 Sequence.AddStringInitStep(Entity.getType()); 3722} 3723 3724/// \brief Attempt value initialization (C++ [dcl.init]p7). 3725static void TryValueInitialization(Sema &S, 3726 const InitializedEntity &Entity, 3727 const InitializationKind &Kind, 3728 InitializationSequence &Sequence, 3729 InitListExpr *InitList) { 3730 assert((!InitList || InitList->getNumInits() == 0) && 3731 "Shouldn't use value-init for non-empty init lists"); 3732 3733 // C++98 [dcl.init]p5, C++11 [dcl.init]p7: 3734 // 3735 // To value-initialize an object of type T means: 3736 QualType T = Entity.getType(); 3737 3738 // -- if T is an array type, then each element is value-initialized; 3739 T = S.Context.getBaseElementType(T); 3740 3741 if (const RecordType *RT = T->getAs<RecordType>()) { 3742 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3743 bool NeedZeroInitialization = true; 3744 if (!S.getLangOpts().CPlusPlus11) { 3745 // C++98: 3746 // -- if T is a class type (clause 9) with a user-declared constructor 3747 // (12.1), then the default constructor for T is called (and the 3748 // initialization is ill-formed if T has no accessible default 3749 // constructor); 3750 if (ClassDecl->hasUserDeclaredConstructor()) 3751 NeedZeroInitialization = false; 3752 } else { 3753 // C++11: 3754 // -- if T is a class type (clause 9) with either no default constructor 3755 // (12.1 [class.ctor]) or a default constructor that is user-provided 3756 // or deleted, then the object is default-initialized; 3757 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); 3758 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) 3759 NeedZeroInitialization = false; 3760 } 3761 3762 // -- if T is a (possibly cv-qualified) non-union class type without a 3763 // user-provided or deleted default constructor, then the object is 3764 // zero-initialized and, if T has a non-trivial default constructor, 3765 // default-initialized; 3766 // The 'non-union' here was removed by DR1502. The 'non-trivial default 3767 // constructor' part was removed by DR1507. 3768 if (NeedZeroInitialization) 3769 Sequence.AddZeroInitializationStep(Entity.getType()); 3770 3771 // C++03: 3772 // -- if T is a non-union class type without a user-declared constructor, 3773 // then every non-static data member and base class component of T is 3774 // value-initialized; 3775 // [...] A program that calls for [...] value-initialization of an 3776 // entity of reference type is ill-formed. 3777 // 3778 // C++11 doesn't need this handling, because value-initialization does not 3779 // occur recursively there, and the implicit default constructor is 3780 // defined as deleted in the problematic cases. 3781 if (!S.getLangOpts().CPlusPlus11 && 3782 ClassDecl->hasUninitializedReferenceMember()) { 3783 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); 3784 return; 3785 } 3786 3787 // If this is list-value-initialization, pass the empty init list on when 3788 // building the constructor call. This affects the semantics of a few 3789 // things (such as whether an explicit default constructor can be called). 3790 Expr *InitListAsExpr = InitList; 3791 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); 3792 bool InitListSyntax = InitList; 3793 3794 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence, 3795 InitListSyntax); 3796 } 3797 } 3798 3799 Sequence.AddZeroInitializationStep(Entity.getType()); 3800} 3801 3802/// \brief Attempt default initialization (C++ [dcl.init]p6). 3803static void TryDefaultInitialization(Sema &S, 3804 const InitializedEntity &Entity, 3805 const InitializationKind &Kind, 3806 InitializationSequence &Sequence) { 3807 assert(Kind.getKind() == InitializationKind::IK_Default); 3808 3809 // C++ [dcl.init]p6: 3810 // To default-initialize an object of type T means: 3811 // - if T is an array type, each element is default-initialized; 3812 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 3813 3814 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 3815 // constructor for T is called (and the initialization is ill-formed if 3816 // T has no accessible default constructor); 3817 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { 3818 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence); 3819 return; 3820 } 3821 3822 // - otherwise, no initialization is performed. 3823 3824 // If a program calls for the default initialization of an object of 3825 // a const-qualified type T, T shall be a class type with a user-provided 3826 // default constructor. 3827 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { 3828 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 3829 return; 3830 } 3831 3832 // If the destination type has a lifetime property, zero-initialize it. 3833 if (DestType.getQualifiers().hasObjCLifetime()) { 3834 Sequence.AddZeroInitializationStep(Entity.getType()); 3835 return; 3836 } 3837} 3838 3839/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 3840/// which enumerates all conversion functions and performs overload resolution 3841/// to select the best. 3842static void TryUserDefinedConversion(Sema &S, 3843 const InitializedEntity &Entity, 3844 const InitializationKind &Kind, 3845 Expr *Initializer, 3846 InitializationSequence &Sequence) { 3847 QualType DestType = Entity.getType(); 3848 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 3849 QualType SourceType = Initializer->getType(); 3850 assert((DestType->isRecordType() || SourceType->isRecordType()) && 3851 "Must have a class type to perform a user-defined conversion"); 3852 3853 // Build the candidate set directly in the initialization sequence 3854 // structure, so that it will persist if we fail. 3855 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3856 CandidateSet.clear(); 3857 3858 // Determine whether we are allowed to call explicit constructors or 3859 // explicit conversion operators. 3860 bool AllowExplicit = Kind.AllowExplicit(); 3861 3862 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 3863 // The type we're converting to is a class type. Enumerate its constructors 3864 // to see if there is a suitable conversion. 3865 CXXRecordDecl *DestRecordDecl 3866 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 3867 3868 // Try to complete the type we're converting to. 3869 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 3870 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl); 3871 // The container holding the constructors can under certain conditions 3872 // be changed while iterating. To be safe we copy the lookup results 3873 // to a new container. 3874 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end()); 3875 for (SmallVector<NamedDecl*, 8>::iterator 3876 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end(); 3877 Con != ConEnd; ++Con) { 3878 NamedDecl *D = *Con; 3879 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3880 3881 // Find the constructor (which may be a template). 3882 CXXConstructorDecl *Constructor = 0; 3883 FunctionTemplateDecl *ConstructorTmpl 3884 = dyn_cast<FunctionTemplateDecl>(D); 3885 if (ConstructorTmpl) 3886 Constructor = cast<CXXConstructorDecl>( 3887 ConstructorTmpl->getTemplatedDecl()); 3888 else 3889 Constructor = cast<CXXConstructorDecl>(D); 3890 3891 if (!Constructor->isInvalidDecl() && 3892 Constructor->isConvertingConstructor(AllowExplicit)) { 3893 if (ConstructorTmpl) 3894 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3895 /*ExplicitArgs*/ 0, 3896 Initializer, CandidateSet, 3897 /*SuppressUserConversions=*/true); 3898 else 3899 S.AddOverloadCandidate(Constructor, FoundDecl, 3900 Initializer, CandidateSet, 3901 /*SuppressUserConversions=*/true); 3902 } 3903 } 3904 } 3905 } 3906 3907 SourceLocation DeclLoc = Initializer->getLocStart(); 3908 3909 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 3910 // The type we're converting from is a class type, enumerate its conversion 3911 // functions. 3912 3913 // We can only enumerate the conversion functions for a complete type; if 3914 // the type isn't complete, simply skip this step. 3915 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) { 3916 CXXRecordDecl *SourceRecordDecl 3917 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 3918 3919 std::pair<CXXRecordDecl::conversion_iterator, 3920 CXXRecordDecl::conversion_iterator> 3921 Conversions = SourceRecordDecl->getVisibleConversionFunctions(); 3922 for (CXXRecordDecl::conversion_iterator 3923 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3924 NamedDecl *D = *I; 3925 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3926 if (isa<UsingShadowDecl>(D)) 3927 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3928 3929 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3930 CXXConversionDecl *Conv; 3931 if (ConvTemplate) 3932 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3933 else 3934 Conv = cast<CXXConversionDecl>(D); 3935 3936 if (AllowExplicit || !Conv->isExplicit()) { 3937 if (ConvTemplate) 3938 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 3939 ActingDC, Initializer, DestType, 3940 CandidateSet); 3941 else 3942 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 3943 Initializer, DestType, CandidateSet); 3944 } 3945 } 3946 } 3947 } 3948 3949 // Perform overload resolution. If it fails, return the failed result. 3950 OverloadCandidateSet::iterator Best; 3951 if (OverloadingResult Result 3952 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3953 Sequence.SetOverloadFailure( 3954 InitializationSequence::FK_UserConversionOverloadFailed, 3955 Result); 3956 return; 3957 } 3958 3959 FunctionDecl *Function = Best->Function; 3960 Function->setReferenced(); 3961 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3962 3963 if (isa<CXXConstructorDecl>(Function)) { 3964 // Add the user-defined conversion step. Any cv-qualification conversion is 3965 // subsumed by the initialization. Per DR5, the created temporary is of the 3966 // cv-unqualified type of the destination. 3967 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 3968 DestType.getUnqualifiedType(), 3969 HadMultipleCandidates); 3970 return; 3971 } 3972 3973 // Add the user-defined conversion step that calls the conversion function. 3974 QualType ConvType = Function->getCallResultType(); 3975 if (ConvType->getAs<RecordType>()) { 3976 // If we're converting to a class type, there may be an copy of 3977 // the resulting temporary object (possible to create an object of 3978 // a base class type). That copy is not a separate conversion, so 3979 // we just make a note of the actual destination type (possibly a 3980 // base class of the type returned by the conversion function) and 3981 // let the user-defined conversion step handle the conversion. 3982 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType, 3983 HadMultipleCandidates); 3984 return; 3985 } 3986 3987 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 3988 HadMultipleCandidates); 3989 3990 // If the conversion following the call to the conversion function 3991 // is interesting, add it as a separate step. 3992 if (Best->FinalConversion.First || Best->FinalConversion.Second || 3993 Best->FinalConversion.Third) { 3994 ImplicitConversionSequence ICS; 3995 ICS.setStandard(); 3996 ICS.Standard = Best->FinalConversion; 3997 Sequence.AddConversionSequenceStep(ICS, DestType); 3998 } 3999} 4000 4001/// The non-zero enum values here are indexes into diagnostic alternatives. 4002enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 4003 4004/// Determines whether this expression is an acceptable ICR source. 4005static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 4006 bool isAddressOf, bool &isWeakAccess) { 4007 // Skip parens. 4008 e = e->IgnoreParens(); 4009 4010 // Skip address-of nodes. 4011 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 4012 if (op->getOpcode() == UO_AddrOf) 4013 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, 4014 isWeakAccess); 4015 4016 // Skip certain casts. 4017 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 4018 switch (ce->getCastKind()) { 4019 case CK_Dependent: 4020 case CK_BitCast: 4021 case CK_LValueBitCast: 4022 case CK_NoOp: 4023 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); 4024 4025 case CK_ArrayToPointerDecay: 4026 return IIK_nonscalar; 4027 4028 case CK_NullToPointer: 4029 return IIK_okay; 4030 4031 default: 4032 break; 4033 } 4034 4035 // If we have a declaration reference, it had better be a local variable. 4036 } else if (isa<DeclRefExpr>(e)) { 4037 // set isWeakAccess to true, to mean that there will be an implicit 4038 // load which requires a cleanup. 4039 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 4040 isWeakAccess = true; 4041 4042 if (!isAddressOf) return IIK_nonlocal; 4043 4044 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 4045 if (!var) return IIK_nonlocal; 4046 4047 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 4048 4049 // If we have a conditional operator, check both sides. 4050 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 4051 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, 4052 isWeakAccess)) 4053 return iik; 4054 4055 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); 4056 4057 // These are never scalar. 4058 } else if (isa<ArraySubscriptExpr>(e)) { 4059 return IIK_nonscalar; 4060 4061 // Otherwise, it needs to be a null pointer constant. 4062 } else { 4063 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 4064 ? IIK_okay : IIK_nonlocal); 4065 } 4066 4067 return IIK_nonlocal; 4068} 4069 4070/// Check whether the given expression is a valid operand for an 4071/// indirect copy/restore. 4072static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 4073 assert(src->isRValue()); 4074 bool isWeakAccess = false; 4075 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); 4076 // If isWeakAccess to true, there will be an implicit 4077 // load which requires a cleanup. 4078 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) 4079 S.ExprNeedsCleanups = true; 4080 4081 if (iik == IIK_okay) return; 4082 4083 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 4084 << ((unsigned) iik - 1) // shift index into diagnostic explanations 4085 << src->getSourceRange(); 4086} 4087 4088/// \brief Determine whether we have compatible array types for the 4089/// purposes of GNU by-copy array initialization. 4090static bool hasCompatibleArrayTypes(ASTContext &Context, 4091 const ArrayType *Dest, 4092 const ArrayType *Source) { 4093 // If the source and destination array types are equivalent, we're 4094 // done. 4095 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 4096 return true; 4097 4098 // Make sure that the element types are the same. 4099 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 4100 return false; 4101 4102 // The only mismatch we allow is when the destination is an 4103 // incomplete array type and the source is a constant array type. 4104 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 4105} 4106 4107static bool tryObjCWritebackConversion(Sema &S, 4108 InitializationSequence &Sequence, 4109 const InitializedEntity &Entity, 4110 Expr *Initializer) { 4111 bool ArrayDecay = false; 4112 QualType ArgType = Initializer->getType(); 4113 QualType ArgPointee; 4114 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 4115 ArrayDecay = true; 4116 ArgPointee = ArgArrayType->getElementType(); 4117 ArgType = S.Context.getPointerType(ArgPointee); 4118 } 4119 4120 // Handle write-back conversion. 4121 QualType ConvertedArgType; 4122 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 4123 ConvertedArgType)) 4124 return false; 4125 4126 // We should copy unless we're passing to an argument explicitly 4127 // marked 'out'. 4128 bool ShouldCopy = true; 4129 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 4130 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 4131 4132 // Do we need an lvalue conversion? 4133 if (ArrayDecay || Initializer->isGLValue()) { 4134 ImplicitConversionSequence ICS; 4135 ICS.setStandard(); 4136 ICS.Standard.setAsIdentityConversion(); 4137 4138 QualType ResultType; 4139 if (ArrayDecay) { 4140 ICS.Standard.First = ICK_Array_To_Pointer; 4141 ResultType = S.Context.getPointerType(ArgPointee); 4142 } else { 4143 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 4144 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 4145 } 4146 4147 Sequence.AddConversionSequenceStep(ICS, ResultType); 4148 } 4149 4150 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 4151 return true; 4152} 4153 4154static bool TryOCLSamplerInitialization(Sema &S, 4155 InitializationSequence &Sequence, 4156 QualType DestType, 4157 Expr *Initializer) { 4158 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || 4159 !Initializer->isIntegerConstantExpr(S.getASTContext())) 4160 return false; 4161 4162 Sequence.AddOCLSamplerInitStep(DestType); 4163 return true; 4164} 4165 4166// 4167// OpenCL 1.2 spec, s6.12.10 4168// 4169// The event argument can also be used to associate the 4170// async_work_group_copy with a previous async copy allowing 4171// an event to be shared by multiple async copies; otherwise 4172// event should be zero. 4173// 4174static bool TryOCLZeroEventInitialization(Sema &S, 4175 InitializationSequence &Sequence, 4176 QualType DestType, 4177 Expr *Initializer) { 4178 if (!S.getLangOpts().OpenCL || !DestType->isEventT() || 4179 !Initializer->isIntegerConstantExpr(S.getASTContext()) || 4180 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0)) 4181 return false; 4182 4183 Sequence.AddOCLZeroEventStep(DestType); 4184 return true; 4185} 4186 4187InitializationSequence::InitializationSequence(Sema &S, 4188 const InitializedEntity &Entity, 4189 const InitializationKind &Kind, 4190 MultiExprArg Args) 4191 : FailedCandidateSet(Kind.getLocation()) { 4192 ASTContext &Context = S.Context; 4193 4194 // Eliminate non-overload placeholder types in the arguments. We 4195 // need to do this before checking whether types are dependent 4196 // because lowering a pseudo-object expression might well give us 4197 // something of dependent type. 4198 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4199 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 4200 // FIXME: should we be doing this here? 4201 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 4202 if (result.isInvalid()) { 4203 SetFailed(FK_PlaceholderType); 4204 return; 4205 } 4206 Args[I] = result.take(); 4207 } 4208 4209 // C++0x [dcl.init]p16: 4210 // The semantics of initializers are as follows. The destination type is 4211 // the type of the object or reference being initialized and the source 4212 // type is the type of the initializer expression. The source type is not 4213 // defined when the initializer is a braced-init-list or when it is a 4214 // parenthesized list of expressions. 4215 QualType DestType = Entity.getType(); 4216 4217 if (DestType->isDependentType() || 4218 Expr::hasAnyTypeDependentArguments(Args)) { 4219 SequenceKind = DependentSequence; 4220 return; 4221 } 4222 4223 // Almost everything is a normal sequence. 4224 setSequenceKind(NormalSequence); 4225 4226 QualType SourceType; 4227 Expr *Initializer = 0; 4228 if (Args.size() == 1) { 4229 Initializer = Args[0]; 4230 if (!isa<InitListExpr>(Initializer)) 4231 SourceType = Initializer->getType(); 4232 } 4233 4234 // - If the initializer is a (non-parenthesized) braced-init-list, the 4235 // object is list-initialized (8.5.4). 4236 if (Kind.getKind() != InitializationKind::IK_Direct) { 4237 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 4238 TryListInitialization(S, Entity, Kind, InitList, *this); 4239 return; 4240 } 4241 } 4242 4243 // - If the destination type is a reference type, see 8.5.3. 4244 if (DestType->isReferenceType()) { 4245 // C++0x [dcl.init.ref]p1: 4246 // A variable declared to be a T& or T&&, that is, "reference to type T" 4247 // (8.3.2), shall be initialized by an object, or function, of type T or 4248 // by an object that can be converted into a T. 4249 // (Therefore, multiple arguments are not permitted.) 4250 if (Args.size() != 1) 4251 SetFailed(FK_TooManyInitsForReference); 4252 else 4253 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 4254 return; 4255 } 4256 4257 // - If the initializer is (), the object is value-initialized. 4258 if (Kind.getKind() == InitializationKind::IK_Value || 4259 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 4260 TryValueInitialization(S, Entity, Kind, *this); 4261 return; 4262 } 4263 4264 // Handle default initialization. 4265 if (Kind.getKind() == InitializationKind::IK_Default) { 4266 TryDefaultInitialization(S, Entity, Kind, *this); 4267 return; 4268 } 4269 4270 // - If the destination type is an array of characters, an array of 4271 // char16_t, an array of char32_t, or an array of wchar_t, and the 4272 // initializer is a string literal, see 8.5.2. 4273 // - Otherwise, if the destination type is an array, the program is 4274 // ill-formed. 4275 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 4276 if (Initializer && isa<VariableArrayType>(DestAT)) { 4277 SetFailed(FK_VariableLengthArrayHasInitializer); 4278 return; 4279 } 4280 4281 if (Initializer && IsStringInit(Initializer, DestAT, Context)) { 4282 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 4283 return; 4284 } 4285 4286 // Note: as an GNU C extension, we allow initialization of an 4287 // array from a compound literal that creates an array of the same 4288 // type, so long as the initializer has no side effects. 4289 if (!S.getLangOpts().CPlusPlus && Initializer && 4290 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 4291 Initializer->getType()->isArrayType()) { 4292 const ArrayType *SourceAT 4293 = Context.getAsArrayType(Initializer->getType()); 4294 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 4295 SetFailed(FK_ArrayTypeMismatch); 4296 else if (Initializer->HasSideEffects(S.Context)) 4297 SetFailed(FK_NonConstantArrayInit); 4298 else { 4299 AddArrayInitStep(DestType); 4300 } 4301 } 4302 // Note: as a GNU C++ extension, we allow list-initialization of a 4303 // class member of array type from a parenthesized initializer list. 4304 else if (S.getLangOpts().CPlusPlus && 4305 Entity.getKind() == InitializedEntity::EK_Member && 4306 Initializer && isa<InitListExpr>(Initializer)) { 4307 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 4308 *this); 4309 AddParenthesizedArrayInitStep(DestType); 4310 } else if (DestAT->getElementType()->isAnyCharacterType()) 4311 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 4312 else 4313 SetFailed(FK_ArrayNeedsInitList); 4314 4315 return; 4316 } 4317 4318 // Determine whether we should consider writeback conversions for 4319 // Objective-C ARC. 4320 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 4321 Entity.getKind() == InitializedEntity::EK_Parameter; 4322 4323 // We're at the end of the line for C: it's either a write-back conversion 4324 // or it's a C assignment. There's no need to check anything else. 4325 if (!S.getLangOpts().CPlusPlus) { 4326 // If allowed, check whether this is an Objective-C writeback conversion. 4327 if (allowObjCWritebackConversion && 4328 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 4329 return; 4330 } 4331 4332 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 4333 return; 4334 4335 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer)) 4336 return; 4337 4338 // Handle initialization in C 4339 AddCAssignmentStep(DestType); 4340 MaybeProduceObjCObject(S, *this, Entity); 4341 return; 4342 } 4343 4344 assert(S.getLangOpts().CPlusPlus); 4345 4346 // - If the destination type is a (possibly cv-qualified) class type: 4347 if (DestType->isRecordType()) { 4348 // - If the initialization is direct-initialization, or if it is 4349 // copy-initialization where the cv-unqualified version of the 4350 // source type is the same class as, or a derived class of, the 4351 // class of the destination, constructors are considered. [...] 4352 if (Kind.getKind() == InitializationKind::IK_Direct || 4353 (Kind.getKind() == InitializationKind::IK_Copy && 4354 (Context.hasSameUnqualifiedType(SourceType, DestType) || 4355 S.IsDerivedFrom(SourceType, DestType)))) 4356 TryConstructorInitialization(S, Entity, Kind, Args, 4357 Entity.getType(), *this); 4358 // - Otherwise (i.e., for the remaining copy-initialization cases), 4359 // user-defined conversion sequences that can convert from the source 4360 // type to the destination type or (when a conversion function is 4361 // used) to a derived class thereof are enumerated as described in 4362 // 13.3.1.4, and the best one is chosen through overload resolution 4363 // (13.3). 4364 else 4365 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 4366 return; 4367 } 4368 4369 if (Args.size() > 1) { 4370 SetFailed(FK_TooManyInitsForScalar); 4371 return; 4372 } 4373 assert(Args.size() == 1 && "Zero-argument case handled above"); 4374 4375 // - Otherwise, if the source type is a (possibly cv-qualified) class 4376 // type, conversion functions are considered. 4377 if (!SourceType.isNull() && SourceType->isRecordType()) { 4378 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 4379 MaybeProduceObjCObject(S, *this, Entity); 4380 return; 4381 } 4382 4383 // - Otherwise, the initial value of the object being initialized is the 4384 // (possibly converted) value of the initializer expression. Standard 4385 // conversions (Clause 4) will be used, if necessary, to convert the 4386 // initializer expression to the cv-unqualified version of the 4387 // destination type; no user-defined conversions are considered. 4388 4389 ImplicitConversionSequence ICS 4390 = S.TryImplicitConversion(Initializer, Entity.getType(), 4391 /*SuppressUserConversions*/true, 4392 /*AllowExplicitConversions*/ false, 4393 /*InOverloadResolution*/ false, 4394 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 4395 allowObjCWritebackConversion); 4396 4397 if (ICS.isStandard() && 4398 ICS.Standard.Second == ICK_Writeback_Conversion) { 4399 // Objective-C ARC writeback conversion. 4400 4401 // We should copy unless we're passing to an argument explicitly 4402 // marked 'out'. 4403 bool ShouldCopy = true; 4404 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 4405 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 4406 4407 // If there was an lvalue adjustment, add it as a separate conversion. 4408 if (ICS.Standard.First == ICK_Array_To_Pointer || 4409 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 4410 ImplicitConversionSequence LvalueICS; 4411 LvalueICS.setStandard(); 4412 LvalueICS.Standard.setAsIdentityConversion(); 4413 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 4414 LvalueICS.Standard.First = ICS.Standard.First; 4415 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 4416 } 4417 4418 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 4419 } else if (ICS.isBad()) { 4420 DeclAccessPair dap; 4421 if (Initializer->getType() == Context.OverloadTy && 4422 !S.ResolveAddressOfOverloadedFunction(Initializer 4423 , DestType, false, dap)) 4424 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4425 else 4426 SetFailed(InitializationSequence::FK_ConversionFailed); 4427 } else { 4428 AddConversionSequenceStep(ICS, Entity.getType()); 4429 4430 MaybeProduceObjCObject(S, *this, Entity); 4431 } 4432} 4433 4434InitializationSequence::~InitializationSequence() { 4435 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(), 4436 StepEnd = Steps.end(); 4437 Step != StepEnd; ++Step) 4438 Step->Destroy(); 4439} 4440 4441//===----------------------------------------------------------------------===// 4442// Perform initialization 4443//===----------------------------------------------------------------------===// 4444static Sema::AssignmentAction 4445getAssignmentAction(const InitializedEntity &Entity) { 4446 switch(Entity.getKind()) { 4447 case InitializedEntity::EK_Variable: 4448 case InitializedEntity::EK_New: 4449 case InitializedEntity::EK_Exception: 4450 case InitializedEntity::EK_Base: 4451 case InitializedEntity::EK_Delegating: 4452 return Sema::AA_Initializing; 4453 4454 case InitializedEntity::EK_Parameter: 4455 if (Entity.getDecl() && 4456 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 4457 return Sema::AA_Sending; 4458 4459 return Sema::AA_Passing; 4460 4461 case InitializedEntity::EK_Result: 4462 return Sema::AA_Returning; 4463 4464 case InitializedEntity::EK_Temporary: 4465 // FIXME: Can we tell apart casting vs. converting? 4466 return Sema::AA_Casting; 4467 4468 case InitializedEntity::EK_Member: 4469 case InitializedEntity::EK_ArrayElement: 4470 case InitializedEntity::EK_VectorElement: 4471 case InitializedEntity::EK_ComplexElement: 4472 case InitializedEntity::EK_BlockElement: 4473 case InitializedEntity::EK_LambdaCapture: 4474 case InitializedEntity::EK_CompoundLiteralInit: 4475 return Sema::AA_Initializing; 4476 } 4477 4478 llvm_unreachable("Invalid EntityKind!"); 4479} 4480 4481/// \brief Whether we should bind a created object as a temporary when 4482/// initializing the given entity. 4483static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 4484 switch (Entity.getKind()) { 4485 case InitializedEntity::EK_ArrayElement: 4486 case InitializedEntity::EK_Member: 4487 case InitializedEntity::EK_Result: 4488 case InitializedEntity::EK_New: 4489 case InitializedEntity::EK_Variable: 4490 case InitializedEntity::EK_Base: 4491 case InitializedEntity::EK_Delegating: 4492 case InitializedEntity::EK_VectorElement: 4493 case InitializedEntity::EK_ComplexElement: 4494 case InitializedEntity::EK_Exception: 4495 case InitializedEntity::EK_BlockElement: 4496 case InitializedEntity::EK_LambdaCapture: 4497 case InitializedEntity::EK_CompoundLiteralInit: 4498 return false; 4499 4500 case InitializedEntity::EK_Parameter: 4501 case InitializedEntity::EK_Temporary: 4502 return true; 4503 } 4504 4505 llvm_unreachable("missed an InitializedEntity kind?"); 4506} 4507 4508/// \brief Whether the given entity, when initialized with an object 4509/// created for that initialization, requires destruction. 4510static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 4511 switch (Entity.getKind()) { 4512 case InitializedEntity::EK_Result: 4513 case InitializedEntity::EK_New: 4514 case InitializedEntity::EK_Base: 4515 case InitializedEntity::EK_Delegating: 4516 case InitializedEntity::EK_VectorElement: 4517 case InitializedEntity::EK_ComplexElement: 4518 case InitializedEntity::EK_BlockElement: 4519 case InitializedEntity::EK_LambdaCapture: 4520 return false; 4521 4522 case InitializedEntity::EK_Member: 4523 case InitializedEntity::EK_Variable: 4524 case InitializedEntity::EK_Parameter: 4525 case InitializedEntity::EK_Temporary: 4526 case InitializedEntity::EK_ArrayElement: 4527 case InitializedEntity::EK_Exception: 4528 case InitializedEntity::EK_CompoundLiteralInit: 4529 return true; 4530 } 4531 4532 llvm_unreachable("missed an InitializedEntity kind?"); 4533} 4534 4535/// \brief Look for copy and move constructors and constructor templates, for 4536/// copying an object via direct-initialization (per C++11 [dcl.init]p16). 4537static void LookupCopyAndMoveConstructors(Sema &S, 4538 OverloadCandidateSet &CandidateSet, 4539 CXXRecordDecl *Class, 4540 Expr *CurInitExpr) { 4541 DeclContext::lookup_result R = S.LookupConstructors(Class); 4542 // The container holding the constructors can under certain conditions 4543 // be changed while iterating (e.g. because of deserialization). 4544 // To be safe we copy the lookup results to a new container. 4545 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end()); 4546 for (SmallVector<NamedDecl*, 16>::iterator 4547 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) { 4548 NamedDecl *D = *CI; 4549 CXXConstructorDecl *Constructor = 0; 4550 4551 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) { 4552 // Handle copy/moveconstructors, only. 4553 if (!Constructor || Constructor->isInvalidDecl() || 4554 !Constructor->isCopyOrMoveConstructor() || 4555 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 4556 continue; 4557 4558 DeclAccessPair FoundDecl 4559 = DeclAccessPair::make(Constructor, Constructor->getAccess()); 4560 S.AddOverloadCandidate(Constructor, FoundDecl, 4561 CurInitExpr, CandidateSet); 4562 continue; 4563 } 4564 4565 // Handle constructor templates. 4566 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D); 4567 if (ConstructorTmpl->isInvalidDecl()) 4568 continue; 4569 4570 Constructor = cast<CXXConstructorDecl>( 4571 ConstructorTmpl->getTemplatedDecl()); 4572 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 4573 continue; 4574 4575 // FIXME: Do we need to limit this to copy-constructor-like 4576 // candidates? 4577 DeclAccessPair FoundDecl 4578 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess()); 4579 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0, 4580 CurInitExpr, CandidateSet, true); 4581 } 4582} 4583 4584/// \brief Get the location at which initialization diagnostics should appear. 4585static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 4586 Expr *Initializer) { 4587 switch (Entity.getKind()) { 4588 case InitializedEntity::EK_Result: 4589 return Entity.getReturnLoc(); 4590 4591 case InitializedEntity::EK_Exception: 4592 return Entity.getThrowLoc(); 4593 4594 case InitializedEntity::EK_Variable: 4595 return Entity.getDecl()->getLocation(); 4596 4597 case InitializedEntity::EK_LambdaCapture: 4598 return Entity.getCaptureLoc(); 4599 4600 case InitializedEntity::EK_ArrayElement: 4601 case InitializedEntity::EK_Member: 4602 case InitializedEntity::EK_Parameter: 4603 case InitializedEntity::EK_Temporary: 4604 case InitializedEntity::EK_New: 4605 case InitializedEntity::EK_Base: 4606 case InitializedEntity::EK_Delegating: 4607 case InitializedEntity::EK_VectorElement: 4608 case InitializedEntity::EK_ComplexElement: 4609 case InitializedEntity::EK_BlockElement: 4610 case InitializedEntity::EK_CompoundLiteralInit: 4611 return Initializer->getLocStart(); 4612 } 4613 llvm_unreachable("missed an InitializedEntity kind?"); 4614} 4615 4616/// \brief Make a (potentially elidable) temporary copy of the object 4617/// provided by the given initializer by calling the appropriate copy 4618/// constructor. 4619/// 4620/// \param S The Sema object used for type-checking. 4621/// 4622/// \param T The type of the temporary object, which must either be 4623/// the type of the initializer expression or a superclass thereof. 4624/// 4625/// \param Entity The entity being initialized. 4626/// 4627/// \param CurInit The initializer expression. 4628/// 4629/// \param IsExtraneousCopy Whether this is an "extraneous" copy that 4630/// is permitted in C++03 (but not C++0x) when binding a reference to 4631/// an rvalue. 4632/// 4633/// \returns An expression that copies the initializer expression into 4634/// a temporary object, or an error expression if a copy could not be 4635/// created. 4636static ExprResult CopyObject(Sema &S, 4637 QualType T, 4638 const InitializedEntity &Entity, 4639 ExprResult CurInit, 4640 bool IsExtraneousCopy) { 4641 // Determine which class type we're copying to. 4642 Expr *CurInitExpr = (Expr *)CurInit.get(); 4643 CXXRecordDecl *Class = 0; 4644 if (const RecordType *Record = T->getAs<RecordType>()) 4645 Class = cast<CXXRecordDecl>(Record->getDecl()); 4646 if (!Class) 4647 return CurInit; 4648 4649 // C++0x [class.copy]p32: 4650 // When certain criteria are met, an implementation is allowed to 4651 // omit the copy/move construction of a class object, even if the 4652 // copy/move constructor and/or destructor for the object have 4653 // side effects. [...] 4654 // - when a temporary class object that has not been bound to a 4655 // reference (12.2) would be copied/moved to a class object 4656 // with the same cv-unqualified type, the copy/move operation 4657 // can be omitted by constructing the temporary object 4658 // directly into the target of the omitted copy/move 4659 // 4660 // Note that the other three bullets are handled elsewhere. Copy 4661 // elision for return statements and throw expressions are handled as part 4662 // of constructor initialization, while copy elision for exception handlers 4663 // is handled by the run-time. 4664 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class); 4665 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 4666 4667 // Make sure that the type we are copying is complete. 4668 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 4669 return CurInit; 4670 4671 // Perform overload resolution using the class's copy/move constructors. 4672 // Only consider constructors and constructor templates. Per 4673 // C++0x [dcl.init]p16, second bullet to class types, this initialization 4674 // is direct-initialization. 4675 OverloadCandidateSet CandidateSet(Loc); 4676 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr); 4677 4678 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4679 4680 OverloadCandidateSet::iterator Best; 4681 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 4682 case OR_Success: 4683 break; 4684 4685 case OR_No_Viable_Function: 4686 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 4687 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 4688 : diag::err_temp_copy_no_viable) 4689 << (int)Entity.getKind() << CurInitExpr->getType() 4690 << CurInitExpr->getSourceRange(); 4691 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); 4692 if (!IsExtraneousCopy || S.isSFINAEContext()) 4693 return ExprError(); 4694 return CurInit; 4695 4696 case OR_Ambiguous: 4697 S.Diag(Loc, diag::err_temp_copy_ambiguous) 4698 << (int)Entity.getKind() << CurInitExpr->getType() 4699 << CurInitExpr->getSourceRange(); 4700 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); 4701 return ExprError(); 4702 4703 case OR_Deleted: 4704 S.Diag(Loc, diag::err_temp_copy_deleted) 4705 << (int)Entity.getKind() << CurInitExpr->getType() 4706 << CurInitExpr->getSourceRange(); 4707 S.NoteDeletedFunction(Best->Function); 4708 return ExprError(); 4709 } 4710 4711 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 4712 SmallVector<Expr*, 8> ConstructorArgs; 4713 CurInit.release(); // Ownership transferred into MultiExprArg, below. 4714 4715 S.CheckConstructorAccess(Loc, Constructor, Entity, 4716 Best->FoundDecl.getAccess(), IsExtraneousCopy); 4717 4718 if (IsExtraneousCopy) { 4719 // If this is a totally extraneous copy for C++03 reference 4720 // binding purposes, just return the original initialization 4721 // expression. We don't generate an (elided) copy operation here 4722 // because doing so would require us to pass down a flag to avoid 4723 // infinite recursion, where each step adds another extraneous, 4724 // elidable copy. 4725 4726 // Instantiate the default arguments of any extra parameters in 4727 // the selected copy constructor, as if we were going to create a 4728 // proper call to the copy constructor. 4729 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 4730 ParmVarDecl *Parm = Constructor->getParamDecl(I); 4731 if (S.RequireCompleteType(Loc, Parm->getType(), 4732 diag::err_call_incomplete_argument)) 4733 break; 4734 4735 // Build the default argument expression; we don't actually care 4736 // if this succeeds or not, because this routine will complain 4737 // if there was a problem. 4738 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 4739 } 4740 4741 return S.Owned(CurInitExpr); 4742 } 4743 4744 // Determine the arguments required to actually perform the 4745 // constructor call (we might have derived-to-base conversions, or 4746 // the copy constructor may have default arguments). 4747 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) 4748 return ExprError(); 4749 4750 // Actually perform the constructor call. 4751 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable, 4752 ConstructorArgs, 4753 HadMultipleCandidates, 4754 /*ListInit*/ false, 4755 /*ZeroInit*/ false, 4756 CXXConstructExpr::CK_Complete, 4757 SourceRange()); 4758 4759 // If we're supposed to bind temporaries, do so. 4760 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 4761 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4762 return CurInit; 4763} 4764 4765/// \brief Check whether elidable copy construction for binding a reference to 4766/// a temporary would have succeeded if we were building in C++98 mode, for 4767/// -Wc++98-compat. 4768static void CheckCXX98CompatAccessibleCopy(Sema &S, 4769 const InitializedEntity &Entity, 4770 Expr *CurInitExpr) { 4771 assert(S.getLangOpts().CPlusPlus11); 4772 4773 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 4774 if (!Record) 4775 return; 4776 4777 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 4778 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc) 4779 == DiagnosticsEngine::Ignored) 4780 return; 4781 4782 // Find constructors which would have been considered. 4783 OverloadCandidateSet CandidateSet(Loc); 4784 LookupCopyAndMoveConstructors( 4785 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr); 4786 4787 // Perform overload resolution. 4788 OverloadCandidateSet::iterator Best; 4789 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best); 4790 4791 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 4792 << OR << (int)Entity.getKind() << CurInitExpr->getType() 4793 << CurInitExpr->getSourceRange(); 4794 4795 switch (OR) { 4796 case OR_Success: 4797 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 4798 Entity, Best->FoundDecl.getAccess(), Diag); 4799 // FIXME: Check default arguments as far as that's possible. 4800 break; 4801 4802 case OR_No_Viable_Function: 4803 S.Diag(Loc, Diag); 4804 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); 4805 break; 4806 4807 case OR_Ambiguous: 4808 S.Diag(Loc, Diag); 4809 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); 4810 break; 4811 4812 case OR_Deleted: 4813 S.Diag(Loc, Diag); 4814 S.NoteDeletedFunction(Best->Function); 4815 break; 4816 } 4817} 4818 4819void InitializationSequence::PrintInitLocationNote(Sema &S, 4820 const InitializedEntity &Entity) { 4821 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) { 4822 if (Entity.getDecl()->getLocation().isInvalid()) 4823 return; 4824 4825 if (Entity.getDecl()->getDeclName()) 4826 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 4827 << Entity.getDecl()->getDeclName(); 4828 else 4829 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 4830 } 4831} 4832 4833static bool isReferenceBinding(const InitializationSequence::Step &s) { 4834 return s.Kind == InitializationSequence::SK_BindReference || 4835 s.Kind == InitializationSequence::SK_BindReferenceToTemporary; 4836} 4837 4838/// Returns true if the parameters describe a constructor initialization of 4839/// an explicit temporary object, e.g. "Point(x, y)". 4840static bool isExplicitTemporary(const InitializedEntity &Entity, 4841 const InitializationKind &Kind, 4842 unsigned NumArgs) { 4843 switch (Entity.getKind()) { 4844 case InitializedEntity::EK_Temporary: 4845 case InitializedEntity::EK_CompoundLiteralInit: 4846 break; 4847 default: 4848 return false; 4849 } 4850 4851 switch (Kind.getKind()) { 4852 case InitializationKind::IK_DirectList: 4853 return true; 4854 // FIXME: Hack to work around cast weirdness. 4855 case InitializationKind::IK_Direct: 4856 case InitializationKind::IK_Value: 4857 return NumArgs != 1; 4858 default: 4859 return false; 4860 } 4861} 4862 4863static ExprResult 4864PerformConstructorInitialization(Sema &S, 4865 const InitializedEntity &Entity, 4866 const InitializationKind &Kind, 4867 MultiExprArg Args, 4868 const InitializationSequence::Step& Step, 4869 bool &ConstructorInitRequiresZeroInit, 4870 bool IsListInitialization) { 4871 unsigned NumArgs = Args.size(); 4872 CXXConstructorDecl *Constructor 4873 = cast<CXXConstructorDecl>(Step.Function.Function); 4874 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 4875 4876 // Build a call to the selected constructor. 4877 SmallVector<Expr*, 8> ConstructorArgs; 4878 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 4879 ? Kind.getEqualLoc() 4880 : Kind.getLocation(); 4881 4882 if (Kind.getKind() == InitializationKind::IK_Default) { 4883 // Force even a trivial, implicit default constructor to be 4884 // semantically checked. We do this explicitly because we don't build 4885 // the definition for completely trivial constructors. 4886 assert(Constructor->getParent() && "No parent class for constructor."); 4887 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 4888 Constructor->isTrivial() && !Constructor->isUsed(false)) 4889 S.DefineImplicitDefaultConstructor(Loc, Constructor); 4890 } 4891 4892 ExprResult CurInit = S.Owned((Expr *)0); 4893 4894 // C++ [over.match.copy]p1: 4895 // - When initializing a temporary to be bound to the first parameter 4896 // of a constructor that takes a reference to possibly cv-qualified 4897 // T as its first argument, called with a single argument in the 4898 // context of direct-initialization, explicit conversion functions 4899 // are also considered. 4900 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() && 4901 Args.size() == 1 && 4902 Constructor->isCopyOrMoveConstructor(); 4903 4904 // Determine the arguments required to actually perform the constructor 4905 // call. 4906 if (S.CompleteConstructorCall(Constructor, Args, 4907 Loc, ConstructorArgs, 4908 AllowExplicitConv, 4909 IsListInitialization)) 4910 return ExprError(); 4911 4912 4913 if (isExplicitTemporary(Entity, Kind, NumArgs)) { 4914 // An explicitly-constructed temporary, e.g., X(1, 2). 4915 S.MarkFunctionReferenced(Loc, Constructor); 4916 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 4917 return ExprError(); 4918 4919 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 4920 if (!TSInfo) 4921 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 4922 SourceRange ParenRange; 4923 if (Kind.getKind() != InitializationKind::IK_DirectList) 4924 ParenRange = Kind.getParenRange(); 4925 4926 CurInit = S.Owned( 4927 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor, 4928 TSInfo, ConstructorArgs, 4929 ParenRange, IsListInitialization, 4930 HadMultipleCandidates, 4931 ConstructorInitRequiresZeroInit)); 4932 } else { 4933 CXXConstructExpr::ConstructionKind ConstructKind = 4934 CXXConstructExpr::CK_Complete; 4935 4936 if (Entity.getKind() == InitializedEntity::EK_Base) { 4937 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 4938 CXXConstructExpr::CK_VirtualBase : 4939 CXXConstructExpr::CK_NonVirtualBase; 4940 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 4941 ConstructKind = CXXConstructExpr::CK_Delegating; 4942 } 4943 4944 // Only get the parenthesis range if it is a direct construction. 4945 SourceRange parenRange = 4946 Kind.getKind() == InitializationKind::IK_Direct ? 4947 Kind.getParenRange() : SourceRange(); 4948 4949 // If the entity allows NRVO, mark the construction as elidable 4950 // unconditionally. 4951 if (Entity.allowsNRVO()) 4952 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4953 Constructor, /*Elidable=*/true, 4954 ConstructorArgs, 4955 HadMultipleCandidates, 4956 IsListInitialization, 4957 ConstructorInitRequiresZeroInit, 4958 ConstructKind, 4959 parenRange); 4960 else 4961 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4962 Constructor, 4963 ConstructorArgs, 4964 HadMultipleCandidates, 4965 IsListInitialization, 4966 ConstructorInitRequiresZeroInit, 4967 ConstructKind, 4968 parenRange); 4969 } 4970 if (CurInit.isInvalid()) 4971 return ExprError(); 4972 4973 // Only check access if all of that succeeded. 4974 S.CheckConstructorAccess(Loc, Constructor, Entity, 4975 Step.Function.FoundDecl.getAccess()); 4976 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 4977 return ExprError(); 4978 4979 if (shouldBindAsTemporary(Entity)) 4980 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4981 4982 return CurInit; 4983} 4984 4985/// Determine whether the specified InitializedEntity definitely has a lifetime 4986/// longer than the current full-expression. Conservatively returns false if 4987/// it's unclear. 4988static bool 4989InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) { 4990 const InitializedEntity *Top = &Entity; 4991 while (Top->getParent()) 4992 Top = Top->getParent(); 4993 4994 switch (Top->getKind()) { 4995 case InitializedEntity::EK_Variable: 4996 case InitializedEntity::EK_Result: 4997 case InitializedEntity::EK_Exception: 4998 case InitializedEntity::EK_Member: 4999 case InitializedEntity::EK_New: 5000 case InitializedEntity::EK_Base: 5001 case InitializedEntity::EK_Delegating: 5002 return true; 5003 5004 case InitializedEntity::EK_ArrayElement: 5005 case InitializedEntity::EK_VectorElement: 5006 case InitializedEntity::EK_BlockElement: 5007 case InitializedEntity::EK_ComplexElement: 5008 // Could not determine what the full initialization is. Assume it might not 5009 // outlive the full-expression. 5010 return false; 5011 5012 case InitializedEntity::EK_Parameter: 5013 case InitializedEntity::EK_Temporary: 5014 case InitializedEntity::EK_LambdaCapture: 5015 case InitializedEntity::EK_CompoundLiteralInit: 5016 // The entity being initialized might not outlive the full-expression. 5017 return false; 5018 } 5019 5020 llvm_unreachable("unknown entity kind"); 5021} 5022 5023ExprResult 5024InitializationSequence::Perform(Sema &S, 5025 const InitializedEntity &Entity, 5026 const InitializationKind &Kind, 5027 MultiExprArg Args, 5028 QualType *ResultType) { 5029 if (Failed()) { 5030 Diagnose(S, Entity, Kind, Args); 5031 return ExprError(); 5032 } 5033 5034 if (getKind() == DependentSequence) { 5035 // If the declaration is a non-dependent, incomplete array type 5036 // that has an initializer, then its type will be completed once 5037 // the initializer is instantiated. 5038 if (ResultType && !Entity.getType()->isDependentType() && 5039 Args.size() == 1) { 5040 QualType DeclType = Entity.getType(); 5041 if (const IncompleteArrayType *ArrayT 5042 = S.Context.getAsIncompleteArrayType(DeclType)) { 5043 // FIXME: We don't currently have the ability to accurately 5044 // compute the length of an initializer list without 5045 // performing full type-checking of the initializer list 5046 // (since we have to determine where braces are implicitly 5047 // introduced and such). So, we fall back to making the array 5048 // type a dependently-sized array type with no specified 5049 // bound. 5050 if (isa<InitListExpr>((Expr *)Args[0])) { 5051 SourceRange Brackets; 5052 5053 // Scavange the location of the brackets from the entity, if we can. 5054 if (DeclaratorDecl *DD = Entity.getDecl()) { 5055 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 5056 TypeLoc TL = TInfo->getTypeLoc(); 5057 if (IncompleteArrayTypeLoc ArrayLoc = 5058 TL.getAs<IncompleteArrayTypeLoc>()) 5059 Brackets = ArrayLoc.getBracketsRange(); 5060 } 5061 } 5062 5063 *ResultType 5064 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 5065 /*NumElts=*/0, 5066 ArrayT->getSizeModifier(), 5067 ArrayT->getIndexTypeCVRQualifiers(), 5068 Brackets); 5069 } 5070 5071 } 5072 } 5073 if (Kind.getKind() == InitializationKind::IK_Direct && 5074 !Kind.isExplicitCast()) { 5075 // Rebuild the ParenListExpr. 5076 SourceRange ParenRange = Kind.getParenRange(); 5077 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), 5078 Args); 5079 } 5080 assert(Kind.getKind() == InitializationKind::IK_Copy || 5081 Kind.isExplicitCast() || 5082 Kind.getKind() == InitializationKind::IK_DirectList); 5083 return ExprResult(Args[0]); 5084 } 5085 5086 // No steps means no initialization. 5087 if (Steps.empty()) 5088 return S.Owned((Expr *)0); 5089 5090 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && 5091 Args.size() == 1 && isa<InitListExpr>(Args[0]) && 5092 Entity.getKind() != InitializedEntity::EK_Parameter) { 5093 // Produce a C++98 compatibility warning if we are initializing a reference 5094 // from an initializer list. For parameters, we produce a better warning 5095 // elsewhere. 5096 Expr *Init = Args[0]; 5097 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init) 5098 << Init->getSourceRange(); 5099 } 5100 5101 // Diagnose cases where we initialize a pointer to an array temporary, and the 5102 // pointer obviously outlives the temporary. 5103 if (Args.size() == 1 && Args[0]->getType()->isArrayType() && 5104 Entity.getType()->isPointerType() && 5105 InitializedEntityOutlivesFullExpression(Entity)) { 5106 Expr *Init = Args[0]; 5107 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context); 5108 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary) 5109 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay) 5110 << Init->getSourceRange(); 5111 } 5112 5113 QualType DestType = Entity.getType().getNonReferenceType(); 5114 // FIXME: Ugly hack around the fact that Entity.getType() is not 5115 // the same as Entity.getDecl()->getType() in cases involving type merging, 5116 // and we want latter when it makes sense. 5117 if (ResultType) 5118 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 5119 Entity.getType(); 5120 5121 ExprResult CurInit = S.Owned((Expr *)0); 5122 5123 // For initialization steps that start with a single initializer, 5124 // grab the only argument out the Args and place it into the "current" 5125 // initializer. 5126 switch (Steps.front().Kind) { 5127 case SK_ResolveAddressOfOverloadedFunction: 5128 case SK_CastDerivedToBaseRValue: 5129 case SK_CastDerivedToBaseXValue: 5130 case SK_CastDerivedToBaseLValue: 5131 case SK_BindReference: 5132 case SK_BindReferenceToTemporary: 5133 case SK_ExtraneousCopyToTemporary: 5134 case SK_UserConversion: 5135 case SK_QualificationConversionLValue: 5136 case SK_QualificationConversionXValue: 5137 case SK_QualificationConversionRValue: 5138 case SK_LValueToRValue: 5139 case SK_ConversionSequence: 5140 case SK_ListInitialization: 5141 case SK_UnwrapInitList: 5142 case SK_RewrapInitList: 5143 case SK_CAssignment: 5144 case SK_StringInit: 5145 case SK_ObjCObjectConversion: 5146 case SK_ArrayInit: 5147 case SK_ParenthesizedArrayInit: 5148 case SK_PassByIndirectCopyRestore: 5149 case SK_PassByIndirectRestore: 5150 case SK_ProduceObjCObject: 5151 case SK_StdInitializerList: 5152 case SK_OCLSamplerInit: 5153 case SK_OCLZeroEvent: { 5154 assert(Args.size() == 1); 5155 CurInit = Args[0]; 5156 if (!CurInit.get()) return ExprError(); 5157 break; 5158 } 5159 5160 case SK_ConstructorInitialization: 5161 case SK_ListConstructorCall: 5162 case SK_ZeroInitialization: 5163 break; 5164 } 5165 5166 // Walk through the computed steps for the initialization sequence, 5167 // performing the specified conversions along the way. 5168 bool ConstructorInitRequiresZeroInit = false; 5169 for (step_iterator Step = step_begin(), StepEnd = step_end(); 5170 Step != StepEnd; ++Step) { 5171 if (CurInit.isInvalid()) 5172 return ExprError(); 5173 5174 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 5175 5176 switch (Step->Kind) { 5177 case SK_ResolveAddressOfOverloadedFunction: 5178 // Overload resolution determined which function invoke; update the 5179 // initializer to reflect that choice. 5180 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 5181 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) 5182 return ExprError(); 5183 CurInit = S.FixOverloadedFunctionReference(CurInit, 5184 Step->Function.FoundDecl, 5185 Step->Function.Function); 5186 break; 5187 5188 case SK_CastDerivedToBaseRValue: 5189 case SK_CastDerivedToBaseXValue: 5190 case SK_CastDerivedToBaseLValue: { 5191 // We have a derived-to-base cast that produces either an rvalue or an 5192 // lvalue. Perform that cast. 5193 5194 CXXCastPath BasePath; 5195 5196 // Casts to inaccessible base classes are allowed with C-style casts. 5197 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 5198 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 5199 CurInit.get()->getLocStart(), 5200 CurInit.get()->getSourceRange(), 5201 &BasePath, IgnoreBaseAccess)) 5202 return ExprError(); 5203 5204 if (S.BasePathInvolvesVirtualBase(BasePath)) { 5205 QualType T = SourceType; 5206 if (const PointerType *Pointer = T->getAs<PointerType>()) 5207 T = Pointer->getPointeeType(); 5208 if (const RecordType *RecordTy = T->getAs<RecordType>()) 5209 S.MarkVTableUsed(CurInit.get()->getLocStart(), 5210 cast<CXXRecordDecl>(RecordTy->getDecl())); 5211 } 5212 5213 ExprValueKind VK = 5214 Step->Kind == SK_CastDerivedToBaseLValue ? 5215 VK_LValue : 5216 (Step->Kind == SK_CastDerivedToBaseXValue ? 5217 VK_XValue : 5218 VK_RValue); 5219 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 5220 Step->Type, 5221 CK_DerivedToBase, 5222 CurInit.get(), 5223 &BasePath, VK)); 5224 break; 5225 } 5226 5227 case SK_BindReference: 5228 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5). 5229 if (CurInit.get()->refersToBitField()) { 5230 // We don't necessarily have an unambiguous source bit-field. 5231 FieldDecl *BitField = CurInit.get()->getSourceBitField(); 5232 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 5233 << Entity.getType().isVolatileQualified() 5234 << (BitField ? BitField->getDeclName() : DeclarationName()) 5235 << (BitField != NULL) 5236 << CurInit.get()->getSourceRange(); 5237 if (BitField) 5238 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 5239 5240 return ExprError(); 5241 } 5242 5243 if (CurInit.get()->refersToVectorElement()) { 5244 // References cannot bind to vector elements. 5245 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 5246 << Entity.getType().isVolatileQualified() 5247 << CurInit.get()->getSourceRange(); 5248 PrintInitLocationNote(S, Entity); 5249 return ExprError(); 5250 } 5251 5252 // Reference binding does not have any corresponding ASTs. 5253 5254 // Check exception specifications 5255 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 5256 return ExprError(); 5257 5258 break; 5259 5260 case SK_BindReferenceToTemporary: 5261 // Make sure the "temporary" is actually an rvalue. 5262 assert(CurInit.get()->isRValue() && "not a temporary"); 5263 5264 // Check exception specifications 5265 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 5266 return ExprError(); 5267 5268 // Materialize the temporary into memory. 5269 CurInit = new (S.Context) MaterializeTemporaryExpr( 5270 Entity.getType().getNonReferenceType(), 5271 CurInit.get(), 5272 Entity.getType()->isLValueReferenceType()); 5273 5274 // If we're binding to an Objective-C object that has lifetime, we 5275 // need cleanups. 5276 if (S.getLangOpts().ObjCAutoRefCount && 5277 CurInit.get()->getType()->isObjCLifetimeType()) 5278 S.ExprNeedsCleanups = true; 5279 5280 break; 5281 5282 case SK_ExtraneousCopyToTemporary: 5283 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 5284 /*IsExtraneousCopy=*/true); 5285 break; 5286 5287 case SK_UserConversion: { 5288 // We have a user-defined conversion that invokes either a constructor 5289 // or a conversion function. 5290 CastKind CastKind; 5291 bool IsCopy = false; 5292 FunctionDecl *Fn = Step->Function.Function; 5293 DeclAccessPair FoundFn = Step->Function.FoundDecl; 5294 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 5295 bool CreatedObject = false; 5296 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 5297 // Build a call to the selected constructor. 5298 SmallVector<Expr*, 8> ConstructorArgs; 5299 SourceLocation Loc = CurInit.get()->getLocStart(); 5300 CurInit.release(); // Ownership transferred into MultiExprArg, below. 5301 5302 // Determine the arguments required to actually perform the constructor 5303 // call. 5304 Expr *Arg = CurInit.get(); 5305 if (S.CompleteConstructorCall(Constructor, 5306 MultiExprArg(&Arg, 1), 5307 Loc, ConstructorArgs)) 5308 return ExprError(); 5309 5310 // Build an expression that constructs a temporary. 5311 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 5312 ConstructorArgs, 5313 HadMultipleCandidates, 5314 /*ListInit*/ false, 5315 /*ZeroInit*/ false, 5316 CXXConstructExpr::CK_Complete, 5317 SourceRange()); 5318 if (CurInit.isInvalid()) 5319 return ExprError(); 5320 5321 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity, 5322 FoundFn.getAccess()); 5323 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 5324 return ExprError(); 5325 5326 CastKind = CK_ConstructorConversion; 5327 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 5328 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 5329 S.IsDerivedFrom(SourceType, Class)) 5330 IsCopy = true; 5331 5332 CreatedObject = true; 5333 } else { 5334 // Build a call to the conversion function. 5335 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 5336 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0, 5337 FoundFn); 5338 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 5339 return ExprError(); 5340 5341 // FIXME: Should we move this initialization into a separate 5342 // derived-to-base conversion? I believe the answer is "no", because 5343 // we don't want to turn off access control here for c-style casts. 5344 ExprResult CurInitExprRes = 5345 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0, 5346 FoundFn, Conversion); 5347 if(CurInitExprRes.isInvalid()) 5348 return ExprError(); 5349 CurInit = CurInitExprRes; 5350 5351 // Build the actual call to the conversion function. 5352 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 5353 HadMultipleCandidates); 5354 if (CurInit.isInvalid() || !CurInit.get()) 5355 return ExprError(); 5356 5357 CastKind = CK_UserDefinedConversion; 5358 5359 CreatedObject = Conversion->getResultType()->isRecordType(); 5360 } 5361 5362 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back()); 5363 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity); 5364 5365 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) { 5366 QualType T = CurInit.get()->getType(); 5367 if (const RecordType *Record = T->getAs<RecordType>()) { 5368 CXXDestructorDecl *Destructor 5369 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 5370 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, 5371 S.PDiag(diag::err_access_dtor_temp) << T); 5372 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor); 5373 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart())) 5374 return ExprError(); 5375 } 5376 } 5377 5378 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 5379 CurInit.get()->getType(), 5380 CastKind, CurInit.get(), 0, 5381 CurInit.get()->getValueKind())); 5382 if (MaybeBindToTemp) 5383 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 5384 if (RequiresCopy) 5385 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 5386 CurInit, /*IsExtraneousCopy=*/false); 5387 break; 5388 } 5389 5390 case SK_QualificationConversionLValue: 5391 case SK_QualificationConversionXValue: 5392 case SK_QualificationConversionRValue: { 5393 // Perform a qualification conversion; these can never go wrong. 5394 ExprValueKind VK = 5395 Step->Kind == SK_QualificationConversionLValue ? 5396 VK_LValue : 5397 (Step->Kind == SK_QualificationConversionXValue ? 5398 VK_XValue : 5399 VK_RValue); 5400 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK); 5401 break; 5402 } 5403 5404 case SK_LValueToRValue: { 5405 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue"); 5406 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type, 5407 CK_LValueToRValue, 5408 CurInit.take(), 5409 /*BasePath=*/0, 5410 VK_RValue)); 5411 break; 5412 } 5413 5414 case SK_ConversionSequence: { 5415 Sema::CheckedConversionKind CCK 5416 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 5417 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 5418 : Kind.isExplicitCast()? Sema::CCK_OtherCast 5419 : Sema::CCK_ImplicitConversion; 5420 ExprResult CurInitExprRes = 5421 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 5422 getAssignmentAction(Entity), CCK); 5423 if (CurInitExprRes.isInvalid()) 5424 return ExprError(); 5425 CurInit = CurInitExprRes; 5426 break; 5427 } 5428 5429 case SK_ListInitialization: { 5430 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 5431 // Hack: We must pass *ResultType if available in order to set the type 5432 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 5433 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a 5434 // temporary, not a reference, so we should pass Ty. 5435 // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 5436 // Since this step is never used for a reference directly, we explicitly 5437 // unwrap references here and rewrap them afterwards. 5438 // We also need to create a InitializeTemporary entity for this. 5439 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type; 5440 bool IsTemporary = Entity.getType()->isReferenceType(); 5441 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 5442 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; 5443 InitListChecker PerformInitList(S, InitEntity, 5444 InitList, Ty, /*VerifyOnly=*/false, 5445 Kind.getKind() != InitializationKind::IK_DirectList || 5446 !S.getLangOpts().CPlusPlus11); 5447 if (PerformInitList.HadError()) 5448 return ExprError(); 5449 5450 if (ResultType) { 5451 if ((*ResultType)->isRValueReferenceType()) 5452 Ty = S.Context.getRValueReferenceType(Ty); 5453 else if ((*ResultType)->isLValueReferenceType()) 5454 Ty = S.Context.getLValueReferenceType(Ty, 5455 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue()); 5456 *ResultType = Ty; 5457 } 5458 5459 InitListExpr *StructuredInitList = 5460 PerformInitList.getFullyStructuredList(); 5461 CurInit.release(); 5462 CurInit = shouldBindAsTemporary(InitEntity) 5463 ? S.MaybeBindToTemporary(StructuredInitList) 5464 : S.Owned(StructuredInitList); 5465 break; 5466 } 5467 5468 case SK_ListConstructorCall: { 5469 // When an initializer list is passed for a parameter of type "reference 5470 // to object", we don't get an EK_Temporary entity, but instead an 5471 // EK_Parameter entity with reference type. 5472 // FIXME: This is a hack. What we really should do is create a user 5473 // conversion step for this case, but this makes it considerably more 5474 // complicated. For now, this will do. 5475 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 5476 Entity.getType().getNonReferenceType()); 5477 bool UseTemporary = Entity.getType()->isReferenceType(); 5478 assert(Args.size() == 1 && "expected a single argument for list init"); 5479 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 5480 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) 5481 << InitList->getSourceRange(); 5482 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 5483 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : 5484 Entity, 5485 Kind, Arg, *Step, 5486 ConstructorInitRequiresZeroInit, 5487 /*IsListInitialization*/ true); 5488 break; 5489 } 5490 5491 case SK_UnwrapInitList: 5492 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0)); 5493 break; 5494 5495 case SK_RewrapInitList: { 5496 Expr *E = CurInit.take(); 5497 InitListExpr *Syntactic = Step->WrappingSyntacticList; 5498 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 5499 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); 5500 ILE->setSyntacticForm(Syntactic); 5501 ILE->setType(E->getType()); 5502 ILE->setValueKind(E->getValueKind()); 5503 CurInit = S.Owned(ILE); 5504 break; 5505 } 5506 5507 case SK_ConstructorInitialization: { 5508 // When an initializer list is passed for a parameter of type "reference 5509 // to object", we don't get an EK_Temporary entity, but instead an 5510 // EK_Parameter entity with reference type. 5511 // FIXME: This is a hack. What we really should do is create a user 5512 // conversion step for this case, but this makes it considerably more 5513 // complicated. For now, this will do. 5514 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 5515 Entity.getType().getNonReferenceType()); 5516 bool UseTemporary = Entity.getType()->isReferenceType(); 5517 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity 5518 : Entity, 5519 Kind, Args, *Step, 5520 ConstructorInitRequiresZeroInit, 5521 /*IsListInitialization*/ false); 5522 break; 5523 } 5524 5525 case SK_ZeroInitialization: { 5526 step_iterator NextStep = Step; 5527 ++NextStep; 5528 if (NextStep != StepEnd && 5529 (NextStep->Kind == SK_ConstructorInitialization || 5530 NextStep->Kind == SK_ListConstructorCall)) { 5531 // The need for zero-initialization is recorded directly into 5532 // the call to the object's constructor within the next step. 5533 ConstructorInitRequiresZeroInit = true; 5534 } else if (Kind.getKind() == InitializationKind::IK_Value && 5535 S.getLangOpts().CPlusPlus && 5536 !Kind.isImplicitValueInit()) { 5537 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 5538 if (!TSInfo) 5539 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 5540 Kind.getRange().getBegin()); 5541 5542 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr( 5543 TSInfo->getType().getNonLValueExprType(S.Context), 5544 TSInfo, 5545 Kind.getRange().getEnd())); 5546 } else { 5547 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 5548 } 5549 break; 5550 } 5551 5552 case SK_CAssignment: { 5553 QualType SourceType = CurInit.get()->getType(); 5554 ExprResult Result = CurInit; 5555 Sema::AssignConvertType ConvTy = 5556 S.CheckSingleAssignmentConstraints(Step->Type, Result); 5557 if (Result.isInvalid()) 5558 return ExprError(); 5559 CurInit = Result; 5560 5561 // If this is a call, allow conversion to a transparent union. 5562 ExprResult CurInitExprRes = CurInit; 5563 if (ConvTy != Sema::Compatible && 5564 Entity.getKind() == InitializedEntity::EK_Parameter && 5565 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 5566 == Sema::Compatible) 5567 ConvTy = Sema::Compatible; 5568 if (CurInitExprRes.isInvalid()) 5569 return ExprError(); 5570 CurInit = CurInitExprRes; 5571 5572 bool Complained; 5573 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 5574 Step->Type, SourceType, 5575 CurInit.get(), 5576 getAssignmentAction(Entity), 5577 &Complained)) { 5578 PrintInitLocationNote(S, Entity); 5579 return ExprError(); 5580 } else if (Complained) 5581 PrintInitLocationNote(S, Entity); 5582 break; 5583 } 5584 5585 case SK_StringInit: { 5586 QualType Ty = Step->Type; 5587 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, 5588 S.Context.getAsArrayType(Ty), S); 5589 break; 5590 } 5591 5592 case SK_ObjCObjectConversion: 5593 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, 5594 CK_ObjCObjectLValueCast, 5595 CurInit.get()->getValueKind()); 5596 break; 5597 5598 case SK_ArrayInit: 5599 // Okay: we checked everything before creating this step. Note that 5600 // this is a GNU extension. 5601 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 5602 << Step->Type << CurInit.get()->getType() 5603 << CurInit.get()->getSourceRange(); 5604 5605 // If the destination type is an incomplete array type, update the 5606 // type accordingly. 5607 if (ResultType) { 5608 if (const IncompleteArrayType *IncompleteDest 5609 = S.Context.getAsIncompleteArrayType(Step->Type)) { 5610 if (const ConstantArrayType *ConstantSource 5611 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 5612 *ResultType = S.Context.getConstantArrayType( 5613 IncompleteDest->getElementType(), 5614 ConstantSource->getSize(), 5615 ArrayType::Normal, 0); 5616 } 5617 } 5618 } 5619 break; 5620 5621 case SK_ParenthesizedArrayInit: 5622 // Okay: we checked everything before creating this step. Note that 5623 // this is a GNU extension. 5624 S.Diag(Kind.getLocation(), diag::ext_array_init_parens) 5625 << CurInit.get()->getSourceRange(); 5626 break; 5627 5628 case SK_PassByIndirectCopyRestore: 5629 case SK_PassByIndirectRestore: 5630 checkIndirectCopyRestoreSource(S, CurInit.get()); 5631 CurInit = S.Owned(new (S.Context) 5632 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type, 5633 Step->Kind == SK_PassByIndirectCopyRestore)); 5634 break; 5635 5636 case SK_ProduceObjCObject: 5637 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type, 5638 CK_ARCProduceObject, 5639 CurInit.take(), 0, VK_RValue)); 5640 break; 5641 5642 case SK_StdInitializerList: { 5643 QualType Dest = Step->Type; 5644 QualType E; 5645 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E); 5646 (void)Success; 5647 assert(Success && "Destination type changed?"); 5648 5649 // If the element type has a destructor, check it. 5650 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) { 5651 if (!RD->hasIrrelevantDestructor()) { 5652 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) { 5653 S.MarkFunctionReferenced(Kind.getLocation(), Destructor); 5654 S.CheckDestructorAccess(Kind.getLocation(), Destructor, 5655 S.PDiag(diag::err_access_dtor_temp) << E); 5656 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation())) 5657 return ExprError(); 5658 } 5659 } 5660 } 5661 5662 InitListExpr *ILE = cast<InitListExpr>(CurInit.take()); 5663 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init) 5664 << ILE->getSourceRange(); 5665 unsigned NumInits = ILE->getNumInits(); 5666 SmallVector<Expr*, 16> Converted(NumInits); 5667 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary( 5668 S.Context.getConstantArrayType(E, 5669 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 5670 NumInits), 5671 ArrayType::Normal, 0)); 5672 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context, 5673 0, HiddenArray); 5674 for (unsigned i = 0; i < NumInits; ++i) { 5675 Element.setElementIndex(i); 5676 ExprResult Init = S.Owned(ILE->getInit(i)); 5677 ExprResult Res = S.PerformCopyInitialization( 5678 Element, Init.get()->getExprLoc(), Init, 5679 /*TopLevelOfInitList=*/ true); 5680 assert(!Res.isInvalid() && "Result changed since try phase."); 5681 Converted[i] = Res.take(); 5682 } 5683 InitListExpr *Semantic = new (S.Context) 5684 InitListExpr(S.Context, ILE->getLBraceLoc(), 5685 Converted, ILE->getRBraceLoc()); 5686 Semantic->setSyntacticForm(ILE); 5687 Semantic->setType(Dest); 5688 Semantic->setInitializesStdInitializerList(); 5689 CurInit = S.Owned(Semantic); 5690 break; 5691 } 5692 case SK_OCLSamplerInit: { 5693 assert(Step->Type->isSamplerT() && 5694 "Sampler initialization on non sampler type."); 5695 5696 QualType SourceType = CurInit.get()->getType(); 5697 InitializedEntity::EntityKind EntityKind = Entity.getKind(); 5698 5699 if (EntityKind == InitializedEntity::EK_Parameter) { 5700 if (!SourceType->isSamplerT()) 5701 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) 5702 << SourceType; 5703 } else if (EntityKind != InitializedEntity::EK_Variable) { 5704 llvm_unreachable("Invalid EntityKind!"); 5705 } 5706 5707 break; 5708 } 5709 case SK_OCLZeroEvent: { 5710 assert(Step->Type->isEventT() && 5711 "Event initialization on non event type."); 5712 5713 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, 5714 CK_ZeroToOCLEvent, 5715 CurInit.get()->getValueKind()); 5716 break; 5717 } 5718 } 5719 } 5720 5721 // Diagnose non-fatal problems with the completed initialization. 5722 if (Entity.getKind() == InitializedEntity::EK_Member && 5723 cast<FieldDecl>(Entity.getDecl())->isBitField()) 5724 S.CheckBitFieldInitialization(Kind.getLocation(), 5725 cast<FieldDecl>(Entity.getDecl()), 5726 CurInit.get()); 5727 5728 return CurInit; 5729} 5730 5731/// Somewhere within T there is an uninitialized reference subobject. 5732/// Dig it out and diagnose it. 5733static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, 5734 QualType T) { 5735 if (T->isReferenceType()) { 5736 S.Diag(Loc, diag::err_reference_without_init) 5737 << T.getNonReferenceType(); 5738 return true; 5739 } 5740 5741 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5742 if (!RD || !RD->hasUninitializedReferenceMember()) 5743 return false; 5744 5745 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5746 FE = RD->field_end(); FI != FE; ++FI) { 5747 if (FI->isUnnamedBitfield()) 5748 continue; 5749 5750 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { 5751 S.Diag(Loc, diag::note_value_initialization_here) << RD; 5752 return true; 5753 } 5754 } 5755 5756 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5757 BE = RD->bases_end(); 5758 BI != BE; ++BI) { 5759 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) { 5760 S.Diag(Loc, diag::note_value_initialization_here) << RD; 5761 return true; 5762 } 5763 } 5764 5765 return false; 5766} 5767 5768 5769//===----------------------------------------------------------------------===// 5770// Diagnose initialization failures 5771//===----------------------------------------------------------------------===// 5772 5773/// Emit notes associated with an initialization that failed due to a 5774/// "simple" conversion failure. 5775static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, 5776 Expr *op) { 5777 QualType destType = entity.getType(); 5778 if (destType.getNonReferenceType()->isObjCObjectPointerType() && 5779 op->getType()->isObjCObjectPointerType()) { 5780 5781 // Emit a possible note about the conversion failing because the 5782 // operand is a message send with a related result type. 5783 S.EmitRelatedResultTypeNote(op); 5784 5785 // Emit a possible note about a return failing because we're 5786 // expecting a related result type. 5787 if (entity.getKind() == InitializedEntity::EK_Result) 5788 S.EmitRelatedResultTypeNoteForReturn(destType); 5789 } 5790} 5791 5792bool InitializationSequence::Diagnose(Sema &S, 5793 const InitializedEntity &Entity, 5794 const InitializationKind &Kind, 5795 ArrayRef<Expr *> Args) { 5796 if (!Failed()) 5797 return false; 5798 5799 QualType DestType = Entity.getType(); 5800 switch (Failure) { 5801 case FK_TooManyInitsForReference: 5802 // FIXME: Customize for the initialized entity? 5803 if (Args.empty()) { 5804 // Dig out the reference subobject which is uninitialized and diagnose it. 5805 // If this is value-initialization, this could be nested some way within 5806 // the target type. 5807 assert(Kind.getKind() == InitializationKind::IK_Value || 5808 DestType->isReferenceType()); 5809 bool Diagnosed = 5810 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); 5811 assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); 5812 (void)Diagnosed; 5813 } else // FIXME: diagnostic below could be better! 5814 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 5815 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd()); 5816 break; 5817 5818 case FK_ArrayNeedsInitList: 5819 case FK_ArrayNeedsInitListOrStringLiteral: 5820 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 5821 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 5822 break; 5823 5824 case FK_ArrayTypeMismatch: 5825 case FK_NonConstantArrayInit: 5826 S.Diag(Kind.getLocation(), 5827 (Failure == FK_ArrayTypeMismatch 5828 ? diag::err_array_init_different_type 5829 : diag::err_array_init_non_constant_array)) 5830 << DestType.getNonReferenceType() 5831 << Args[0]->getType() 5832 << Args[0]->getSourceRange(); 5833 break; 5834 5835 case FK_VariableLengthArrayHasInitializer: 5836 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 5837 << Args[0]->getSourceRange(); 5838 break; 5839 5840 case FK_AddressOfOverloadFailed: { 5841 DeclAccessPair Found; 5842 S.ResolveAddressOfOverloadedFunction(Args[0], 5843 DestType.getNonReferenceType(), 5844 true, 5845 Found); 5846 break; 5847 } 5848 5849 case FK_ReferenceInitOverloadFailed: 5850 case FK_UserConversionOverloadFailed: 5851 switch (FailedOverloadResult) { 5852 case OR_Ambiguous: 5853 if (Failure == FK_UserConversionOverloadFailed) 5854 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 5855 << Args[0]->getType() << DestType 5856 << Args[0]->getSourceRange(); 5857 else 5858 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 5859 << DestType << Args[0]->getType() 5860 << Args[0]->getSourceRange(); 5861 5862 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); 5863 break; 5864 5865 case OR_No_Viable_Function: 5866 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 5867 << Args[0]->getType() << DestType.getNonReferenceType() 5868 << Args[0]->getSourceRange(); 5869 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); 5870 break; 5871 5872 case OR_Deleted: { 5873 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 5874 << Args[0]->getType() << DestType.getNonReferenceType() 5875 << Args[0]->getSourceRange(); 5876 OverloadCandidateSet::iterator Best; 5877 OverloadingResult Ovl 5878 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, 5879 true); 5880 if (Ovl == OR_Deleted) { 5881 S.NoteDeletedFunction(Best->Function); 5882 } else { 5883 llvm_unreachable("Inconsistent overload resolution?"); 5884 } 5885 break; 5886 } 5887 5888 case OR_Success: 5889 llvm_unreachable("Conversion did not fail!"); 5890 } 5891 break; 5892 5893 case FK_NonConstLValueReferenceBindingToTemporary: 5894 if (isa<InitListExpr>(Args[0])) { 5895 S.Diag(Kind.getLocation(), 5896 diag::err_lvalue_reference_bind_to_initlist) 5897 << DestType.getNonReferenceType().isVolatileQualified() 5898 << DestType.getNonReferenceType() 5899 << Args[0]->getSourceRange(); 5900 break; 5901 } 5902 // Intentional fallthrough 5903 5904 case FK_NonConstLValueReferenceBindingToUnrelated: 5905 S.Diag(Kind.getLocation(), 5906 Failure == FK_NonConstLValueReferenceBindingToTemporary 5907 ? diag::err_lvalue_reference_bind_to_temporary 5908 : diag::err_lvalue_reference_bind_to_unrelated) 5909 << DestType.getNonReferenceType().isVolatileQualified() 5910 << DestType.getNonReferenceType() 5911 << Args[0]->getType() 5912 << Args[0]->getSourceRange(); 5913 break; 5914 5915 case FK_RValueReferenceBindingToLValue: 5916 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 5917 << DestType.getNonReferenceType() << Args[0]->getType() 5918 << Args[0]->getSourceRange(); 5919 break; 5920 5921 case FK_ReferenceInitDropsQualifiers: 5922 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 5923 << DestType.getNonReferenceType() 5924 << Args[0]->getType() 5925 << Args[0]->getSourceRange(); 5926 break; 5927 5928 case FK_ReferenceInitFailed: 5929 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 5930 << DestType.getNonReferenceType() 5931 << Args[0]->isLValue() 5932 << Args[0]->getType() 5933 << Args[0]->getSourceRange(); 5934 emitBadConversionNotes(S, Entity, Args[0]); 5935 break; 5936 5937 case FK_ConversionFailed: { 5938 QualType FromType = Args[0]->getType(); 5939 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 5940 << (int)Entity.getKind() 5941 << DestType 5942 << Args[0]->isLValue() 5943 << FromType 5944 << Args[0]->getSourceRange(); 5945 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 5946 S.Diag(Kind.getLocation(), PDiag); 5947 emitBadConversionNotes(S, Entity, Args[0]); 5948 break; 5949 } 5950 5951 case FK_ConversionFromPropertyFailed: 5952 // No-op. This error has already been reported. 5953 break; 5954 5955 case FK_TooManyInitsForScalar: { 5956 SourceRange R; 5957 5958 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 5959 R = SourceRange(InitList->getInit(0)->getLocEnd(), 5960 InitList->getLocEnd()); 5961 else 5962 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd()); 5963 5964 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin())); 5965 if (Kind.isCStyleOrFunctionalCast()) 5966 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 5967 << R; 5968 else 5969 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 5970 << /*scalar=*/2 << R; 5971 break; 5972 } 5973 5974 case FK_ReferenceBindingToInitList: 5975 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 5976 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 5977 break; 5978 5979 case FK_InitListBadDestinationType: 5980 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 5981 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 5982 break; 5983 5984 case FK_ListConstructorOverloadFailed: 5985 case FK_ConstructorOverloadFailed: { 5986 SourceRange ArgsRange; 5987 if (Args.size()) 5988 ArgsRange = SourceRange(Args.front()->getLocStart(), 5989 Args.back()->getLocEnd()); 5990 5991 if (Failure == FK_ListConstructorOverloadFailed) { 5992 assert(Args.size() == 1 && "List construction from other than 1 argument."); 5993 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 5994 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 5995 } 5996 5997 // FIXME: Using "DestType" for the entity we're printing is probably 5998 // bad. 5999 switch (FailedOverloadResult) { 6000 case OR_Ambiguous: 6001 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 6002 << DestType << ArgsRange; 6003 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); 6004 break; 6005 6006 case OR_No_Viable_Function: 6007 if (Kind.getKind() == InitializationKind::IK_Default && 6008 (Entity.getKind() == InitializedEntity::EK_Base || 6009 Entity.getKind() == InitializedEntity::EK_Member) && 6010 isa<CXXConstructorDecl>(S.CurContext)) { 6011 // This is implicit default initialization of a member or 6012 // base within a constructor. If no viable function was 6013 // found, notify the user that she needs to explicitly 6014 // initialize this base/member. 6015 CXXConstructorDecl *Constructor 6016 = cast<CXXConstructorDecl>(S.CurContext); 6017 if (Entity.getKind() == InitializedEntity::EK_Base) { 6018 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 6019 << (Constructor->getInheritedConstructor() ? 2 : 6020 Constructor->isImplicit() ? 1 : 0) 6021 << S.Context.getTypeDeclType(Constructor->getParent()) 6022 << /*base=*/0 6023 << Entity.getType(); 6024 6025 RecordDecl *BaseDecl 6026 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 6027 ->getDecl(); 6028 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 6029 << S.Context.getTagDeclType(BaseDecl); 6030 } else { 6031 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 6032 << (Constructor->getInheritedConstructor() ? 2 : 6033 Constructor->isImplicit() ? 1 : 0) 6034 << S.Context.getTypeDeclType(Constructor->getParent()) 6035 << /*member=*/1 6036 << Entity.getName(); 6037 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl); 6038 6039 if (const RecordType *Record 6040 = Entity.getType()->getAs<RecordType>()) 6041 S.Diag(Record->getDecl()->getLocation(), 6042 diag::note_previous_decl) 6043 << S.Context.getTagDeclType(Record->getDecl()); 6044 } 6045 break; 6046 } 6047 6048 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 6049 << DestType << ArgsRange; 6050 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); 6051 break; 6052 6053 case OR_Deleted: { 6054 OverloadCandidateSet::iterator Best; 6055 OverloadingResult Ovl 6056 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 6057 if (Ovl != OR_Deleted) { 6058 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 6059 << true << DestType << ArgsRange; 6060 llvm_unreachable("Inconsistent overload resolution?"); 6061 break; 6062 } 6063 6064 // If this is a defaulted or implicitly-declared function, then 6065 // it was implicitly deleted. Make it clear that the deletion was 6066 // implicit. 6067 if (S.isImplicitlyDeleted(Best->Function)) 6068 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) 6069 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) 6070 << DestType << ArgsRange; 6071 else 6072 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 6073 << true << DestType << ArgsRange; 6074 6075 S.NoteDeletedFunction(Best->Function); 6076 break; 6077 } 6078 6079 case OR_Success: 6080 llvm_unreachable("Conversion did not fail!"); 6081 } 6082 } 6083 break; 6084 6085 case FK_DefaultInitOfConst: 6086 if (Entity.getKind() == InitializedEntity::EK_Member && 6087 isa<CXXConstructorDecl>(S.CurContext)) { 6088 // This is implicit default-initialization of a const member in 6089 // a constructor. Complain that it needs to be explicitly 6090 // initialized. 6091 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 6092 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 6093 << (Constructor->getInheritedConstructor() ? 2 : 6094 Constructor->isImplicit() ? 1 : 0) 6095 << S.Context.getTypeDeclType(Constructor->getParent()) 6096 << /*const=*/1 6097 << Entity.getName(); 6098 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 6099 << Entity.getName(); 6100 } else { 6101 S.Diag(Kind.getLocation(), diag::err_default_init_const) 6102 << DestType << (bool)DestType->getAs<RecordType>(); 6103 } 6104 break; 6105 6106 case FK_Incomplete: 6107 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, 6108 diag::err_init_incomplete_type); 6109 break; 6110 6111 case FK_ListInitializationFailed: { 6112 // Run the init list checker again to emit diagnostics. 6113 InitListExpr* InitList = cast<InitListExpr>(Args[0]); 6114 QualType DestType = Entity.getType(); 6115 InitListChecker DiagnoseInitList(S, Entity, InitList, 6116 DestType, /*VerifyOnly=*/false, 6117 Kind.getKind() != InitializationKind::IK_DirectList || 6118 !S.getLangOpts().CPlusPlus11); 6119 assert(DiagnoseInitList.HadError() && 6120 "Inconsistent init list check result."); 6121 break; 6122 } 6123 6124 case FK_PlaceholderType: { 6125 // FIXME: Already diagnosed! 6126 break; 6127 } 6128 6129 case FK_InitListElementCopyFailure: { 6130 // Try to perform all copies again. 6131 InitListExpr* InitList = cast<InitListExpr>(Args[0]); 6132 unsigned NumInits = InitList->getNumInits(); 6133 QualType DestType = Entity.getType(); 6134 QualType E; 6135 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E); 6136 (void)Success; 6137 assert(Success && "Where did the std::initializer_list go?"); 6138 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary( 6139 S.Context.getConstantArrayType(E, 6140 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 6141 NumInits), 6142 ArrayType::Normal, 0)); 6143 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context, 6144 0, HiddenArray); 6145 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors 6146 // where the init list type is wrong, e.g. 6147 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 }; 6148 // FIXME: Emit a note if we hit the limit? 6149 int ErrorCount = 0; 6150 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) { 6151 Element.setElementIndex(i); 6152 ExprResult Init = S.Owned(InitList->getInit(i)); 6153 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init) 6154 .isInvalid()) 6155 ++ErrorCount; 6156 } 6157 break; 6158 } 6159 6160 case FK_ExplicitConstructor: { 6161 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) 6162 << Args[0]->getSourceRange(); 6163 OverloadCandidateSet::iterator Best; 6164 OverloadingResult Ovl 6165 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 6166 (void)Ovl; 6167 assert(Ovl == OR_Success && "Inconsistent overload resolution"); 6168 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 6169 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here); 6170 break; 6171 } 6172 } 6173 6174 PrintInitLocationNote(S, Entity); 6175 return true; 6176} 6177 6178void InitializationSequence::dump(raw_ostream &OS) const { 6179 switch (SequenceKind) { 6180 case FailedSequence: { 6181 OS << "Failed sequence: "; 6182 switch (Failure) { 6183 case FK_TooManyInitsForReference: 6184 OS << "too many initializers for reference"; 6185 break; 6186 6187 case FK_ArrayNeedsInitList: 6188 OS << "array requires initializer list"; 6189 break; 6190 6191 case FK_ArrayNeedsInitListOrStringLiteral: 6192 OS << "array requires initializer list or string literal"; 6193 break; 6194 6195 case FK_ArrayTypeMismatch: 6196 OS << "array type mismatch"; 6197 break; 6198 6199 case FK_NonConstantArrayInit: 6200 OS << "non-constant array initializer"; 6201 break; 6202 6203 case FK_AddressOfOverloadFailed: 6204 OS << "address of overloaded function failed"; 6205 break; 6206 6207 case FK_ReferenceInitOverloadFailed: 6208 OS << "overload resolution for reference initialization failed"; 6209 break; 6210 6211 case FK_NonConstLValueReferenceBindingToTemporary: 6212 OS << "non-const lvalue reference bound to temporary"; 6213 break; 6214 6215 case FK_NonConstLValueReferenceBindingToUnrelated: 6216 OS << "non-const lvalue reference bound to unrelated type"; 6217 break; 6218 6219 case FK_RValueReferenceBindingToLValue: 6220 OS << "rvalue reference bound to an lvalue"; 6221 break; 6222 6223 case FK_ReferenceInitDropsQualifiers: 6224 OS << "reference initialization drops qualifiers"; 6225 break; 6226 6227 case FK_ReferenceInitFailed: 6228 OS << "reference initialization failed"; 6229 break; 6230 6231 case FK_ConversionFailed: 6232 OS << "conversion failed"; 6233 break; 6234 6235 case FK_ConversionFromPropertyFailed: 6236 OS << "conversion from property failed"; 6237 break; 6238 6239 case FK_TooManyInitsForScalar: 6240 OS << "too many initializers for scalar"; 6241 break; 6242 6243 case FK_ReferenceBindingToInitList: 6244 OS << "referencing binding to initializer list"; 6245 break; 6246 6247 case FK_InitListBadDestinationType: 6248 OS << "initializer list for non-aggregate, non-scalar type"; 6249 break; 6250 6251 case FK_UserConversionOverloadFailed: 6252 OS << "overloading failed for user-defined conversion"; 6253 break; 6254 6255 case FK_ConstructorOverloadFailed: 6256 OS << "constructor overloading failed"; 6257 break; 6258 6259 case FK_DefaultInitOfConst: 6260 OS << "default initialization of a const variable"; 6261 break; 6262 6263 case FK_Incomplete: 6264 OS << "initialization of incomplete type"; 6265 break; 6266 6267 case FK_ListInitializationFailed: 6268 OS << "list initialization checker failure"; 6269 break; 6270 6271 case FK_VariableLengthArrayHasInitializer: 6272 OS << "variable length array has an initializer"; 6273 break; 6274 6275 case FK_PlaceholderType: 6276 OS << "initializer expression isn't contextually valid"; 6277 break; 6278 6279 case FK_ListConstructorOverloadFailed: 6280 OS << "list constructor overloading failed"; 6281 break; 6282 6283 case FK_InitListElementCopyFailure: 6284 OS << "copy construction of initializer list element failed"; 6285 break; 6286 6287 case FK_ExplicitConstructor: 6288 OS << "list copy initialization chose explicit constructor"; 6289 break; 6290 } 6291 OS << '\n'; 6292 return; 6293 } 6294 6295 case DependentSequence: 6296 OS << "Dependent sequence\n"; 6297 return; 6298 6299 case NormalSequence: 6300 OS << "Normal sequence: "; 6301 break; 6302 } 6303 6304 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 6305 if (S != step_begin()) { 6306 OS << " -> "; 6307 } 6308 6309 switch (S->Kind) { 6310 case SK_ResolveAddressOfOverloadedFunction: 6311 OS << "resolve address of overloaded function"; 6312 break; 6313 6314 case SK_CastDerivedToBaseRValue: 6315 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 6316 break; 6317 6318 case SK_CastDerivedToBaseXValue: 6319 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 6320 break; 6321 6322 case SK_CastDerivedToBaseLValue: 6323 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 6324 break; 6325 6326 case SK_BindReference: 6327 OS << "bind reference to lvalue"; 6328 break; 6329 6330 case SK_BindReferenceToTemporary: 6331 OS << "bind reference to a temporary"; 6332 break; 6333 6334 case SK_ExtraneousCopyToTemporary: 6335 OS << "extraneous C++03 copy to temporary"; 6336 break; 6337 6338 case SK_UserConversion: 6339 OS << "user-defined conversion via " << *S->Function.Function; 6340 break; 6341 6342 case SK_QualificationConversionRValue: 6343 OS << "qualification conversion (rvalue)"; 6344 break; 6345 6346 case SK_QualificationConversionXValue: 6347 OS << "qualification conversion (xvalue)"; 6348 break; 6349 6350 case SK_QualificationConversionLValue: 6351 OS << "qualification conversion (lvalue)"; 6352 break; 6353 6354 case SK_LValueToRValue: 6355 OS << "load (lvalue to rvalue)"; 6356 break; 6357 6358 case SK_ConversionSequence: 6359 OS << "implicit conversion sequence ("; 6360 S->ICS->DebugPrint(); // FIXME: use OS 6361 OS << ")"; 6362 break; 6363 6364 case SK_ListInitialization: 6365 OS << "list aggregate initialization"; 6366 break; 6367 6368 case SK_ListConstructorCall: 6369 OS << "list initialization via constructor"; 6370 break; 6371 6372 case SK_UnwrapInitList: 6373 OS << "unwrap reference initializer list"; 6374 break; 6375 6376 case SK_RewrapInitList: 6377 OS << "rewrap reference initializer list"; 6378 break; 6379 6380 case SK_ConstructorInitialization: 6381 OS << "constructor initialization"; 6382 break; 6383 6384 case SK_ZeroInitialization: 6385 OS << "zero initialization"; 6386 break; 6387 6388 case SK_CAssignment: 6389 OS << "C assignment"; 6390 break; 6391 6392 case SK_StringInit: 6393 OS << "string initialization"; 6394 break; 6395 6396 case SK_ObjCObjectConversion: 6397 OS << "Objective-C object conversion"; 6398 break; 6399 6400 case SK_ArrayInit: 6401 OS << "array initialization"; 6402 break; 6403 6404 case SK_ParenthesizedArrayInit: 6405 OS << "parenthesized array initialization"; 6406 break; 6407 6408 case SK_PassByIndirectCopyRestore: 6409 OS << "pass by indirect copy and restore"; 6410 break; 6411 6412 case SK_PassByIndirectRestore: 6413 OS << "pass by indirect restore"; 6414 break; 6415 6416 case SK_ProduceObjCObject: 6417 OS << "Objective-C object retension"; 6418 break; 6419 6420 case SK_StdInitializerList: 6421 OS << "std::initializer_list from initializer list"; 6422 break; 6423 6424 case SK_OCLSamplerInit: 6425 OS << "OpenCL sampler_t from integer constant"; 6426 break; 6427 6428 case SK_OCLZeroEvent: 6429 OS << "OpenCL event_t from zero"; 6430 break; 6431 } 6432 6433 OS << " [" << S->Type.getAsString() << ']'; 6434 } 6435 6436 OS << '\n'; 6437} 6438 6439void InitializationSequence::dump() const { 6440 dump(llvm::errs()); 6441} 6442 6443static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq, 6444 QualType EntityType, 6445 const Expr *PreInit, 6446 const Expr *PostInit) { 6447 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent()) 6448 return; 6449 6450 // A narrowing conversion can only appear as the final implicit conversion in 6451 // an initialization sequence. 6452 const InitializationSequence::Step &LastStep = Seq.step_end()[-1]; 6453 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence) 6454 return; 6455 6456 const ImplicitConversionSequence &ICS = *LastStep.ICS; 6457 const StandardConversionSequence *SCS = 0; 6458 switch (ICS.getKind()) { 6459 case ImplicitConversionSequence::StandardConversion: 6460 SCS = &ICS.Standard; 6461 break; 6462 case ImplicitConversionSequence::UserDefinedConversion: 6463 SCS = &ICS.UserDefined.After; 6464 break; 6465 case ImplicitConversionSequence::AmbiguousConversion: 6466 case ImplicitConversionSequence::EllipsisConversion: 6467 case ImplicitConversionSequence::BadConversion: 6468 return; 6469 } 6470 6471 // Determine the type prior to the narrowing conversion. If a conversion 6472 // operator was used, this may be different from both the type of the entity 6473 // and of the pre-initialization expression. 6474 QualType PreNarrowingType = PreInit->getType(); 6475 if (Seq.step_begin() + 1 != Seq.step_end()) 6476 PreNarrowingType = Seq.step_end()[-2].Type; 6477 6478 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. 6479 APValue ConstantValue; 6480 QualType ConstantType; 6481 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, 6482 ConstantType)) { 6483 case NK_Not_Narrowing: 6484 // No narrowing occurred. 6485 return; 6486 6487 case NK_Type_Narrowing: 6488 // This was a floating-to-integer conversion, which is always considered a 6489 // narrowing conversion even if the value is a constant and can be 6490 // represented exactly as an integer. 6491 S.Diag(PostInit->getLocStart(), 6492 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11? 6493 diag::warn_init_list_type_narrowing 6494 : S.isSFINAEContext()? 6495 diag::err_init_list_type_narrowing_sfinae 6496 : diag::err_init_list_type_narrowing) 6497 << PostInit->getSourceRange() 6498 << PreNarrowingType.getLocalUnqualifiedType() 6499 << EntityType.getLocalUnqualifiedType(); 6500 break; 6501 6502 case NK_Constant_Narrowing: 6503 // A constant value was narrowed. 6504 S.Diag(PostInit->getLocStart(), 6505 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11? 6506 diag::warn_init_list_constant_narrowing 6507 : S.isSFINAEContext()? 6508 diag::err_init_list_constant_narrowing_sfinae 6509 : diag::err_init_list_constant_narrowing) 6510 << PostInit->getSourceRange() 6511 << ConstantValue.getAsString(S.getASTContext(), ConstantType) 6512 << EntityType.getLocalUnqualifiedType(); 6513 break; 6514 6515 case NK_Variable_Narrowing: 6516 // A variable's value may have been narrowed. 6517 S.Diag(PostInit->getLocStart(), 6518 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11? 6519 diag::warn_init_list_variable_narrowing 6520 : S.isSFINAEContext()? 6521 diag::err_init_list_variable_narrowing_sfinae 6522 : diag::err_init_list_variable_narrowing) 6523 << PostInit->getSourceRange() 6524 << PreNarrowingType.getLocalUnqualifiedType() 6525 << EntityType.getLocalUnqualifiedType(); 6526 break; 6527 } 6528 6529 SmallString<128> StaticCast; 6530 llvm::raw_svector_ostream OS(StaticCast); 6531 OS << "static_cast<"; 6532 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 6533 // It's important to use the typedef's name if there is one so that the 6534 // fixit doesn't break code using types like int64_t. 6535 // 6536 // FIXME: This will break if the typedef requires qualification. But 6537 // getQualifiedNameAsString() includes non-machine-parsable components. 6538 OS << *TT->getDecl(); 6539 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 6540 OS << BT->getName(S.getLangOpts()); 6541 else { 6542 // Oops, we didn't find the actual type of the variable. Don't emit a fixit 6543 // with a broken cast. 6544 return; 6545 } 6546 OS << ">("; 6547 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override) 6548 << PostInit->getSourceRange() 6549 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str()) 6550 << FixItHint::CreateInsertion( 6551 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")"); 6552} 6553 6554//===----------------------------------------------------------------------===// 6555// Initialization helper functions 6556//===----------------------------------------------------------------------===// 6557bool 6558Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 6559 ExprResult Init) { 6560 if (Init.isInvalid()) 6561 return false; 6562 6563 Expr *InitE = Init.get(); 6564 assert(InitE && "No initialization expression"); 6565 6566 InitializationKind Kind 6567 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation()); 6568 InitializationSequence Seq(*this, Entity, Kind, InitE); 6569 return !Seq.Failed(); 6570} 6571 6572ExprResult 6573Sema::PerformCopyInitialization(const InitializedEntity &Entity, 6574 SourceLocation EqualLoc, 6575 ExprResult Init, 6576 bool TopLevelOfInitList, 6577 bool AllowExplicit) { 6578 if (Init.isInvalid()) 6579 return ExprError(); 6580 6581 Expr *InitE = Init.get(); 6582 assert(InitE && "No initialization expression?"); 6583 6584 if (EqualLoc.isInvalid()) 6585 EqualLoc = InitE->getLocStart(); 6586 6587 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 6588 EqualLoc, 6589 AllowExplicit); 6590 InitializationSequence Seq(*this, Entity, Kind, InitE); 6591 Init.release(); 6592 6593 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); 6594 6595 if (!Result.isInvalid() && TopLevelOfInitList) 6596 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(), 6597 InitE, Result.get()); 6598 6599 return Result; 6600} 6601