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