SemaInit.cpp revision d458926d0d7e9d2d180952b4eff63d0c2ddb4838
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// This file also implements Sema::CheckInitializerTypes. 15// 16//===----------------------------------------------------------------------===// 17 18#include "SemaInit.h" 19#include "Sema.h" 20#include "clang/Parse/Designator.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "clang/AST/TypeLoc.h" 25#include "llvm/Support/ErrorHandling.h" 26#include <map> 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// Sema Initialization Checking 31//===----------------------------------------------------------------------===// 32 33static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) { 34 const ArrayType *AT = Context.getAsArrayType(DeclType); 35 if (!AT) return 0; 36 37 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 38 return 0; 39 40 // See if this is a string literal or @encode. 41 Init = Init->IgnoreParens(); 42 43 // Handle @encode, which is a narrow string. 44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 45 return Init; 46 47 // Otherwise we can only handle string literals. 48 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 49 if (SL == 0) return 0; 50 51 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 52 // char array can be initialized with a narrow string. 53 // Only allow char x[] = "foo"; not char x[] = L"foo"; 54 if (!SL->isWide()) 55 return ElemTy->isCharType() ? Init : 0; 56 57 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 58 // correction from DR343): "An array with element type compatible with a 59 // qualified or unqualified version of wchar_t may be initialized by a wide 60 // string literal, optionally enclosed in braces." 61 if (Context.typesAreCompatible(Context.getWCharType(), 62 ElemTy.getUnqualifiedType())) 63 return Init; 64 65 return 0; 66} 67 68static bool CheckSingleInitializer(Expr *&Init, QualType DeclType, 69 bool DirectInit, Sema &S) { 70 // Get the type before calling CheckSingleAssignmentConstraints(), since 71 // it can promote the expression. 72 QualType InitType = Init->getType(); 73 74 if (S.getLangOptions().CPlusPlus) { 75 // FIXME: I dislike this error message. A lot. 76 if (S.PerformImplicitConversion(Init, DeclType, 77 Sema::AA_Initializing, DirectInit)) { 78 ImplicitConversionSequence ICS; 79 OverloadCandidateSet CandidateSet; 80 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined, 81 CandidateSet, 82 true, false, false) != OR_Ambiguous) 83 return S.Diag(Init->getSourceRange().getBegin(), 84 diag::err_typecheck_convert_incompatible) 85 << DeclType << Init->getType() << Sema::AA_Initializing 86 << Init->getSourceRange(); 87 S.Diag(Init->getSourceRange().getBegin(), 88 diag::err_typecheck_convert_ambiguous) 89 << DeclType << Init->getType() << Init->getSourceRange(); 90 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 91 return true; 92 } 93 return false; 94 } 95 96 Sema::AssignConvertType ConvTy = 97 S.CheckSingleAssignmentConstraints(DeclType, Init); 98 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 99 InitType, Init, Sema::AA_Initializing); 100} 101 102static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) { 103 // Get the length of the string as parsed. 104 uint64_t StrLength = 105 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 106 107 108 const ArrayType *AT = S.Context.getAsArrayType(DeclT); 109 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 110 // C99 6.7.8p14. We have an array of character type with unknown size 111 // being initialized to a string literal. 112 llvm::APSInt ConstVal(32); 113 ConstVal = StrLength; 114 // Return a new array type (C99 6.7.8p22). 115 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 116 ConstVal, 117 ArrayType::Normal, 0); 118 return; 119 } 120 121 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 122 123 // C99 6.7.8p14. We have an array of character type with known size. However, 124 // the size may be smaller or larger than the string we are initializing. 125 // FIXME: Avoid truncation for 64-bit length strings. 126 if (StrLength-1 > CAT->getSize().getZExtValue()) 127 S.Diag(Str->getSourceRange().getBegin(), 128 diag::warn_initializer_string_for_char_array_too_long) 129 << Str->getSourceRange(); 130 131 // Set the type to the actual size that we are initializing. If we have 132 // something like: 133 // char x[1] = "foo"; 134 // then this will set the string literal's type to char[1]. 135 Str->setType(DeclT); 136} 137 138//===----------------------------------------------------------------------===// 139// Semantic checking for initializer lists. 140//===----------------------------------------------------------------------===// 141 142/// @brief Semantic checking for initializer lists. 143/// 144/// The InitListChecker class contains a set of routines that each 145/// handle the initialization of a certain kind of entity, e.g., 146/// arrays, vectors, struct/union types, scalars, etc. The 147/// InitListChecker itself performs a recursive walk of the subobject 148/// structure of the type to be initialized, while stepping through 149/// the initializer list one element at a time. The IList and Index 150/// parameters to each of the Check* routines contain the active 151/// (syntactic) initializer list and the index into that initializer 152/// list that represents the current initializer. Each routine is 153/// responsible for moving that Index forward as it consumes elements. 154/// 155/// Each Check* routine also has a StructuredList/StructuredIndex 156/// arguments, which contains the current the "structured" (semantic) 157/// initializer list and the index into that initializer list where we 158/// are copying initializers as we map them over to the semantic 159/// list. Once we have completed our recursive walk of the subobject 160/// structure, we will have constructed a full semantic initializer 161/// list. 162/// 163/// C99 designators cause changes in the initializer list traversal, 164/// because they make the initialization "jump" into a specific 165/// subobject and then continue the initialization from that 166/// point. CheckDesignatedInitializer() recursively steps into the 167/// designated subobject and manages backing out the recursion to 168/// initialize the subobjects after the one designated. 169namespace { 170class InitListChecker { 171 Sema &SemaRef; 172 bool hadError; 173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 174 InitListExpr *FullyStructuredList; 175 176 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T, 177 unsigned &Index, InitListExpr *StructuredList, 178 unsigned &StructuredIndex, 179 bool TopLevelObject = false); 180 void CheckExplicitInitList(InitListExpr *IList, QualType &T, 181 unsigned &Index, InitListExpr *StructuredList, 182 unsigned &StructuredIndex, 183 bool TopLevelObject = false); 184 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType, 185 bool SubobjectIsDesignatorContext, 186 unsigned &Index, 187 InitListExpr *StructuredList, 188 unsigned &StructuredIndex, 189 bool TopLevelObject = false); 190 void CheckSubElementType(InitListExpr *IList, QualType ElemType, 191 unsigned &Index, 192 InitListExpr *StructuredList, 193 unsigned &StructuredIndex); 194 void CheckScalarType(InitListExpr *IList, QualType DeclType, 195 unsigned &Index, 196 InitListExpr *StructuredList, 197 unsigned &StructuredIndex); 198 void CheckReferenceType(InitListExpr *IList, QualType DeclType, 199 unsigned &Index, 200 InitListExpr *StructuredList, 201 unsigned &StructuredIndex); 202 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index, 203 InitListExpr *StructuredList, 204 unsigned &StructuredIndex); 205 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType, 206 RecordDecl::field_iterator Field, 207 bool SubobjectIsDesignatorContext, unsigned &Index, 208 InitListExpr *StructuredList, 209 unsigned &StructuredIndex, 210 bool TopLevelObject = false); 211 void CheckArrayType(InitListExpr *IList, QualType &DeclType, 212 llvm::APSInt elementIndex, 213 bool SubobjectIsDesignatorContext, unsigned &Index, 214 InitListExpr *StructuredList, 215 unsigned &StructuredIndex); 216 bool CheckDesignatedInitializer(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 Sema::OwningExprResult MemberInit 289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, 290 Sema::MultiExprArg(SemaRef, 0, 0)); 291 if (MemberInit.isInvalid()) { 292 hadError = true; 293 return; 294 } 295 296 if (hadError) { 297 // Do nothing 298 } else if (Init < NumInits) { 299 ILE->setInit(Init, MemberInit.takeAs<Expr>()); 300 } else if (InitSeq.getKind() 301 == InitializationSequence::ConstructorInitialization) { 302 // Value-initialization requires a constructor call, so 303 // extend the initializer list to include the constructor 304 // call and make a note that we'll need to take another pass 305 // through the initializer list. 306 ILE->updateInit(Init, MemberInit.takeAs<Expr>()); 307 RequiresSecondPass = true; 308 } 309 } else if (InitListExpr *InnerILE 310 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 311 FillInValueInitializations(MemberEntity, InnerILE, 312 RequiresSecondPass); 313} 314 315/// Recursively replaces NULL values within the given initializer list 316/// with expressions that perform value-initialization of the 317/// appropriate type. 318void 319InitListChecker::FillInValueInitializations(const InitializedEntity &Entity, 320 InitListExpr *ILE, 321 bool &RequiresSecondPass) { 322 assert((ILE->getType() != SemaRef.Context.VoidTy) && 323 "Should not have void type"); 324 SourceLocation Loc = ILE->getSourceRange().getBegin(); 325 if (ILE->getSyntacticForm()) 326 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 327 328 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 329 if (RType->getDecl()->isUnion() && 330 ILE->getInitializedFieldInUnion()) 331 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(), 332 Entity, ILE, RequiresSecondPass); 333 else { 334 unsigned Init = 0; 335 for (RecordDecl::field_iterator 336 Field = RType->getDecl()->field_begin(), 337 FieldEnd = RType->getDecl()->field_end(); 338 Field != FieldEnd; ++Field) { 339 if (Field->isUnnamedBitfield()) 340 continue; 341 342 if (hadError) 343 return; 344 345 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass); 346 if (hadError) 347 return; 348 349 ++Init; 350 351 // Only look at the first initialization of a union. 352 if (RType->getDecl()->isUnion()) 353 break; 354 } 355 } 356 357 return; 358 } 359 360 QualType ElementType; 361 362 InitializedEntity ElementEntity = Entity; 363 unsigned NumInits = ILE->getNumInits(); 364 unsigned NumElements = NumInits; 365 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 366 ElementType = AType->getElementType(); 367 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 368 NumElements = CAType->getSize().getZExtValue(); 369 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 370 0, Entity); 371 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 372 ElementType = VType->getElementType(); 373 NumElements = VType->getNumElements(); 374 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 375 0, Entity); 376 } else 377 ElementType = ILE->getType(); 378 379 380 for (unsigned Init = 0; Init != NumElements; ++Init) { 381 if (hadError) 382 return; 383 384 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement) 385 ElementEntity.setElementIndex(Init); 386 387 if (Init >= NumInits || !ILE->getInit(Init)) { 388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 389 true); 390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0); 391 if (!InitSeq) { 392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0); 393 hadError = true; 394 return; 395 } 396 397 Sema::OwningExprResult ElementInit 398 = InitSeq.Perform(SemaRef, ElementEntity, Kind, 399 Sema::MultiExprArg(SemaRef, 0, 0)); 400 if (ElementInit.isInvalid()) { 401 hadError = true; 402 return; 403 } 404 405 if (hadError) { 406 // Do nothing 407 } else if (Init < NumInits) { 408 ILE->setInit(Init, ElementInit.takeAs<Expr>()); 409 } else if (InitSeq.getKind() 410 == InitializationSequence::ConstructorInitialization) { 411 // Value-initialization requires a constructor call, so 412 // extend the initializer list to include the constructor 413 // call and make a note that we'll need to take another pass 414 // through the initializer list. 415 ILE->updateInit(Init, ElementInit.takeAs<Expr>()); 416 RequiresSecondPass = true; 417 } 418 } else if (InitListExpr *InnerILE 419 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 420 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass); 421 } 422} 423 424 425InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 426 InitListExpr *IL, QualType &T) 427 : SemaRef(S) { 428 hadError = false; 429 430 unsigned newIndex = 0; 431 unsigned newStructuredIndex = 0; 432 FullyStructuredList 433 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 434 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex, 435 /*TopLevelObject=*/true); 436 437 if (!hadError) { 438 bool RequiresSecondPass = false; 439 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass); 440 if (RequiresSecondPass && !hadError) 441 FillInValueInitializations(Entity, FullyStructuredList, 442 RequiresSecondPass); 443 } 444} 445 446int InitListChecker::numArrayElements(QualType DeclType) { 447 // FIXME: use a proper constant 448 int maxElements = 0x7FFFFFFF; 449 if (const ConstantArrayType *CAT = 450 SemaRef.Context.getAsConstantArrayType(DeclType)) { 451 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 452 } 453 return maxElements; 454} 455 456int InitListChecker::numStructUnionElements(QualType DeclType) { 457 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 458 int InitializableMembers = 0; 459 for (RecordDecl::field_iterator 460 Field = structDecl->field_begin(), 461 FieldEnd = structDecl->field_end(); 462 Field != FieldEnd; ++Field) { 463 if ((*Field)->getIdentifier() || !(*Field)->isBitField()) 464 ++InitializableMembers; 465 } 466 if (structDecl->isUnion()) 467 return std::min(InitializableMembers, 1); 468 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 469} 470 471void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList, 472 QualType T, unsigned &Index, 473 InitListExpr *StructuredList, 474 unsigned &StructuredIndex, 475 bool TopLevelObject) { 476 int maxElements = 0; 477 478 if (T->isArrayType()) 479 maxElements = numArrayElements(T); 480 else if (T->isStructureType() || T->isUnionType()) 481 maxElements = numStructUnionElements(T); 482 else if (T->isVectorType()) 483 maxElements = T->getAs<VectorType>()->getNumElements(); 484 else 485 assert(0 && "CheckImplicitInitList(): Illegal type"); 486 487 if (maxElements == 0) { 488 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 489 diag::err_implicit_empty_initializer); 490 ++Index; 491 hadError = true; 492 return; 493 } 494 495 // Build a structured initializer list corresponding to this subobject. 496 InitListExpr *StructuredSubobjectInitList 497 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 498 StructuredIndex, 499 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 500 ParentIList->getSourceRange().getEnd())); 501 unsigned StructuredSubobjectInitIndex = 0; 502 503 // Check the element types and build the structural subobject. 504 unsigned StartIndex = Index; 505 CheckListElementTypes(ParentIList, T, false, Index, 506 StructuredSubobjectInitList, 507 StructuredSubobjectInitIndex, 508 TopLevelObject); 509 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 510 StructuredSubobjectInitList->setType(T); 511 512 // Update the structured sub-object initializer so that it's ending 513 // range corresponds with the end of the last initializer it used. 514 if (EndIndex < ParentIList->getNumInits()) { 515 SourceLocation EndLoc 516 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 517 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 518 } 519} 520 521void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T, 522 unsigned &Index, 523 InitListExpr *StructuredList, 524 unsigned &StructuredIndex, 525 bool TopLevelObject) { 526 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 527 SyntacticToSemantic[IList] = StructuredList; 528 StructuredList->setSyntacticForm(IList); 529 CheckListElementTypes(IList, T, true, Index, StructuredList, 530 StructuredIndex, TopLevelObject); 531 IList->setType(T); 532 StructuredList->setType(T); 533 if (hadError) 534 return; 535 536 if (Index < IList->getNumInits()) { 537 // We have leftover initializers 538 if (StructuredIndex == 1 && 539 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 540 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 541 if (SemaRef.getLangOptions().CPlusPlus) { 542 DK = diag::err_excess_initializers_in_char_array_initializer; 543 hadError = true; 544 } 545 // Special-case 546 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 547 << IList->getInit(Index)->getSourceRange(); 548 } else if (!T->isIncompleteType()) { 549 // Don't complain for incomplete types, since we'll get an error 550 // elsewhere 551 QualType CurrentObjectType = StructuredList->getType(); 552 int initKind = 553 CurrentObjectType->isArrayType()? 0 : 554 CurrentObjectType->isVectorType()? 1 : 555 CurrentObjectType->isScalarType()? 2 : 556 CurrentObjectType->isUnionType()? 3 : 557 4; 558 559 unsigned DK = diag::warn_excess_initializers; 560 if (SemaRef.getLangOptions().CPlusPlus) { 561 DK = diag::err_excess_initializers; 562 hadError = true; 563 } 564 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 565 DK = diag::err_excess_initializers; 566 hadError = true; 567 } 568 569 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 570 << initKind << IList->getInit(Index)->getSourceRange(); 571 } 572 } 573 574 if (T->isScalarType() && !TopLevelObject) 575 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 576 << IList->getSourceRange() 577 << CodeModificationHint::CreateRemoval(IList->getLocStart()) 578 << CodeModificationHint::CreateRemoval(IList->getLocEnd()); 579} 580 581void InitListChecker::CheckListElementTypes(InitListExpr *IList, 582 QualType &DeclType, 583 bool SubobjectIsDesignatorContext, 584 unsigned &Index, 585 InitListExpr *StructuredList, 586 unsigned &StructuredIndex, 587 bool TopLevelObject) { 588 if (DeclType->isScalarType()) { 589 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex); 590 } else if (DeclType->isVectorType()) { 591 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex); 592 } else if (DeclType->isAggregateType()) { 593 if (DeclType->isRecordType()) { 594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 595 CheckStructUnionTypes(IList, DeclType, RD->field_begin(), 596 SubobjectIsDesignatorContext, Index, 597 StructuredList, StructuredIndex, 598 TopLevelObject); 599 } else if (DeclType->isArrayType()) { 600 llvm::APSInt Zero( 601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 602 false); 603 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index, 604 StructuredList, StructuredIndex); 605 } else 606 assert(0 && "Aggregate that isn't a structure or array?!"); 607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 608 // This type is invalid, issue a diagnostic. 609 ++Index; 610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 611 << DeclType; 612 hadError = true; 613 } else if (DeclType->isRecordType()) { 614 // C++ [dcl.init]p14: 615 // [...] If the class is an aggregate (8.5.1), and the initializer 616 // is a brace-enclosed list, see 8.5.1. 617 // 618 // Note: 8.5.1 is handled below; here, we diagnose the case where 619 // we have an initializer list and a destination type that is not 620 // an aggregate. 621 // FIXME: In C++0x, this is yet another form of initialization. 622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 623 << DeclType << IList->getSourceRange(); 624 hadError = true; 625 } else if (DeclType->isReferenceType()) { 626 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex); 627 } else { 628 // In C, all types are either scalars or aggregates, but 629 // additional handling is needed here for C++ (and possibly others?). 630 assert(0 && "Unsupported initializer type"); 631 } 632} 633 634void InitListChecker::CheckSubElementType(InitListExpr *IList, 635 QualType ElemType, 636 unsigned &Index, 637 InitListExpr *StructuredList, 638 unsigned &StructuredIndex) { 639 Expr *expr = IList->getInit(Index); 640 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 641 unsigned newIndex = 0; 642 unsigned newStructuredIndex = 0; 643 InitListExpr *newStructuredList 644 = getStructuredSubobjectInit(IList, Index, ElemType, 645 StructuredList, StructuredIndex, 646 SubInitList->getSourceRange()); 647 CheckExplicitInitList(SubInitList, ElemType, newIndex, 648 newStructuredList, newStructuredIndex); 649 ++StructuredIndex; 650 ++Index; 651 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) { 652 CheckStringInit(Str, ElemType, SemaRef); 653 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 654 ++Index; 655 } else if (ElemType->isScalarType()) { 656 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex); 657 } else if (ElemType->isReferenceType()) { 658 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex); 659 } else { 660 if (SemaRef.getLangOptions().CPlusPlus) { 661 // C++ [dcl.init.aggr]p12: 662 // All implicit type conversions (clause 4) are considered when 663 // initializing the aggregate member with an ini- tializer from 664 // an initializer-list. If the initializer can initialize a 665 // member, the member is initialized. [...] 666 ImplicitConversionSequence ICS 667 = SemaRef.TryCopyInitialization(expr, ElemType, 668 /*SuppressUserConversions=*/false, 669 /*ForceRValue=*/false, 670 /*InOverloadResolution=*/false); 671 672 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) { 673 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS, 674 Sema::AA_Initializing)) 675 hadError = true; 676 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 677 ++Index; 678 return; 679 } 680 681 // Fall through for subaggregate initialization 682 } else { 683 // C99 6.7.8p13: 684 // 685 // The initializer for a structure or union object that has 686 // automatic storage duration shall be either an initializer 687 // list as described below, or a single expression that has 688 // compatible structure or union type. In the latter case, the 689 // initial value of the object, including unnamed members, is 690 // that of the expression. 691 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 692 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) { 693 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 694 ++Index; 695 return; 696 } 697 698 // Fall through for subaggregate initialization 699 } 700 701 // C++ [dcl.init.aggr]p12: 702 // 703 // [...] Otherwise, if the member is itself a non-empty 704 // subaggregate, brace elision is assumed and the initializer is 705 // considered for the initialization of the first member of 706 // the subaggregate. 707 if (ElemType->isAggregateType() || ElemType->isVectorType()) { 708 CheckImplicitInitList(IList, ElemType, Index, StructuredList, 709 StructuredIndex); 710 ++StructuredIndex; 711 } else { 712 // We cannot initialize this element, so let 713 // PerformCopyInitialization produce the appropriate diagnostic. 714 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing); 715 hadError = true; 716 ++Index; 717 ++StructuredIndex; 718 } 719 } 720} 721 722void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType, 723 unsigned &Index, 724 InitListExpr *StructuredList, 725 unsigned &StructuredIndex) { 726 if (Index < IList->getNumInits()) { 727 Expr *expr = IList->getInit(Index); 728 if (isa<InitListExpr>(expr)) { 729 SemaRef.Diag(IList->getLocStart(), 730 diag::err_many_braces_around_scalar_init) 731 << IList->getSourceRange(); 732 hadError = true; 733 ++Index; 734 ++StructuredIndex; 735 return; 736 } else if (isa<DesignatedInitExpr>(expr)) { 737 SemaRef.Diag(expr->getSourceRange().getBegin(), 738 diag::err_designator_for_scalar_init) 739 << DeclType << expr->getSourceRange(); 740 hadError = true; 741 ++Index; 742 ++StructuredIndex; 743 return; 744 } 745 746 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 747 if (CheckSingleInitializer(expr, DeclType, false, SemaRef)) 748 hadError = true; // types weren't compatible. 749 else if (savExpr != expr) { 750 // The type was promoted, update initializer list. 751 IList->setInit(Index, expr); 752 } 753 if (hadError) 754 ++StructuredIndex; 755 else 756 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 757 ++Index; 758 } else { 759 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) 760 << IList->getSourceRange(); 761 hadError = true; 762 ++Index; 763 ++StructuredIndex; 764 return; 765 } 766} 767 768void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType, 769 unsigned &Index, 770 InitListExpr *StructuredList, 771 unsigned &StructuredIndex) { 772 if (Index < IList->getNumInits()) { 773 Expr *expr = IList->getInit(Index); 774 if (isa<InitListExpr>(expr)) { 775 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 776 << DeclType << IList->getSourceRange(); 777 hadError = true; 778 ++Index; 779 ++StructuredIndex; 780 return; 781 } 782 783 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 784 if (SemaRef.CheckReferenceInit(expr, DeclType, 785 /*FIXME:*/expr->getLocStart(), 786 /*SuppressUserConversions=*/false, 787 /*AllowExplicit=*/false, 788 /*ForceRValue=*/false)) 789 hadError = true; 790 else if (savExpr != expr) { 791 // The type was promoted, update initializer list. 792 IList->setInit(Index, expr); 793 } 794 if (hadError) 795 ++StructuredIndex; 796 else 797 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 798 ++Index; 799 } else { 800 // FIXME: It would be wonderful if we could point at the actual member. In 801 // general, it would be useful to pass location information down the stack, 802 // so that we know the location (or decl) of the "current object" being 803 // initialized. 804 SemaRef.Diag(IList->getLocStart(), 805 diag::err_init_reference_member_uninitialized) 806 << DeclType 807 << IList->getSourceRange(); 808 hadError = true; 809 ++Index; 810 ++StructuredIndex; 811 return; 812 } 813} 814 815void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType, 816 unsigned &Index, 817 InitListExpr *StructuredList, 818 unsigned &StructuredIndex) { 819 if (Index < IList->getNumInits()) { 820 const VectorType *VT = DeclType->getAs<VectorType>(); 821 unsigned maxElements = VT->getNumElements(); 822 unsigned numEltsInit = 0; 823 QualType elementType = VT->getElementType(); 824 825 if (!SemaRef.getLangOptions().OpenCL) { 826 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 827 // Don't attempt to go past the end of the init list 828 if (Index >= IList->getNumInits()) 829 break; 830 CheckSubElementType(IList, elementType, Index, 831 StructuredList, StructuredIndex); 832 } 833 } else { 834 // OpenCL initializers allows vectors to be constructed from vectors. 835 for (unsigned i = 0; i < maxElements; ++i) { 836 // Don't attempt to go past the end of the init list 837 if (Index >= IList->getNumInits()) 838 break; 839 QualType IType = IList->getInit(Index)->getType(); 840 if (!IType->isVectorType()) { 841 CheckSubElementType(IList, elementType, Index, 842 StructuredList, StructuredIndex); 843 ++numEltsInit; 844 } else { 845 const VectorType *IVT = IType->getAs<VectorType>(); 846 unsigned numIElts = IVT->getNumElements(); 847 QualType VecType = SemaRef.Context.getExtVectorType(elementType, 848 numIElts); 849 CheckSubElementType(IList, VecType, Index, 850 StructuredList, StructuredIndex); 851 numEltsInit += numIElts; 852 } 853 } 854 } 855 856 // OpenCL & AltiVec require all elements to be initialized. 857 if (numEltsInit != maxElements) 858 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec) 859 SemaRef.Diag(IList->getSourceRange().getBegin(), 860 diag::err_vector_incorrect_num_initializers) 861 << (numEltsInit < maxElements) << maxElements << numEltsInit; 862 } 863} 864 865void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType, 866 llvm::APSInt elementIndex, 867 bool SubobjectIsDesignatorContext, 868 unsigned &Index, 869 InitListExpr *StructuredList, 870 unsigned &StructuredIndex) { 871 // Check for the special-case of initializing an array with a string. 872 if (Index < IList->getNumInits()) { 873 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType, 874 SemaRef.Context)) { 875 CheckStringInit(Str, DeclType, SemaRef); 876 // We place the string literal directly into the resulting 877 // initializer list. This is the only place where the structure 878 // of the structured initializer list doesn't match exactly, 879 // because doing so would involve allocating one character 880 // constant for each string. 881 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 882 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 883 ++Index; 884 return; 885 } 886 } 887 if (const VariableArrayType *VAT = 888 SemaRef.Context.getAsVariableArrayType(DeclType)) { 889 // Check for VLAs; in standard C it would be possible to check this 890 // earlier, but I don't know where clang accepts VLAs (gcc accepts 891 // them in all sorts of strange places). 892 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 893 diag::err_variable_object_no_init) 894 << VAT->getSizeExpr()->getSourceRange(); 895 hadError = true; 896 ++Index; 897 ++StructuredIndex; 898 return; 899 } 900 901 // We might know the maximum number of elements in advance. 902 llvm::APSInt maxElements(elementIndex.getBitWidth(), 903 elementIndex.isUnsigned()); 904 bool maxElementsKnown = false; 905 if (const ConstantArrayType *CAT = 906 SemaRef.Context.getAsConstantArrayType(DeclType)) { 907 maxElements = CAT->getSize(); 908 elementIndex.extOrTrunc(maxElements.getBitWidth()); 909 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 910 maxElementsKnown = true; 911 } 912 913 QualType elementType = SemaRef.Context.getAsArrayType(DeclType) 914 ->getElementType(); 915 while (Index < IList->getNumInits()) { 916 Expr *Init = IList->getInit(Index); 917 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 918 // If we're not the subobject that matches up with the '{' for 919 // the designator, we shouldn't be handling the 920 // designator. Return immediately. 921 if (!SubobjectIsDesignatorContext) 922 return; 923 924 // Handle this designated initializer. elementIndex will be 925 // updated to be the next array element we'll initialize. 926 if (CheckDesignatedInitializer(IList, DIE, 0, 927 DeclType, 0, &elementIndex, Index, 928 StructuredList, StructuredIndex, true, 929 false)) { 930 hadError = true; 931 continue; 932 } 933 934 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 935 maxElements.extend(elementIndex.getBitWidth()); 936 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 937 elementIndex.extend(maxElements.getBitWidth()); 938 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 939 940 // If the array is of incomplete type, keep track of the number of 941 // elements in the initializer. 942 if (!maxElementsKnown && elementIndex > maxElements) 943 maxElements = elementIndex; 944 945 continue; 946 } 947 948 // If we know the maximum number of elements, and we've already 949 // hit it, stop consuming elements in the initializer list. 950 if (maxElementsKnown && elementIndex == maxElements) 951 break; 952 953 // Check this element. 954 CheckSubElementType(IList, elementType, Index, 955 StructuredList, StructuredIndex); 956 ++elementIndex; 957 958 // If the array is of incomplete type, keep track of the number of 959 // elements in the initializer. 960 if (!maxElementsKnown && elementIndex > maxElements) 961 maxElements = elementIndex; 962 } 963 if (!hadError && DeclType->isIncompleteArrayType()) { 964 // If this is an incomplete array type, the actual type needs to 965 // be calculated here. 966 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 967 if (maxElements == Zero) { 968 // Sizing an array implicitly to zero is not allowed by ISO C, 969 // but is supported by GNU. 970 SemaRef.Diag(IList->getLocStart(), 971 diag::ext_typecheck_zero_array_size); 972 } 973 974 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 975 ArrayType::Normal, 0); 976 } 977} 978 979void InitListChecker::CheckStructUnionTypes(InitListExpr *IList, 980 QualType DeclType, 981 RecordDecl::field_iterator Field, 982 bool SubobjectIsDesignatorContext, 983 unsigned &Index, 984 InitListExpr *StructuredList, 985 unsigned &StructuredIndex, 986 bool TopLevelObject) { 987 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 988 989 // If the record is invalid, some of it's members are invalid. To avoid 990 // confusion, we forgo checking the intializer for the entire record. 991 if (structDecl->isInvalidDecl()) { 992 hadError = true; 993 return; 994 } 995 996 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 997 // Value-initialize the first named member of the union. 998 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 999 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1000 Field != FieldEnd; ++Field) { 1001 if (Field->getDeclName()) { 1002 StructuredList->setInitializedFieldInUnion(*Field); 1003 break; 1004 } 1005 } 1006 return; 1007 } 1008 1009 // If structDecl is a forward declaration, this loop won't do 1010 // anything except look at designated initializers; That's okay, 1011 // because an error should get printed out elsewhere. It might be 1012 // worthwhile to skip over the rest of the initializer, though. 1013 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1014 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1015 bool InitializedSomething = false; 1016 while (Index < IList->getNumInits()) { 1017 Expr *Init = IList->getInit(Index); 1018 1019 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1020 // If we're not the subobject that matches up with the '{' for 1021 // the designator, we shouldn't be handling the 1022 // designator. Return immediately. 1023 if (!SubobjectIsDesignatorContext) 1024 return; 1025 1026 // Handle this designated initializer. Field will be updated to 1027 // the next field that we'll be initializing. 1028 if (CheckDesignatedInitializer(IList, DIE, 0, 1029 DeclType, &Field, 0, Index, 1030 StructuredList, StructuredIndex, 1031 true, TopLevelObject)) 1032 hadError = true; 1033 1034 InitializedSomething = true; 1035 continue; 1036 } 1037 1038 if (Field == FieldEnd) { 1039 // We've run out of fields. We're done. 1040 break; 1041 } 1042 1043 // We've already initialized a member of a union. We're done. 1044 if (InitializedSomething && DeclType->isUnionType()) 1045 break; 1046 1047 // If we've hit the flexible array member at the end, we're done. 1048 if (Field->getType()->isIncompleteArrayType()) 1049 break; 1050 1051 if (Field->isUnnamedBitfield()) { 1052 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1053 ++Field; 1054 continue; 1055 } 1056 1057 CheckSubElementType(IList, Field->getType(), Index, 1058 StructuredList, StructuredIndex); 1059 InitializedSomething = true; 1060 1061 if (DeclType->isUnionType()) { 1062 // Initialize the first field within the union. 1063 StructuredList->setInitializedFieldInUnion(*Field); 1064 } 1065 1066 ++Field; 1067 } 1068 1069 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1070 Index >= IList->getNumInits()) 1071 return; 1072 1073 // Handle GNU flexible array initializers. 1074 if (!TopLevelObject && 1075 (!isa<InitListExpr>(IList->getInit(Index)) || 1076 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1077 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1078 diag::err_flexible_array_init_nonempty) 1079 << IList->getInit(Index)->getSourceRange().getBegin(); 1080 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1081 << *Field; 1082 hadError = true; 1083 ++Index; 1084 return; 1085 } else { 1086 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1087 diag::ext_flexible_array_init) 1088 << IList->getInit(Index)->getSourceRange().getBegin(); 1089 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1090 << *Field; 1091 } 1092 1093 if (isa<InitListExpr>(IList->getInit(Index))) 1094 CheckSubElementType(IList, Field->getType(), Index, StructuredList, 1095 StructuredIndex); 1096 else 1097 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList, 1098 StructuredIndex); 1099} 1100 1101/// \brief Expand a field designator that refers to a member of an 1102/// anonymous struct or union into a series of field designators that 1103/// refers to the field within the appropriate subobject. 1104/// 1105/// Field/FieldIndex will be updated to point to the (new) 1106/// currently-designated field. 1107static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1108 DesignatedInitExpr *DIE, 1109 unsigned DesigIdx, 1110 FieldDecl *Field, 1111 RecordDecl::field_iterator &FieldIter, 1112 unsigned &FieldIndex) { 1113 typedef DesignatedInitExpr::Designator Designator; 1114 1115 // Build the path from the current object to the member of the 1116 // anonymous struct/union (backwards). 1117 llvm::SmallVector<FieldDecl *, 4> Path; 1118 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path); 1119 1120 // Build the replacement designators. 1121 llvm::SmallVector<Designator, 4> Replacements; 1122 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 1123 FI = Path.rbegin(), FIEnd = Path.rend(); 1124 FI != FIEnd; ++FI) { 1125 if (FI + 1 == FIEnd) 1126 Replacements.push_back(Designator((IdentifierInfo *)0, 1127 DIE->getDesignator(DesigIdx)->getDotLoc(), 1128 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1129 else 1130 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1131 SourceLocation())); 1132 Replacements.back().setField(*FI); 1133 } 1134 1135 // Expand the current designator into the set of replacement 1136 // designators, so we have a full subobject path down to where the 1137 // member of the anonymous struct/union is actually stored. 1138 DIE->ExpandDesignator(DesigIdx, &Replacements[0], 1139 &Replacements[0] + Replacements.size()); 1140 1141 // Update FieldIter/FieldIndex; 1142 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext()); 1143 FieldIter = Record->field_begin(); 1144 FieldIndex = 0; 1145 for (RecordDecl::field_iterator FEnd = Record->field_end(); 1146 FieldIter != FEnd; ++FieldIter) { 1147 if (FieldIter->isUnnamedBitfield()) 1148 continue; 1149 1150 if (*FieldIter == Path.back()) 1151 return; 1152 1153 ++FieldIndex; 1154 } 1155 1156 assert(false && "Unable to find anonymous struct/union field"); 1157} 1158 1159/// @brief Check the well-formedness of a C99 designated initializer. 1160/// 1161/// Determines whether the designated initializer @p DIE, which 1162/// resides at the given @p Index within the initializer list @p 1163/// IList, is well-formed for a current object of type @p DeclType 1164/// (C99 6.7.8). The actual subobject that this designator refers to 1165/// within the current subobject is returned in either 1166/// @p NextField or @p NextElementIndex (whichever is appropriate). 1167/// 1168/// @param IList The initializer list in which this designated 1169/// initializer occurs. 1170/// 1171/// @param DIE The designated initializer expression. 1172/// 1173/// @param DesigIdx The index of the current designator. 1174/// 1175/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1176/// into which the designation in @p DIE should refer. 1177/// 1178/// @param NextField If non-NULL and the first designator in @p DIE is 1179/// a field, this will be set to the field declaration corresponding 1180/// to the field named by the designator. 1181/// 1182/// @param NextElementIndex If non-NULL and the first designator in @p 1183/// DIE is an array designator or GNU array-range designator, this 1184/// will be set to the last index initialized by this designator. 1185/// 1186/// @param Index Index into @p IList where the designated initializer 1187/// @p DIE occurs. 1188/// 1189/// @param StructuredList The initializer list expression that 1190/// describes all of the subobject initializers in the order they'll 1191/// actually be initialized. 1192/// 1193/// @returns true if there was an error, false otherwise. 1194bool 1195InitListChecker::CheckDesignatedInitializer(InitListExpr *IList, 1196 DesignatedInitExpr *DIE, 1197 unsigned DesigIdx, 1198 QualType &CurrentObjectType, 1199 RecordDecl::field_iterator *NextField, 1200 llvm::APSInt *NextElementIndex, 1201 unsigned &Index, 1202 InitListExpr *StructuredList, 1203 unsigned &StructuredIndex, 1204 bool FinishSubobjectInit, 1205 bool TopLevelObject) { 1206 if (DesigIdx == DIE->size()) { 1207 // Check the actual initialization for the designated object type. 1208 bool prevHadError = hadError; 1209 1210 // Temporarily remove the designator expression from the 1211 // initializer list that the child calls see, so that we don't try 1212 // to re-process the designator. 1213 unsigned OldIndex = Index; 1214 IList->setInit(OldIndex, DIE->getInit()); 1215 1216 CheckSubElementType(IList, CurrentObjectType, Index, 1217 StructuredList, StructuredIndex); 1218 1219 // Restore the designated initializer expression in the syntactic 1220 // form of the initializer list. 1221 if (IList->getInit(OldIndex) != DIE->getInit()) 1222 DIE->setInit(IList->getInit(OldIndex)); 1223 IList->setInit(OldIndex, DIE); 1224 1225 return hadError && !prevHadError; 1226 } 1227 1228 bool IsFirstDesignator = (DesigIdx == 0); 1229 assert((IsFirstDesignator || StructuredList) && 1230 "Need a non-designated initializer list to start from"); 1231 1232 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1233 // Determine the structural initializer list that corresponds to the 1234 // current subobject. 1235 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1236 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1237 StructuredList, StructuredIndex, 1238 SourceRange(D->getStartLocation(), 1239 DIE->getSourceRange().getEnd())); 1240 assert(StructuredList && "Expected a structured initializer list"); 1241 1242 if (D->isFieldDesignator()) { 1243 // C99 6.7.8p7: 1244 // 1245 // If a designator has the form 1246 // 1247 // . identifier 1248 // 1249 // then the current object (defined below) shall have 1250 // structure or union type and the identifier shall be the 1251 // name of a member of that type. 1252 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1253 if (!RT) { 1254 SourceLocation Loc = D->getDotLoc(); 1255 if (Loc.isInvalid()) 1256 Loc = D->getFieldLoc(); 1257 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1258 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1259 ++Index; 1260 return true; 1261 } 1262 1263 // Note: we perform a linear search of the fields here, despite 1264 // the fact that we have a faster lookup method, because we always 1265 // need to compute the field's index. 1266 FieldDecl *KnownField = D->getField(); 1267 IdentifierInfo *FieldName = D->getFieldName(); 1268 unsigned FieldIndex = 0; 1269 RecordDecl::field_iterator 1270 Field = RT->getDecl()->field_begin(), 1271 FieldEnd = RT->getDecl()->field_end(); 1272 for (; Field != FieldEnd; ++Field) { 1273 if (Field->isUnnamedBitfield()) 1274 continue; 1275 1276 if (KnownField == *Field || Field->getIdentifier() == FieldName) 1277 break; 1278 1279 ++FieldIndex; 1280 } 1281 1282 if (Field == FieldEnd) { 1283 // There was no normal field in the struct with the designated 1284 // name. Perform another lookup for this name, which may find 1285 // something that we can't designate (e.g., a member function), 1286 // may find nothing, or may find a member of an anonymous 1287 // struct/union. 1288 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1289 if (Lookup.first == Lookup.second) { 1290 // Name lookup didn't find anything. 1291 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1292 << FieldName << CurrentObjectType; 1293 ++Index; 1294 return true; 1295 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) && 1296 cast<RecordDecl>((*Lookup.first)->getDeclContext()) 1297 ->isAnonymousStructOrUnion()) { 1298 // Handle an field designator that refers to a member of an 1299 // anonymous struct or union. 1300 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, 1301 cast<FieldDecl>(*Lookup.first), 1302 Field, FieldIndex); 1303 D = DIE->getDesignator(DesigIdx); 1304 } else { 1305 // Name lookup found something, but it wasn't a field. 1306 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1307 << FieldName; 1308 SemaRef.Diag((*Lookup.first)->getLocation(), 1309 diag::note_field_designator_found); 1310 ++Index; 1311 return true; 1312 } 1313 } else if (!KnownField && 1314 cast<RecordDecl>((*Field)->getDeclContext()) 1315 ->isAnonymousStructOrUnion()) { 1316 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field, 1317 Field, FieldIndex); 1318 D = DIE->getDesignator(DesigIdx); 1319 } 1320 1321 // All of the fields of a union are located at the same place in 1322 // the initializer list. 1323 if (RT->getDecl()->isUnion()) { 1324 FieldIndex = 0; 1325 StructuredList->setInitializedFieldInUnion(*Field); 1326 } 1327 1328 // Update the designator with the field declaration. 1329 D->setField(*Field); 1330 1331 // Make sure that our non-designated initializer list has space 1332 // for a subobject corresponding to this field. 1333 if (FieldIndex >= StructuredList->getNumInits()) 1334 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1335 1336 // This designator names a flexible array member. 1337 if (Field->getType()->isIncompleteArrayType()) { 1338 bool Invalid = false; 1339 if ((DesigIdx + 1) != DIE->size()) { 1340 // We can't designate an object within the flexible array 1341 // member (because GCC doesn't allow it). 1342 DesignatedInitExpr::Designator *NextD 1343 = DIE->getDesignator(DesigIdx + 1); 1344 SemaRef.Diag(NextD->getStartLocation(), 1345 diag::err_designator_into_flexible_array_member) 1346 << SourceRange(NextD->getStartLocation(), 1347 DIE->getSourceRange().getEnd()); 1348 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1349 << *Field; 1350 Invalid = true; 1351 } 1352 1353 if (!hadError && !isa<InitListExpr>(DIE->getInit())) { 1354 // The initializer is not an initializer list. 1355 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1356 diag::err_flexible_array_init_needs_braces) 1357 << DIE->getInit()->getSourceRange(); 1358 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1359 << *Field; 1360 Invalid = true; 1361 } 1362 1363 // Handle GNU flexible array initializers. 1364 if (!Invalid && !TopLevelObject && 1365 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1366 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1367 diag::err_flexible_array_init_nonempty) 1368 << DIE->getSourceRange().getBegin(); 1369 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1370 << *Field; 1371 Invalid = true; 1372 } 1373 1374 if (Invalid) { 1375 ++Index; 1376 return true; 1377 } 1378 1379 // Initialize the array. 1380 bool prevHadError = hadError; 1381 unsigned newStructuredIndex = FieldIndex; 1382 unsigned OldIndex = Index; 1383 IList->setInit(Index, DIE->getInit()); 1384 CheckSubElementType(IList, Field->getType(), Index, 1385 StructuredList, newStructuredIndex); 1386 IList->setInit(OldIndex, DIE); 1387 if (hadError && !prevHadError) { 1388 ++Field; 1389 ++FieldIndex; 1390 if (NextField) 1391 *NextField = Field; 1392 StructuredIndex = FieldIndex; 1393 return true; 1394 } 1395 } else { 1396 // Recurse to check later designated subobjects. 1397 QualType FieldType = (*Field)->getType(); 1398 unsigned newStructuredIndex = FieldIndex; 1399 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0, 1400 Index, StructuredList, newStructuredIndex, 1401 true, false)) 1402 return true; 1403 } 1404 1405 // Find the position of the next field to be initialized in this 1406 // subobject. 1407 ++Field; 1408 ++FieldIndex; 1409 1410 // If this the first designator, our caller will continue checking 1411 // the rest of this struct/class/union subobject. 1412 if (IsFirstDesignator) { 1413 if (NextField) 1414 *NextField = Field; 1415 StructuredIndex = FieldIndex; 1416 return false; 1417 } 1418 1419 if (!FinishSubobjectInit) 1420 return false; 1421 1422 // We've already initialized something in the union; we're done. 1423 if (RT->getDecl()->isUnion()) 1424 return hadError; 1425 1426 // Check the remaining fields within this class/struct/union subobject. 1427 bool prevHadError = hadError; 1428 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index, 1429 StructuredList, FieldIndex); 1430 return hadError && !prevHadError; 1431 } 1432 1433 // C99 6.7.8p6: 1434 // 1435 // If a designator has the form 1436 // 1437 // [ constant-expression ] 1438 // 1439 // then the current object (defined below) shall have array 1440 // type and the expression shall be an integer constant 1441 // expression. If the array is of unknown size, any 1442 // nonnegative value is valid. 1443 // 1444 // Additionally, cope with the GNU extension that permits 1445 // designators of the form 1446 // 1447 // [ constant-expression ... constant-expression ] 1448 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1449 if (!AT) { 1450 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1451 << CurrentObjectType; 1452 ++Index; 1453 return true; 1454 } 1455 1456 Expr *IndexExpr = 0; 1457 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1458 if (D->isArrayDesignator()) { 1459 IndexExpr = DIE->getArrayIndex(*D); 1460 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1461 DesignatedEndIndex = DesignatedStartIndex; 1462 } else { 1463 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1464 1465 1466 DesignatedStartIndex = 1467 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1468 DesignatedEndIndex = 1469 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1470 IndexExpr = DIE->getArrayRangeEnd(*D); 1471 1472 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue()) 1473 FullyStructuredList->sawArrayRangeDesignator(); 1474 } 1475 1476 if (isa<ConstantArrayType>(AT)) { 1477 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1478 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1479 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1480 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1481 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1482 if (DesignatedEndIndex >= MaxElements) { 1483 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1484 diag::err_array_designator_too_large) 1485 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1486 << IndexExpr->getSourceRange(); 1487 ++Index; 1488 return true; 1489 } 1490 } else { 1491 // Make sure the bit-widths and signedness match. 1492 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1493 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1494 else if (DesignatedStartIndex.getBitWidth() < 1495 DesignatedEndIndex.getBitWidth()) 1496 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1497 DesignatedStartIndex.setIsUnsigned(true); 1498 DesignatedEndIndex.setIsUnsigned(true); 1499 } 1500 1501 // Make sure that our non-designated initializer list has space 1502 // for a subobject corresponding to this array element. 1503 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1504 StructuredList->resizeInits(SemaRef.Context, 1505 DesignatedEndIndex.getZExtValue() + 1); 1506 1507 // Repeatedly perform subobject initializations in the range 1508 // [DesignatedStartIndex, DesignatedEndIndex]. 1509 1510 // Move to the next designator 1511 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1512 unsigned OldIndex = Index; 1513 while (DesignatedStartIndex <= DesignatedEndIndex) { 1514 // Recurse to check later designated subobjects. 1515 QualType ElementType = AT->getElementType(); 1516 Index = OldIndex; 1517 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0, 1518 Index, StructuredList, ElementIndex, 1519 (DesignatedStartIndex == DesignatedEndIndex), 1520 false)) 1521 return true; 1522 1523 // Move to the next index in the array that we'll be initializing. 1524 ++DesignatedStartIndex; 1525 ElementIndex = DesignatedStartIndex.getZExtValue(); 1526 } 1527 1528 // If this the first designator, our caller will continue checking 1529 // the rest of this array subobject. 1530 if (IsFirstDesignator) { 1531 if (NextElementIndex) 1532 *NextElementIndex = DesignatedStartIndex; 1533 StructuredIndex = ElementIndex; 1534 return false; 1535 } 1536 1537 if (!FinishSubobjectInit) 1538 return false; 1539 1540 // Check the remaining elements within this array subobject. 1541 bool prevHadError = hadError; 1542 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index, 1543 StructuredList, ElementIndex); 1544 return hadError && !prevHadError; 1545} 1546 1547// Get the structured initializer list for a subobject of type 1548// @p CurrentObjectType. 1549InitListExpr * 1550InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1551 QualType CurrentObjectType, 1552 InitListExpr *StructuredList, 1553 unsigned StructuredIndex, 1554 SourceRange InitRange) { 1555 Expr *ExistingInit = 0; 1556 if (!StructuredList) 1557 ExistingInit = SyntacticToSemantic[IList]; 1558 else if (StructuredIndex < StructuredList->getNumInits()) 1559 ExistingInit = StructuredList->getInit(StructuredIndex); 1560 1561 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1562 return Result; 1563 1564 if (ExistingInit) { 1565 // We are creating an initializer list that initializes the 1566 // subobjects of the current object, but there was already an 1567 // initialization that completely initialized the current 1568 // subobject, e.g., by a compound literal: 1569 // 1570 // struct X { int a, b; }; 1571 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1572 // 1573 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1574 // designated initializer re-initializes the whole 1575 // subobject [0], overwriting previous initializers. 1576 SemaRef.Diag(InitRange.getBegin(), 1577 diag::warn_subobject_initializer_overrides) 1578 << InitRange; 1579 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1580 diag::note_previous_initializer) 1581 << /*FIXME:has side effects=*/0 1582 << ExistingInit->getSourceRange(); 1583 } 1584 1585 InitListExpr *Result 1586 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0, 1587 InitRange.getEnd()); 1588 1589 Result->setType(CurrentObjectType); 1590 1591 // Pre-allocate storage for the structured initializer list. 1592 unsigned NumElements = 0; 1593 unsigned NumInits = 0; 1594 if (!StructuredList) 1595 NumInits = IList->getNumInits(); 1596 else if (Index < IList->getNumInits()) { 1597 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) 1598 NumInits = SubList->getNumInits(); 1599 } 1600 1601 if (const ArrayType *AType 1602 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1603 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1604 NumElements = CAType->getSize().getZExtValue(); 1605 // Simple heuristic so that we don't allocate a very large 1606 // initializer with many empty entries at the end. 1607 if (NumInits && NumElements > NumInits) 1608 NumElements = 0; 1609 } 1610 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 1611 NumElements = VType->getNumElements(); 1612 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1613 RecordDecl *RDecl = RType->getDecl(); 1614 if (RDecl->isUnion()) 1615 NumElements = 1; 1616 else 1617 NumElements = std::distance(RDecl->field_begin(), 1618 RDecl->field_end()); 1619 } 1620 1621 if (NumElements < NumInits) 1622 NumElements = IList->getNumInits(); 1623 1624 Result->reserveInits(NumElements); 1625 1626 // Link this new initializer list into the structured initializer 1627 // lists. 1628 if (StructuredList) 1629 StructuredList->updateInit(StructuredIndex, Result); 1630 else { 1631 Result->setSyntacticForm(IList); 1632 SyntacticToSemantic[IList] = Result; 1633 } 1634 1635 return Result; 1636} 1637 1638/// Update the initializer at index @p StructuredIndex within the 1639/// structured initializer list to the value @p expr. 1640void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1641 unsigned &StructuredIndex, 1642 Expr *expr) { 1643 // No structured initializer list to update 1644 if (!StructuredList) 1645 return; 1646 1647 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) { 1648 // This initializer overwrites a previous initializer. Warn. 1649 SemaRef.Diag(expr->getSourceRange().getBegin(), 1650 diag::warn_initializer_overrides) 1651 << expr->getSourceRange(); 1652 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1653 diag::note_previous_initializer) 1654 << /*FIXME:has side effects=*/0 1655 << PrevInit->getSourceRange(); 1656 } 1657 1658 ++StructuredIndex; 1659} 1660 1661/// Check that the given Index expression is a valid array designator 1662/// value. This is essentailly just a wrapper around 1663/// VerifyIntegerConstantExpression that also checks for negative values 1664/// and produces a reasonable diagnostic if there is a 1665/// failure. Returns true if there was an error, false otherwise. If 1666/// everything went okay, Value will receive the value of the constant 1667/// expression. 1668static bool 1669CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1670 SourceLocation Loc = Index->getSourceRange().getBegin(); 1671 1672 // Make sure this is an integer constant expression. 1673 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1674 return true; 1675 1676 if (Value.isSigned() && Value.isNegative()) 1677 return S.Diag(Loc, diag::err_array_designator_negative) 1678 << Value.toString(10) << Index->getSourceRange(); 1679 1680 Value.setIsUnsigned(true); 1681 return false; 1682} 1683 1684Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1685 SourceLocation Loc, 1686 bool GNUSyntax, 1687 OwningExprResult Init) { 1688 typedef DesignatedInitExpr::Designator ASTDesignator; 1689 1690 bool Invalid = false; 1691 llvm::SmallVector<ASTDesignator, 32> Designators; 1692 llvm::SmallVector<Expr *, 32> InitExpressions; 1693 1694 // Build designators and check array designator expressions. 1695 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1696 const Designator &D = Desig.getDesignator(Idx); 1697 switch (D.getKind()) { 1698 case Designator::FieldDesignator: 1699 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1700 D.getFieldLoc())); 1701 break; 1702 1703 case Designator::ArrayDesignator: { 1704 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1705 llvm::APSInt IndexValue; 1706 if (!Index->isTypeDependent() && 1707 !Index->isValueDependent() && 1708 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1709 Invalid = true; 1710 else { 1711 Designators.push_back(ASTDesignator(InitExpressions.size(), 1712 D.getLBracketLoc(), 1713 D.getRBracketLoc())); 1714 InitExpressions.push_back(Index); 1715 } 1716 break; 1717 } 1718 1719 case Designator::ArrayRangeDesignator: { 1720 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1721 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1722 llvm::APSInt StartValue; 1723 llvm::APSInt EndValue; 1724 bool StartDependent = StartIndex->isTypeDependent() || 1725 StartIndex->isValueDependent(); 1726 bool EndDependent = EndIndex->isTypeDependent() || 1727 EndIndex->isValueDependent(); 1728 if ((!StartDependent && 1729 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1730 (!EndDependent && 1731 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1732 Invalid = true; 1733 else { 1734 // Make sure we're comparing values with the same bit width. 1735 if (StartDependent || EndDependent) { 1736 // Nothing to compute. 1737 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1738 EndValue.extend(StartValue.getBitWidth()); 1739 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1740 StartValue.extend(EndValue.getBitWidth()); 1741 1742 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1743 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1744 << StartValue.toString(10) << EndValue.toString(10) 1745 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1746 Invalid = true; 1747 } else { 1748 Designators.push_back(ASTDesignator(InitExpressions.size(), 1749 D.getLBracketLoc(), 1750 D.getEllipsisLoc(), 1751 D.getRBracketLoc())); 1752 InitExpressions.push_back(StartIndex); 1753 InitExpressions.push_back(EndIndex); 1754 } 1755 } 1756 break; 1757 } 1758 } 1759 } 1760 1761 if (Invalid || Init.isInvalid()) 1762 return ExprError(); 1763 1764 // Clear out the expressions within the designation. 1765 Desig.ClearExprs(*this); 1766 1767 DesignatedInitExpr *DIE 1768 = DesignatedInitExpr::Create(Context, 1769 Designators.data(), Designators.size(), 1770 InitExpressions.data(), InitExpressions.size(), 1771 Loc, GNUSyntax, Init.takeAs<Expr>()); 1772 return Owned(DIE); 1773} 1774 1775bool Sema::CheckInitList(const InitializedEntity &Entity, 1776 InitListExpr *&InitList, QualType &DeclType) { 1777 InitListChecker CheckInitList(*this, Entity, InitList, DeclType); 1778 if (!CheckInitList.HadError()) 1779 InitList = CheckInitList.getFullyStructuredList(); 1780 1781 return CheckInitList.HadError(); 1782} 1783 1784//===----------------------------------------------------------------------===// 1785// Initialization entity 1786//===----------------------------------------------------------------------===// 1787 1788InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 1789 const InitializedEntity &Parent) 1790 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index) 1791{ 1792 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) 1793 Type = AT->getElementType(); 1794 else 1795 Type = Parent.getType()->getAs<VectorType>()->getElementType(); 1796} 1797 1798InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 1799 CXXBaseSpecifier *Base) 1800{ 1801 InitializedEntity Result; 1802 Result.Kind = EK_Base; 1803 Result.Base = Base; 1804 Result.Type = Base->getType(); 1805 return Result; 1806} 1807 1808DeclarationName InitializedEntity::getName() const { 1809 switch (getKind()) { 1810 case EK_Variable: 1811 case EK_Parameter: 1812 case EK_Member: 1813 return VariableOrMember->getDeclName(); 1814 1815 case EK_Result: 1816 case EK_Exception: 1817 case EK_New: 1818 case EK_Temporary: 1819 case EK_Base: 1820 case EK_ArrayOrVectorElement: 1821 return DeclarationName(); 1822 } 1823 1824 // Silence GCC warning 1825 return DeclarationName(); 1826} 1827 1828DeclaratorDecl *InitializedEntity::getDecl() const { 1829 switch (getKind()) { 1830 case EK_Variable: 1831 case EK_Parameter: 1832 case EK_Member: 1833 return VariableOrMember; 1834 1835 case EK_Result: 1836 case EK_Exception: 1837 case EK_New: 1838 case EK_Temporary: 1839 case EK_Base: 1840 case EK_ArrayOrVectorElement: 1841 return 0; 1842 } 1843 1844 // Silence GCC warning 1845 return 0; 1846} 1847 1848//===----------------------------------------------------------------------===// 1849// Initialization sequence 1850//===----------------------------------------------------------------------===// 1851 1852void InitializationSequence::Step::Destroy() { 1853 switch (Kind) { 1854 case SK_ResolveAddressOfOverloadedFunction: 1855 case SK_CastDerivedToBaseRValue: 1856 case SK_CastDerivedToBaseLValue: 1857 case SK_BindReference: 1858 case SK_BindReferenceToTemporary: 1859 case SK_UserConversion: 1860 case SK_QualificationConversionRValue: 1861 case SK_QualificationConversionLValue: 1862 case SK_ListInitialization: 1863 case SK_ConstructorInitialization: 1864 case SK_ZeroInitialization: 1865 case SK_CAssignment: 1866 case SK_StringInit: 1867 break; 1868 1869 case SK_ConversionSequence: 1870 delete ICS; 1871 } 1872} 1873 1874void InitializationSequence::AddAddressOverloadResolutionStep( 1875 FunctionDecl *Function) { 1876 Step S; 1877 S.Kind = SK_ResolveAddressOfOverloadedFunction; 1878 S.Type = Function->getType(); 1879 S.Function = Function; 1880 Steps.push_back(S); 1881} 1882 1883void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 1884 bool IsLValue) { 1885 Step S; 1886 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue; 1887 S.Type = BaseType; 1888 Steps.push_back(S); 1889} 1890 1891void InitializationSequence::AddReferenceBindingStep(QualType T, 1892 bool BindingTemporary) { 1893 Step S; 1894 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 1895 S.Type = T; 1896 Steps.push_back(S); 1897} 1898 1899void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 1900 QualType T) { 1901 Step S; 1902 S.Kind = SK_UserConversion; 1903 S.Type = T; 1904 S.Function = Function; 1905 Steps.push_back(S); 1906} 1907 1908void InitializationSequence::AddQualificationConversionStep(QualType Ty, 1909 bool IsLValue) { 1910 Step S; 1911 S.Kind = IsLValue? SK_QualificationConversionLValue 1912 : SK_QualificationConversionRValue; 1913 S.Type = Ty; 1914 Steps.push_back(S); 1915} 1916 1917void InitializationSequence::AddConversionSequenceStep( 1918 const ImplicitConversionSequence &ICS, 1919 QualType T) { 1920 Step S; 1921 S.Kind = SK_ConversionSequence; 1922 S.Type = T; 1923 S.ICS = new ImplicitConversionSequence(ICS); 1924 Steps.push_back(S); 1925} 1926 1927void InitializationSequence::AddListInitializationStep(QualType T) { 1928 Step S; 1929 S.Kind = SK_ListInitialization; 1930 S.Type = T; 1931 Steps.push_back(S); 1932} 1933 1934void 1935InitializationSequence::AddConstructorInitializationStep( 1936 CXXConstructorDecl *Constructor, 1937 QualType T) { 1938 Step S; 1939 S.Kind = SK_ConstructorInitialization; 1940 S.Type = T; 1941 S.Function = Constructor; 1942 Steps.push_back(S); 1943} 1944 1945void InitializationSequence::AddZeroInitializationStep(QualType T) { 1946 Step S; 1947 S.Kind = SK_ZeroInitialization; 1948 S.Type = T; 1949 Steps.push_back(S); 1950} 1951 1952void InitializationSequence::AddCAssignmentStep(QualType T) { 1953 Step S; 1954 S.Kind = SK_CAssignment; 1955 S.Type = T; 1956 Steps.push_back(S); 1957} 1958 1959void InitializationSequence::AddStringInitStep(QualType T) { 1960 Step S; 1961 S.Kind = SK_StringInit; 1962 S.Type = T; 1963 Steps.push_back(S); 1964} 1965 1966void InitializationSequence::SetOverloadFailure(FailureKind Failure, 1967 OverloadingResult Result) { 1968 SequenceKind = FailedSequence; 1969 this->Failure = Failure; 1970 this->FailedOverloadResult = Result; 1971} 1972 1973//===----------------------------------------------------------------------===// 1974// Attempt initialization 1975//===----------------------------------------------------------------------===// 1976 1977/// \brief Attempt list initialization (C++0x [dcl.init.list]) 1978static void TryListInitialization(Sema &S, 1979 const InitializedEntity &Entity, 1980 const InitializationKind &Kind, 1981 InitListExpr *InitList, 1982 InitializationSequence &Sequence) { 1983 // FIXME: We only perform rudimentary checking of list 1984 // initializations at this point, then assume that any list 1985 // initialization of an array, aggregate, or scalar will be 1986 // well-formed. We we actually "perform" list initialization, we'll 1987 // do all of the necessary checking. C++0x initializer lists will 1988 // force us to perform more checking here. 1989 Sequence.setSequenceKind(InitializationSequence::ListInitialization); 1990 1991 QualType DestType = Entity.getType(); 1992 1993 // C++ [dcl.init]p13: 1994 // If T is a scalar type, then a declaration of the form 1995 // 1996 // T x = { a }; 1997 // 1998 // is equivalent to 1999 // 2000 // T x = a; 2001 if (DestType->isScalarType()) { 2002 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) { 2003 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 2004 return; 2005 } 2006 2007 // Assume scalar initialization from a single value works. 2008 } else if (DestType->isAggregateType()) { 2009 // Assume aggregate initialization works. 2010 } else if (DestType->isVectorType()) { 2011 // Assume vector initialization works. 2012 } else if (DestType->isReferenceType()) { 2013 // FIXME: C++0x defines behavior for this. 2014 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 2015 return; 2016 } else if (DestType->isRecordType()) { 2017 // FIXME: C++0x defines behavior for this 2018 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 2019 } 2020 2021 // Add a general "list initialization" step. 2022 Sequence.AddListInitializationStep(DestType); 2023} 2024 2025/// \brief Try a reference initialization that involves calling a conversion 2026/// function. 2027/// 2028/// FIXME: look intos DRs 656, 896 2029static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 2030 const InitializedEntity &Entity, 2031 const InitializationKind &Kind, 2032 Expr *Initializer, 2033 bool AllowRValues, 2034 InitializationSequence &Sequence) { 2035 QualType DestType = Entity.getType(); 2036 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2037 QualType T1 = cv1T1.getUnqualifiedType(); 2038 QualType cv2T2 = Initializer->getType(); 2039 QualType T2 = cv2T2.getUnqualifiedType(); 2040 2041 bool DerivedToBase; 2042 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 2043 T1, T2, DerivedToBase) && 2044 "Must have incompatible references when binding via conversion"); 2045 (void)DerivedToBase; 2046 2047 // Build the candidate set directly in the initialization sequence 2048 // structure, so that it will persist if we fail. 2049 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2050 CandidateSet.clear(); 2051 2052 // Determine whether we are allowed to call explicit constructors or 2053 // explicit conversion operators. 2054 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2055 2056 const RecordType *T1RecordType = 0; 2057 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) { 2058 // The type we're converting to is a class type. Enumerate its constructors 2059 // to see if there is a suitable conversion. 2060 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 2061 2062 DeclarationName ConstructorName 2063 = S.Context.DeclarationNames.getCXXConstructorName( 2064 S.Context.getCanonicalType(T1).getUnqualifiedType()); 2065 DeclContext::lookup_iterator Con, ConEnd; 2066 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName); 2067 Con != ConEnd; ++Con) { 2068 // Find the constructor (which may be a template). 2069 CXXConstructorDecl *Constructor = 0; 2070 FunctionTemplateDecl *ConstructorTmpl 2071 = dyn_cast<FunctionTemplateDecl>(*Con); 2072 if (ConstructorTmpl) 2073 Constructor = cast<CXXConstructorDecl>( 2074 ConstructorTmpl->getTemplatedDecl()); 2075 else 2076 Constructor = cast<CXXConstructorDecl>(*Con); 2077 2078 if (!Constructor->isInvalidDecl() && 2079 Constructor->isConvertingConstructor(AllowExplicit)) { 2080 if (ConstructorTmpl) 2081 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2082 &Initializer, 1, CandidateSet); 2083 else 2084 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet); 2085 } 2086 } 2087 } 2088 2089 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) { 2090 // The type we're converting from is a class type, enumerate its conversion 2091 // functions. 2092 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 2093 2094 // Determine the type we are converting to. If we are allowed to 2095 // convert to an rvalue, take the type that the destination type 2096 // refers to. 2097 QualType ToType = AllowRValues? cv1T1 : DestType; 2098 2099 const UnresolvedSet *Conversions 2100 = T2RecordDecl->getVisibleConversionFunctions(); 2101 for (UnresolvedSet::iterator I = Conversions->begin(), 2102 E = Conversions->end(); 2103 I != E; ++I) { 2104 NamedDecl *D = *I; 2105 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2106 if (isa<UsingShadowDecl>(D)) 2107 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2108 2109 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2110 CXXConversionDecl *Conv; 2111 if (ConvTemplate) 2112 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2113 else 2114 Conv = cast<CXXConversionDecl>(*I); 2115 2116 // If the conversion function doesn't return a reference type, 2117 // it can't be considered for this conversion unless we're allowed to 2118 // consider rvalues. 2119 // FIXME: Do we need to make sure that we only consider conversion 2120 // candidates with reference-compatible results? That might be needed to 2121 // break recursion. 2122 if ((AllowExplicit || !Conv->isExplicit()) && 2123 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 2124 if (ConvTemplate) 2125 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer, 2126 ToType, CandidateSet); 2127 else 2128 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1, 2129 CandidateSet); 2130 } 2131 } 2132 } 2133 2134 SourceLocation DeclLoc = Initializer->getLocStart(); 2135 2136 // Perform overload resolution. If it fails, return the failed result. 2137 OverloadCandidateSet::iterator Best; 2138 if (OverloadingResult Result 2139 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) 2140 return Result; 2141 2142 FunctionDecl *Function = Best->Function; 2143 2144 // Compute the returned type of the conversion. 2145 if (isa<CXXConversionDecl>(Function)) 2146 T2 = Function->getResultType(); 2147 else 2148 T2 = cv1T1; 2149 2150 // Add the user-defined conversion step. 2151 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType()); 2152 2153 // Determine whether we need to perform derived-to-base or 2154 // cv-qualification adjustments. 2155 bool NewDerivedToBase = false; 2156 Sema::ReferenceCompareResult NewRefRelationship 2157 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(), 2158 NewDerivedToBase); 2159 assert(NewRefRelationship != Sema::Ref_Incompatible && 2160 "Overload resolution picked a bad conversion function"); 2161 (void)NewRefRelationship; 2162 if (NewDerivedToBase) 2163 Sequence.AddDerivedToBaseCastStep( 2164 S.Context.getQualifiedType(T1, 2165 T2.getNonReferenceType().getQualifiers()), 2166 /*isLValue=*/true); 2167 2168 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 2169 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType()); 2170 2171 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 2172 return OR_Success; 2173} 2174 2175/// \brief Attempt reference initialization (C++0x [dcl.init.list]) 2176static void TryReferenceInitialization(Sema &S, 2177 const InitializedEntity &Entity, 2178 const InitializationKind &Kind, 2179 Expr *Initializer, 2180 InitializationSequence &Sequence) { 2181 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding); 2182 2183 QualType DestType = Entity.getType(); 2184 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2185 QualType T1 = cv1T1.getUnqualifiedType(); 2186 QualType cv2T2 = Initializer->getType(); 2187 QualType T2 = cv2T2.getUnqualifiedType(); 2188 SourceLocation DeclLoc = Initializer->getLocStart(); 2189 2190 // If the initializer is the address of an overloaded function, try 2191 // to resolve the overloaded function. If all goes well, T2 is the 2192 // type of the resulting function. 2193 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2194 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, 2195 T1, 2196 false); 2197 if (!Fn) { 2198 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2199 return; 2200 } 2201 2202 Sequence.AddAddressOverloadResolutionStep(Fn); 2203 cv2T2 = Fn->getType(); 2204 T2 = cv2T2.getUnqualifiedType(); 2205 } 2206 2207 // FIXME: Rvalue references 2208 bool ForceRValue = false; 2209 2210 // Compute some basic properties of the types and the initializer. 2211 bool isLValueRef = DestType->isLValueReferenceType(); 2212 bool isRValueRef = !isLValueRef; 2213 bool DerivedToBase = false; 2214 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 2215 Initializer->isLvalue(S.Context); 2216 Sema::ReferenceCompareResult RefRelationship 2217 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase); 2218 2219 // C++0x [dcl.init.ref]p5: 2220 // A reference to type "cv1 T1" is initialized by an expression of type 2221 // "cv2 T2" as follows: 2222 // 2223 // - If the reference is an lvalue reference and the initializer 2224 // expression 2225 OverloadingResult ConvOvlResult = OR_Success; 2226 if (isLValueRef) { 2227 if (InitLvalue == Expr::LV_Valid && 2228 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2229 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 2230 // reference-compatible with "cv2 T2," or 2231 // 2232 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a 2233 // bit-field when we're determining whether the reference initialization 2234 // can occur. This property will be checked by PerformInitialization. 2235 if (DerivedToBase) 2236 Sequence.AddDerivedToBaseCastStep( 2237 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()), 2238 /*isLValue=*/true); 2239 if (cv1T1.getQualifiers() != cv2T2.getQualifiers()) 2240 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true); 2241 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false); 2242 return; 2243 } 2244 2245 // - has a class type (i.e., T2 is a class type), where T1 is not 2246 // reference-related to T2, and can be implicitly converted to an 2247 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 2248 // with "cv3 T3" (this conversion is selected by enumerating the 2249 // applicable conversion functions (13.3.1.6) and choosing the best 2250 // one through overload resolution (13.3)), 2251 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) { 2252 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 2253 Initializer, 2254 /*AllowRValues=*/false, 2255 Sequence); 2256 if (ConvOvlResult == OR_Success) 2257 return; 2258 } 2259 } 2260 2261 // - Otherwise, the reference shall be an lvalue reference to a 2262 // non-volatile const type (i.e., cv1 shall be const), or the reference 2263 // shall be an rvalue reference and the initializer expression shall 2264 // be an rvalue. 2265 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) || 2266 (isRValueRef && InitLvalue != Expr::LV_Valid))) { 2267 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2268 Sequence.SetOverloadFailure( 2269 InitializationSequence::FK_ReferenceInitOverloadFailed, 2270 ConvOvlResult); 2271 else if (isLValueRef) 2272 Sequence.SetFailed(InitLvalue == Expr::LV_Valid 2273 ? (RefRelationship == Sema::Ref_Related 2274 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 2275 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 2276 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 2277 else 2278 Sequence.SetFailed( 2279 InitializationSequence::FK_RValueReferenceBindingToLValue); 2280 2281 return; 2282 } 2283 2284 // - If T1 and T2 are class types and 2285 if (T1->isRecordType() && T2->isRecordType()) { 2286 // - the initializer expression is an rvalue and "cv1 T1" is 2287 // reference-compatible with "cv2 T2", or 2288 if (InitLvalue != Expr::LV_Valid && 2289 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2290 if (DerivedToBase) 2291 Sequence.AddDerivedToBaseCastStep( 2292 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()), 2293 /*isLValue=*/false); 2294 if (cv1T1.getQualifiers() != cv2T2.getQualifiers()) 2295 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false); 2296 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2297 return; 2298 } 2299 2300 // - T1 is not reference-related to T2 and the initializer expression 2301 // can be implicitly converted to an rvalue of type "cv3 T3" (this 2302 // conversion is selected by enumerating the applicable conversion 2303 // functions (13.3.1.6) and choosing the best one through overload 2304 // resolution (13.3)), 2305 if (RefRelationship == Sema::Ref_Incompatible) { 2306 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 2307 Kind, Initializer, 2308 /*AllowRValues=*/true, 2309 Sequence); 2310 if (ConvOvlResult) 2311 Sequence.SetOverloadFailure( 2312 InitializationSequence::FK_ReferenceInitOverloadFailed, 2313 ConvOvlResult); 2314 2315 return; 2316 } 2317 2318 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2319 return; 2320 } 2321 2322 // - If the initializer expression is an rvalue, with T2 an array type, 2323 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference 2324 // is bound to the object represented by the rvalue (see 3.10). 2325 // FIXME: How can an array type be reference-compatible with anything? 2326 // Don't we mean the element types of T1 and T2? 2327 2328 // - Otherwise, a temporary of type “cv1 T1” is created and initialized 2329 // from the initializer expression using the rules for a non-reference 2330 // copy initialization (8.5). The reference is then bound to the 2331 // temporary. [...] 2332 // Determine whether we are allowed to call explicit constructors or 2333 // explicit conversion operators. 2334 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 2335 ImplicitConversionSequence ICS 2336 = S.TryImplicitConversion(Initializer, cv1T1, 2337 /*SuppressUserConversions=*/false, AllowExplicit, 2338 /*ForceRValue=*/false, 2339 /*FIXME:InOverloadResolution=*/false, 2340 /*UserCast=*/Kind.isExplicitCast()); 2341 2342 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 2343 // FIXME: Use the conversion function set stored in ICS to turn 2344 // this into an overloading ambiguity diagnostic. However, we need 2345 // to keep that set as an OverloadCandidateSet rather than as some 2346 // other kind of set. 2347 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2348 Sequence.SetOverloadFailure( 2349 InitializationSequence::FK_ReferenceInitOverloadFailed, 2350 ConvOvlResult); 2351 else 2352 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 2353 return; 2354 } 2355 2356 // [...] If T1 is reference-related to T2, cv1 must be the 2357 // same cv-qualification as, or greater cv-qualification 2358 // than, cv2; otherwise, the program is ill-formed. 2359 if (RefRelationship == Sema::Ref_Related && 2360 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) { 2361 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2362 return; 2363 } 2364 2365 // Perform the actual conversion. 2366 Sequence.AddConversionSequenceStep(ICS, cv1T1); 2367 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2368 return; 2369} 2370 2371/// \brief Attempt character array initialization from a string literal 2372/// (C++ [dcl.init.string], C99 6.7.8). 2373static void TryStringLiteralInitialization(Sema &S, 2374 const InitializedEntity &Entity, 2375 const InitializationKind &Kind, 2376 Expr *Initializer, 2377 InitializationSequence &Sequence) { 2378 Sequence.setSequenceKind(InitializationSequence::StringInit); 2379 Sequence.AddStringInitStep(Entity.getType()); 2380} 2381 2382/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2383/// enumerates the constructors of the initialized entity and performs overload 2384/// resolution to select the best. 2385static void TryConstructorInitialization(Sema &S, 2386 const InitializedEntity &Entity, 2387 const InitializationKind &Kind, 2388 Expr **Args, unsigned NumArgs, 2389 QualType DestType, 2390 InitializationSequence &Sequence) { 2391 if (Kind.getKind() == InitializationKind::IK_Copy) 2392 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion); 2393 else 2394 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization); 2395 2396 // Build the candidate set directly in the initialization sequence 2397 // structure, so that it will persist if we fail. 2398 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2399 CandidateSet.clear(); 2400 2401 // Determine whether we are allowed to call explicit constructors or 2402 // explicit conversion operators. 2403 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct || 2404 Kind.getKind() == InitializationKind::IK_Value || 2405 Kind.getKind() == InitializationKind::IK_Default); 2406 2407 // The type we're converting to is a class type. Enumerate its constructors 2408 // to see if one is suitable. 2409 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2410 assert(DestRecordType && "Constructor initialization requires record type"); 2411 CXXRecordDecl *DestRecordDecl 2412 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2413 2414 DeclarationName ConstructorName 2415 = S.Context.DeclarationNames.getCXXConstructorName( 2416 S.Context.getCanonicalType(DestType).getUnqualifiedType()); 2417 DeclContext::lookup_iterator Con, ConEnd; 2418 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName); 2419 Con != ConEnd; ++Con) { 2420 // Find the constructor (which may be a template). 2421 CXXConstructorDecl *Constructor = 0; 2422 FunctionTemplateDecl *ConstructorTmpl 2423 = dyn_cast<FunctionTemplateDecl>(*Con); 2424 if (ConstructorTmpl) 2425 Constructor = cast<CXXConstructorDecl>( 2426 ConstructorTmpl->getTemplatedDecl()); 2427 else 2428 Constructor = cast<CXXConstructorDecl>(*Con); 2429 2430 if (!Constructor->isInvalidDecl() && 2431 (AllowExplicit || !Constructor->isExplicit())) { 2432 if (ConstructorTmpl) 2433 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2434 Args, NumArgs, CandidateSet); 2435 else 2436 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 2437 } 2438 } 2439 2440 SourceLocation DeclLoc = Kind.getLocation(); 2441 2442 // Perform overload resolution. If it fails, return the failed result. 2443 OverloadCandidateSet::iterator Best; 2444 if (OverloadingResult Result 2445 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) { 2446 Sequence.SetOverloadFailure( 2447 InitializationSequence::FK_ConstructorOverloadFailed, 2448 Result); 2449 return; 2450 } 2451 2452 // Add the constructor initialization step. Any cv-qualification conversion is 2453 // subsumed by the initialization. 2454 if (Kind.getKind() == InitializationKind::IK_Copy) { 2455 Sequence.AddUserConversionStep(Best->Function, DestType); 2456 } else { 2457 Sequence.AddConstructorInitializationStep( 2458 cast<CXXConstructorDecl>(Best->Function), 2459 DestType); 2460 } 2461} 2462 2463/// \brief Attempt value initialization (C++ [dcl.init]p7). 2464static void TryValueInitialization(Sema &S, 2465 const InitializedEntity &Entity, 2466 const InitializationKind &Kind, 2467 InitializationSequence &Sequence) { 2468 // C++ [dcl.init]p5: 2469 // 2470 // To value-initialize an object of type T means: 2471 QualType T = Entity.getType(); 2472 2473 // -- if T is an array type, then each element is value-initialized; 2474 while (const ArrayType *AT = S.Context.getAsArrayType(T)) 2475 T = AT->getElementType(); 2476 2477 if (const RecordType *RT = T->getAs<RecordType>()) { 2478 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2479 // -- if T is a class type (clause 9) with a user-declared 2480 // constructor (12.1), then the default constructor for T is 2481 // called (and the initialization is ill-formed if T has no 2482 // accessible default constructor); 2483 // 2484 // FIXME: we really want to refer to a single subobject of the array, 2485 // but Entity doesn't have a way to capture that (yet). 2486 if (ClassDecl->hasUserDeclaredConstructor()) 2487 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2488 2489 // -- if T is a (possibly cv-qualified) non-union class type 2490 // without a user-provided constructor, then the object is 2491 // zero-initialized and, if T’s implicitly-declared default 2492 // constructor is non-trivial, that constructor is called. 2493 if ((ClassDecl->getTagKind() == TagDecl::TK_class || 2494 ClassDecl->getTagKind() == TagDecl::TK_struct) && 2495 !ClassDecl->hasTrivialConstructor()) { 2496 Sequence.AddZeroInitializationStep(Entity.getType()); 2497 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2498 } 2499 } 2500 } 2501 2502 Sequence.AddZeroInitializationStep(Entity.getType()); 2503 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization); 2504} 2505 2506/// \brief Attempt default initialization (C++ [dcl.init]p6). 2507static void TryDefaultInitialization(Sema &S, 2508 const InitializedEntity &Entity, 2509 const InitializationKind &Kind, 2510 InitializationSequence &Sequence) { 2511 assert(Kind.getKind() == InitializationKind::IK_Default); 2512 2513 // C++ [dcl.init]p6: 2514 // To default-initialize an object of type T means: 2515 // - if T is an array type, each element is default-initialized; 2516 QualType DestType = Entity.getType(); 2517 while (const ArrayType *Array = S.Context.getAsArrayType(DestType)) 2518 DestType = Array->getElementType(); 2519 2520 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 2521 // constructor for T is called (and the initialization is ill-formed if 2522 // T has no accessible default constructor); 2523 if (DestType->isRecordType()) { 2524 // FIXME: If a program calls for the default initialization of an object of 2525 // a const-qualified type T, T shall be a class type with a user-provided 2526 // default constructor. 2527 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, 2528 Sequence); 2529 } 2530 2531 // - otherwise, no initialization is performed. 2532 Sequence.setSequenceKind(InitializationSequence::NoInitialization); 2533 2534 // If a program calls for the default initialization of an object of 2535 // a const-qualified type T, T shall be a class type with a user-provided 2536 // default constructor. 2537 if (DestType.isConstQualified()) 2538 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2539} 2540 2541/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 2542/// which enumerates all conversion functions and performs overload resolution 2543/// to select the best. 2544static void TryUserDefinedConversion(Sema &S, 2545 const InitializedEntity &Entity, 2546 const InitializationKind &Kind, 2547 Expr *Initializer, 2548 InitializationSequence &Sequence) { 2549 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion); 2550 2551 QualType DestType = Entity.getType(); 2552 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 2553 QualType SourceType = Initializer->getType(); 2554 assert((DestType->isRecordType() || SourceType->isRecordType()) && 2555 "Must have a class type to perform a user-defined conversion"); 2556 2557 // Build the candidate set directly in the initialization sequence 2558 // structure, so that it will persist if we fail. 2559 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2560 CandidateSet.clear(); 2561 2562 // Determine whether we are allowed to call explicit constructors or 2563 // explicit conversion operators. 2564 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2565 2566 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 2567 // The type we're converting to is a class type. Enumerate its constructors 2568 // to see if there is a suitable conversion. 2569 CXXRecordDecl *DestRecordDecl 2570 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2571 2572 DeclarationName ConstructorName 2573 = S.Context.DeclarationNames.getCXXConstructorName( 2574 S.Context.getCanonicalType(DestType).getUnqualifiedType()); 2575 DeclContext::lookup_iterator Con, ConEnd; 2576 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName); 2577 Con != ConEnd; ++Con) { 2578 // Find the constructor (which may be a template). 2579 CXXConstructorDecl *Constructor = 0; 2580 FunctionTemplateDecl *ConstructorTmpl 2581 = dyn_cast<FunctionTemplateDecl>(*Con); 2582 if (ConstructorTmpl) 2583 Constructor = cast<CXXConstructorDecl>( 2584 ConstructorTmpl->getTemplatedDecl()); 2585 else 2586 Constructor = cast<CXXConstructorDecl>(*Con); 2587 2588 if (!Constructor->isInvalidDecl() && 2589 Constructor->isConvertingConstructor(AllowExplicit)) { 2590 if (ConstructorTmpl) 2591 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2592 &Initializer, 1, CandidateSet); 2593 else 2594 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet); 2595 } 2596 } 2597 } 2598 2599 SourceLocation DeclLoc = Initializer->getLocStart(); 2600 2601 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 2602 // The type we're converting from is a class type, enumerate its conversion 2603 // functions. 2604 2605 // We can only enumerate the conversion functions for a complete type; if 2606 // the type isn't complete, simply skip this step. 2607 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) { 2608 CXXRecordDecl *SourceRecordDecl 2609 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 2610 2611 const UnresolvedSet *Conversions 2612 = SourceRecordDecl->getVisibleConversionFunctions(); 2613 for (UnresolvedSet::iterator I = Conversions->begin(), 2614 E = Conversions->end(); 2615 I != E; ++I) { 2616 NamedDecl *D = *I; 2617 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2618 if (isa<UsingShadowDecl>(D)) 2619 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2620 2621 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2622 CXXConversionDecl *Conv; 2623 if (ConvTemplate) 2624 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2625 else 2626 Conv = cast<CXXConversionDecl>(*I); 2627 2628 if (AllowExplicit || !Conv->isExplicit()) { 2629 if (ConvTemplate) 2630 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, 2631 Initializer, DestType, 2632 CandidateSet); 2633 else 2634 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType, 2635 CandidateSet); 2636 } 2637 } 2638 } 2639 } 2640 2641 // Perform overload resolution. If it fails, return the failed result. 2642 OverloadCandidateSet::iterator Best; 2643 if (OverloadingResult Result 2644 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) { 2645 Sequence.SetOverloadFailure( 2646 InitializationSequence::FK_UserConversionOverloadFailed, 2647 Result); 2648 return; 2649 } 2650 2651 FunctionDecl *Function = Best->Function; 2652 2653 if (isa<CXXConstructorDecl>(Function)) { 2654 // Add the user-defined conversion step. Any cv-qualification conversion is 2655 // subsumed by the initialization. 2656 Sequence.AddUserConversionStep(Function, DestType); 2657 return; 2658 } 2659 2660 // Add the user-defined conversion step that calls the conversion function. 2661 QualType ConvType = Function->getResultType().getNonReferenceType(); 2662 Sequence.AddUserConversionStep(Function, ConvType); 2663 2664 // If the conversion following the call to the conversion function is 2665 // interesting, add it as a separate step. 2666 if (Best->FinalConversion.First || Best->FinalConversion.Second || 2667 Best->FinalConversion.Third) { 2668 ImplicitConversionSequence ICS; 2669 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 2670 ICS.Standard = Best->FinalConversion; 2671 Sequence.AddConversionSequenceStep(ICS, DestType); 2672 } 2673} 2674 2675/// \brief Attempt an implicit conversion (C++ [conv]) converting from one 2676/// non-class type to another. 2677static void TryImplicitConversion(Sema &S, 2678 const InitializedEntity &Entity, 2679 const InitializationKind &Kind, 2680 Expr *Initializer, 2681 InitializationSequence &Sequence) { 2682 ImplicitConversionSequence ICS 2683 = S.TryImplicitConversion(Initializer, Entity.getType(), 2684 /*SuppressUserConversions=*/true, 2685 /*AllowExplicit=*/false, 2686 /*ForceRValue=*/false, 2687 /*FIXME:InOverloadResolution=*/false, 2688 /*UserCast=*/Kind.isExplicitCast()); 2689 2690 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 2691 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed); 2692 return; 2693 } 2694 2695 Sequence.AddConversionSequenceStep(ICS, Entity.getType()); 2696} 2697 2698InitializationSequence::InitializationSequence(Sema &S, 2699 const InitializedEntity &Entity, 2700 const InitializationKind &Kind, 2701 Expr **Args, 2702 unsigned NumArgs) { 2703 ASTContext &Context = S.Context; 2704 2705 // C++0x [dcl.init]p16: 2706 // The semantics of initializers are as follows. The destination type is 2707 // the type of the object or reference being initialized and the source 2708 // type is the type of the initializer expression. The source type is not 2709 // defined when the initializer is a braced-init-list or when it is a 2710 // parenthesized list of expressions. 2711 QualType DestType = Entity.getType(); 2712 2713 if (DestType->isDependentType() || 2714 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 2715 SequenceKind = DependentSequence; 2716 return; 2717 } 2718 2719 QualType SourceType; 2720 Expr *Initializer = 0; 2721 if (NumArgs == 1) { 2722 Initializer = Args[0]; 2723 if (!isa<InitListExpr>(Initializer)) 2724 SourceType = Initializer->getType(); 2725 } 2726 2727 // - If the initializer is a braced-init-list, the object is 2728 // list-initialized (8.5.4). 2729 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 2730 TryListInitialization(S, Entity, Kind, InitList, *this); 2731 return; 2732 } 2733 2734 // - If the destination type is a reference type, see 8.5.3. 2735 if (DestType->isReferenceType()) { 2736 // C++0x [dcl.init.ref]p1: 2737 // A variable declared to be a T& or T&&, that is, "reference to type T" 2738 // (8.3.2), shall be initialized by an object, or function, of type T or 2739 // by an object that can be converted into a T. 2740 // (Therefore, multiple arguments are not permitted.) 2741 if (NumArgs != 1) 2742 SetFailed(FK_TooManyInitsForReference); 2743 else 2744 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 2745 return; 2746 } 2747 2748 // - If the destination type is an array of characters, an array of 2749 // char16_t, an array of char32_t, or an array of wchar_t, and the 2750 // initializer is a string literal, see 8.5.2. 2751 if (Initializer && IsStringInit(Initializer, DestType, Context)) { 2752 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 2753 return; 2754 } 2755 2756 // - If the initializer is (), the object is value-initialized. 2757 if (Kind.getKind() == InitializationKind::IK_Value || 2758 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) { 2759 TryValueInitialization(S, Entity, Kind, *this); 2760 return; 2761 } 2762 2763 // Handle default initialization. 2764 if (Kind.getKind() == InitializationKind::IK_Default){ 2765 TryDefaultInitialization(S, Entity, Kind, *this); 2766 return; 2767 } 2768 2769 // - Otherwise, if the destination type is an array, the program is 2770 // ill-formed. 2771 if (const ArrayType *AT = Context.getAsArrayType(DestType)) { 2772 if (AT->getElementType()->isAnyCharacterType()) 2773 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 2774 else 2775 SetFailed(FK_ArrayNeedsInitList); 2776 2777 return; 2778 } 2779 2780 // Handle initialization in C 2781 if (!S.getLangOptions().CPlusPlus) { 2782 setSequenceKind(CAssignment); 2783 AddCAssignmentStep(DestType); 2784 return; 2785 } 2786 2787 // - If the destination type is a (possibly cv-qualified) class type: 2788 if (DestType->isRecordType()) { 2789 // - If the initialization is direct-initialization, or if it is 2790 // copy-initialization where the cv-unqualified version of the 2791 // source type is the same class as, or a derived class of, the 2792 // class of the destination, constructors are considered. [...] 2793 if (Kind.getKind() == InitializationKind::IK_Direct || 2794 (Kind.getKind() == InitializationKind::IK_Copy && 2795 (Context.hasSameUnqualifiedType(SourceType, DestType) || 2796 S.IsDerivedFrom(SourceType, DestType)))) 2797 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, 2798 Entity.getType(), *this); 2799 // - Otherwise (i.e., for the remaining copy-initialization cases), 2800 // user-defined conversion sequences that can convert from the source 2801 // type to the destination type or (when a conversion function is 2802 // used) to a derived class thereof are enumerated as described in 2803 // 13.3.1.4, and the best one is chosen through overload resolution 2804 // (13.3). 2805 else 2806 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 2807 return; 2808 } 2809 2810 if (NumArgs > 1) { 2811 SetFailed(FK_TooManyInitsForScalar); 2812 return; 2813 } 2814 assert(NumArgs == 1 && "Zero-argument case handled above"); 2815 2816 // - Otherwise, if the source type is a (possibly cv-qualified) class 2817 // type, conversion functions are considered. 2818 if (!SourceType.isNull() && SourceType->isRecordType()) { 2819 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 2820 return; 2821 } 2822 2823 // - Otherwise, the initial value of the object being initialized is the 2824 // (possibly converted) value of the initializer expression. Standard 2825 // conversions (Clause 4) will be used, if necessary, to convert the 2826 // initializer expression to the cv-unqualified version of the 2827 // destination type; no user-defined conversions are considered. 2828 setSequenceKind(StandardConversion); 2829 TryImplicitConversion(S, Entity, Kind, Initializer, *this); 2830} 2831 2832InitializationSequence::~InitializationSequence() { 2833 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(), 2834 StepEnd = Steps.end(); 2835 Step != StepEnd; ++Step) 2836 Step->Destroy(); 2837} 2838 2839//===----------------------------------------------------------------------===// 2840// Perform initialization 2841//===----------------------------------------------------------------------===// 2842static Sema::AssignmentAction 2843getAssignmentAction(const InitializedEntity &Entity) { 2844 switch(Entity.getKind()) { 2845 case InitializedEntity::EK_Variable: 2846 case InitializedEntity::EK_New: 2847 return Sema::AA_Initializing; 2848 2849 case InitializedEntity::EK_Parameter: 2850 // FIXME: Can we tell when we're sending vs. passing? 2851 return Sema::AA_Passing; 2852 2853 case InitializedEntity::EK_Result: 2854 return Sema::AA_Returning; 2855 2856 case InitializedEntity::EK_Exception: 2857 case InitializedEntity::EK_Base: 2858 llvm_unreachable("No assignment action for C++-specific initialization"); 2859 break; 2860 2861 case InitializedEntity::EK_Temporary: 2862 // FIXME: Can we tell apart casting vs. converting? 2863 return Sema::AA_Casting; 2864 2865 case InitializedEntity::EK_Member: 2866 case InitializedEntity::EK_ArrayOrVectorElement: 2867 return Sema::AA_Initializing; 2868 } 2869 2870 return Sema::AA_Converting; 2871} 2872 2873static bool shouldBindAsTemporary(const InitializedEntity &Entity, 2874 bool IsCopy) { 2875 switch (Entity.getKind()) { 2876 case InitializedEntity::EK_Result: 2877 case InitializedEntity::EK_Exception: 2878 return !IsCopy; 2879 2880 case InitializedEntity::EK_New: 2881 case InitializedEntity::EK_Variable: 2882 case InitializedEntity::EK_Base: 2883 case InitializedEntity::EK_Member: 2884 case InitializedEntity::EK_ArrayOrVectorElement: 2885 return false; 2886 2887 case InitializedEntity::EK_Parameter: 2888 case InitializedEntity::EK_Temporary: 2889 return true; 2890 } 2891 2892 llvm_unreachable("missed an InitializedEntity kind?"); 2893} 2894 2895/// \brief If we need to perform an additional copy of the initialized object 2896/// for this kind of entity (e.g., the result of a function or an object being 2897/// thrown), make the copy. 2898static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S, 2899 const InitializedEntity &Entity, 2900 const InitializationKind &Kind, 2901 Sema::OwningExprResult CurInit) { 2902 SourceLocation Loc; 2903 2904 switch (Entity.getKind()) { 2905 case InitializedEntity::EK_Result: 2906 if (Entity.getType()->isReferenceType()) 2907 return move(CurInit); 2908 Loc = Entity.getReturnLoc(); 2909 break; 2910 2911 case InitializedEntity::EK_Exception: 2912 Loc = Entity.getThrowLoc(); 2913 break; 2914 2915 case InitializedEntity::EK_Variable: 2916 if (Entity.getType()->isReferenceType() || 2917 Kind.getKind() != InitializationKind::IK_Copy) 2918 return move(CurInit); 2919 Loc = Entity.getDecl()->getLocation(); 2920 break; 2921 2922 case InitializedEntity::EK_Parameter: 2923 // FIXME: Do we need this initialization for a parameter? 2924 return move(CurInit); 2925 2926 case InitializedEntity::EK_New: 2927 case InitializedEntity::EK_Temporary: 2928 case InitializedEntity::EK_Base: 2929 case InitializedEntity::EK_Member: 2930 case InitializedEntity::EK_ArrayOrVectorElement: 2931 // We don't need to copy for any of these initialized entities. 2932 return move(CurInit); 2933 } 2934 2935 Expr *CurInitExpr = (Expr *)CurInit.get(); 2936 CXXRecordDecl *Class = 0; 2937 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>()) 2938 Class = cast<CXXRecordDecl>(Record->getDecl()); 2939 if (!Class) 2940 return move(CurInit); 2941 2942 // Perform overload resolution using the class's copy constructors. 2943 DeclarationName ConstructorName 2944 = S.Context.DeclarationNames.getCXXConstructorName( 2945 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class))); 2946 DeclContext::lookup_iterator Con, ConEnd; 2947 OverloadCandidateSet CandidateSet; 2948 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName); 2949 Con != ConEnd; ++Con) { 2950 // Find the constructor (which may be a template). 2951 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con); 2952 if (!Constructor || Constructor->isInvalidDecl() || 2953 !Constructor->isCopyConstructor()) 2954 continue; 2955 2956 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet); 2957 } 2958 2959 OverloadCandidateSet::iterator Best; 2960 switch (S.BestViableFunction(CandidateSet, Loc, Best)) { 2961 case OR_Success: 2962 break; 2963 2964 case OR_No_Viable_Function: 2965 S.Diag(Loc, diag::err_temp_copy_no_viable) 2966 << (int)Entity.getKind() << CurInitExpr->getType() 2967 << CurInitExpr->getSourceRange(); 2968 S.PrintOverloadCandidates(CandidateSet, false); 2969 return S.ExprError(); 2970 2971 case OR_Ambiguous: 2972 S.Diag(Loc, diag::err_temp_copy_ambiguous) 2973 << (int)Entity.getKind() << CurInitExpr->getType() 2974 << CurInitExpr->getSourceRange(); 2975 S.PrintOverloadCandidates(CandidateSet, true); 2976 return S.ExprError(); 2977 2978 case OR_Deleted: 2979 S.Diag(Loc, diag::err_temp_copy_deleted) 2980 << (int)Entity.getKind() << CurInitExpr->getType() 2981 << CurInitExpr->getSourceRange(); 2982 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 2983 << Best->Function->isDeleted(); 2984 return S.ExprError(); 2985 } 2986 2987 CurInit.release(); 2988 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(), 2989 cast<CXXConstructorDecl>(Best->Function), 2990 /*Elidable=*/true, 2991 Sema::MultiExprArg(S, 2992 (void**)&CurInitExpr, 1)); 2993} 2994 2995Action::OwningExprResult 2996InitializationSequence::Perform(Sema &S, 2997 const InitializedEntity &Entity, 2998 const InitializationKind &Kind, 2999 Action::MultiExprArg Args, 3000 QualType *ResultType) { 3001 if (SequenceKind == FailedSequence) { 3002 unsigned NumArgs = Args.size(); 3003 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 3004 return S.ExprError(); 3005 } 3006 3007 if (SequenceKind == DependentSequence) { 3008 // If the declaration is a non-dependent, incomplete array type 3009 // that has an initializer, then its type will be completed once 3010 // the initializer is instantiated. 3011 if (ResultType && !Entity.getType()->isDependentType() && 3012 Args.size() == 1) { 3013 QualType DeclType = Entity.getType(); 3014 if (const IncompleteArrayType *ArrayT 3015 = S.Context.getAsIncompleteArrayType(DeclType)) { 3016 // FIXME: We don't currently have the ability to accurately 3017 // compute the length of an initializer list without 3018 // performing full type-checking of the initializer list 3019 // (since we have to determine where braces are implicitly 3020 // introduced and such). So, we fall back to making the array 3021 // type a dependently-sized array type with no specified 3022 // bound. 3023 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 3024 SourceRange Brackets; 3025 3026 // Scavange the location of the brackets from the entity, if we can. 3027 if (DeclaratorDecl *DD = Entity.getDecl()) { 3028 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 3029 TypeLoc TL = TInfo->getTypeLoc(); 3030 if (IncompleteArrayTypeLoc *ArrayLoc 3031 = dyn_cast<IncompleteArrayTypeLoc>(&TL)) 3032 Brackets = ArrayLoc->getBracketsRange(); 3033 } 3034 } 3035 3036 *ResultType 3037 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 3038 /*NumElts=*/0, 3039 ArrayT->getSizeModifier(), 3040 ArrayT->getIndexTypeCVRQualifiers(), 3041 Brackets); 3042 } 3043 3044 } 3045 } 3046 3047 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast()) 3048 return Sema::OwningExprResult(S, Args.release()[0]); 3049 3050 unsigned NumArgs = Args.size(); 3051 return S.Owned(new (S.Context) ParenListExpr(S.Context, 3052 SourceLocation(), 3053 (Expr **)Args.release(), 3054 NumArgs, 3055 SourceLocation())); 3056 } 3057 3058 if (SequenceKind == NoInitialization) 3059 return S.Owned((Expr *)0); 3060 3061 QualType DestType = Entity.getType().getNonReferenceType(); 3062 // FIXME: Ugly hack around the fact that Entity.getType() is not 3063 // the same as Entity.getDecl()->getType() in cases involving type merging, 3064 // and we want latter when it makes sense. 3065 if (ResultType) 3066 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 3067 Entity.getType(); 3068 3069 Sema::OwningExprResult CurInit = S.Owned((Expr *)0); 3070 3071 assert(!Steps.empty() && "Cannot have an empty initialization sequence"); 3072 3073 // For initialization steps that start with a single initializer, 3074 // grab the only argument out the Args and place it into the "current" 3075 // initializer. 3076 switch (Steps.front().Kind) { 3077 case SK_ResolveAddressOfOverloadedFunction: 3078 case SK_CastDerivedToBaseRValue: 3079 case SK_CastDerivedToBaseLValue: 3080 case SK_BindReference: 3081 case SK_BindReferenceToTemporary: 3082 case SK_UserConversion: 3083 case SK_QualificationConversionLValue: 3084 case SK_QualificationConversionRValue: 3085 case SK_ConversionSequence: 3086 case SK_ListInitialization: 3087 case SK_CAssignment: 3088 case SK_StringInit: 3089 assert(Args.size() == 1); 3090 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain()); 3091 if (CurInit.isInvalid()) 3092 return S.ExprError(); 3093 break; 3094 3095 case SK_ConstructorInitialization: 3096 case SK_ZeroInitialization: 3097 break; 3098 } 3099 3100 // Walk through the computed steps for the initialization sequence, 3101 // performing the specified conversions along the way. 3102 bool ConstructorInitRequiresZeroInit = false; 3103 for (step_iterator Step = step_begin(), StepEnd = step_end(); 3104 Step != StepEnd; ++Step) { 3105 if (CurInit.isInvalid()) 3106 return S.ExprError(); 3107 3108 Expr *CurInitExpr = (Expr *)CurInit.get(); 3109 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType(); 3110 3111 switch (Step->Kind) { 3112 case SK_ResolveAddressOfOverloadedFunction: 3113 // Overload resolution determined which function invoke; update the 3114 // initializer to reflect that choice. 3115 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function); 3116 break; 3117 3118 case SK_CastDerivedToBaseRValue: 3119 case SK_CastDerivedToBaseLValue: { 3120 // We have a derived-to-base cast that produces either an rvalue or an 3121 // lvalue. Perform that cast. 3122 3123 // Casts to inaccessible base classes are allowed with C-style casts. 3124 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 3125 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 3126 CurInitExpr->getLocStart(), 3127 CurInitExpr->getSourceRange(), 3128 IgnoreBaseAccess)) 3129 return S.ExprError(); 3130 3131 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type, 3132 CastExpr::CK_DerivedToBase, 3133 (Expr*)CurInit.release(), 3134 Step->Kind == SK_CastDerivedToBaseLValue)); 3135 break; 3136 } 3137 3138 case SK_BindReference: 3139 if (FieldDecl *BitField = CurInitExpr->getBitField()) { 3140 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 3141 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 3142 << Entity.getType().isVolatileQualified() 3143 << BitField->getDeclName() 3144 << CurInitExpr->getSourceRange(); 3145 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 3146 return S.ExprError(); 3147 } 3148 3149 // Reference binding does not have any corresponding ASTs. 3150 3151 // Check exception specifications 3152 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 3153 return S.ExprError(); 3154 break; 3155 3156 case SK_BindReferenceToTemporary: 3157 // Check exception specifications 3158 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 3159 return S.ExprError(); 3160 3161 // FIXME: At present, we have no AST to describe when we need to make a 3162 // temporary to bind a reference to. We should. 3163 break; 3164 3165 case SK_UserConversion: { 3166 // We have a user-defined conversion that invokes either a constructor 3167 // or a conversion function. 3168 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 3169 bool IsCopy = false; 3170 if (CXXConstructorDecl *Constructor 3171 = dyn_cast<CXXConstructorDecl>(Step->Function)) { 3172 // Build a call to the selected constructor. 3173 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S); 3174 SourceLocation Loc = CurInitExpr->getLocStart(); 3175 CurInit.release(); // Ownership transferred into MultiExprArg, below. 3176 3177 // Determine the arguments required to actually perform the constructor 3178 // call. 3179 if (S.CompleteConstructorCall(Constructor, 3180 Sema::MultiExprArg(S, 3181 (void **)&CurInitExpr, 3182 1), 3183 Loc, ConstructorArgs)) 3184 return S.ExprError(); 3185 3186 // Build the an expression that constructs a temporary. 3187 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 3188 move_arg(ConstructorArgs)); 3189 if (CurInit.isInvalid()) 3190 return S.ExprError(); 3191 3192 CastKind = CastExpr::CK_ConstructorConversion; 3193 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 3194 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 3195 S.IsDerivedFrom(SourceType, Class)) 3196 IsCopy = true; 3197 } else { 3198 // Build a call to the conversion function. 3199 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function); 3200 3201 // FIXME: Should we move this initialization into a separate 3202 // derived-to-base conversion? I believe the answer is "no", because 3203 // we don't want to turn off access control here for c-style casts. 3204 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion)) 3205 return S.ExprError(); 3206 3207 // Do a little dance to make sure that CurInit has the proper 3208 // pointer. 3209 CurInit.release(); 3210 3211 // Build the actual call to the conversion function. 3212 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion)); 3213 if (CurInit.isInvalid() || !CurInit.get()) 3214 return S.ExprError(); 3215 3216 CastKind = CastExpr::CK_UserDefinedConversion; 3217 } 3218 3219 if (shouldBindAsTemporary(Entity, IsCopy)) 3220 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3221 3222 CurInitExpr = CurInit.takeAs<Expr>(); 3223 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(), 3224 CastKind, 3225 CurInitExpr, 3226 false)); 3227 3228 if (!IsCopy) 3229 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit)); 3230 break; 3231 } 3232 3233 case SK_QualificationConversionLValue: 3234 case SK_QualificationConversionRValue: 3235 // Perform a qualification conversion; these can never go wrong. 3236 S.ImpCastExprToType(CurInitExpr, Step->Type, 3237 CastExpr::CK_NoOp, 3238 Step->Kind == SK_QualificationConversionLValue); 3239 CurInit.release(); 3240 CurInit = S.Owned(CurInitExpr); 3241 break; 3242 3243 case SK_ConversionSequence: 3244 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting, 3245 false, false, *Step->ICS)) 3246 return S.ExprError(); 3247 3248 CurInit.release(); 3249 CurInit = S.Owned(CurInitExpr); 3250 break; 3251 3252 case SK_ListInitialization: { 3253 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr); 3254 QualType Ty = Step->Type; 3255 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty)) 3256 return S.ExprError(); 3257 3258 CurInit.release(); 3259 CurInit = S.Owned(InitList); 3260 break; 3261 } 3262 3263 case SK_ConstructorInitialization: { 3264 CXXConstructorDecl *Constructor 3265 = cast<CXXConstructorDecl>(Step->Function); 3266 3267 // Build a call to the selected constructor. 3268 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S); 3269 SourceLocation Loc = Kind.getLocation(); 3270 3271 // Determine the arguments required to actually perform the constructor 3272 // call. 3273 if (S.CompleteConstructorCall(Constructor, move(Args), 3274 Loc, ConstructorArgs)) 3275 return S.ExprError(); 3276 3277 // Build the an expression that constructs a temporary. 3278 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 3279 Constructor, 3280 move_arg(ConstructorArgs), 3281 ConstructorInitRequiresZeroInit); 3282 if (CurInit.isInvalid()) 3283 return S.ExprError(); 3284 3285 bool Elidable 3286 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable(); 3287 if (shouldBindAsTemporary(Entity, Elidable)) 3288 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3289 3290 if (!Elidable) 3291 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit)); 3292 break; 3293 } 3294 3295 case SK_ZeroInitialization: { 3296 step_iterator NextStep = Step; 3297 ++NextStep; 3298 if (NextStep != StepEnd && 3299 NextStep->Kind == SK_ConstructorInitialization) { 3300 // The need for zero-initialization is recorded directly into 3301 // the call to the object's constructor within the next step. 3302 ConstructorInitRequiresZeroInit = true; 3303 } else if (Kind.getKind() == InitializationKind::IK_Value && 3304 S.getLangOptions().CPlusPlus && 3305 !Kind.isImplicitValueInit()) { 3306 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type, 3307 Kind.getRange().getBegin(), 3308 Kind.getRange().getEnd())); 3309 } else { 3310 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 3311 } 3312 break; 3313 } 3314 3315 case SK_CAssignment: { 3316 QualType SourceType = CurInitExpr->getType(); 3317 Sema::AssignConvertType ConvTy = 3318 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr); 3319 3320 // If this is a call, allow conversion to a transparent union. 3321 if (ConvTy != Sema::Compatible && 3322 Entity.getKind() == InitializedEntity::EK_Parameter && 3323 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr) 3324 == Sema::Compatible) 3325 ConvTy = Sema::Compatible; 3326 3327 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 3328 Step->Type, SourceType, 3329 CurInitExpr, getAssignmentAction(Entity))) 3330 return S.ExprError(); 3331 3332 CurInit.release(); 3333 CurInit = S.Owned(CurInitExpr); 3334 break; 3335 } 3336 3337 case SK_StringInit: { 3338 QualType Ty = Step->Type; 3339 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S); 3340 break; 3341 } 3342 } 3343 } 3344 3345 return move(CurInit); 3346} 3347 3348//===----------------------------------------------------------------------===// 3349// Diagnose initialization failures 3350//===----------------------------------------------------------------------===// 3351bool InitializationSequence::Diagnose(Sema &S, 3352 const InitializedEntity &Entity, 3353 const InitializationKind &Kind, 3354 Expr **Args, unsigned NumArgs) { 3355 if (SequenceKind != FailedSequence) 3356 return false; 3357 3358 QualType DestType = Entity.getType(); 3359 switch (Failure) { 3360 case FK_TooManyInitsForReference: 3361 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 3362 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 3363 break; 3364 3365 case FK_ArrayNeedsInitList: 3366 case FK_ArrayNeedsInitListOrStringLiteral: 3367 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 3368 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 3369 break; 3370 3371 case FK_AddressOfOverloadFailed: 3372 S.ResolveAddressOfOverloadedFunction(Args[0], 3373 DestType.getNonReferenceType(), 3374 true); 3375 break; 3376 3377 case FK_ReferenceInitOverloadFailed: 3378 case FK_UserConversionOverloadFailed: 3379 switch (FailedOverloadResult) { 3380 case OR_Ambiguous: 3381 if (Failure == FK_UserConversionOverloadFailed) 3382 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 3383 << Args[0]->getType() << DestType 3384 << Args[0]->getSourceRange(); 3385 else 3386 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 3387 << DestType << Args[0]->getType() 3388 << Args[0]->getSourceRange(); 3389 3390 S.PrintOverloadCandidates(FailedCandidateSet, true); 3391 break; 3392 3393 case OR_No_Viable_Function: 3394 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 3395 << Args[0]->getType() << DestType.getNonReferenceType() 3396 << Args[0]->getSourceRange(); 3397 S.PrintOverloadCandidates(FailedCandidateSet, false); 3398 break; 3399 3400 case OR_Deleted: { 3401 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 3402 << Args[0]->getType() << DestType.getNonReferenceType() 3403 << Args[0]->getSourceRange(); 3404 OverloadCandidateSet::iterator Best; 3405 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet, 3406 Kind.getLocation(), 3407 Best); 3408 if (Ovl == OR_Deleted) { 3409 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3410 << Best->Function->isDeleted(); 3411 } else { 3412 llvm_unreachable("Inconsistent overload resolution?"); 3413 } 3414 break; 3415 } 3416 3417 case OR_Success: 3418 llvm_unreachable("Conversion did not fail!"); 3419 break; 3420 } 3421 break; 3422 3423 case FK_NonConstLValueReferenceBindingToTemporary: 3424 case FK_NonConstLValueReferenceBindingToUnrelated: 3425 S.Diag(Kind.getLocation(), 3426 Failure == FK_NonConstLValueReferenceBindingToTemporary 3427 ? diag::err_lvalue_reference_bind_to_temporary 3428 : diag::err_lvalue_reference_bind_to_unrelated) 3429 << DestType.getNonReferenceType() 3430 << Args[0]->getType() 3431 << Args[0]->getSourceRange(); 3432 break; 3433 3434 case FK_RValueReferenceBindingToLValue: 3435 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 3436 << Args[0]->getSourceRange(); 3437 break; 3438 3439 case FK_ReferenceInitDropsQualifiers: 3440 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 3441 << DestType.getNonReferenceType() 3442 << Args[0]->getType() 3443 << Args[0]->getSourceRange(); 3444 break; 3445 3446 case FK_ReferenceInitFailed: 3447 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 3448 << DestType.getNonReferenceType() 3449 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 3450 << Args[0]->getType() 3451 << Args[0]->getSourceRange(); 3452 break; 3453 3454 case FK_ConversionFailed: 3455 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed) 3456 << (int)Entity.getKind() 3457 << DestType 3458 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 3459 << Args[0]->getType() 3460 << Args[0]->getSourceRange(); 3461 break; 3462 3463 case FK_TooManyInitsForScalar: { 3464 SourceRange R; 3465 3466 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 3467 R = SourceRange(InitList->getInit(1)->getLocStart(), 3468 InitList->getLocEnd()); 3469 else 3470 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 3471 3472 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 3473 << /*scalar=*/2 << R; 3474 break; 3475 } 3476 3477 case FK_ReferenceBindingToInitList: 3478 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 3479 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 3480 break; 3481 3482 case FK_InitListBadDestinationType: 3483 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 3484 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 3485 break; 3486 3487 case FK_ConstructorOverloadFailed: { 3488 SourceRange ArgsRange; 3489 if (NumArgs) 3490 ArgsRange = SourceRange(Args[0]->getLocStart(), 3491 Args[NumArgs - 1]->getLocEnd()); 3492 3493 // FIXME: Using "DestType" for the entity we're printing is probably 3494 // bad. 3495 switch (FailedOverloadResult) { 3496 case OR_Ambiguous: 3497 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 3498 << DestType << ArgsRange; 3499 S.PrintOverloadCandidates(FailedCandidateSet, true); 3500 break; 3501 3502 case OR_No_Viable_Function: 3503 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 3504 << DestType << ArgsRange; 3505 S.PrintOverloadCandidates(FailedCandidateSet, false); 3506 break; 3507 3508 case OR_Deleted: { 3509 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 3510 << true << DestType << ArgsRange; 3511 OverloadCandidateSet::iterator Best; 3512 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet, 3513 Kind.getLocation(), 3514 Best); 3515 if (Ovl == OR_Deleted) { 3516 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3517 << Best->Function->isDeleted(); 3518 } else { 3519 llvm_unreachable("Inconsistent overload resolution?"); 3520 } 3521 break; 3522 } 3523 3524 case OR_Success: 3525 llvm_unreachable("Conversion did not fail!"); 3526 break; 3527 } 3528 break; 3529 } 3530 3531 case FK_DefaultInitOfConst: 3532 S.Diag(Kind.getLocation(), diag::err_default_init_const) 3533 << DestType; 3534 break; 3535 } 3536 3537 return true; 3538} 3539 3540//===----------------------------------------------------------------------===// 3541// Initialization helper functions 3542//===----------------------------------------------------------------------===// 3543Sema::OwningExprResult 3544Sema::PerformCopyInitialization(const InitializedEntity &Entity, 3545 SourceLocation EqualLoc, 3546 OwningExprResult Init) { 3547 if (Init.isInvalid()) 3548 return ExprError(); 3549 3550 Expr *InitE = (Expr *)Init.get(); 3551 assert(InitE && "No initialization expression?"); 3552 3553 if (EqualLoc.isInvalid()) 3554 EqualLoc = InitE->getLocStart(); 3555 3556 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 3557 EqualLoc); 3558 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 3559 Init.release(); 3560 return Seq.Perform(*this, Entity, Kind, 3561 MultiExprArg(*this, (void**)&InitE, 1)); 3562} 3563