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