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