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