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