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