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