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