SemaInit.cpp revision 856d3798af7c2f7251e4a295f3da7a09ce4c62ab
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 InitializedEntity MemberEntity = 1188 InitializedEntity::InitializeMember(*Field, &Entity); 1189 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1190 StructuredList, StructuredIndex); 1191 InitializedSomething = true; 1192 1193 if (DeclType->isUnionType()) { 1194 // Initialize the first field within the union. 1195 StructuredList->setInitializedFieldInUnion(*Field); 1196 } 1197 1198 ++Field; 1199 } 1200 1201 // Emit warnings for missing struct field initializers. 1202 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd && 1203 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) { 1204 // It is possible we have one or more unnamed bitfields remaining. 1205 // Find first (if any) named field and emit warning. 1206 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 1207 it != end; ++it) { 1208 if (!it->isUnnamedBitfield()) { 1209 SemaRef.Diag(IList->getSourceRange().getEnd(), 1210 diag::warn_missing_field_initializers) << it->getName(); 1211 break; 1212 } 1213 } 1214 } 1215 1216 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1217 Index >= IList->getNumInits()) 1218 return; 1219 1220 // Handle GNU flexible array initializers. 1221 if (!TopLevelObject && 1222 (!isa<InitListExpr>(IList->getInit(Index)) || 1223 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1224 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1225 diag::err_flexible_array_init_nonempty) 1226 << IList->getInit(Index)->getSourceRange().getBegin(); 1227 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1228 << *Field; 1229 hadError = true; 1230 ++Index; 1231 return; 1232 } else { 1233 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1234 diag::ext_flexible_array_init) 1235 << IList->getInit(Index)->getSourceRange().getBegin(); 1236 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1237 << *Field; 1238 } 1239 1240 InitializedEntity MemberEntity = 1241 InitializedEntity::InitializeMember(*Field, &Entity); 1242 1243 if (isa<InitListExpr>(IList->getInit(Index))) 1244 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1245 StructuredList, StructuredIndex); 1246 else 1247 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 1248 StructuredList, StructuredIndex); 1249} 1250 1251/// \brief Expand a field designator that refers to a member of an 1252/// anonymous struct or union into a series of field designators that 1253/// refers to the field within the appropriate subobject. 1254/// 1255static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1256 DesignatedInitExpr *DIE, 1257 unsigned DesigIdx, 1258 IndirectFieldDecl *IndirectField) { 1259 typedef DesignatedInitExpr::Designator Designator; 1260 1261 // Build the replacement designators. 1262 llvm::SmallVector<Designator, 4> Replacements; 1263 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 1264 PE = IndirectField->chain_end(); PI != PE; ++PI) { 1265 if (PI + 1 == PE) 1266 Replacements.push_back(Designator((IdentifierInfo *)0, 1267 DIE->getDesignator(DesigIdx)->getDotLoc(), 1268 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1269 else 1270 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1271 SourceLocation())); 1272 assert(isa<FieldDecl>(*PI)); 1273 Replacements.back().setField(cast<FieldDecl>(*PI)); 1274 } 1275 1276 // Expand the current designator into the set of replacement 1277 // designators, so we have a full subobject path down to where the 1278 // member of the anonymous struct/union is actually stored. 1279 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 1280 &Replacements[0] + Replacements.size()); 1281} 1282 1283/// \brief Given an implicit anonymous field, search the IndirectField that 1284/// corresponds to FieldName. 1285static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField, 1286 IdentifierInfo *FieldName) { 1287 assert(AnonField->isAnonymousStructOrUnion()); 1288 Decl *NextDecl = AnonField->getNextDeclInContext(); 1289 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) { 1290 if (FieldName && FieldName == IF->getAnonField()->getIdentifier()) 1291 return IF; 1292 NextDecl = NextDecl->getNextDeclInContext(); 1293 } 1294 return 0; 1295} 1296 1297/// @brief Check the well-formedness of a C99 designated initializer. 1298/// 1299/// Determines whether the designated initializer @p DIE, which 1300/// resides at the given @p Index within the initializer list @p 1301/// IList, is well-formed for a current object of type @p DeclType 1302/// (C99 6.7.8). The actual subobject that this designator refers to 1303/// within the current subobject is returned in either 1304/// @p NextField or @p NextElementIndex (whichever is appropriate). 1305/// 1306/// @param IList The initializer list in which this designated 1307/// initializer occurs. 1308/// 1309/// @param DIE The designated initializer expression. 1310/// 1311/// @param DesigIdx The index of the current designator. 1312/// 1313/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1314/// into which the designation in @p DIE should refer. 1315/// 1316/// @param NextField If non-NULL and the first designator in @p DIE is 1317/// a field, this will be set to the field declaration corresponding 1318/// to the field named by the designator. 1319/// 1320/// @param NextElementIndex If non-NULL and the first designator in @p 1321/// DIE is an array designator or GNU array-range designator, this 1322/// will be set to the last index initialized by this designator. 1323/// 1324/// @param Index Index into @p IList where the designated initializer 1325/// @p DIE occurs. 1326/// 1327/// @param StructuredList The initializer list expression that 1328/// describes all of the subobject initializers in the order they'll 1329/// actually be initialized. 1330/// 1331/// @returns true if there was an error, false otherwise. 1332bool 1333InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 1334 InitListExpr *IList, 1335 DesignatedInitExpr *DIE, 1336 unsigned DesigIdx, 1337 QualType &CurrentObjectType, 1338 RecordDecl::field_iterator *NextField, 1339 llvm::APSInt *NextElementIndex, 1340 unsigned &Index, 1341 InitListExpr *StructuredList, 1342 unsigned &StructuredIndex, 1343 bool FinishSubobjectInit, 1344 bool TopLevelObject) { 1345 if (DesigIdx == DIE->size()) { 1346 // Check the actual initialization for the designated object type. 1347 bool prevHadError = hadError; 1348 1349 // Temporarily remove the designator expression from the 1350 // initializer list that the child calls see, so that we don't try 1351 // to re-process the designator. 1352 unsigned OldIndex = Index; 1353 IList->setInit(OldIndex, DIE->getInit()); 1354 1355 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 1356 StructuredList, StructuredIndex); 1357 1358 // Restore the designated initializer expression in the syntactic 1359 // form of the initializer list. 1360 if (IList->getInit(OldIndex) != DIE->getInit()) 1361 DIE->setInit(IList->getInit(OldIndex)); 1362 IList->setInit(OldIndex, DIE); 1363 1364 return hadError && !prevHadError; 1365 } 1366 1367 bool IsFirstDesignator = (DesigIdx == 0); 1368 assert((IsFirstDesignator || StructuredList) && 1369 "Need a non-designated initializer list to start from"); 1370 1371 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1372 // Determine the structural initializer list that corresponds to the 1373 // current subobject. 1374 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1375 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1376 StructuredList, StructuredIndex, 1377 SourceRange(D->getStartLocation(), 1378 DIE->getSourceRange().getEnd())); 1379 assert(StructuredList && "Expected a structured initializer list"); 1380 1381 if (D->isFieldDesignator()) { 1382 // C99 6.7.8p7: 1383 // 1384 // If a designator has the form 1385 // 1386 // . identifier 1387 // 1388 // then the current object (defined below) shall have 1389 // structure or union type and the identifier shall be the 1390 // name of a member of that type. 1391 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1392 if (!RT) { 1393 SourceLocation Loc = D->getDotLoc(); 1394 if (Loc.isInvalid()) 1395 Loc = D->getFieldLoc(); 1396 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1397 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1398 ++Index; 1399 return true; 1400 } 1401 1402 // Note: we perform a linear search of the fields here, despite 1403 // the fact that we have a faster lookup method, because we always 1404 // need to compute the field's index. 1405 FieldDecl *KnownField = D->getField(); 1406 IdentifierInfo *FieldName = D->getFieldName(); 1407 unsigned FieldIndex = 0; 1408 RecordDecl::field_iterator 1409 Field = RT->getDecl()->field_begin(), 1410 FieldEnd = RT->getDecl()->field_end(); 1411 for (; Field != FieldEnd; ++Field) { 1412 if (Field->isUnnamedBitfield()) 1413 continue; 1414 1415 // If we find a field representing an anonymous field, look in the 1416 // IndirectFieldDecl that follow for the designated initializer. 1417 if (!KnownField && Field->isAnonymousStructOrUnion()) { 1418 if (IndirectFieldDecl *IF = 1419 FindIndirectFieldDesignator(*Field, FieldName)) { 1420 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF); 1421 D = DIE->getDesignator(DesigIdx); 1422 break; 1423 } 1424 } 1425 if (KnownField && KnownField == *Field) 1426 break; 1427 if (FieldName && FieldName == Field->getIdentifier()) 1428 break; 1429 1430 ++FieldIndex; 1431 } 1432 1433 if (Field == FieldEnd) { 1434 // There was no normal field in the struct with the designated 1435 // name. Perform another lookup for this name, which may find 1436 // something that we can't designate (e.g., a member function), 1437 // may find nothing, or may find a member of an anonymous 1438 // struct/union. 1439 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1440 FieldDecl *ReplacementField = 0; 1441 if (Lookup.first == Lookup.second) { 1442 // Name lookup didn't find anything. Determine whether this 1443 // was a typo for another field name. 1444 LookupResult R(SemaRef, FieldName, D->getFieldLoc(), 1445 Sema::LookupMemberName); 1446 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false, 1447 Sema::CTC_NoKeywords) && 1448 (ReplacementField = R.getAsSingle<FieldDecl>()) && 1449 ReplacementField->getDeclContext()->getRedeclContext() 1450 ->Equals(RT->getDecl())) { 1451 SemaRef.Diag(D->getFieldLoc(), 1452 diag::err_field_designator_unknown_suggest) 1453 << FieldName << CurrentObjectType << R.getLookupName() 1454 << FixItHint::CreateReplacement(D->getFieldLoc(), 1455 R.getLookupName().getAsString()); 1456 SemaRef.Diag(ReplacementField->getLocation(), 1457 diag::note_previous_decl) 1458 << ReplacementField->getDeclName(); 1459 } else { 1460 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1461 << FieldName << CurrentObjectType; 1462 ++Index; 1463 return true; 1464 } 1465 } 1466 1467 if (!ReplacementField) { 1468 // Name lookup found something, but it wasn't a field. 1469 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1470 << FieldName; 1471 SemaRef.Diag((*Lookup.first)->getLocation(), 1472 diag::note_field_designator_found); 1473 ++Index; 1474 return true; 1475 } 1476 1477 if (!KnownField) { 1478 // The replacement field comes from typo correction; find it 1479 // in the list of fields. 1480 FieldIndex = 0; 1481 Field = RT->getDecl()->field_begin(); 1482 for (; Field != FieldEnd; ++Field) { 1483 if (Field->isUnnamedBitfield()) 1484 continue; 1485 1486 if (ReplacementField == *Field || 1487 Field->getIdentifier() == ReplacementField->getIdentifier()) 1488 break; 1489 1490 ++FieldIndex; 1491 } 1492 } 1493 } 1494 1495 // All of the fields of a union are located at the same place in 1496 // the initializer list. 1497 if (RT->getDecl()->isUnion()) { 1498 FieldIndex = 0; 1499 StructuredList->setInitializedFieldInUnion(*Field); 1500 } 1501 1502 // Update the designator with the field declaration. 1503 D->setField(*Field); 1504 1505 // Make sure that our non-designated initializer list has space 1506 // for a subobject corresponding to this field. 1507 if (FieldIndex >= StructuredList->getNumInits()) 1508 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1509 1510 // This designator names a flexible array member. 1511 if (Field->getType()->isIncompleteArrayType()) { 1512 bool Invalid = false; 1513 if ((DesigIdx + 1) != DIE->size()) { 1514 // We can't designate an object within the flexible array 1515 // member (because GCC doesn't allow it). 1516 DesignatedInitExpr::Designator *NextD 1517 = DIE->getDesignator(DesigIdx + 1); 1518 SemaRef.Diag(NextD->getStartLocation(), 1519 diag::err_designator_into_flexible_array_member) 1520 << SourceRange(NextD->getStartLocation(), 1521 DIE->getSourceRange().getEnd()); 1522 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1523 << *Field; 1524 Invalid = true; 1525 } 1526 1527 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 1528 !isa<StringLiteral>(DIE->getInit())) { 1529 // The initializer is not an initializer list. 1530 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1531 diag::err_flexible_array_init_needs_braces) 1532 << DIE->getInit()->getSourceRange(); 1533 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1534 << *Field; 1535 Invalid = true; 1536 } 1537 1538 // Handle GNU flexible array initializers. 1539 if (!Invalid && !TopLevelObject && 1540 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1541 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1542 diag::err_flexible_array_init_nonempty) 1543 << DIE->getSourceRange().getBegin(); 1544 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1545 << *Field; 1546 Invalid = true; 1547 } 1548 1549 if (Invalid) { 1550 ++Index; 1551 return true; 1552 } 1553 1554 // Initialize the array. 1555 bool prevHadError = hadError; 1556 unsigned newStructuredIndex = FieldIndex; 1557 unsigned OldIndex = Index; 1558 IList->setInit(Index, DIE->getInit()); 1559 1560 InitializedEntity MemberEntity = 1561 InitializedEntity::InitializeMember(*Field, &Entity); 1562 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1563 StructuredList, newStructuredIndex); 1564 1565 IList->setInit(OldIndex, DIE); 1566 if (hadError && !prevHadError) { 1567 ++Field; 1568 ++FieldIndex; 1569 if (NextField) 1570 *NextField = Field; 1571 StructuredIndex = FieldIndex; 1572 return true; 1573 } 1574 } else { 1575 // Recurse to check later designated subobjects. 1576 QualType FieldType = (*Field)->getType(); 1577 unsigned newStructuredIndex = FieldIndex; 1578 1579 InitializedEntity MemberEntity = 1580 InitializedEntity::InitializeMember(*Field, &Entity); 1581 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 1582 FieldType, 0, 0, Index, 1583 StructuredList, newStructuredIndex, 1584 true, false)) 1585 return true; 1586 } 1587 1588 // Find the position of the next field to be initialized in this 1589 // subobject. 1590 ++Field; 1591 ++FieldIndex; 1592 1593 // If this the first designator, our caller will continue checking 1594 // the rest of this struct/class/union subobject. 1595 if (IsFirstDesignator) { 1596 if (NextField) 1597 *NextField = Field; 1598 StructuredIndex = FieldIndex; 1599 return false; 1600 } 1601 1602 if (!FinishSubobjectInit) 1603 return false; 1604 1605 // We've already initialized something in the union; we're done. 1606 if (RT->getDecl()->isUnion()) 1607 return hadError; 1608 1609 // Check the remaining fields within this class/struct/union subobject. 1610 bool prevHadError = hadError; 1611 1612 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index, 1613 StructuredList, FieldIndex); 1614 return hadError && !prevHadError; 1615 } 1616 1617 // C99 6.7.8p6: 1618 // 1619 // If a designator has the form 1620 // 1621 // [ constant-expression ] 1622 // 1623 // then the current object (defined below) shall have array 1624 // type and the expression shall be an integer constant 1625 // expression. If the array is of unknown size, any 1626 // nonnegative value is valid. 1627 // 1628 // Additionally, cope with the GNU extension that permits 1629 // designators of the form 1630 // 1631 // [ constant-expression ... constant-expression ] 1632 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1633 if (!AT) { 1634 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1635 << CurrentObjectType; 1636 ++Index; 1637 return true; 1638 } 1639 1640 Expr *IndexExpr = 0; 1641 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1642 if (D->isArrayDesignator()) { 1643 IndexExpr = DIE->getArrayIndex(*D); 1644 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1645 DesignatedEndIndex = DesignatedStartIndex; 1646 } else { 1647 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1648 1649 DesignatedStartIndex = 1650 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1651 DesignatedEndIndex = 1652 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1653 IndexExpr = DIE->getArrayRangeEnd(*D); 1654 1655 // Codegen can't handle evaluating array range designators that have side 1656 // effects, because we replicate the AST value for each initialized element. 1657 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 1658 // elements with something that has a side effect, so codegen can emit an 1659 // "error unsupported" error instead of miscompiling the app. 1660 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 1661 DIE->getInit()->HasSideEffects(SemaRef.Context)) 1662 FullyStructuredList->sawArrayRangeDesignator(); 1663 } 1664 1665 if (isa<ConstantArrayType>(AT)) { 1666 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1667 DesignatedStartIndex 1668 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1669 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1670 DesignatedEndIndex 1671 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1672 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1673 if (DesignatedEndIndex >= MaxElements) { 1674 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1675 diag::err_array_designator_too_large) 1676 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1677 << IndexExpr->getSourceRange(); 1678 ++Index; 1679 return true; 1680 } 1681 } else { 1682 // Make sure the bit-widths and signedness match. 1683 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1684 DesignatedEndIndex 1685 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1686 else if (DesignatedStartIndex.getBitWidth() < 1687 DesignatedEndIndex.getBitWidth()) 1688 DesignatedStartIndex 1689 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1690 DesignatedStartIndex.setIsUnsigned(true); 1691 DesignatedEndIndex.setIsUnsigned(true); 1692 } 1693 1694 // Make sure that our non-designated initializer list has space 1695 // for a subobject corresponding to this array element. 1696 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1697 StructuredList->resizeInits(SemaRef.Context, 1698 DesignatedEndIndex.getZExtValue() + 1); 1699 1700 // Repeatedly perform subobject initializations in the range 1701 // [DesignatedStartIndex, DesignatedEndIndex]. 1702 1703 // Move to the next designator 1704 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1705 unsigned OldIndex = Index; 1706 1707 InitializedEntity ElementEntity = 1708 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1709 1710 while (DesignatedStartIndex <= DesignatedEndIndex) { 1711 // Recurse to check later designated subobjects. 1712 QualType ElementType = AT->getElementType(); 1713 Index = OldIndex; 1714 1715 ElementEntity.setElementIndex(ElementIndex); 1716 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1, 1717 ElementType, 0, 0, Index, 1718 StructuredList, ElementIndex, 1719 (DesignatedStartIndex == DesignatedEndIndex), 1720 false)) 1721 return true; 1722 1723 // Move to the next index in the array that we'll be initializing. 1724 ++DesignatedStartIndex; 1725 ElementIndex = DesignatedStartIndex.getZExtValue(); 1726 } 1727 1728 // If this the first designator, our caller will continue checking 1729 // the rest of this array subobject. 1730 if (IsFirstDesignator) { 1731 if (NextElementIndex) 1732 *NextElementIndex = DesignatedStartIndex; 1733 StructuredIndex = ElementIndex; 1734 return false; 1735 } 1736 1737 if (!FinishSubobjectInit) 1738 return false; 1739 1740 // Check the remaining elements within this array subobject. 1741 bool prevHadError = hadError; 1742 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 1743 /*SubobjectIsDesignatorContext=*/false, Index, 1744 StructuredList, ElementIndex); 1745 return hadError && !prevHadError; 1746} 1747 1748// Get the structured initializer list for a subobject of type 1749// @p CurrentObjectType. 1750InitListExpr * 1751InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1752 QualType CurrentObjectType, 1753 InitListExpr *StructuredList, 1754 unsigned StructuredIndex, 1755 SourceRange InitRange) { 1756 Expr *ExistingInit = 0; 1757 if (!StructuredList) 1758 ExistingInit = SyntacticToSemantic[IList]; 1759 else if (StructuredIndex < StructuredList->getNumInits()) 1760 ExistingInit = StructuredList->getInit(StructuredIndex); 1761 1762 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1763 return Result; 1764 1765 if (ExistingInit) { 1766 // We are creating an initializer list that initializes the 1767 // subobjects of the current object, but there was already an 1768 // initialization that completely initialized the current 1769 // subobject, e.g., by a compound literal: 1770 // 1771 // struct X { int a, b; }; 1772 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1773 // 1774 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1775 // designated initializer re-initializes the whole 1776 // subobject [0], overwriting previous initializers. 1777 SemaRef.Diag(InitRange.getBegin(), 1778 diag::warn_subobject_initializer_overrides) 1779 << InitRange; 1780 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1781 diag::note_previous_initializer) 1782 << /*FIXME:has side effects=*/0 1783 << ExistingInit->getSourceRange(); 1784 } 1785 1786 InitListExpr *Result 1787 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 1788 InitRange.getBegin(), 0, 0, 1789 InitRange.getEnd()); 1790 1791 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context)); 1792 1793 // Pre-allocate storage for the structured initializer list. 1794 unsigned NumElements = 0; 1795 unsigned NumInits = 0; 1796 bool GotNumInits = false; 1797 if (!StructuredList) { 1798 NumInits = IList->getNumInits(); 1799 GotNumInits = true; 1800 } else if (Index < IList->getNumInits()) { 1801 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) { 1802 NumInits = SubList->getNumInits(); 1803 GotNumInits = true; 1804 } 1805 } 1806 1807 if (const ArrayType *AType 1808 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1809 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1810 NumElements = CAType->getSize().getZExtValue(); 1811 // Simple heuristic so that we don't allocate a very large 1812 // initializer with many empty entries at the end. 1813 if (GotNumInits && NumElements > NumInits) 1814 NumElements = 0; 1815 } 1816 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 1817 NumElements = VType->getNumElements(); 1818 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1819 RecordDecl *RDecl = RType->getDecl(); 1820 if (RDecl->isUnion()) 1821 NumElements = 1; 1822 else 1823 NumElements = std::distance(RDecl->field_begin(), 1824 RDecl->field_end()); 1825 } 1826 1827 if (NumElements < NumInits) 1828 NumElements = IList->getNumInits(); 1829 1830 Result->reserveInits(SemaRef.Context, NumElements); 1831 1832 // Link this new initializer list into the structured initializer 1833 // lists. 1834 if (StructuredList) 1835 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 1836 else { 1837 Result->setSyntacticForm(IList); 1838 SyntacticToSemantic[IList] = Result; 1839 } 1840 1841 return Result; 1842} 1843 1844/// Update the initializer at index @p StructuredIndex within the 1845/// structured initializer list to the value @p expr. 1846void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1847 unsigned &StructuredIndex, 1848 Expr *expr) { 1849 // No structured initializer list to update 1850 if (!StructuredList) 1851 return; 1852 1853 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 1854 StructuredIndex, expr)) { 1855 // This initializer overwrites a previous initializer. Warn. 1856 SemaRef.Diag(expr->getSourceRange().getBegin(), 1857 diag::warn_initializer_overrides) 1858 << expr->getSourceRange(); 1859 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1860 diag::note_previous_initializer) 1861 << /*FIXME:has side effects=*/0 1862 << PrevInit->getSourceRange(); 1863 } 1864 1865 ++StructuredIndex; 1866} 1867 1868/// Check that the given Index expression is a valid array designator 1869/// value. This is essentailly just a wrapper around 1870/// VerifyIntegerConstantExpression that also checks for negative values 1871/// and produces a reasonable diagnostic if there is a 1872/// failure. Returns true if there was an error, false otherwise. If 1873/// everything went okay, Value will receive the value of the constant 1874/// expression. 1875static bool 1876CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1877 SourceLocation Loc = Index->getSourceRange().getBegin(); 1878 1879 // Make sure this is an integer constant expression. 1880 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1881 return true; 1882 1883 if (Value.isSigned() && Value.isNegative()) 1884 return S.Diag(Loc, diag::err_array_designator_negative) 1885 << Value.toString(10) << Index->getSourceRange(); 1886 1887 Value.setIsUnsigned(true); 1888 return false; 1889} 1890 1891ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1892 SourceLocation Loc, 1893 bool GNUSyntax, 1894 ExprResult Init) { 1895 typedef DesignatedInitExpr::Designator ASTDesignator; 1896 1897 bool Invalid = false; 1898 llvm::SmallVector<ASTDesignator, 32> Designators; 1899 llvm::SmallVector<Expr *, 32> InitExpressions; 1900 1901 // Build designators and check array designator expressions. 1902 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1903 const Designator &D = Desig.getDesignator(Idx); 1904 switch (D.getKind()) { 1905 case Designator::FieldDesignator: 1906 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1907 D.getFieldLoc())); 1908 break; 1909 1910 case Designator::ArrayDesignator: { 1911 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1912 llvm::APSInt IndexValue; 1913 if (!Index->isTypeDependent() && 1914 !Index->isValueDependent() && 1915 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1916 Invalid = true; 1917 else { 1918 Designators.push_back(ASTDesignator(InitExpressions.size(), 1919 D.getLBracketLoc(), 1920 D.getRBracketLoc())); 1921 InitExpressions.push_back(Index); 1922 } 1923 break; 1924 } 1925 1926 case Designator::ArrayRangeDesignator: { 1927 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1928 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1929 llvm::APSInt StartValue; 1930 llvm::APSInt EndValue; 1931 bool StartDependent = StartIndex->isTypeDependent() || 1932 StartIndex->isValueDependent(); 1933 bool EndDependent = EndIndex->isTypeDependent() || 1934 EndIndex->isValueDependent(); 1935 if ((!StartDependent && 1936 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1937 (!EndDependent && 1938 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1939 Invalid = true; 1940 else { 1941 // Make sure we're comparing values with the same bit width. 1942 if (StartDependent || EndDependent) { 1943 // Nothing to compute. 1944 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1945 EndValue = EndValue.extend(StartValue.getBitWidth()); 1946 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1947 StartValue = StartValue.extend(EndValue.getBitWidth()); 1948 1949 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1950 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1951 << StartValue.toString(10) << EndValue.toString(10) 1952 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1953 Invalid = true; 1954 } else { 1955 Designators.push_back(ASTDesignator(InitExpressions.size(), 1956 D.getLBracketLoc(), 1957 D.getEllipsisLoc(), 1958 D.getRBracketLoc())); 1959 InitExpressions.push_back(StartIndex); 1960 InitExpressions.push_back(EndIndex); 1961 } 1962 } 1963 break; 1964 } 1965 } 1966 } 1967 1968 if (Invalid || Init.isInvalid()) 1969 return ExprError(); 1970 1971 // Clear out the expressions within the designation. 1972 Desig.ClearExprs(*this); 1973 1974 DesignatedInitExpr *DIE 1975 = DesignatedInitExpr::Create(Context, 1976 Designators.data(), Designators.size(), 1977 InitExpressions.data(), InitExpressions.size(), 1978 Loc, GNUSyntax, Init.takeAs<Expr>()); 1979 1980 if (getLangOptions().CPlusPlus) 1981 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx) 1982 << DIE->getSourceRange(); 1983 else if (!getLangOptions().C99) 1984 Diag(DIE->getLocStart(), diag::ext_designated_init) 1985 << DIE->getSourceRange(); 1986 1987 return Owned(DIE); 1988} 1989 1990bool Sema::CheckInitList(const InitializedEntity &Entity, 1991 InitListExpr *&InitList, QualType &DeclType) { 1992 InitListChecker CheckInitList(*this, Entity, InitList, DeclType); 1993 if (!CheckInitList.HadError()) 1994 InitList = CheckInitList.getFullyStructuredList(); 1995 1996 return CheckInitList.HadError(); 1997} 1998 1999//===----------------------------------------------------------------------===// 2000// Initialization entity 2001//===----------------------------------------------------------------------===// 2002 2003InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 2004 const InitializedEntity &Parent) 2005 : Parent(&Parent), Index(Index) 2006{ 2007 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 2008 Kind = EK_ArrayElement; 2009 Type = AT->getElementType(); 2010 } else { 2011 Kind = EK_VectorElement; 2012 Type = Parent.getType()->getAs<VectorType>()->getElementType(); 2013 } 2014} 2015 2016InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 2017 CXXBaseSpecifier *Base, 2018 bool IsInheritedVirtualBase) 2019{ 2020 InitializedEntity Result; 2021 Result.Kind = EK_Base; 2022 Result.Base = reinterpret_cast<uintptr_t>(Base); 2023 if (IsInheritedVirtualBase) 2024 Result.Base |= 0x01; 2025 2026 Result.Type = Base->getType(); 2027 return Result; 2028} 2029 2030DeclarationName InitializedEntity::getName() const { 2031 switch (getKind()) { 2032 case EK_Parameter: { 2033 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2034 return (D ? D->getDeclName() : DeclarationName()); 2035 } 2036 2037 case EK_Variable: 2038 case EK_Member: 2039 return VariableOrMember->getDeclName(); 2040 2041 case EK_Result: 2042 case EK_Exception: 2043 case EK_New: 2044 case EK_Temporary: 2045 case EK_Base: 2046 case EK_Delegating: 2047 case EK_ArrayElement: 2048 case EK_VectorElement: 2049 case EK_BlockElement: 2050 return DeclarationName(); 2051 } 2052 2053 // Silence GCC warning 2054 return DeclarationName(); 2055} 2056 2057DeclaratorDecl *InitializedEntity::getDecl() const { 2058 switch (getKind()) { 2059 case EK_Variable: 2060 case EK_Member: 2061 return VariableOrMember; 2062 2063 case EK_Parameter: 2064 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2065 2066 case EK_Result: 2067 case EK_Exception: 2068 case EK_New: 2069 case EK_Temporary: 2070 case EK_Base: 2071 case EK_Delegating: 2072 case EK_ArrayElement: 2073 case EK_VectorElement: 2074 case EK_BlockElement: 2075 return 0; 2076 } 2077 2078 // Silence GCC warning 2079 return 0; 2080} 2081 2082bool InitializedEntity::allowsNRVO() const { 2083 switch (getKind()) { 2084 case EK_Result: 2085 case EK_Exception: 2086 return LocAndNRVO.NRVO; 2087 2088 case EK_Variable: 2089 case EK_Parameter: 2090 case EK_Member: 2091 case EK_New: 2092 case EK_Temporary: 2093 case EK_Base: 2094 case EK_Delegating: 2095 case EK_ArrayElement: 2096 case EK_VectorElement: 2097 case EK_BlockElement: 2098 break; 2099 } 2100 2101 return false; 2102} 2103 2104//===----------------------------------------------------------------------===// 2105// Initialization sequence 2106//===----------------------------------------------------------------------===// 2107 2108void InitializationSequence::Step::Destroy() { 2109 switch (Kind) { 2110 case SK_ResolveAddressOfOverloadedFunction: 2111 case SK_CastDerivedToBaseRValue: 2112 case SK_CastDerivedToBaseXValue: 2113 case SK_CastDerivedToBaseLValue: 2114 case SK_BindReference: 2115 case SK_BindReferenceToTemporary: 2116 case SK_ExtraneousCopyToTemporary: 2117 case SK_UserConversion: 2118 case SK_QualificationConversionRValue: 2119 case SK_QualificationConversionXValue: 2120 case SK_QualificationConversionLValue: 2121 case SK_ListInitialization: 2122 case SK_ConstructorInitialization: 2123 case SK_ZeroInitialization: 2124 case SK_CAssignment: 2125 case SK_StringInit: 2126 case SK_ObjCObjectConversion: 2127 case SK_ArrayInit: 2128 case SK_PassByIndirectCopyRestore: 2129 case SK_PassByIndirectRestore: 2130 case SK_ProduceObjCObject: 2131 break; 2132 2133 case SK_ConversionSequence: 2134 delete ICS; 2135 } 2136} 2137 2138bool InitializationSequence::isDirectReferenceBinding() const { 2139 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference; 2140} 2141 2142bool InitializationSequence::isAmbiguous() const { 2143 if (!Failed()) 2144 return false; 2145 2146 switch (getFailureKind()) { 2147 case FK_TooManyInitsForReference: 2148 case FK_ArrayNeedsInitList: 2149 case FK_ArrayNeedsInitListOrStringLiteral: 2150 case FK_AddressOfOverloadFailed: // FIXME: Could do better 2151 case FK_NonConstLValueReferenceBindingToTemporary: 2152 case FK_NonConstLValueReferenceBindingToUnrelated: 2153 case FK_RValueReferenceBindingToLValue: 2154 case FK_ReferenceInitDropsQualifiers: 2155 case FK_ReferenceInitFailed: 2156 case FK_ConversionFailed: 2157 case FK_ConversionFromPropertyFailed: 2158 case FK_TooManyInitsForScalar: 2159 case FK_ReferenceBindingToInitList: 2160 case FK_InitListBadDestinationType: 2161 case FK_DefaultInitOfConst: 2162 case FK_Incomplete: 2163 case FK_ArrayTypeMismatch: 2164 case FK_NonConstantArrayInit: 2165 return false; 2166 2167 case FK_ReferenceInitOverloadFailed: 2168 case FK_UserConversionOverloadFailed: 2169 case FK_ConstructorOverloadFailed: 2170 return FailedOverloadResult == OR_Ambiguous; 2171 } 2172 2173 return false; 2174} 2175 2176bool InitializationSequence::isConstructorInitialization() const { 2177 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 2178} 2179 2180void InitializationSequence::AddAddressOverloadResolutionStep( 2181 FunctionDecl *Function, 2182 DeclAccessPair Found) { 2183 Step S; 2184 S.Kind = SK_ResolveAddressOfOverloadedFunction; 2185 S.Type = Function->getType(); 2186 S.Function.Function = Function; 2187 S.Function.FoundDecl = Found; 2188 Steps.push_back(S); 2189} 2190 2191void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 2192 ExprValueKind VK) { 2193 Step S; 2194 switch (VK) { 2195 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 2196 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 2197 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 2198 default: llvm_unreachable("No such category"); 2199 } 2200 S.Type = BaseType; 2201 Steps.push_back(S); 2202} 2203 2204void InitializationSequence::AddReferenceBindingStep(QualType T, 2205 bool BindingTemporary) { 2206 Step S; 2207 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2208 S.Type = T; 2209 Steps.push_back(S); 2210} 2211 2212void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 2213 Step S; 2214 S.Kind = SK_ExtraneousCopyToTemporary; 2215 S.Type = T; 2216 Steps.push_back(S); 2217} 2218 2219void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2220 DeclAccessPair FoundDecl, 2221 QualType T) { 2222 Step S; 2223 S.Kind = SK_UserConversion; 2224 S.Type = T; 2225 S.Function.Function = Function; 2226 S.Function.FoundDecl = FoundDecl; 2227 Steps.push_back(S); 2228} 2229 2230void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2231 ExprValueKind VK) { 2232 Step S; 2233 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 2234 switch (VK) { 2235 case VK_RValue: 2236 S.Kind = SK_QualificationConversionRValue; 2237 break; 2238 case VK_XValue: 2239 S.Kind = SK_QualificationConversionXValue; 2240 break; 2241 case VK_LValue: 2242 S.Kind = SK_QualificationConversionLValue; 2243 break; 2244 } 2245 S.Type = Ty; 2246 Steps.push_back(S); 2247} 2248 2249void InitializationSequence::AddConversionSequenceStep( 2250 const ImplicitConversionSequence &ICS, 2251 QualType T) { 2252 Step S; 2253 S.Kind = SK_ConversionSequence; 2254 S.Type = T; 2255 S.ICS = new ImplicitConversionSequence(ICS); 2256 Steps.push_back(S); 2257} 2258 2259void InitializationSequence::AddListInitializationStep(QualType T) { 2260 Step S; 2261 S.Kind = SK_ListInitialization; 2262 S.Type = T; 2263 Steps.push_back(S); 2264} 2265 2266void 2267InitializationSequence::AddConstructorInitializationStep( 2268 CXXConstructorDecl *Constructor, 2269 AccessSpecifier Access, 2270 QualType T) { 2271 Step S; 2272 S.Kind = SK_ConstructorInitialization; 2273 S.Type = T; 2274 S.Function.Function = Constructor; 2275 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access); 2276 Steps.push_back(S); 2277} 2278 2279void InitializationSequence::AddZeroInitializationStep(QualType T) { 2280 Step S; 2281 S.Kind = SK_ZeroInitialization; 2282 S.Type = T; 2283 Steps.push_back(S); 2284} 2285 2286void InitializationSequence::AddCAssignmentStep(QualType T) { 2287 Step S; 2288 S.Kind = SK_CAssignment; 2289 S.Type = T; 2290 Steps.push_back(S); 2291} 2292 2293void InitializationSequence::AddStringInitStep(QualType T) { 2294 Step S; 2295 S.Kind = SK_StringInit; 2296 S.Type = T; 2297 Steps.push_back(S); 2298} 2299 2300void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 2301 Step S; 2302 S.Kind = SK_ObjCObjectConversion; 2303 S.Type = T; 2304 Steps.push_back(S); 2305} 2306 2307void InitializationSequence::AddArrayInitStep(QualType T) { 2308 Step S; 2309 S.Kind = SK_ArrayInit; 2310 S.Type = T; 2311 Steps.push_back(S); 2312} 2313 2314void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 2315 bool shouldCopy) { 2316 Step s; 2317 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 2318 : SK_PassByIndirectRestore); 2319 s.Type = type; 2320 Steps.push_back(s); 2321} 2322 2323void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 2324 Step S; 2325 S.Kind = SK_ProduceObjCObject; 2326 S.Type = T; 2327 Steps.push_back(S); 2328} 2329 2330void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2331 OverloadingResult Result) { 2332 setSequenceKind(FailedSequence); 2333 this->Failure = Failure; 2334 this->FailedOverloadResult = Result; 2335} 2336 2337//===----------------------------------------------------------------------===// 2338// Attempt initialization 2339//===----------------------------------------------------------------------===// 2340 2341static void MaybeProduceObjCObject(Sema &S, 2342 InitializationSequence &Sequence, 2343 const InitializedEntity &Entity) { 2344 if (!S.getLangOptions().ObjCAutoRefCount) return; 2345 2346 /// When initializing a parameter, produce the value if it's marked 2347 /// __attribute__((ns_consumed)). 2348 if (Entity.getKind() == InitializedEntity::EK_Parameter) { 2349 if (!Entity.isParameterConsumed()) 2350 return; 2351 2352 assert(Entity.getType()->isObjCRetainableType() && 2353 "consuming an object of unretainable type?"); 2354 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2355 2356 /// When initializing a return value, if the return type is a 2357 /// retainable type, then returns need to immediately retain the 2358 /// object. If an autorelease is required, it will be done at the 2359 /// last instant. 2360 } else if (Entity.getKind() == InitializedEntity::EK_Result) { 2361 if (!Entity.getType()->isObjCRetainableType()) 2362 return; 2363 2364 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2365 } 2366} 2367 2368/// \brief Attempt list initialization (C++0x [dcl.init.list]) 2369static void TryListInitialization(Sema &S, 2370 const InitializedEntity &Entity, 2371 const InitializationKind &Kind, 2372 InitListExpr *InitList, 2373 InitializationSequence &Sequence) { 2374 // FIXME: We only perform rudimentary checking of list 2375 // initializations at this point, then assume that any list 2376 // initialization of an array, aggregate, or scalar will be 2377 // well-formed. When we actually "perform" list initialization, we'll 2378 // do all of the necessary checking. C++0x initializer lists will 2379 // force us to perform more checking here. 2380 2381 QualType DestType = Entity.getType(); 2382 2383 // C++ [dcl.init]p13: 2384 // If T is a scalar type, then a declaration of the form 2385 // 2386 // T x = { a }; 2387 // 2388 // is equivalent to 2389 // 2390 // T x = a; 2391 if (DestType->isScalarType()) { 2392 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) { 2393 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 2394 return; 2395 } 2396 2397 // Assume scalar initialization from a single value works. 2398 } else if (DestType->isAggregateType()) { 2399 // Assume aggregate initialization works. 2400 } else if (DestType->isVectorType()) { 2401 // Assume vector initialization works. 2402 } else if (DestType->isReferenceType()) { 2403 // FIXME: C++0x defines behavior for this. 2404 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 2405 return; 2406 } else if (DestType->isRecordType()) { 2407 // FIXME: C++0x defines behavior for this 2408 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 2409 } 2410 2411 // Add a general "list initialization" step. 2412 Sequence.AddListInitializationStep(DestType); 2413} 2414 2415/// \brief Try a reference initialization that involves calling a conversion 2416/// function. 2417static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 2418 const InitializedEntity &Entity, 2419 const InitializationKind &Kind, 2420 Expr *Initializer, 2421 bool AllowRValues, 2422 InitializationSequence &Sequence) { 2423 QualType DestType = Entity.getType(); 2424 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2425 QualType T1 = cv1T1.getUnqualifiedType(); 2426 QualType cv2T2 = Initializer->getType(); 2427 QualType T2 = cv2T2.getUnqualifiedType(); 2428 2429 bool DerivedToBase; 2430 bool ObjCConversion; 2431 bool ObjCLifetimeConversion; 2432 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 2433 T1, T2, DerivedToBase, 2434 ObjCConversion, 2435 ObjCLifetimeConversion) && 2436 "Must have incompatible references when binding via conversion"); 2437 (void)DerivedToBase; 2438 (void)ObjCConversion; 2439 (void)ObjCLifetimeConversion; 2440 2441 // Build the candidate set directly in the initialization sequence 2442 // structure, so that it will persist if we fail. 2443 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2444 CandidateSet.clear(); 2445 2446 // Determine whether we are allowed to call explicit constructors or 2447 // explicit conversion operators. 2448 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2449 2450 const RecordType *T1RecordType = 0; 2451 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 2452 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) { 2453 // The type we're converting to is a class type. Enumerate its constructors 2454 // to see if there is a suitable conversion. 2455 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 2456 2457 DeclContext::lookup_iterator Con, ConEnd; 2458 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl); 2459 Con != ConEnd; ++Con) { 2460 NamedDecl *D = *Con; 2461 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2462 2463 // Find the constructor (which may be a template). 2464 CXXConstructorDecl *Constructor = 0; 2465 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2466 if (ConstructorTmpl) 2467 Constructor = cast<CXXConstructorDecl>( 2468 ConstructorTmpl->getTemplatedDecl()); 2469 else 2470 Constructor = cast<CXXConstructorDecl>(D); 2471 2472 if (!Constructor->isInvalidDecl() && 2473 Constructor->isConvertingConstructor(AllowExplicit)) { 2474 if (ConstructorTmpl) 2475 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2476 /*ExplicitArgs*/ 0, 2477 &Initializer, 1, CandidateSet, 2478 /*SuppressUserConversions=*/true); 2479 else 2480 S.AddOverloadCandidate(Constructor, FoundDecl, 2481 &Initializer, 1, CandidateSet, 2482 /*SuppressUserConversions=*/true); 2483 } 2484 } 2485 } 2486 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 2487 return OR_No_Viable_Function; 2488 2489 const RecordType *T2RecordType = 0; 2490 if ((T2RecordType = T2->getAs<RecordType>()) && 2491 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) { 2492 // The type we're converting from is a class type, enumerate its conversion 2493 // functions. 2494 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 2495 2496 const UnresolvedSetImpl *Conversions 2497 = T2RecordDecl->getVisibleConversionFunctions(); 2498 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 2499 E = Conversions->end(); I != E; ++I) { 2500 NamedDecl *D = *I; 2501 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2502 if (isa<UsingShadowDecl>(D)) 2503 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2504 2505 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2506 CXXConversionDecl *Conv; 2507 if (ConvTemplate) 2508 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2509 else 2510 Conv = cast<CXXConversionDecl>(D); 2511 2512 // If the conversion function doesn't return a reference type, 2513 // it can't be considered for this conversion unless we're allowed to 2514 // consider rvalues. 2515 // FIXME: Do we need to make sure that we only consider conversion 2516 // candidates with reference-compatible results? That might be needed to 2517 // break recursion. 2518 if ((AllowExplicit || !Conv->isExplicit()) && 2519 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 2520 if (ConvTemplate) 2521 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 2522 ActingDC, Initializer, 2523 DestType, CandidateSet); 2524 else 2525 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 2526 Initializer, DestType, CandidateSet); 2527 } 2528 } 2529 } 2530 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 2531 return OR_No_Viable_Function; 2532 2533 SourceLocation DeclLoc = Initializer->getLocStart(); 2534 2535 // Perform overload resolution. If it fails, return the failed result. 2536 OverloadCandidateSet::iterator Best; 2537 if (OverloadingResult Result 2538 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) 2539 return Result; 2540 2541 FunctionDecl *Function = Best->Function; 2542 2543 // This is the overload that will actually be used for the initialization, so 2544 // mark it as used. 2545 S.MarkDeclarationReferenced(DeclLoc, Function); 2546 2547 // Compute the returned type of the conversion. 2548 if (isa<CXXConversionDecl>(Function)) 2549 T2 = Function->getResultType(); 2550 else 2551 T2 = cv1T1; 2552 2553 // Add the user-defined conversion step. 2554 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 2555 T2.getNonLValueExprType(S.Context)); 2556 2557 // Determine whether we need to perform derived-to-base or 2558 // cv-qualification adjustments. 2559 ExprValueKind VK = VK_RValue; 2560 if (T2->isLValueReferenceType()) 2561 VK = VK_LValue; 2562 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>()) 2563 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 2564 2565 bool NewDerivedToBase = false; 2566 bool NewObjCConversion = false; 2567 bool NewObjCLifetimeConversion = false; 2568 Sema::ReferenceCompareResult NewRefRelationship 2569 = S.CompareReferenceRelationship(DeclLoc, T1, 2570 T2.getNonLValueExprType(S.Context), 2571 NewDerivedToBase, NewObjCConversion, 2572 NewObjCLifetimeConversion); 2573 if (NewRefRelationship == Sema::Ref_Incompatible) { 2574 // If the type we've converted to is not reference-related to the 2575 // type we're looking for, then there is another conversion step 2576 // we need to perform to produce a temporary of the right type 2577 // that we'll be binding to. 2578 ImplicitConversionSequence ICS; 2579 ICS.setStandard(); 2580 ICS.Standard = Best->FinalConversion; 2581 T2 = ICS.Standard.getToType(2); 2582 Sequence.AddConversionSequenceStep(ICS, T2); 2583 } else if (NewDerivedToBase) 2584 Sequence.AddDerivedToBaseCastStep( 2585 S.Context.getQualifiedType(T1, 2586 T2.getNonReferenceType().getQualifiers()), 2587 VK); 2588 else if (NewObjCConversion) 2589 Sequence.AddObjCObjectConversionStep( 2590 S.Context.getQualifiedType(T1, 2591 T2.getNonReferenceType().getQualifiers())); 2592 2593 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 2594 Sequence.AddQualificationConversionStep(cv1T1, VK); 2595 2596 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 2597 return OR_Success; 2598} 2599 2600/// \brief Attempt reference initialization (C++0x [dcl.init.ref]) 2601static void TryReferenceInitialization(Sema &S, 2602 const InitializedEntity &Entity, 2603 const InitializationKind &Kind, 2604 Expr *Initializer, 2605 InitializationSequence &Sequence) { 2606 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding); 2607 2608 QualType DestType = Entity.getType(); 2609 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2610 Qualifiers T1Quals; 2611 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 2612 QualType cv2T2 = Initializer->getType(); 2613 Qualifiers T2Quals; 2614 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 2615 SourceLocation DeclLoc = Initializer->getLocStart(); 2616 2617 // If the initializer is the address of an overloaded function, try 2618 // to resolve the overloaded function. If all goes well, T2 is the 2619 // type of the resulting function. 2620 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2621 DeclAccessPair Found; 2622 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, 2623 T1, 2624 false, 2625 Found)) { 2626 Sequence.AddAddressOverloadResolutionStep(Fn, Found); 2627 cv2T2 = Fn->getType(); 2628 T2 = cv2T2.getUnqualifiedType(); 2629 } else if (!T1->isRecordType()) { 2630 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2631 return; 2632 } 2633 } 2634 2635 // Compute some basic properties of the types and the initializer. 2636 bool isLValueRef = DestType->isLValueReferenceType(); 2637 bool isRValueRef = !isLValueRef; 2638 bool DerivedToBase = false; 2639 bool ObjCConversion = false; 2640 bool ObjCLifetimeConversion = false; 2641 Expr::Classification InitCategory = Initializer->Classify(S.Context); 2642 Sema::ReferenceCompareResult RefRelationship 2643 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, 2644 ObjCConversion, ObjCLifetimeConversion); 2645 2646 // C++0x [dcl.init.ref]p5: 2647 // A reference to type "cv1 T1" is initialized by an expression of type 2648 // "cv2 T2" as follows: 2649 // 2650 // - If the reference is an lvalue reference and the initializer 2651 // expression 2652 // Note the analogous bullet points for rvlaue refs to functions. Because 2653 // there are no function rvalues in C++, rvalue refs to functions are treated 2654 // like lvalue refs. 2655 OverloadingResult ConvOvlResult = OR_Success; 2656 bool T1Function = T1->isFunctionType(); 2657 if (isLValueRef || T1Function) { 2658 if (InitCategory.isLValue() && 2659 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 2660 (Kind.isCStyleOrFunctionalCast() && 2661 RefRelationship == Sema::Ref_Related))) { 2662 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 2663 // reference-compatible with "cv2 T2," or 2664 // 2665 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a 2666 // bit-field when we're determining whether the reference initialization 2667 // can occur. However, we do pay attention to whether it is a bit-field 2668 // to decide whether we're actually binding to a temporary created from 2669 // the bit-field. 2670 if (DerivedToBase) 2671 Sequence.AddDerivedToBaseCastStep( 2672 S.Context.getQualifiedType(T1, T2Quals), 2673 VK_LValue); 2674 else if (ObjCConversion) 2675 Sequence.AddObjCObjectConversionStep( 2676 S.Context.getQualifiedType(T1, T2Quals)); 2677 2678 if (T1Quals != T2Quals) 2679 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue); 2680 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() && 2681 (Initializer->getBitField() || Initializer->refersToVectorElement()); 2682 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary); 2683 return; 2684 } 2685 2686 // - has a class type (i.e., T2 is a class type), where T1 is not 2687 // reference-related to T2, and can be implicitly converted to an 2688 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 2689 // with "cv3 T3" (this conversion is selected by enumerating the 2690 // applicable conversion functions (13.3.1.6) and choosing the best 2691 // one through overload resolution (13.3)), 2692 // If we have an rvalue ref to function type here, the rhs must be 2693 // an rvalue. 2694 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 2695 (isLValueRef || InitCategory.isRValue())) { 2696 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 2697 Initializer, 2698 /*AllowRValues=*/isRValueRef, 2699 Sequence); 2700 if (ConvOvlResult == OR_Success) 2701 return; 2702 if (ConvOvlResult != OR_No_Viable_Function) { 2703 Sequence.SetOverloadFailure( 2704 InitializationSequence::FK_ReferenceInitOverloadFailed, 2705 ConvOvlResult); 2706 } 2707 } 2708 } 2709 2710 // - Otherwise, the reference shall be an lvalue reference to a 2711 // non-volatile const type (i.e., cv1 shall be const), or the reference 2712 // shall be an rvalue reference. 2713 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) { 2714 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 2715 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2716 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2717 Sequence.SetOverloadFailure( 2718 InitializationSequence::FK_ReferenceInitOverloadFailed, 2719 ConvOvlResult); 2720 else 2721 Sequence.SetFailed(InitCategory.isLValue() 2722 ? (RefRelationship == Sema::Ref_Related 2723 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 2724 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 2725 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 2726 2727 return; 2728 } 2729 2730 // - If the initializer expression 2731 // - is an xvalue, class prvalue, array prvalue, or function lvalue and 2732 // "cv1 T1" is reference-compatible with "cv2 T2" 2733 // Note: functions are handled below. 2734 if (!T1Function && 2735 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 2736 (Kind.isCStyleOrFunctionalCast() && 2737 RefRelationship == Sema::Ref_Related)) && 2738 (InitCategory.isXValue() || 2739 (InitCategory.isPRValue() && T2->isRecordType()) || 2740 (InitCategory.isPRValue() && T2->isArrayType()))) { 2741 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue; 2742 if (InitCategory.isPRValue() && T2->isRecordType()) { 2743 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 2744 // compiler the freedom to perform a copy here or bind to the 2745 // object, while C++0x requires that we bind directly to the 2746 // object. Hence, we always bind to the object without making an 2747 // extra copy. However, in C++03 requires that we check for the 2748 // presence of a suitable copy constructor: 2749 // 2750 // The constructor that would be used to make the copy shall 2751 // be callable whether or not the copy is actually done. 2752 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft) 2753 Sequence.AddExtraneousCopyToTemporary(cv2T2); 2754 } 2755 2756 if (DerivedToBase) 2757 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals), 2758 ValueKind); 2759 else if (ObjCConversion) 2760 Sequence.AddObjCObjectConversionStep( 2761 S.Context.getQualifiedType(T1, T2Quals)); 2762 2763 if (T1Quals != T2Quals) 2764 Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 2765 Sequence.AddReferenceBindingStep(cv1T1, 2766 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType())); 2767 return; 2768 } 2769 2770 // - has a class type (i.e., T2 is a class type), where T1 is not 2771 // reference-related to T2, and can be implicitly converted to an 2772 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 2773 // where "cv1 T1" is reference-compatible with "cv3 T3", 2774 if (T2->isRecordType()) { 2775 if (RefRelationship == Sema::Ref_Incompatible) { 2776 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 2777 Kind, Initializer, 2778 /*AllowRValues=*/true, 2779 Sequence); 2780 if (ConvOvlResult) 2781 Sequence.SetOverloadFailure( 2782 InitializationSequence::FK_ReferenceInitOverloadFailed, 2783 ConvOvlResult); 2784 2785 return; 2786 } 2787 2788 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2789 return; 2790 } 2791 2792 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 2793 // from the initializer expression using the rules for a non-reference 2794 // copy initialization (8.5). The reference is then bound to the 2795 // temporary. [...] 2796 2797 // Determine whether we are allowed to call explicit constructors or 2798 // explicit conversion operators. 2799 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 2800 2801 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 2802 2803 ImplicitConversionSequence ICS 2804 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 2805 /*SuppressUserConversions*/ false, 2806 AllowExplicit, 2807 /*FIXME:InOverloadResolution=*/false, 2808 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 2809 /*AllowObjCWritebackConversion=*/false); 2810 2811 if (ICS.isBad()) { 2812 // FIXME: Use the conversion function set stored in ICS to turn 2813 // this into an overloading ambiguity diagnostic. However, we need 2814 // to keep that set as an OverloadCandidateSet rather than as some 2815 // other kind of set. 2816 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2817 Sequence.SetOverloadFailure( 2818 InitializationSequence::FK_ReferenceInitOverloadFailed, 2819 ConvOvlResult); 2820 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 2821 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2822 else 2823 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 2824 return; 2825 } else { 2826 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 2827 } 2828 2829 // [...] If T1 is reference-related to T2, cv1 must be the 2830 // same cv-qualification as, or greater cv-qualification 2831 // than, cv2; otherwise, the program is ill-formed. 2832 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 2833 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 2834 if (RefRelationship == Sema::Ref_Related && 2835 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { 2836 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2837 return; 2838 } 2839 2840 // [...] If T1 is reference-related to T2 and the reference is an rvalue 2841 // reference, the initializer expression shall not be an lvalue. 2842 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 2843 InitCategory.isLValue()) { 2844 Sequence.SetFailed( 2845 InitializationSequence::FK_RValueReferenceBindingToLValue); 2846 return; 2847 } 2848 2849 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2850 return; 2851} 2852 2853/// \brief Attempt character array initialization from a string literal 2854/// (C++ [dcl.init.string], C99 6.7.8). 2855static void TryStringLiteralInitialization(Sema &S, 2856 const InitializedEntity &Entity, 2857 const InitializationKind &Kind, 2858 Expr *Initializer, 2859 InitializationSequence &Sequence) { 2860 Sequence.AddStringInitStep(Entity.getType()); 2861} 2862 2863/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2864/// enumerates the constructors of the initialized entity and performs overload 2865/// resolution to select the best. 2866static void TryConstructorInitialization(Sema &S, 2867 const InitializedEntity &Entity, 2868 const InitializationKind &Kind, 2869 Expr **Args, unsigned NumArgs, 2870 QualType DestType, 2871 InitializationSequence &Sequence) { 2872 // Build the candidate set directly in the initialization sequence 2873 // structure, so that it will persist if we fail. 2874 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2875 CandidateSet.clear(); 2876 2877 // Determine whether we are allowed to call explicit constructors or 2878 // explicit conversion operators. 2879 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct || 2880 Kind.getKind() == InitializationKind::IK_Value || 2881 Kind.getKind() == InitializationKind::IK_Default); 2882 2883 // The type we're constructing needs to be complete. 2884 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 2885 Sequence.SetFailed(InitializationSequence::FK_Incomplete); 2886 return; 2887 } 2888 2889 // The type we're converting to is a class type. Enumerate its constructors 2890 // to see if one is suitable. 2891 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2892 assert(DestRecordType && "Constructor initialization requires record type"); 2893 CXXRecordDecl *DestRecordDecl 2894 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2895 2896 DeclContext::lookup_iterator Con, ConEnd; 2897 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 2898 Con != ConEnd; ++Con) { 2899 NamedDecl *D = *Con; 2900 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2901 bool SuppressUserConversions = false; 2902 2903 // Find the constructor (which may be a template). 2904 CXXConstructorDecl *Constructor = 0; 2905 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2906 if (ConstructorTmpl) 2907 Constructor = cast<CXXConstructorDecl>( 2908 ConstructorTmpl->getTemplatedDecl()); 2909 else { 2910 Constructor = cast<CXXConstructorDecl>(D); 2911 2912 // If we're performing copy initialization using a copy constructor, we 2913 // suppress user-defined conversions on the arguments. 2914 // FIXME: Move constructors? 2915 if (Kind.getKind() == InitializationKind::IK_Copy && 2916 Constructor->isCopyConstructor()) 2917 SuppressUserConversions = true; 2918 } 2919 2920 if (!Constructor->isInvalidDecl() && 2921 (AllowExplicit || !Constructor->isExplicit())) { 2922 if (ConstructorTmpl) 2923 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2924 /*ExplicitArgs*/ 0, 2925 Args, NumArgs, CandidateSet, 2926 SuppressUserConversions); 2927 else 2928 S.AddOverloadCandidate(Constructor, FoundDecl, 2929 Args, NumArgs, CandidateSet, 2930 SuppressUserConversions); 2931 } 2932 } 2933 2934 SourceLocation DeclLoc = Kind.getLocation(); 2935 2936 // Perform overload resolution. If it fails, return the failed result. 2937 OverloadCandidateSet::iterator Best; 2938 if (OverloadingResult Result 2939 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 2940 Sequence.SetOverloadFailure( 2941 InitializationSequence::FK_ConstructorOverloadFailed, 2942 Result); 2943 return; 2944 } 2945 2946 // C++0x [dcl.init]p6: 2947 // If a program calls for the default initialization of an object 2948 // of a const-qualified type T, T shall be a class type with a 2949 // user-provided default constructor. 2950 if (Kind.getKind() == InitializationKind::IK_Default && 2951 Entity.getType().isConstQualified() && 2952 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) { 2953 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2954 return; 2955 } 2956 2957 // Add the constructor initialization step. Any cv-qualification conversion is 2958 // subsumed by the initialization. 2959 Sequence.AddConstructorInitializationStep( 2960 cast<CXXConstructorDecl>(Best->Function), 2961 Best->FoundDecl.getAccess(), 2962 DestType); 2963} 2964 2965/// \brief Attempt value initialization (C++ [dcl.init]p7). 2966static void TryValueInitialization(Sema &S, 2967 const InitializedEntity &Entity, 2968 const InitializationKind &Kind, 2969 InitializationSequence &Sequence) { 2970 // C++ [dcl.init]p5: 2971 // 2972 // To value-initialize an object of type T means: 2973 QualType T = Entity.getType(); 2974 2975 // -- if T is an array type, then each element is value-initialized; 2976 while (const ArrayType *AT = S.Context.getAsArrayType(T)) 2977 T = AT->getElementType(); 2978 2979 if (const RecordType *RT = T->getAs<RecordType>()) { 2980 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2981 // -- if T is a class type (clause 9) with a user-declared 2982 // constructor (12.1), then the default constructor for T is 2983 // called (and the initialization is ill-formed if T has no 2984 // accessible default constructor); 2985 // 2986 // FIXME: we really want to refer to a single subobject of the array, 2987 // but Entity doesn't have a way to capture that (yet). 2988 if (ClassDecl->hasUserDeclaredConstructor()) 2989 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2990 2991 // -- if T is a (possibly cv-qualified) non-union class type 2992 // without a user-provided constructor, then the object is 2993 // zero-initialized and, if T's implicitly-declared default 2994 // constructor is non-trivial, that constructor is called. 2995 if ((ClassDecl->getTagKind() == TTK_Class || 2996 ClassDecl->getTagKind() == TTK_Struct)) { 2997 Sequence.AddZeroInitializationStep(Entity.getType()); 2998 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2999 } 3000 } 3001 } 3002 3003 Sequence.AddZeroInitializationStep(Entity.getType()); 3004} 3005 3006/// \brief Attempt default initialization (C++ [dcl.init]p6). 3007static void TryDefaultInitialization(Sema &S, 3008 const InitializedEntity &Entity, 3009 const InitializationKind &Kind, 3010 InitializationSequence &Sequence) { 3011 assert(Kind.getKind() == InitializationKind::IK_Default); 3012 3013 // C++ [dcl.init]p6: 3014 // To default-initialize an object of type T means: 3015 // - if T is an array type, each element is default-initialized; 3016 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 3017 3018 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 3019 // constructor for T is called (and the initialization is ill-formed if 3020 // T has no accessible default constructor); 3021 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) { 3022 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence); 3023 return; 3024 } 3025 3026 // - otherwise, no initialization is performed. 3027 3028 // If a program calls for the default initialization of an object of 3029 // a const-qualified type T, T shall be a class type with a user-provided 3030 // default constructor. 3031 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) { 3032 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 3033 return; 3034 } 3035 3036 // If the destination type has a lifetime property, zero-initialize it. 3037 if (DestType.getQualifiers().hasObjCLifetime()) { 3038 Sequence.AddZeroInitializationStep(Entity.getType()); 3039 return; 3040 } 3041} 3042 3043/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 3044/// which enumerates all conversion functions and performs overload resolution 3045/// to select the best. 3046static void TryUserDefinedConversion(Sema &S, 3047 const InitializedEntity &Entity, 3048 const InitializationKind &Kind, 3049 Expr *Initializer, 3050 InitializationSequence &Sequence) { 3051 QualType DestType = Entity.getType(); 3052 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 3053 QualType SourceType = Initializer->getType(); 3054 assert((DestType->isRecordType() || SourceType->isRecordType()) && 3055 "Must have a class type to perform a user-defined conversion"); 3056 3057 // Build the candidate set directly in the initialization sequence 3058 // structure, so that it will persist if we fail. 3059 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3060 CandidateSet.clear(); 3061 3062 // Determine whether we are allowed to call explicit constructors or 3063 // explicit conversion operators. 3064 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 3065 3066 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 3067 // The type we're converting to is a class type. Enumerate its constructors 3068 // to see if there is a suitable conversion. 3069 CXXRecordDecl *DestRecordDecl 3070 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 3071 3072 // Try to complete the type we're converting to. 3073 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 3074 DeclContext::lookup_iterator Con, ConEnd; 3075 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 3076 Con != ConEnd; ++Con) { 3077 NamedDecl *D = *Con; 3078 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3079 3080 // Find the constructor (which may be a template). 3081 CXXConstructorDecl *Constructor = 0; 3082 FunctionTemplateDecl *ConstructorTmpl 3083 = dyn_cast<FunctionTemplateDecl>(D); 3084 if (ConstructorTmpl) 3085 Constructor = cast<CXXConstructorDecl>( 3086 ConstructorTmpl->getTemplatedDecl()); 3087 else 3088 Constructor = cast<CXXConstructorDecl>(D); 3089 3090 if (!Constructor->isInvalidDecl() && 3091 Constructor->isConvertingConstructor(AllowExplicit)) { 3092 if (ConstructorTmpl) 3093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3094 /*ExplicitArgs*/ 0, 3095 &Initializer, 1, CandidateSet, 3096 /*SuppressUserConversions=*/true); 3097 else 3098 S.AddOverloadCandidate(Constructor, FoundDecl, 3099 &Initializer, 1, CandidateSet, 3100 /*SuppressUserConversions=*/true); 3101 } 3102 } 3103 } 3104 } 3105 3106 SourceLocation DeclLoc = Initializer->getLocStart(); 3107 3108 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 3109 // The type we're converting from is a class type, enumerate its conversion 3110 // functions. 3111 3112 // We can only enumerate the conversion functions for a complete type; if 3113 // the type isn't complete, simply skip this step. 3114 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) { 3115 CXXRecordDecl *SourceRecordDecl 3116 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 3117 3118 const UnresolvedSetImpl *Conversions 3119 = SourceRecordDecl->getVisibleConversionFunctions(); 3120 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 3121 E = Conversions->end(); 3122 I != E; ++I) { 3123 NamedDecl *D = *I; 3124 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3125 if (isa<UsingShadowDecl>(D)) 3126 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3127 3128 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3129 CXXConversionDecl *Conv; 3130 if (ConvTemplate) 3131 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3132 else 3133 Conv = cast<CXXConversionDecl>(D); 3134 3135 if (AllowExplicit || !Conv->isExplicit()) { 3136 if (ConvTemplate) 3137 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 3138 ActingDC, Initializer, DestType, 3139 CandidateSet); 3140 else 3141 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 3142 Initializer, DestType, CandidateSet); 3143 } 3144 } 3145 } 3146 } 3147 3148 // Perform overload resolution. If it fails, return the failed result. 3149 OverloadCandidateSet::iterator Best; 3150 if (OverloadingResult Result 3151 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3152 Sequence.SetOverloadFailure( 3153 InitializationSequence::FK_UserConversionOverloadFailed, 3154 Result); 3155 return; 3156 } 3157 3158 FunctionDecl *Function = Best->Function; 3159 S.MarkDeclarationReferenced(DeclLoc, Function); 3160 3161 if (isa<CXXConstructorDecl>(Function)) { 3162 // Add the user-defined conversion step. Any cv-qualification conversion is 3163 // subsumed by the initialization. 3164 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType); 3165 return; 3166 } 3167 3168 // Add the user-defined conversion step that calls the conversion function. 3169 QualType ConvType = Function->getCallResultType(); 3170 if (ConvType->getAs<RecordType>()) { 3171 // If we're converting to a class type, there may be an copy if 3172 // the resulting temporary object (possible to create an object of 3173 // a base class type). That copy is not a separate conversion, so 3174 // we just make a note of the actual destination type (possibly a 3175 // base class of the type returned by the conversion function) and 3176 // let the user-defined conversion step handle the conversion. 3177 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType); 3178 return; 3179 } 3180 3181 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType); 3182 3183 // If the conversion following the call to the conversion function 3184 // is interesting, add it as a separate step. 3185 if (Best->FinalConversion.First || Best->FinalConversion.Second || 3186 Best->FinalConversion.Third) { 3187 ImplicitConversionSequence ICS; 3188 ICS.setStandard(); 3189 ICS.Standard = Best->FinalConversion; 3190 Sequence.AddConversionSequenceStep(ICS, DestType); 3191 } 3192} 3193 3194/// The non-zero enum values here are indexes into diagnostic alternatives. 3195enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 3196 3197/// Determines whether this expression is an acceptable ICR source. 3198static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e) { 3199 // Skip parens. 3200 e = e->IgnoreParens(); 3201 3202 // Skip address-of nodes. 3203 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 3204 if (op->getOpcode() == UO_AddrOf) 3205 return isInvalidICRSource(C, op->getSubExpr()); 3206 3207 // Skip certain casts. 3208 } else if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 3209 switch (cast->getCastKind()) { 3210 case CK_Dependent: 3211 case CK_BitCast: 3212 case CK_LValueBitCast: 3213 case CK_LValueToRValue: 3214 case CK_NoOp: 3215 return isInvalidICRSource(C, cast->getSubExpr()); 3216 3217 case CK_ArrayToPointerDecay: 3218 return IIK_nonscalar; 3219 3220 case CK_NullToPointer: 3221 return IIK_okay; 3222 3223 default: 3224 break; 3225 } 3226 3227 // If we have a declaration reference, it had better be a local variable. 3228 } else if (DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(e)) { 3229 if (VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl())) 3230 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 3231 3232 // If we have a conditional operator, check both sides. 3233 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 3234 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS())) 3235 return iik; 3236 3237 return isInvalidICRSource(C, cond->getRHS()); 3238 3239 // These are never scalar. 3240 } else if (isa<ArraySubscriptExpr>(e)) { 3241 return IIK_nonscalar; 3242 3243 // Otherwise, it needs to be a null pointer constant. 3244 } else { 3245 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 3246 ? IIK_okay : IIK_nonlocal); 3247 } 3248 3249 return IIK_nonlocal; 3250} 3251 3252/// Check whether the given expression is a valid operand for an 3253/// indirect copy/restore. 3254static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 3255 assert(src->isRValue()); 3256 3257 InvalidICRKind iik = isInvalidICRSource(S.Context, src); 3258 if (iik == IIK_okay) return; 3259 3260 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 3261 << ((unsigned) iik - 1) // shift index into diagnostic explanations 3262 << src->getSourceRange(); 3263} 3264 3265/// \brief Determine whether we have compatible array types for the 3266/// purposes of GNU by-copy array initialization. 3267static bool hasCompatibleArrayTypes(ASTContext &Context, 3268 const ArrayType *Dest, 3269 const ArrayType *Source) { 3270 // If the source and destination array types are equivalent, we're 3271 // done. 3272 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 3273 return true; 3274 3275 // Make sure that the element types are the same. 3276 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 3277 return false; 3278 3279 // The only mismatch we allow is when the destination is an 3280 // incomplete array type and the source is a constant array type. 3281 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 3282} 3283 3284static bool tryObjCWritebackConversion(Sema &S, 3285 InitializationSequence &Sequence, 3286 const InitializedEntity &Entity, 3287 Expr *Initializer) { 3288 bool ArrayDecay = false; 3289 QualType ArgType = Initializer->getType(); 3290 QualType ArgPointee; 3291 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 3292 ArrayDecay = true; 3293 ArgPointee = ArgArrayType->getElementType(); 3294 ArgType = S.Context.getPointerType(ArgPointee); 3295 } 3296 3297 // Handle write-back conversion. 3298 QualType ConvertedArgType; 3299 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 3300 ConvertedArgType)) 3301 return false; 3302 3303 // We should copy unless we're passing to an argument explicitly 3304 // marked 'out'. 3305 bool ShouldCopy = true; 3306 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 3307 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 3308 3309 // Do we need an lvalue conversion? 3310 if (ArrayDecay || Initializer->isGLValue()) { 3311 ImplicitConversionSequence ICS; 3312 ICS.setStandard(); 3313 ICS.Standard.setAsIdentityConversion(); 3314 3315 QualType ResultType; 3316 if (ArrayDecay) { 3317 ICS.Standard.First = ICK_Array_To_Pointer; 3318 ResultType = S.Context.getPointerType(ArgPointee); 3319 } else { 3320 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 3321 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 3322 } 3323 3324 Sequence.AddConversionSequenceStep(ICS, ResultType); 3325 } 3326 3327 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 3328 return true; 3329} 3330 3331InitializationSequence::InitializationSequence(Sema &S, 3332 const InitializedEntity &Entity, 3333 const InitializationKind &Kind, 3334 Expr **Args, 3335 unsigned NumArgs) 3336 : FailedCandidateSet(Kind.getLocation()) { 3337 ASTContext &Context = S.Context; 3338 3339 // C++0x [dcl.init]p16: 3340 // The semantics of initializers are as follows. The destination type is 3341 // the type of the object or reference being initialized and the source 3342 // type is the type of the initializer expression. The source type is not 3343 // defined when the initializer is a braced-init-list or when it is a 3344 // parenthesized list of expressions. 3345 QualType DestType = Entity.getType(); 3346 3347 if (DestType->isDependentType() || 3348 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 3349 SequenceKind = DependentSequence; 3350 return; 3351 } 3352 3353 // Almost everything is a normal sequence. 3354 setSequenceKind(NormalSequence); 3355 3356 for (unsigned I = 0; I != NumArgs; ++I) 3357 if (Args[I]->getObjectKind() == OK_ObjCProperty) { 3358 ExprResult Result = S.ConvertPropertyForRValue(Args[I]); 3359 if (Result.isInvalid()) { 3360 SetFailed(FK_ConversionFromPropertyFailed); 3361 return; 3362 } 3363 Args[I] = Result.take(); 3364 } 3365 3366 QualType SourceType; 3367 Expr *Initializer = 0; 3368 if (NumArgs == 1) { 3369 Initializer = Args[0]; 3370 if (!isa<InitListExpr>(Initializer)) 3371 SourceType = Initializer->getType(); 3372 } 3373 3374 // - If the initializer is a braced-init-list, the object is 3375 // list-initialized (8.5.4). 3376 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 3377 TryListInitialization(S, Entity, Kind, InitList, *this); 3378 return; 3379 } 3380 3381 // - If the destination type is a reference type, see 8.5.3. 3382 if (DestType->isReferenceType()) { 3383 // C++0x [dcl.init.ref]p1: 3384 // A variable declared to be a T& or T&&, that is, "reference to type T" 3385 // (8.3.2), shall be initialized by an object, or function, of type T or 3386 // by an object that can be converted into a T. 3387 // (Therefore, multiple arguments are not permitted.) 3388 if (NumArgs != 1) 3389 SetFailed(FK_TooManyInitsForReference); 3390 else 3391 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 3392 return; 3393 } 3394 3395 // - If the initializer is (), the object is value-initialized. 3396 if (Kind.getKind() == InitializationKind::IK_Value || 3397 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) { 3398 TryValueInitialization(S, Entity, Kind, *this); 3399 return; 3400 } 3401 3402 // Handle default initialization. 3403 if (Kind.getKind() == InitializationKind::IK_Default) { 3404 TryDefaultInitialization(S, Entity, Kind, *this); 3405 return; 3406 } 3407 3408 // - If the destination type is an array of characters, an array of 3409 // char16_t, an array of char32_t, or an array of wchar_t, and the 3410 // initializer is a string literal, see 8.5.2. 3411 // - Otherwise, if the destination type is an array, the program is 3412 // ill-formed. 3413 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 3414 if (Initializer && IsStringInit(Initializer, DestAT, Context)) { 3415 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 3416 return; 3417 } 3418 3419 // Note: as an GNU C extension, we allow initialization of an 3420 // array from a compound literal that creates an array of the same 3421 // type, so long as the initializer has no side effects. 3422 if (!S.getLangOptions().CPlusPlus && Initializer && 3423 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 3424 Initializer->getType()->isArrayType()) { 3425 const ArrayType *SourceAT 3426 = Context.getAsArrayType(Initializer->getType()); 3427 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 3428 SetFailed(FK_ArrayTypeMismatch); 3429 else if (Initializer->HasSideEffects(S.Context)) 3430 SetFailed(FK_NonConstantArrayInit); 3431 else { 3432 AddArrayInitStep(DestType); 3433 } 3434 } else if (DestAT->getElementType()->isAnyCharacterType()) 3435 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 3436 else 3437 SetFailed(FK_ArrayNeedsInitList); 3438 3439 return; 3440 } 3441 3442 // Determine whether we should consider writeback conversions for 3443 // Objective-C ARC. 3444 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount && 3445 Entity.getKind() == InitializedEntity::EK_Parameter; 3446 3447 // We're at the end of the line for C: it's either a write-back conversion 3448 // or it's a C assignment. There's no need to check anything else. 3449 if (!S.getLangOptions().CPlusPlus) { 3450 // If allowed, check whether this is an Objective-C writeback conversion. 3451 if (allowObjCWritebackConversion && 3452 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 3453 return; 3454 } 3455 3456 // Handle initialization in C 3457 AddCAssignmentStep(DestType); 3458 MaybeProduceObjCObject(S, *this, Entity); 3459 return; 3460 } 3461 3462 assert(S.getLangOptions().CPlusPlus); 3463 3464 // - If the destination type is a (possibly cv-qualified) class type: 3465 if (DestType->isRecordType()) { 3466 // - If the initialization is direct-initialization, or if it is 3467 // copy-initialization where the cv-unqualified version of the 3468 // source type is the same class as, or a derived class of, the 3469 // class of the destination, constructors are considered. [...] 3470 if (Kind.getKind() == InitializationKind::IK_Direct || 3471 (Kind.getKind() == InitializationKind::IK_Copy && 3472 (Context.hasSameUnqualifiedType(SourceType, DestType) || 3473 S.IsDerivedFrom(SourceType, DestType)))) 3474 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, 3475 Entity.getType(), *this); 3476 // - Otherwise (i.e., for the remaining copy-initialization cases), 3477 // user-defined conversion sequences that can convert from the source 3478 // type to the destination type or (when a conversion function is 3479 // used) to a derived class thereof are enumerated as described in 3480 // 13.3.1.4, and the best one is chosen through overload resolution 3481 // (13.3). 3482 else 3483 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 3484 return; 3485 } 3486 3487 if (NumArgs > 1) { 3488 SetFailed(FK_TooManyInitsForScalar); 3489 return; 3490 } 3491 assert(NumArgs == 1 && "Zero-argument case handled above"); 3492 3493 // - Otherwise, if the source type is a (possibly cv-qualified) class 3494 // type, conversion functions are considered. 3495 if (!SourceType.isNull() && SourceType->isRecordType()) { 3496 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 3497 MaybeProduceObjCObject(S, *this, Entity); 3498 return; 3499 } 3500 3501 // - Otherwise, the initial value of the object being initialized is the 3502 // (possibly converted) value of the initializer expression. Standard 3503 // conversions (Clause 4) will be used, if necessary, to convert the 3504 // initializer expression to the cv-unqualified version of the 3505 // destination type; no user-defined conversions are considered. 3506 3507 ImplicitConversionSequence ICS 3508 = S.TryImplicitConversion(Initializer, Entity.getType(), 3509 /*SuppressUserConversions*/true, 3510 /*AllowExplicitConversions*/ false, 3511 /*InOverloadResolution*/ false, 3512 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 3513 allowObjCWritebackConversion); 3514 3515 if (ICS.isStandard() && 3516 ICS.Standard.Second == ICK_Writeback_Conversion) { 3517 // Objective-C ARC writeback conversion. 3518 3519 // We should copy unless we're passing to an argument explicitly 3520 // marked 'out'. 3521 bool ShouldCopy = true; 3522 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 3523 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 3524 3525 // If there was an lvalue adjustment, add it as a separate conversion. 3526 if (ICS.Standard.First == ICK_Array_To_Pointer || 3527 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 3528 ImplicitConversionSequence LvalueICS; 3529 LvalueICS.setStandard(); 3530 LvalueICS.Standard.setAsIdentityConversion(); 3531 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 3532 LvalueICS.Standard.First = ICS.Standard.First; 3533 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 3534 } 3535 3536 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 3537 } else if (ICS.isBad()) { 3538 DeclAccessPair dap; 3539 if (Initializer->getType() == Context.OverloadTy && 3540 !S.ResolveAddressOfOverloadedFunction(Initializer 3541 , DestType, false, dap)) 3542 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3543 else 3544 SetFailed(InitializationSequence::FK_ConversionFailed); 3545 } else { 3546 AddConversionSequenceStep(ICS, Entity.getType()); 3547 3548 MaybeProduceObjCObject(S, *this, Entity); 3549 } 3550} 3551 3552InitializationSequence::~InitializationSequence() { 3553 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(), 3554 StepEnd = Steps.end(); 3555 Step != StepEnd; ++Step) 3556 Step->Destroy(); 3557} 3558 3559//===----------------------------------------------------------------------===// 3560// Perform initialization 3561//===----------------------------------------------------------------------===// 3562static Sema::AssignmentAction 3563getAssignmentAction(const InitializedEntity &Entity) { 3564 switch(Entity.getKind()) { 3565 case InitializedEntity::EK_Variable: 3566 case InitializedEntity::EK_New: 3567 case InitializedEntity::EK_Exception: 3568 case InitializedEntity::EK_Base: 3569 case InitializedEntity::EK_Delegating: 3570 return Sema::AA_Initializing; 3571 3572 case InitializedEntity::EK_Parameter: 3573 if (Entity.getDecl() && 3574 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 3575 return Sema::AA_Sending; 3576 3577 return Sema::AA_Passing; 3578 3579 case InitializedEntity::EK_Result: 3580 return Sema::AA_Returning; 3581 3582 case InitializedEntity::EK_Temporary: 3583 // FIXME: Can we tell apart casting vs. converting? 3584 return Sema::AA_Casting; 3585 3586 case InitializedEntity::EK_Member: 3587 case InitializedEntity::EK_ArrayElement: 3588 case InitializedEntity::EK_VectorElement: 3589 case InitializedEntity::EK_BlockElement: 3590 return Sema::AA_Initializing; 3591 } 3592 3593 return Sema::AA_Converting; 3594} 3595 3596/// \brief Whether we should binding a created object as a temporary when 3597/// initializing the given entity. 3598static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 3599 switch (Entity.getKind()) { 3600 case InitializedEntity::EK_ArrayElement: 3601 case InitializedEntity::EK_Member: 3602 case InitializedEntity::EK_Result: 3603 case InitializedEntity::EK_New: 3604 case InitializedEntity::EK_Variable: 3605 case InitializedEntity::EK_Base: 3606 case InitializedEntity::EK_Delegating: 3607 case InitializedEntity::EK_VectorElement: 3608 case InitializedEntity::EK_Exception: 3609 case InitializedEntity::EK_BlockElement: 3610 return false; 3611 3612 case InitializedEntity::EK_Parameter: 3613 case InitializedEntity::EK_Temporary: 3614 return true; 3615 } 3616 3617 llvm_unreachable("missed an InitializedEntity kind?"); 3618} 3619 3620/// \brief Whether the given entity, when initialized with an object 3621/// created for that initialization, requires destruction. 3622static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 3623 switch (Entity.getKind()) { 3624 case InitializedEntity::EK_Member: 3625 case InitializedEntity::EK_Result: 3626 case InitializedEntity::EK_New: 3627 case InitializedEntity::EK_Base: 3628 case InitializedEntity::EK_Delegating: 3629 case InitializedEntity::EK_VectorElement: 3630 case InitializedEntity::EK_BlockElement: 3631 return false; 3632 3633 case InitializedEntity::EK_Variable: 3634 case InitializedEntity::EK_Parameter: 3635 case InitializedEntity::EK_Temporary: 3636 case InitializedEntity::EK_ArrayElement: 3637 case InitializedEntity::EK_Exception: 3638 return true; 3639 } 3640 3641 llvm_unreachable("missed an InitializedEntity kind?"); 3642} 3643 3644/// \brief Make a (potentially elidable) temporary copy of the object 3645/// provided by the given initializer by calling the appropriate copy 3646/// constructor. 3647/// 3648/// \param S The Sema object used for type-checking. 3649/// 3650/// \param T The type of the temporary object, which must either be 3651/// the type of the initializer expression or a superclass thereof. 3652/// 3653/// \param Enter The entity being initialized. 3654/// 3655/// \param CurInit The initializer expression. 3656/// 3657/// \param IsExtraneousCopy Whether this is an "extraneous" copy that 3658/// is permitted in C++03 (but not C++0x) when binding a reference to 3659/// an rvalue. 3660/// 3661/// \returns An expression that copies the initializer expression into 3662/// a temporary object, or an error expression if a copy could not be 3663/// created. 3664static ExprResult CopyObject(Sema &S, 3665 QualType T, 3666 const InitializedEntity &Entity, 3667 ExprResult CurInit, 3668 bool IsExtraneousCopy) { 3669 // Determine which class type we're copying to. 3670 Expr *CurInitExpr = (Expr *)CurInit.get(); 3671 CXXRecordDecl *Class = 0; 3672 if (const RecordType *Record = T->getAs<RecordType>()) 3673 Class = cast<CXXRecordDecl>(Record->getDecl()); 3674 if (!Class) 3675 return move(CurInit); 3676 3677 // C++0x [class.copy]p32: 3678 // When certain criteria are met, an implementation is allowed to 3679 // omit the copy/move construction of a class object, even if the 3680 // copy/move constructor and/or destructor for the object have 3681 // side effects. [...] 3682 // - when a temporary class object that has not been bound to a 3683 // reference (12.2) would be copied/moved to a class object 3684 // with the same cv-unqualified type, the copy/move operation 3685 // can be omitted by constructing the temporary object 3686 // directly into the target of the omitted copy/move 3687 // 3688 // Note that the other three bullets are handled elsewhere. Copy 3689 // elision for return statements and throw expressions are handled as part 3690 // of constructor initialization, while copy elision for exception handlers 3691 // is handled by the run-time. 3692 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class); 3693 SourceLocation Loc; 3694 switch (Entity.getKind()) { 3695 case InitializedEntity::EK_Result: 3696 Loc = Entity.getReturnLoc(); 3697 break; 3698 3699 case InitializedEntity::EK_Exception: 3700 Loc = Entity.getThrowLoc(); 3701 break; 3702 3703 case InitializedEntity::EK_Variable: 3704 Loc = Entity.getDecl()->getLocation(); 3705 break; 3706 3707 case InitializedEntity::EK_ArrayElement: 3708 case InitializedEntity::EK_Member: 3709 case InitializedEntity::EK_Parameter: 3710 case InitializedEntity::EK_Temporary: 3711 case InitializedEntity::EK_New: 3712 case InitializedEntity::EK_Base: 3713 case InitializedEntity::EK_Delegating: 3714 case InitializedEntity::EK_VectorElement: 3715 case InitializedEntity::EK_BlockElement: 3716 Loc = CurInitExpr->getLocStart(); 3717 break; 3718 } 3719 3720 // Make sure that the type we are copying is complete. 3721 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete))) 3722 return move(CurInit); 3723 3724 // Perform overload resolution using the class's copy/move constructors. 3725 DeclContext::lookup_iterator Con, ConEnd; 3726 OverloadCandidateSet CandidateSet(Loc); 3727 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class); 3728 Con != ConEnd; ++Con) { 3729 // Only consider copy/move constructors and constructor templates. Per 3730 // C++0x [dcl.init]p16, second bullet to class types, this 3731 // initialization is direct-initialization. 3732 CXXConstructorDecl *Constructor = 0; 3733 3734 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) { 3735 // Handle copy/moveconstructors, only. 3736 if (!Constructor || Constructor->isInvalidDecl() || 3737 !Constructor->isCopyOrMoveConstructor() || 3738 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 3739 continue; 3740 3741 DeclAccessPair FoundDecl 3742 = DeclAccessPair::make(Constructor, Constructor->getAccess()); 3743 S.AddOverloadCandidate(Constructor, FoundDecl, 3744 &CurInitExpr, 1, CandidateSet); 3745 continue; 3746 } 3747 3748 // Handle constructor templates. 3749 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con); 3750 if (ConstructorTmpl->isInvalidDecl()) 3751 continue; 3752 3753 Constructor = cast<CXXConstructorDecl>( 3754 ConstructorTmpl->getTemplatedDecl()); 3755 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 3756 continue; 3757 3758 // FIXME: Do we need to limit this to copy-constructor-like 3759 // candidates? 3760 DeclAccessPair FoundDecl 3761 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess()); 3762 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0, 3763 &CurInitExpr, 1, CandidateSet, true); 3764 } 3765 3766 OverloadCandidateSet::iterator Best; 3767 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 3768 case OR_Success: 3769 break; 3770 3771 case OR_No_Viable_Function: 3772 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 3773 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 3774 : diag::err_temp_copy_no_viable) 3775 << (int)Entity.getKind() << CurInitExpr->getType() 3776 << CurInitExpr->getSourceRange(); 3777 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1); 3778 if (!IsExtraneousCopy || S.isSFINAEContext()) 3779 return ExprError(); 3780 return move(CurInit); 3781 3782 case OR_Ambiguous: 3783 S.Diag(Loc, diag::err_temp_copy_ambiguous) 3784 << (int)Entity.getKind() << CurInitExpr->getType() 3785 << CurInitExpr->getSourceRange(); 3786 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1); 3787 return ExprError(); 3788 3789 case OR_Deleted: 3790 S.Diag(Loc, diag::err_temp_copy_deleted) 3791 << (int)Entity.getKind() << CurInitExpr->getType() 3792 << CurInitExpr->getSourceRange(); 3793 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3794 << 1 << Best->Function->isDeleted(); 3795 return ExprError(); 3796 } 3797 3798 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3799 ASTOwningVector<Expr*> ConstructorArgs(S); 3800 CurInit.release(); // Ownership transferred into MultiExprArg, below. 3801 3802 S.CheckConstructorAccess(Loc, Constructor, Entity, 3803 Best->FoundDecl.getAccess(), IsExtraneousCopy); 3804 3805 if (IsExtraneousCopy) { 3806 // If this is a totally extraneous copy for C++03 reference 3807 // binding purposes, just return the original initialization 3808 // expression. We don't generate an (elided) copy operation here 3809 // because doing so would require us to pass down a flag to avoid 3810 // infinite recursion, where each step adds another extraneous, 3811 // elidable copy. 3812 3813 // Instantiate the default arguments of any extra parameters in 3814 // the selected copy constructor, as if we were going to create a 3815 // proper call to the copy constructor. 3816 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 3817 ParmVarDecl *Parm = Constructor->getParamDecl(I); 3818 if (S.RequireCompleteType(Loc, Parm->getType(), 3819 S.PDiag(diag::err_call_incomplete_argument))) 3820 break; 3821 3822 // Build the default argument expression; we don't actually care 3823 // if this succeeds or not, because this routine will complain 3824 // if there was a problem. 3825 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 3826 } 3827 3828 return S.Owned(CurInitExpr); 3829 } 3830 3831 S.MarkDeclarationReferenced(Loc, Constructor); 3832 3833 // Determine the arguments required to actually perform the 3834 // constructor call (we might have derived-to-base conversions, or 3835 // the copy constructor may have default arguments). 3836 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1), 3837 Loc, ConstructorArgs)) 3838 return ExprError(); 3839 3840 // Actually perform the constructor call. 3841 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable, 3842 move_arg(ConstructorArgs), 3843 /*ZeroInit*/ false, 3844 CXXConstructExpr::CK_Complete, 3845 SourceRange()); 3846 3847 // If we're supposed to bind temporaries, do so. 3848 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 3849 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3850 return move(CurInit); 3851} 3852 3853void InitializationSequence::PrintInitLocationNote(Sema &S, 3854 const InitializedEntity &Entity) { 3855 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) { 3856 if (Entity.getDecl()->getLocation().isInvalid()) 3857 return; 3858 3859 if (Entity.getDecl()->getDeclName()) 3860 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 3861 << Entity.getDecl()->getDeclName(); 3862 else 3863 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 3864 } 3865} 3866 3867ExprResult 3868InitializationSequence::Perform(Sema &S, 3869 const InitializedEntity &Entity, 3870 const InitializationKind &Kind, 3871 MultiExprArg Args, 3872 QualType *ResultType) { 3873 if (Failed()) { 3874 unsigned NumArgs = Args.size(); 3875 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 3876 return ExprError(); 3877 } 3878 3879 if (getKind() == DependentSequence) { 3880 // If the declaration is a non-dependent, incomplete array type 3881 // that has an initializer, then its type will be completed once 3882 // the initializer is instantiated. 3883 if (ResultType && !Entity.getType()->isDependentType() && 3884 Args.size() == 1) { 3885 QualType DeclType = Entity.getType(); 3886 if (const IncompleteArrayType *ArrayT 3887 = S.Context.getAsIncompleteArrayType(DeclType)) { 3888 // FIXME: We don't currently have the ability to accurately 3889 // compute the length of an initializer list without 3890 // performing full type-checking of the initializer list 3891 // (since we have to determine where braces are implicitly 3892 // introduced and such). So, we fall back to making the array 3893 // type a dependently-sized array type with no specified 3894 // bound. 3895 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 3896 SourceRange Brackets; 3897 3898 // Scavange the location of the brackets from the entity, if we can. 3899 if (DeclaratorDecl *DD = Entity.getDecl()) { 3900 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 3901 TypeLoc TL = TInfo->getTypeLoc(); 3902 if (IncompleteArrayTypeLoc *ArrayLoc 3903 = dyn_cast<IncompleteArrayTypeLoc>(&TL)) 3904 Brackets = ArrayLoc->getBracketsRange(); 3905 } 3906 } 3907 3908 *ResultType 3909 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 3910 /*NumElts=*/0, 3911 ArrayT->getSizeModifier(), 3912 ArrayT->getIndexTypeCVRQualifiers(), 3913 Brackets); 3914 } 3915 3916 } 3917 } 3918 3919 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast()) 3920 return ExprResult(Args.release()[0]); 3921 3922 if (Args.size() == 0) 3923 return S.Owned((Expr *)0); 3924 3925 unsigned NumArgs = Args.size(); 3926 return S.Owned(new (S.Context) ParenListExpr(S.Context, 3927 SourceLocation(), 3928 (Expr **)Args.release(), 3929 NumArgs, 3930 SourceLocation())); 3931 } 3932 3933 // No steps means no initialization. 3934 if (Steps.empty()) 3935 return S.Owned((Expr *)0); 3936 3937 QualType DestType = Entity.getType().getNonReferenceType(); 3938 // FIXME: Ugly hack around the fact that Entity.getType() is not 3939 // the same as Entity.getDecl()->getType() in cases involving type merging, 3940 // and we want latter when it makes sense. 3941 if (ResultType) 3942 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 3943 Entity.getType(); 3944 3945 ExprResult CurInit = S.Owned((Expr *)0); 3946 3947 // For initialization steps that start with a single initializer, 3948 // grab the only argument out the Args and place it into the "current" 3949 // initializer. 3950 switch (Steps.front().Kind) { 3951 case SK_ResolveAddressOfOverloadedFunction: 3952 case SK_CastDerivedToBaseRValue: 3953 case SK_CastDerivedToBaseXValue: 3954 case SK_CastDerivedToBaseLValue: 3955 case SK_BindReference: 3956 case SK_BindReferenceToTemporary: 3957 case SK_ExtraneousCopyToTemporary: 3958 case SK_UserConversion: 3959 case SK_QualificationConversionLValue: 3960 case SK_QualificationConversionXValue: 3961 case SK_QualificationConversionRValue: 3962 case SK_ConversionSequence: 3963 case SK_ListInitialization: 3964 case SK_CAssignment: 3965 case SK_StringInit: 3966 case SK_ObjCObjectConversion: 3967 case SK_ArrayInit: 3968 case SK_PassByIndirectCopyRestore: 3969 case SK_PassByIndirectRestore: 3970 case SK_ProduceObjCObject: { 3971 assert(Args.size() == 1); 3972 CurInit = Args.get()[0]; 3973 if (!CurInit.get()) return ExprError(); 3974 3975 // Read from a property when initializing something with it. 3976 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) { 3977 CurInit = S.ConvertPropertyForRValue(CurInit.take()); 3978 if (CurInit.isInvalid()) 3979 return ExprError(); 3980 } 3981 break; 3982 } 3983 3984 case SK_ConstructorInitialization: 3985 case SK_ZeroInitialization: 3986 break; 3987 } 3988 3989 // Walk through the computed steps for the initialization sequence, 3990 // performing the specified conversions along the way. 3991 bool ConstructorInitRequiresZeroInit = false; 3992 for (step_iterator Step = step_begin(), StepEnd = step_end(); 3993 Step != StepEnd; ++Step) { 3994 if (CurInit.isInvalid()) 3995 return ExprError(); 3996 3997 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 3998 3999 switch (Step->Kind) { 4000 case SK_ResolveAddressOfOverloadedFunction: 4001 // Overload resolution determined which function invoke; update the 4002 // initializer to reflect that choice. 4003 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 4004 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()); 4005 CurInit = S.FixOverloadedFunctionReference(move(CurInit), 4006 Step->Function.FoundDecl, 4007 Step->Function.Function); 4008 break; 4009 4010 case SK_CastDerivedToBaseRValue: 4011 case SK_CastDerivedToBaseXValue: 4012 case SK_CastDerivedToBaseLValue: { 4013 // We have a derived-to-base cast that produces either an rvalue or an 4014 // lvalue. Perform that cast. 4015 4016 CXXCastPath BasePath; 4017 4018 // Casts to inaccessible base classes are allowed with C-style casts. 4019 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 4020 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 4021 CurInit.get()->getLocStart(), 4022 CurInit.get()->getSourceRange(), 4023 &BasePath, IgnoreBaseAccess)) 4024 return ExprError(); 4025 4026 if (S.BasePathInvolvesVirtualBase(BasePath)) { 4027 QualType T = SourceType; 4028 if (const PointerType *Pointer = T->getAs<PointerType>()) 4029 T = Pointer->getPointeeType(); 4030 if (const RecordType *RecordTy = T->getAs<RecordType>()) 4031 S.MarkVTableUsed(CurInit.get()->getLocStart(), 4032 cast<CXXRecordDecl>(RecordTy->getDecl())); 4033 } 4034 4035 ExprValueKind VK = 4036 Step->Kind == SK_CastDerivedToBaseLValue ? 4037 VK_LValue : 4038 (Step->Kind == SK_CastDerivedToBaseXValue ? 4039 VK_XValue : 4040 VK_RValue); 4041 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 4042 Step->Type, 4043 CK_DerivedToBase, 4044 CurInit.get(), 4045 &BasePath, VK)); 4046 break; 4047 } 4048 4049 case SK_BindReference: 4050 if (FieldDecl *BitField = CurInit.get()->getBitField()) { 4051 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 4052 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 4053 << Entity.getType().isVolatileQualified() 4054 << BitField->getDeclName() 4055 << CurInit.get()->getSourceRange(); 4056 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 4057 return ExprError(); 4058 } 4059 4060 if (CurInit.get()->refersToVectorElement()) { 4061 // References cannot bind to vector elements. 4062 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 4063 << Entity.getType().isVolatileQualified() 4064 << CurInit.get()->getSourceRange(); 4065 PrintInitLocationNote(S, Entity); 4066 return ExprError(); 4067 } 4068 4069 // Reference binding does not have any corresponding ASTs. 4070 4071 // Check exception specifications 4072 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 4073 return ExprError(); 4074 4075 break; 4076 4077 case SK_BindReferenceToTemporary: 4078 // Reference binding does not have any corresponding ASTs. 4079 4080 // Check exception specifications 4081 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 4082 return ExprError(); 4083 4084 break; 4085 4086 case SK_ExtraneousCopyToTemporary: 4087 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit), 4088 /*IsExtraneousCopy=*/true); 4089 break; 4090 4091 case SK_UserConversion: { 4092 // We have a user-defined conversion that invokes either a constructor 4093 // or a conversion function. 4094 CastKind CastKind; 4095 bool IsCopy = false; 4096 FunctionDecl *Fn = Step->Function.Function; 4097 DeclAccessPair FoundFn = Step->Function.FoundDecl; 4098 bool CreatedObject = false; 4099 bool IsLvalue = false; 4100 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 4101 // Build a call to the selected constructor. 4102 ASTOwningVector<Expr*> ConstructorArgs(S); 4103 SourceLocation Loc = CurInit.get()->getLocStart(); 4104 CurInit.release(); // Ownership transferred into MultiExprArg, below. 4105 4106 // Determine the arguments required to actually perform the constructor 4107 // call. 4108 Expr *Arg = CurInit.get(); 4109 if (S.CompleteConstructorCall(Constructor, 4110 MultiExprArg(&Arg, 1), 4111 Loc, ConstructorArgs)) 4112 return ExprError(); 4113 4114 // Build the an expression that constructs a temporary. 4115 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 4116 move_arg(ConstructorArgs), 4117 /*ZeroInit*/ false, 4118 CXXConstructExpr::CK_Complete, 4119 SourceRange()); 4120 if (CurInit.isInvalid()) 4121 return ExprError(); 4122 4123 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity, 4124 FoundFn.getAccess()); 4125 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 4126 4127 CastKind = CK_ConstructorConversion; 4128 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 4129 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 4130 S.IsDerivedFrom(SourceType, Class)) 4131 IsCopy = true; 4132 4133 CreatedObject = true; 4134 } else { 4135 // Build a call to the conversion function. 4136 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 4137 IsLvalue = Conversion->getResultType()->isLValueReferenceType(); 4138 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0, 4139 FoundFn); 4140 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 4141 4142 // FIXME: Should we move this initialization into a separate 4143 // derived-to-base conversion? I believe the answer is "no", because 4144 // we don't want to turn off access control here for c-style casts. 4145 ExprResult CurInitExprRes = 4146 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0, 4147 FoundFn, Conversion); 4148 if(CurInitExprRes.isInvalid()) 4149 return ExprError(); 4150 CurInit = move(CurInitExprRes); 4151 4152 // Build the actual call to the conversion function. 4153 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion); 4154 if (CurInit.isInvalid() || !CurInit.get()) 4155 return ExprError(); 4156 4157 CastKind = CK_UserDefinedConversion; 4158 4159 CreatedObject = Conversion->getResultType()->isRecordType(); 4160 } 4161 4162 bool RequiresCopy = !IsCopy && 4163 getKind() != InitializationSequence::ReferenceBinding; 4164 if (RequiresCopy || shouldBindAsTemporary(Entity)) 4165 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4166 else if (CreatedObject && shouldDestroyTemporary(Entity)) { 4167 QualType T = CurInit.get()->getType(); 4168 if (const RecordType *Record = T->getAs<RecordType>()) { 4169 CXXDestructorDecl *Destructor 4170 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 4171 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, 4172 S.PDiag(diag::err_access_dtor_temp) << T); 4173 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor); 4174 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()); 4175 } 4176 } 4177 4178 // FIXME: xvalues 4179 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 4180 CurInit.get()->getType(), 4181 CastKind, CurInit.get(), 0, 4182 IsLvalue ? VK_LValue : VK_RValue)); 4183 4184 if (RequiresCopy) 4185 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 4186 move(CurInit), /*IsExtraneousCopy=*/false); 4187 4188 break; 4189 } 4190 4191 case SK_QualificationConversionLValue: 4192 case SK_QualificationConversionXValue: 4193 case SK_QualificationConversionRValue: { 4194 // Perform a qualification conversion; these can never go wrong. 4195 ExprValueKind VK = 4196 Step->Kind == SK_QualificationConversionLValue ? 4197 VK_LValue : 4198 (Step->Kind == SK_QualificationConversionXValue ? 4199 VK_XValue : 4200 VK_RValue); 4201 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK); 4202 break; 4203 } 4204 4205 case SK_ConversionSequence: { 4206 Sema::CheckedConversionKind CCK 4207 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 4208 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 4209 : Kind.isExplicitCast()? Sema::CCK_OtherCast 4210 : Sema::CCK_ImplicitConversion; 4211 ExprResult CurInitExprRes = 4212 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 4213 getAssignmentAction(Entity), CCK); 4214 if (CurInitExprRes.isInvalid()) 4215 return ExprError(); 4216 CurInit = move(CurInitExprRes); 4217 break; 4218 } 4219 4220 case SK_ListInitialization: { 4221 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 4222 QualType Ty = Step->Type; 4223 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty)) 4224 return ExprError(); 4225 4226 CurInit.release(); 4227 CurInit = S.Owned(InitList); 4228 break; 4229 } 4230 4231 case SK_ConstructorInitialization: { 4232 unsigned NumArgs = Args.size(); 4233 CXXConstructorDecl *Constructor 4234 = cast<CXXConstructorDecl>(Step->Function.Function); 4235 4236 // Build a call to the selected constructor. 4237 ASTOwningVector<Expr*> ConstructorArgs(S); 4238 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 4239 ? Kind.getEqualLoc() 4240 : Kind.getLocation(); 4241 4242 if (Kind.getKind() == InitializationKind::IK_Default) { 4243 // Force even a trivial, implicit default constructor to be 4244 // semantically checked. We do this explicitly because we don't build 4245 // the definition for completely trivial constructors. 4246 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4247 assert(ClassDecl && "No parent class for constructor."); 4248 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 4249 ClassDecl->hasTrivialDefaultConstructor() && 4250 !Constructor->isUsed(false)) 4251 S.DefineImplicitDefaultConstructor(Loc, Constructor); 4252 } 4253 4254 // Determine the arguments required to actually perform the constructor 4255 // call. 4256 if (S.CompleteConstructorCall(Constructor, move(Args), 4257 Loc, ConstructorArgs)) 4258 return ExprError(); 4259 4260 4261 if (Entity.getKind() == InitializedEntity::EK_Temporary && 4262 NumArgs != 1 && // FIXME: Hack to work around cast weirdness 4263 (Kind.getKind() == InitializationKind::IK_Direct || 4264 Kind.getKind() == InitializationKind::IK_Value)) { 4265 // An explicitly-constructed temporary, e.g., X(1, 2). 4266 unsigned NumExprs = ConstructorArgs.size(); 4267 Expr **Exprs = (Expr **)ConstructorArgs.take(); 4268 S.MarkDeclarationReferenced(Loc, Constructor); 4269 S.DiagnoseUseOfDecl(Constructor, Loc); 4270 4271 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 4272 if (!TSInfo) 4273 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 4274 4275 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context, 4276 Constructor, 4277 TSInfo, 4278 Exprs, 4279 NumExprs, 4280 Kind.getParenRange(), 4281 ConstructorInitRequiresZeroInit)); 4282 } else { 4283 CXXConstructExpr::ConstructionKind ConstructKind = 4284 CXXConstructExpr::CK_Complete; 4285 4286 if (Entity.getKind() == InitializedEntity::EK_Base) { 4287 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 4288 CXXConstructExpr::CK_VirtualBase : 4289 CXXConstructExpr::CK_NonVirtualBase; 4290 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 4291 ConstructKind = CXXConstructExpr::CK_Delegating; 4292 } 4293 4294 // Only get the parenthesis range if it is a direct construction. 4295 SourceRange parenRange = 4296 Kind.getKind() == InitializationKind::IK_Direct ? 4297 Kind.getParenRange() : SourceRange(); 4298 4299 // If the entity allows NRVO, mark the construction as elidable 4300 // unconditionally. 4301 if (Entity.allowsNRVO()) 4302 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4303 Constructor, /*Elidable=*/true, 4304 move_arg(ConstructorArgs), 4305 ConstructorInitRequiresZeroInit, 4306 ConstructKind, 4307 parenRange); 4308 else 4309 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4310 Constructor, 4311 move_arg(ConstructorArgs), 4312 ConstructorInitRequiresZeroInit, 4313 ConstructKind, 4314 parenRange); 4315 } 4316 if (CurInit.isInvalid()) 4317 return ExprError(); 4318 4319 // Only check access if all of that succeeded. 4320 S.CheckConstructorAccess(Loc, Constructor, Entity, 4321 Step->Function.FoundDecl.getAccess()); 4322 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc); 4323 4324 if (shouldBindAsTemporary(Entity)) 4325 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4326 4327 break; 4328 } 4329 4330 case SK_ZeroInitialization: { 4331 step_iterator NextStep = Step; 4332 ++NextStep; 4333 if (NextStep != StepEnd && 4334 NextStep->Kind == SK_ConstructorInitialization) { 4335 // The need for zero-initialization is recorded directly into 4336 // the call to the object's constructor within the next step. 4337 ConstructorInitRequiresZeroInit = true; 4338 } else if (Kind.getKind() == InitializationKind::IK_Value && 4339 S.getLangOptions().CPlusPlus && 4340 !Kind.isImplicitValueInit()) { 4341 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 4342 if (!TSInfo) 4343 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 4344 Kind.getRange().getBegin()); 4345 4346 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr( 4347 TSInfo->getType().getNonLValueExprType(S.Context), 4348 TSInfo, 4349 Kind.getRange().getEnd())); 4350 } else { 4351 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 4352 } 4353 break; 4354 } 4355 4356 case SK_CAssignment: { 4357 QualType SourceType = CurInit.get()->getType(); 4358 ExprResult Result = move(CurInit); 4359 Sema::AssignConvertType ConvTy = 4360 S.CheckSingleAssignmentConstraints(Step->Type, Result); 4361 if (Result.isInvalid()) 4362 return ExprError(); 4363 CurInit = move(Result); 4364 4365 // If this is a call, allow conversion to a transparent union. 4366 ExprResult CurInitExprRes = move(CurInit); 4367 if (ConvTy != Sema::Compatible && 4368 Entity.getKind() == InitializedEntity::EK_Parameter && 4369 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 4370 == Sema::Compatible) 4371 ConvTy = Sema::Compatible; 4372 if (CurInitExprRes.isInvalid()) 4373 return ExprError(); 4374 CurInit = move(CurInitExprRes); 4375 4376 bool Complained; 4377 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 4378 Step->Type, SourceType, 4379 CurInit.get(), 4380 getAssignmentAction(Entity), 4381 &Complained)) { 4382 PrintInitLocationNote(S, Entity); 4383 return ExprError(); 4384 } else if (Complained) 4385 PrintInitLocationNote(S, Entity); 4386 break; 4387 } 4388 4389 case SK_StringInit: { 4390 QualType Ty = Step->Type; 4391 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, 4392 S.Context.getAsArrayType(Ty), S); 4393 break; 4394 } 4395 4396 case SK_ObjCObjectConversion: 4397 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, 4398 CK_ObjCObjectLValueCast, 4399 S.CastCategory(CurInit.get())); 4400 break; 4401 4402 case SK_ArrayInit: 4403 // Okay: we checked everything before creating this step. Note that 4404 // this is a GNU extension. 4405 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 4406 << Step->Type << CurInit.get()->getType() 4407 << CurInit.get()->getSourceRange(); 4408 4409 // If the destination type is an incomplete array type, update the 4410 // type accordingly. 4411 if (ResultType) { 4412 if (const IncompleteArrayType *IncompleteDest 4413 = S.Context.getAsIncompleteArrayType(Step->Type)) { 4414 if (const ConstantArrayType *ConstantSource 4415 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 4416 *ResultType = S.Context.getConstantArrayType( 4417 IncompleteDest->getElementType(), 4418 ConstantSource->getSize(), 4419 ArrayType::Normal, 0); 4420 } 4421 } 4422 } 4423 break; 4424 4425 case SK_PassByIndirectCopyRestore: 4426 case SK_PassByIndirectRestore: 4427 checkIndirectCopyRestoreSource(S, CurInit.get()); 4428 CurInit = S.Owned(new (S.Context) 4429 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type, 4430 Step->Kind == SK_PassByIndirectCopyRestore)); 4431 break; 4432 4433 case SK_ProduceObjCObject: 4434 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type, 4435 CK_ObjCProduceObject, 4436 CurInit.take(), 0, VK_RValue)); 4437 break; 4438 } 4439 } 4440 4441 // Diagnose non-fatal problems with the completed initialization. 4442 if (Entity.getKind() == InitializedEntity::EK_Member && 4443 cast<FieldDecl>(Entity.getDecl())->isBitField()) 4444 S.CheckBitFieldInitialization(Kind.getLocation(), 4445 cast<FieldDecl>(Entity.getDecl()), 4446 CurInit.get()); 4447 4448 return move(CurInit); 4449} 4450 4451//===----------------------------------------------------------------------===// 4452// Diagnose initialization failures 4453//===----------------------------------------------------------------------===// 4454bool InitializationSequence::Diagnose(Sema &S, 4455 const InitializedEntity &Entity, 4456 const InitializationKind &Kind, 4457 Expr **Args, unsigned NumArgs) { 4458 if (!Failed()) 4459 return false; 4460 4461 QualType DestType = Entity.getType(); 4462 switch (Failure) { 4463 case FK_TooManyInitsForReference: 4464 // FIXME: Customize for the initialized entity? 4465 if (NumArgs == 0) 4466 S.Diag(Kind.getLocation(), diag::err_reference_without_init) 4467 << DestType.getNonReferenceType(); 4468 else // FIXME: diagnostic below could be better! 4469 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 4470 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 4471 break; 4472 4473 case FK_ArrayNeedsInitList: 4474 case FK_ArrayNeedsInitListOrStringLiteral: 4475 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 4476 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 4477 break; 4478 4479 case FK_ArrayTypeMismatch: 4480 case FK_NonConstantArrayInit: 4481 S.Diag(Kind.getLocation(), 4482 (Failure == FK_ArrayTypeMismatch 4483 ? diag::err_array_init_different_type 4484 : diag::err_array_init_non_constant_array)) 4485 << DestType.getNonReferenceType() 4486 << Args[0]->getType() 4487 << Args[0]->getSourceRange(); 4488 break; 4489 4490 case FK_AddressOfOverloadFailed: { 4491 DeclAccessPair Found; 4492 S.ResolveAddressOfOverloadedFunction(Args[0], 4493 DestType.getNonReferenceType(), 4494 true, 4495 Found); 4496 break; 4497 } 4498 4499 case FK_ReferenceInitOverloadFailed: 4500 case FK_UserConversionOverloadFailed: 4501 switch (FailedOverloadResult) { 4502 case OR_Ambiguous: 4503 if (Failure == FK_UserConversionOverloadFailed) 4504 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 4505 << Args[0]->getType() << DestType 4506 << Args[0]->getSourceRange(); 4507 else 4508 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 4509 << DestType << Args[0]->getType() 4510 << Args[0]->getSourceRange(); 4511 4512 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs); 4513 break; 4514 4515 case OR_No_Viable_Function: 4516 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 4517 << Args[0]->getType() << DestType.getNonReferenceType() 4518 << Args[0]->getSourceRange(); 4519 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 4520 break; 4521 4522 case OR_Deleted: { 4523 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 4524 << Args[0]->getType() << DestType.getNonReferenceType() 4525 << Args[0]->getSourceRange(); 4526 OverloadCandidateSet::iterator Best; 4527 OverloadingResult Ovl 4528 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, 4529 true); 4530 if (Ovl == OR_Deleted) { 4531 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4532 << 1 << Best->Function->isDeleted(); 4533 } else { 4534 llvm_unreachable("Inconsistent overload resolution?"); 4535 } 4536 break; 4537 } 4538 4539 case OR_Success: 4540 llvm_unreachable("Conversion did not fail!"); 4541 break; 4542 } 4543 break; 4544 4545 case FK_NonConstLValueReferenceBindingToTemporary: 4546 case FK_NonConstLValueReferenceBindingToUnrelated: 4547 S.Diag(Kind.getLocation(), 4548 Failure == FK_NonConstLValueReferenceBindingToTemporary 4549 ? diag::err_lvalue_reference_bind_to_temporary 4550 : diag::err_lvalue_reference_bind_to_unrelated) 4551 << DestType.getNonReferenceType().isVolatileQualified() 4552 << DestType.getNonReferenceType() 4553 << Args[0]->getType() 4554 << Args[0]->getSourceRange(); 4555 break; 4556 4557 case FK_RValueReferenceBindingToLValue: 4558 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 4559 << DestType.getNonReferenceType() << Args[0]->getType() 4560 << Args[0]->getSourceRange(); 4561 break; 4562 4563 case FK_ReferenceInitDropsQualifiers: 4564 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 4565 << DestType.getNonReferenceType() 4566 << Args[0]->getType() 4567 << Args[0]->getSourceRange(); 4568 break; 4569 4570 case FK_ReferenceInitFailed: 4571 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 4572 << DestType.getNonReferenceType() 4573 << Args[0]->isLValue() 4574 << Args[0]->getType() 4575 << Args[0]->getSourceRange(); 4576 if (DestType.getNonReferenceType()->isObjCObjectPointerType() && 4577 Args[0]->getType()->isObjCObjectPointerType()) 4578 S.EmitRelatedResultTypeNote(Args[0]); 4579 break; 4580 4581 case FK_ConversionFailed: { 4582 QualType FromType = Args[0]->getType(); 4583 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed) 4584 << (int)Entity.getKind() 4585 << DestType 4586 << Args[0]->isLValue() 4587 << FromType 4588 << Args[0]->getSourceRange(); 4589 if (DestType.getNonReferenceType()->isObjCObjectPointerType() && 4590 Args[0]->getType()->isObjCObjectPointerType()) 4591 S.EmitRelatedResultTypeNote(Args[0]); 4592 break; 4593 } 4594 4595 case FK_ConversionFromPropertyFailed: 4596 // No-op. This error has already been reported. 4597 break; 4598 4599 case FK_TooManyInitsForScalar: { 4600 SourceRange R; 4601 4602 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 4603 R = SourceRange(InitList->getInit(0)->getLocEnd(), 4604 InitList->getLocEnd()); 4605 else 4606 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd()); 4607 4608 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin())); 4609 if (Kind.isCStyleOrFunctionalCast()) 4610 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 4611 << R; 4612 else 4613 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 4614 << /*scalar=*/2 << R; 4615 break; 4616 } 4617 4618 case FK_ReferenceBindingToInitList: 4619 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 4620 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 4621 break; 4622 4623 case FK_InitListBadDestinationType: 4624 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 4625 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 4626 break; 4627 4628 case FK_ConstructorOverloadFailed: { 4629 SourceRange ArgsRange; 4630 if (NumArgs) 4631 ArgsRange = SourceRange(Args[0]->getLocStart(), 4632 Args[NumArgs - 1]->getLocEnd()); 4633 4634 // FIXME: Using "DestType" for the entity we're printing is probably 4635 // bad. 4636 switch (FailedOverloadResult) { 4637 case OR_Ambiguous: 4638 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 4639 << DestType << ArgsRange; 4640 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, 4641 Args, NumArgs); 4642 break; 4643 4644 case OR_No_Viable_Function: 4645 if (Kind.getKind() == InitializationKind::IK_Default && 4646 (Entity.getKind() == InitializedEntity::EK_Base || 4647 Entity.getKind() == InitializedEntity::EK_Member) && 4648 isa<CXXConstructorDecl>(S.CurContext)) { 4649 // This is implicit default initialization of a member or 4650 // base within a constructor. If no viable function was 4651 // found, notify the user that she needs to explicitly 4652 // initialize this base/member. 4653 CXXConstructorDecl *Constructor 4654 = cast<CXXConstructorDecl>(S.CurContext); 4655 if (Entity.getKind() == InitializedEntity::EK_Base) { 4656 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 4657 << Constructor->isImplicit() 4658 << S.Context.getTypeDeclType(Constructor->getParent()) 4659 << /*base=*/0 4660 << Entity.getType(); 4661 4662 RecordDecl *BaseDecl 4663 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 4664 ->getDecl(); 4665 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 4666 << S.Context.getTagDeclType(BaseDecl); 4667 } else { 4668 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 4669 << Constructor->isImplicit() 4670 << S.Context.getTypeDeclType(Constructor->getParent()) 4671 << /*member=*/1 4672 << Entity.getName(); 4673 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl); 4674 4675 if (const RecordType *Record 4676 = Entity.getType()->getAs<RecordType>()) 4677 S.Diag(Record->getDecl()->getLocation(), 4678 diag::note_previous_decl) 4679 << S.Context.getTagDeclType(Record->getDecl()); 4680 } 4681 break; 4682 } 4683 4684 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 4685 << DestType << ArgsRange; 4686 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 4687 break; 4688 4689 case OR_Deleted: { 4690 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 4691 << true << DestType << ArgsRange; 4692 OverloadCandidateSet::iterator Best; 4693 OverloadingResult Ovl 4694 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 4695 if (Ovl == OR_Deleted) { 4696 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4697 << 1 << Best->Function->isDeleted(); 4698 } else { 4699 llvm_unreachable("Inconsistent overload resolution?"); 4700 } 4701 break; 4702 } 4703 4704 case OR_Success: 4705 llvm_unreachable("Conversion did not fail!"); 4706 break; 4707 } 4708 break; 4709 } 4710 4711 case FK_DefaultInitOfConst: 4712 if (Entity.getKind() == InitializedEntity::EK_Member && 4713 isa<CXXConstructorDecl>(S.CurContext)) { 4714 // This is implicit default-initialization of a const member in 4715 // a constructor. Complain that it needs to be explicitly 4716 // initialized. 4717 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 4718 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 4719 << Constructor->isImplicit() 4720 << S.Context.getTypeDeclType(Constructor->getParent()) 4721 << /*const=*/1 4722 << Entity.getName(); 4723 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 4724 << Entity.getName(); 4725 } else { 4726 S.Diag(Kind.getLocation(), diag::err_default_init_const) 4727 << DestType << (bool)DestType->getAs<RecordType>(); 4728 } 4729 break; 4730 4731 case FK_Incomplete: 4732 S.RequireCompleteType(Kind.getLocation(), DestType, 4733 diag::err_init_incomplete_type); 4734 break; 4735 } 4736 4737 PrintInitLocationNote(S, Entity); 4738 return true; 4739} 4740 4741void InitializationSequence::dump(llvm::raw_ostream &OS) const { 4742 switch (SequenceKind) { 4743 case FailedSequence: { 4744 OS << "Failed sequence: "; 4745 switch (Failure) { 4746 case FK_TooManyInitsForReference: 4747 OS << "too many initializers for reference"; 4748 break; 4749 4750 case FK_ArrayNeedsInitList: 4751 OS << "array requires initializer list"; 4752 break; 4753 4754 case FK_ArrayNeedsInitListOrStringLiteral: 4755 OS << "array requires initializer list or string literal"; 4756 break; 4757 4758 case FK_ArrayTypeMismatch: 4759 OS << "array type mismatch"; 4760 break; 4761 4762 case FK_NonConstantArrayInit: 4763 OS << "non-constant array initializer"; 4764 break; 4765 4766 case FK_AddressOfOverloadFailed: 4767 OS << "address of overloaded function failed"; 4768 break; 4769 4770 case FK_ReferenceInitOverloadFailed: 4771 OS << "overload resolution for reference initialization failed"; 4772 break; 4773 4774 case FK_NonConstLValueReferenceBindingToTemporary: 4775 OS << "non-const lvalue reference bound to temporary"; 4776 break; 4777 4778 case FK_NonConstLValueReferenceBindingToUnrelated: 4779 OS << "non-const lvalue reference bound to unrelated type"; 4780 break; 4781 4782 case FK_RValueReferenceBindingToLValue: 4783 OS << "rvalue reference bound to an lvalue"; 4784 break; 4785 4786 case FK_ReferenceInitDropsQualifiers: 4787 OS << "reference initialization drops qualifiers"; 4788 break; 4789 4790 case FK_ReferenceInitFailed: 4791 OS << "reference initialization failed"; 4792 break; 4793 4794 case FK_ConversionFailed: 4795 OS << "conversion failed"; 4796 break; 4797 4798 case FK_ConversionFromPropertyFailed: 4799 OS << "conversion from property failed"; 4800 break; 4801 4802 case FK_TooManyInitsForScalar: 4803 OS << "too many initializers for scalar"; 4804 break; 4805 4806 case FK_ReferenceBindingToInitList: 4807 OS << "referencing binding to initializer list"; 4808 break; 4809 4810 case FK_InitListBadDestinationType: 4811 OS << "initializer list for non-aggregate, non-scalar type"; 4812 break; 4813 4814 case FK_UserConversionOverloadFailed: 4815 OS << "overloading failed for user-defined conversion"; 4816 break; 4817 4818 case FK_ConstructorOverloadFailed: 4819 OS << "constructor overloading failed"; 4820 break; 4821 4822 case FK_DefaultInitOfConst: 4823 OS << "default initialization of a const variable"; 4824 break; 4825 4826 case FK_Incomplete: 4827 OS << "initialization of incomplete type"; 4828 break; 4829 } 4830 OS << '\n'; 4831 return; 4832 } 4833 4834 case DependentSequence: 4835 OS << "Dependent sequence\n"; 4836 return; 4837 4838 case NormalSequence: 4839 OS << "Normal sequence: "; 4840 break; 4841 4842 case ReferenceBinding: 4843 OS << "Reference binding: "; 4844 break; 4845 } 4846 4847 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 4848 if (S != step_begin()) { 4849 OS << " -> "; 4850 } 4851 4852 switch (S->Kind) { 4853 case SK_ResolveAddressOfOverloadedFunction: 4854 OS << "resolve address of overloaded function"; 4855 break; 4856 4857 case SK_CastDerivedToBaseRValue: 4858 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 4859 break; 4860 4861 case SK_CastDerivedToBaseXValue: 4862 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 4863 break; 4864 4865 case SK_CastDerivedToBaseLValue: 4866 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 4867 break; 4868 4869 case SK_BindReference: 4870 OS << "bind reference to lvalue"; 4871 break; 4872 4873 case SK_BindReferenceToTemporary: 4874 OS << "bind reference to a temporary"; 4875 break; 4876 4877 case SK_ExtraneousCopyToTemporary: 4878 OS << "extraneous C++03 copy to temporary"; 4879 break; 4880 4881 case SK_UserConversion: 4882 OS << "user-defined conversion via " << S->Function.Function; 4883 break; 4884 4885 case SK_QualificationConversionRValue: 4886 OS << "qualification conversion (rvalue)"; 4887 4888 case SK_QualificationConversionXValue: 4889 OS << "qualification conversion (xvalue)"; 4890 4891 case SK_QualificationConversionLValue: 4892 OS << "qualification conversion (lvalue)"; 4893 break; 4894 4895 case SK_ConversionSequence: 4896 OS << "implicit conversion sequence ("; 4897 S->ICS->DebugPrint(); // FIXME: use OS 4898 OS << ")"; 4899 break; 4900 4901 case SK_ListInitialization: 4902 OS << "list initialization"; 4903 break; 4904 4905 case SK_ConstructorInitialization: 4906 OS << "constructor initialization"; 4907 break; 4908 4909 case SK_ZeroInitialization: 4910 OS << "zero initialization"; 4911 break; 4912 4913 case SK_CAssignment: 4914 OS << "C assignment"; 4915 break; 4916 4917 case SK_StringInit: 4918 OS << "string initialization"; 4919 break; 4920 4921 case SK_ObjCObjectConversion: 4922 OS << "Objective-C object conversion"; 4923 break; 4924 4925 case SK_ArrayInit: 4926 OS << "array initialization"; 4927 break; 4928 4929 case SK_PassByIndirectCopyRestore: 4930 OS << "pass by indirect copy and restore"; 4931 break; 4932 4933 case SK_PassByIndirectRestore: 4934 OS << "pass by indirect restore"; 4935 break; 4936 4937 case SK_ProduceObjCObject: 4938 OS << "Objective-C object retension"; 4939 break; 4940 } 4941 } 4942} 4943 4944void InitializationSequence::dump() const { 4945 dump(llvm::errs()); 4946} 4947 4948//===----------------------------------------------------------------------===// 4949// Initialization helper functions 4950//===----------------------------------------------------------------------===// 4951bool 4952Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 4953 ExprResult Init) { 4954 if (Init.isInvalid()) 4955 return false; 4956 4957 Expr *InitE = Init.get(); 4958 assert(InitE && "No initialization expression"); 4959 4960 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(), 4961 SourceLocation()); 4962 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 4963 return !Seq.Failed(); 4964} 4965 4966ExprResult 4967Sema::PerformCopyInitialization(const InitializedEntity &Entity, 4968 SourceLocation EqualLoc, 4969 ExprResult Init) { 4970 if (Init.isInvalid()) 4971 return ExprError(); 4972 4973 Expr *InitE = Init.get(); 4974 assert(InitE && "No initialization expression?"); 4975 4976 if (EqualLoc.isInvalid()) 4977 EqualLoc = InitE->getLocStart(); 4978 4979 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 4980 EqualLoc); 4981 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 4982 Init.release(); 4983 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1)); 4984} 4985