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