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