SemaInit.cpp revision 7530c034c0c71a64c5a9173206d9742ae847af8b
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. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/Designator.h" 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Lex/Preprocessor.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExprObjC.h" 23#include "clang/AST/TypeLoc.h" 24#include "llvm/Support/ErrorHandling.h" 25#include "llvm/Support/raw_ostream.h" 26#include <map> 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// Sema Initialization Checking 31//===----------------------------------------------------------------------===// 32 33static Expr *IsStringInit(Expr *Init, const ArrayType *AT, 34 ASTContext &Context) { 35 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 36 return 0; 37 38 // See if this is a string literal or @encode. 39 Init = Init->IgnoreParens(); 40 41 // Handle @encode, which is a narrow string. 42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 43 return Init; 44 45 // Otherwise we can only handle string literals. 46 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 47 if (SL == 0) return 0; 48 49 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 50 51 switch (SL->getKind()) { 52 case StringLiteral::Ascii: 53 case StringLiteral::UTF8: 54 // char array can be initialized with a narrow string. 55 // Only allow char x[] = "foo"; not char x[] = L"foo"; 56 return ElemTy->isCharType() ? Init : 0; 57 case StringLiteral::UTF16: 58 return ElemTy->isChar16Type() ? Init : 0; 59 case StringLiteral::UTF32: 60 return ElemTy->isChar32Type() ? Init : 0; 61 case StringLiteral::Wide: 62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 63 // correction from DR343): "An array with element type compatible with a 64 // qualified or unqualified version of wchar_t may be initialized by a wide 65 // string literal, optionally enclosed in braces." 66 if (Context.typesAreCompatible(Context.getWCharType(), 67 ElemTy.getUnqualifiedType())) 68 return Init; 69 70 return 0; 71 } 72 73 llvm_unreachable("missed a StringLiteral kind?"); 74} 75 76static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) { 77 const ArrayType *arrayType = Context.getAsArrayType(declType); 78 if (!arrayType) return 0; 79 80 return IsStringInit(init, arrayType, Context); 81} 82 83static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 84 Sema &S) { 85 // Get the length of the string as parsed. 86 uint64_t StrLength = 87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 88 89 90 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 91 // C99 6.7.8p14. We have an array of character type with unknown size 92 // being initialized to a string literal. 93 llvm::APSInt ConstVal(32); 94 ConstVal = StrLength; 95 // Return a new array type (C99 6.7.8p22). 96 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 97 ConstVal, 98 ArrayType::Normal, 0); 99 return; 100 } 101 102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 103 104 // We have an array of character type with known size. However, 105 // the size may be smaller or larger than the string we are initializing. 106 // FIXME: Avoid truncation for 64-bit length strings. 107 if (S.getLangOptions().CPlusPlus) { 108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) { 109 // For Pascal strings it's OK to strip off the terminating null character, 110 // so the example below is valid: 111 // 112 // unsigned char a[2] = "\pa"; 113 if (SL->isPascal()) 114 StrLength--; 115 } 116 117 // [dcl.init.string]p2 118 if (StrLength > CAT->getSize().getZExtValue()) 119 S.Diag(Str->getSourceRange().getBegin(), 120 diag::err_initializer_string_for_char_array_too_long) 121 << Str->getSourceRange(); 122 } else { 123 // C99 6.7.8p14. 124 if (StrLength-1 > CAT->getSize().getZExtValue()) 125 S.Diag(Str->getSourceRange().getBegin(), 126 diag::warn_initializer_string_for_char_array_too_long) 127 << Str->getSourceRange(); 128 } 129 130 // Set the type to the actual size that we are initializing. If we have 131 // something like: 132 // char x[1] = "foo"; 133 // then this will set the string literal's type to char[1]. 134 Str->setType(DeclT); 135} 136 137//===----------------------------------------------------------------------===// 138// Semantic checking for initializer lists. 139//===----------------------------------------------------------------------===// 140 141/// @brief Semantic checking for initializer lists. 142/// 143/// The InitListChecker class contains a set of routines that each 144/// handle the initialization of a certain kind of entity, e.g., 145/// arrays, vectors, struct/union types, scalars, etc. The 146/// InitListChecker itself performs a recursive walk of the subobject 147/// structure of the type to be initialized, while stepping through 148/// the initializer list one element at a time. The IList and Index 149/// parameters to each of the Check* routines contain the active 150/// (syntactic) initializer list and the index into that initializer 151/// list that represents the current initializer. Each routine is 152/// responsible for moving that Index forward as it consumes elements. 153/// 154/// Each Check* routine also has a StructuredList/StructuredIndex 155/// arguments, which contains the current "structured" (semantic) 156/// initializer list and the index into that initializer list where we 157/// are copying initializers as we map them over to the semantic 158/// list. Once we have completed our recursive walk of the subobject 159/// structure, we will have constructed a full semantic initializer 160/// list. 161/// 162/// C99 designators cause changes in the initializer list traversal, 163/// because they make the initialization "jump" into a specific 164/// subobject and then continue the initialization from that 165/// point. CheckDesignatedInitializer() recursively steps into the 166/// designated subobject and manages backing out the recursion to 167/// initialize the subobjects after the one designated. 168namespace { 169class InitListChecker { 170 Sema &SemaRef; 171 bool hadError; 172 bool VerifyOnly; // no diagnostics, no structure building 173 bool AllowBraceElision; 174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 175 InitListExpr *FullyStructuredList; 176 177 void CheckImplicitInitList(const InitializedEntity &Entity, 178 InitListExpr *ParentIList, QualType T, 179 unsigned &Index, InitListExpr *StructuredList, 180 unsigned &StructuredIndex); 181 void CheckExplicitInitList(const InitializedEntity &Entity, 182 InitListExpr *IList, QualType &T, 183 unsigned &Index, InitListExpr *StructuredList, 184 unsigned &StructuredIndex, 185 bool TopLevelObject = false); 186 void CheckListElementTypes(const InitializedEntity &Entity, 187 InitListExpr *IList, QualType &DeclType, 188 bool SubobjectIsDesignatorContext, 189 unsigned &Index, 190 InitListExpr *StructuredList, 191 unsigned &StructuredIndex, 192 bool TopLevelObject = false); 193 void CheckSubElementType(const InitializedEntity &Entity, 194 InitListExpr *IList, QualType ElemType, 195 unsigned &Index, 196 InitListExpr *StructuredList, 197 unsigned &StructuredIndex); 198 void CheckComplexType(const InitializedEntity &Entity, 199 InitListExpr *IList, QualType DeclType, 200 unsigned &Index, 201 InitListExpr *StructuredList, 202 unsigned &StructuredIndex); 203 void CheckScalarType(const InitializedEntity &Entity, 204 InitListExpr *IList, QualType DeclType, 205 unsigned &Index, 206 InitListExpr *StructuredList, 207 unsigned &StructuredIndex); 208 void CheckReferenceType(const InitializedEntity &Entity, 209 InitListExpr *IList, QualType DeclType, 210 unsigned &Index, 211 InitListExpr *StructuredList, 212 unsigned &StructuredIndex); 213 void CheckVectorType(const InitializedEntity &Entity, 214 InitListExpr *IList, QualType DeclType, unsigned &Index, 215 InitListExpr *StructuredList, 216 unsigned &StructuredIndex); 217 void CheckStructUnionTypes(const InitializedEntity &Entity, 218 InitListExpr *IList, QualType DeclType, 219 RecordDecl::field_iterator Field, 220 bool SubobjectIsDesignatorContext, unsigned &Index, 221 InitListExpr *StructuredList, 222 unsigned &StructuredIndex, 223 bool TopLevelObject = false); 224 void CheckArrayType(const InitializedEntity &Entity, 225 InitListExpr *IList, QualType &DeclType, 226 llvm::APSInt elementIndex, 227 bool SubobjectIsDesignatorContext, unsigned &Index, 228 InitListExpr *StructuredList, 229 unsigned &StructuredIndex); 230 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 231 InitListExpr *IList, DesignatedInitExpr *DIE, 232 unsigned DesigIdx, 233 QualType &CurrentObjectType, 234 RecordDecl::field_iterator *NextField, 235 llvm::APSInt *NextElementIndex, 236 unsigned &Index, 237 InitListExpr *StructuredList, 238 unsigned &StructuredIndex, 239 bool FinishSubobjectInit, 240 bool TopLevelObject); 241 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 242 QualType CurrentObjectType, 243 InitListExpr *StructuredList, 244 unsigned StructuredIndex, 245 SourceRange InitRange); 246 void UpdateStructuredListElement(InitListExpr *StructuredList, 247 unsigned &StructuredIndex, 248 Expr *expr); 249 int numArrayElements(QualType DeclType); 250 int numStructUnionElements(QualType DeclType); 251 252 void FillInValueInitForField(unsigned Init, FieldDecl *Field, 253 const InitializedEntity &ParentEntity, 254 InitListExpr *ILE, bool &RequiresSecondPass); 255 void FillInValueInitializations(const InitializedEntity &Entity, 256 InitListExpr *ILE, bool &RequiresSecondPass); 257 bool CheckFlexibleArrayInit(const InitializedEntity &Entity, 258 Expr *InitExpr, FieldDecl *Field, 259 bool TopLevelObject); 260 void CheckValueInitializable(const InitializedEntity &Entity); 261 262public: 263 InitListChecker(Sema &S, const InitializedEntity &Entity, 264 InitListExpr *IL, QualType &T, bool VerifyOnly, 265 bool AllowBraceElision); 266 bool HadError() { return hadError; } 267 268 // @brief Retrieves the fully-structured initializer list used for 269 // semantic analysis and code generation. 270 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 271}; 272} // end anonymous namespace 273 274void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) { 275 assert(VerifyOnly && 276 "CheckValueInitializable is only inteded for verification mode."); 277 278 SourceLocation Loc; 279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 280 true); 281 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0); 282 if (InitSeq.Failed()) 283 hadError = true; 284} 285 286void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field, 287 const InitializedEntity &ParentEntity, 288 InitListExpr *ILE, 289 bool &RequiresSecondPass) { 290 SourceLocation Loc = ILE->getSourceRange().getBegin(); 291 unsigned NumInits = ILE->getNumInits(); 292 InitializedEntity MemberEntity 293 = InitializedEntity::InitializeMember(Field, &ParentEntity); 294 if (Init >= NumInits || !ILE->getInit(Init)) { 295 // FIXME: We probably don't need to handle references 296 // specially here, since value-initialization of references is 297 // handled in InitializationSequence. 298 if (Field->getType()->isReferenceType()) { 299 // C++ [dcl.init.aggr]p9: 300 // If an incomplete or empty initializer-list leaves a 301 // member of reference type uninitialized, the program is 302 // ill-formed. 303 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 304 << Field->getType() 305 << ILE->getSyntacticForm()->getSourceRange(); 306 SemaRef.Diag(Field->getLocation(), 307 diag::note_uninit_reference_member); 308 hadError = true; 309 return; 310 } 311 312 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 313 true); 314 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0); 315 if (!InitSeq) { 316 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0); 317 hadError = true; 318 return; 319 } 320 321 ExprResult MemberInit 322 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg()); 323 if (MemberInit.isInvalid()) { 324 hadError = true; 325 return; 326 } 327 328 if (hadError) { 329 // Do nothing 330 } else if (Init < NumInits) { 331 ILE->setInit(Init, MemberInit.takeAs<Expr>()); 332 } else if (InitSeq.isConstructorInitialization()) { 333 // Value-initialization requires a constructor call, so 334 // extend the initializer list to include the constructor 335 // call and make a note that we'll need to take another pass 336 // through the initializer list. 337 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>()); 338 RequiresSecondPass = true; 339 } 340 } else if (InitListExpr *InnerILE 341 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 342 FillInValueInitializations(MemberEntity, InnerILE, 343 RequiresSecondPass); 344} 345 346/// Recursively replaces NULL values within the given initializer list 347/// with expressions that perform value-initialization of the 348/// appropriate type. 349void 350InitListChecker::FillInValueInitializations(const InitializedEntity &Entity, 351 InitListExpr *ILE, 352 bool &RequiresSecondPass) { 353 assert((ILE->getType() != SemaRef.Context.VoidTy) && 354 "Should not have void type"); 355 SourceLocation Loc = ILE->getSourceRange().getBegin(); 356 if (ILE->getSyntacticForm()) 357 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 358 359 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 360 if (RType->getDecl()->isUnion() && 361 ILE->getInitializedFieldInUnion()) 362 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(), 363 Entity, ILE, RequiresSecondPass); 364 else { 365 unsigned Init = 0; 366 for (RecordDecl::field_iterator 367 Field = RType->getDecl()->field_begin(), 368 FieldEnd = RType->getDecl()->field_end(); 369 Field != FieldEnd; ++Field) { 370 if (Field->isUnnamedBitfield()) 371 continue; 372 373 if (hadError) 374 return; 375 376 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass); 377 if (hadError) 378 return; 379 380 ++Init; 381 382 // Only look at the first initialization of a union. 383 if (RType->getDecl()->isUnion()) 384 break; 385 } 386 } 387 388 return; 389 } 390 391 QualType ElementType; 392 393 InitializedEntity ElementEntity = Entity; 394 unsigned NumInits = ILE->getNumInits(); 395 unsigned NumElements = NumInits; 396 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 397 ElementType = AType->getElementType(); 398 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 399 NumElements = CAType->getSize().getZExtValue(); 400 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 401 0, Entity); 402 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 403 ElementType = VType->getElementType(); 404 NumElements = VType->getNumElements(); 405 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 406 0, Entity); 407 } else 408 ElementType = ILE->getType(); 409 410 411 for (unsigned Init = 0; Init != NumElements; ++Init) { 412 if (hadError) 413 return; 414 415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 416 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 417 ElementEntity.setElementIndex(Init); 418 419 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0); 420 if (!InitExpr && !ILE->hasArrayFiller()) { 421 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 422 true); 423 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0); 424 if (!InitSeq) { 425 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0); 426 hadError = true; 427 return; 428 } 429 430 ExprResult ElementInit 431 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg()); 432 if (ElementInit.isInvalid()) { 433 hadError = true; 434 return; 435 } 436 437 if (hadError) { 438 // Do nothing 439 } else if (Init < NumInits) { 440 // For arrays, just set the expression used for value-initialization 441 // of the "holes" in the array. 442 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 443 ILE->setArrayFiller(ElementInit.takeAs<Expr>()); 444 else 445 ILE->setInit(Init, ElementInit.takeAs<Expr>()); 446 } else { 447 // For arrays, just set the expression used for value-initialization 448 // of the rest of elements and exit. 449 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 450 ILE->setArrayFiller(ElementInit.takeAs<Expr>()); 451 return; 452 } 453 454 if (InitSeq.isConstructorInitialization()) { 455 // Value-initialization requires a constructor call, so 456 // extend the initializer list to include the constructor 457 // call and make a note that we'll need to take another pass 458 // through the initializer list. 459 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>()); 460 RequiresSecondPass = true; 461 } 462 } 463 } else if (InitListExpr *InnerILE 464 = dyn_cast_or_null<InitListExpr>(InitExpr)) 465 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass); 466 } 467} 468 469 470InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 471 InitListExpr *IL, QualType &T, 472 bool VerifyOnly, bool AllowBraceElision) 473 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) { 474 hadError = false; 475 476 unsigned newIndex = 0; 477 unsigned newStructuredIndex = 0; 478 FullyStructuredList 479 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 480 CheckExplicitInitList(Entity, IL, T, newIndex, 481 FullyStructuredList, newStructuredIndex, 482 /*TopLevelObject=*/true); 483 484 if (!hadError && !VerifyOnly) { 485 bool RequiresSecondPass = false; 486 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass); 487 if (RequiresSecondPass && !hadError) 488 FillInValueInitializations(Entity, FullyStructuredList, 489 RequiresSecondPass); 490 } 491} 492 493int InitListChecker::numArrayElements(QualType DeclType) { 494 // FIXME: use a proper constant 495 int maxElements = 0x7FFFFFFF; 496 if (const ConstantArrayType *CAT = 497 SemaRef.Context.getAsConstantArrayType(DeclType)) { 498 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 499 } 500 return maxElements; 501} 502 503int InitListChecker::numStructUnionElements(QualType DeclType) { 504 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 505 int InitializableMembers = 0; 506 for (RecordDecl::field_iterator 507 Field = structDecl->field_begin(), 508 FieldEnd = structDecl->field_end(); 509 Field != FieldEnd; ++Field) { 510 if (!Field->isUnnamedBitfield()) 511 ++InitializableMembers; 512 } 513 if (structDecl->isUnion()) 514 return std::min(InitializableMembers, 1); 515 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 516} 517 518void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 519 InitListExpr *ParentIList, 520 QualType T, unsigned &Index, 521 InitListExpr *StructuredList, 522 unsigned &StructuredIndex) { 523 int maxElements = 0; 524 525 if (T->isArrayType()) 526 maxElements = numArrayElements(T); 527 else if (T->isRecordType()) 528 maxElements = numStructUnionElements(T); 529 else if (T->isVectorType()) 530 maxElements = T->getAs<VectorType>()->getNumElements(); 531 else 532 llvm_unreachable("CheckImplicitInitList(): Illegal type"); 533 534 if (maxElements == 0) { 535 if (!VerifyOnly) 536 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 537 diag::err_implicit_empty_initializer); 538 ++Index; 539 hadError = true; 540 return; 541 } 542 543 // Build a structured initializer list corresponding to this subobject. 544 InitListExpr *StructuredSubobjectInitList 545 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 546 StructuredIndex, 547 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 548 ParentIList->getSourceRange().getEnd())); 549 unsigned StructuredSubobjectInitIndex = 0; 550 551 // Check the element types and build the structural subobject. 552 unsigned StartIndex = Index; 553 CheckListElementTypes(Entity, ParentIList, T, 554 /*SubobjectIsDesignatorContext=*/false, Index, 555 StructuredSubobjectInitList, 556 StructuredSubobjectInitIndex); 557 558 if (VerifyOnly) { 559 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType())) 560 hadError = true; 561 } else { 562 StructuredSubobjectInitList->setType(T); 563 564 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 565 // Update the structured sub-object initializer so that it's ending 566 // range corresponds with the end of the last initializer it used. 567 if (EndIndex < ParentIList->getNumInits()) { 568 SourceLocation EndLoc 569 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 570 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 571 } 572 573 // Complain about missing braces. 574 if (T->isArrayType() || T->isRecordType()) { 575 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), 576 AllowBraceElision ? diag::warn_missing_braces : 577 diag::err_missing_braces) 578 << StructuredSubobjectInitList->getSourceRange() 579 << FixItHint::CreateInsertion( 580 StructuredSubobjectInitList->getLocStart(), "{") 581 << FixItHint::CreateInsertion( 582 SemaRef.PP.getLocForEndOfToken( 583 StructuredSubobjectInitList->getLocEnd()), 584 "}"); 585 if (!AllowBraceElision) 586 hadError = true; 587 } 588 } 589} 590 591void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 592 InitListExpr *IList, QualType &T, 593 unsigned &Index, 594 InitListExpr *StructuredList, 595 unsigned &StructuredIndex, 596 bool TopLevelObject) { 597 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 598 if (!VerifyOnly) { 599 SyntacticToSemantic[IList] = StructuredList; 600 StructuredList->setSyntacticForm(IList); 601 } 602 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 603 Index, StructuredList, StructuredIndex, TopLevelObject); 604 if (!VerifyOnly) { 605 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context); 606 IList->setType(ExprTy); 607 StructuredList->setType(ExprTy); 608 } 609 if (hadError) 610 return; 611 612 if (Index < IList->getNumInits()) { 613 // We have leftover initializers 614 if (VerifyOnly) { 615 if (SemaRef.getLangOptions().CPlusPlus || 616 (SemaRef.getLangOptions().OpenCL && 617 IList->getType()->isVectorType())) { 618 hadError = true; 619 } 620 return; 621 } 622 623 if (StructuredIndex == 1 && 624 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 625 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 626 if (SemaRef.getLangOptions().CPlusPlus) { 627 DK = diag::err_excess_initializers_in_char_array_initializer; 628 hadError = true; 629 } 630 // Special-case 631 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 632 << IList->getInit(Index)->getSourceRange(); 633 } else if (!T->isIncompleteType()) { 634 // Don't complain for incomplete types, since we'll get an error 635 // elsewhere 636 QualType CurrentObjectType = StructuredList->getType(); 637 int initKind = 638 CurrentObjectType->isArrayType()? 0 : 639 CurrentObjectType->isVectorType()? 1 : 640 CurrentObjectType->isScalarType()? 2 : 641 CurrentObjectType->isUnionType()? 3 : 642 4; 643 644 unsigned DK = diag::warn_excess_initializers; 645 if (SemaRef.getLangOptions().CPlusPlus) { 646 DK = diag::err_excess_initializers; 647 hadError = true; 648 } 649 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 650 DK = diag::err_excess_initializers; 651 hadError = true; 652 } 653 654 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 655 << initKind << IList->getInit(Index)->getSourceRange(); 656 } 657 } 658 659 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 && 660 !TopLevelObject) 661 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 662 << IList->getSourceRange() 663 << FixItHint::CreateRemoval(IList->getLocStart()) 664 << FixItHint::CreateRemoval(IList->getLocEnd()); 665} 666 667void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 668 InitListExpr *IList, 669 QualType &DeclType, 670 bool SubobjectIsDesignatorContext, 671 unsigned &Index, 672 InitListExpr *StructuredList, 673 unsigned &StructuredIndex, 674 bool TopLevelObject) { 675 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { 676 // Explicitly braced initializer for complex type can be real+imaginary 677 // parts. 678 CheckComplexType(Entity, IList, DeclType, Index, 679 StructuredList, StructuredIndex); 680 } else if (DeclType->isScalarType()) { 681 CheckScalarType(Entity, IList, DeclType, Index, 682 StructuredList, StructuredIndex); 683 } else if (DeclType->isVectorType()) { 684 CheckVectorType(Entity, IList, DeclType, Index, 685 StructuredList, StructuredIndex); 686 } else if (DeclType->isAggregateType()) { 687 if (DeclType->isRecordType()) { 688 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 689 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(), 690 SubobjectIsDesignatorContext, Index, 691 StructuredList, StructuredIndex, 692 TopLevelObject); 693 } else if (DeclType->isArrayType()) { 694 llvm::APSInt Zero( 695 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 696 false); 697 CheckArrayType(Entity, IList, DeclType, Zero, 698 SubobjectIsDesignatorContext, Index, 699 StructuredList, StructuredIndex); 700 } else 701 llvm_unreachable("Aggregate that isn't a structure or array?!"); 702 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 703 // This type is invalid, issue a diagnostic. 704 ++Index; 705 if (!VerifyOnly) 706 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 707 << DeclType; 708 hadError = true; 709 } else if (DeclType->isRecordType()) { 710 // C++ [dcl.init]p14: 711 // [...] If the class is an aggregate (8.5.1), and the initializer 712 // is a brace-enclosed list, see 8.5.1. 713 // 714 // Note: 8.5.1 is handled below; here, we diagnose the case where 715 // we have an initializer list and a destination type that is not 716 // an aggregate. 717 // FIXME: In C++0x, this is yet another form of initialization. 718 if (!VerifyOnly) 719 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 720 << DeclType << IList->getSourceRange(); 721 hadError = true; 722 } else if (DeclType->isReferenceType()) { 723 CheckReferenceType(Entity, IList, DeclType, Index, 724 StructuredList, StructuredIndex); 725 } else if (DeclType->isObjCObjectType()) { 726 if (!VerifyOnly) 727 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class) 728 << DeclType; 729 hadError = true; 730 } else { 731 if (!VerifyOnly) 732 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 733 << DeclType; 734 hadError = true; 735 } 736} 737 738void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 739 InitListExpr *IList, 740 QualType ElemType, 741 unsigned &Index, 742 InitListExpr *StructuredList, 743 unsigned &StructuredIndex) { 744 Expr *expr = IList->getInit(Index); 745 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 746 unsigned newIndex = 0; 747 unsigned newStructuredIndex = 0; 748 InitListExpr *newStructuredList 749 = getStructuredSubobjectInit(IList, Index, ElemType, 750 StructuredList, StructuredIndex, 751 SubInitList->getSourceRange()); 752 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex, 753 newStructuredList, newStructuredIndex); 754 ++StructuredIndex; 755 ++Index; 756 return; 757 } else if (ElemType->isScalarType()) { 758 return CheckScalarType(Entity, IList, ElemType, Index, 759 StructuredList, StructuredIndex); 760 } else if (ElemType->isReferenceType()) { 761 return CheckReferenceType(Entity, IList, ElemType, Index, 762 StructuredList, StructuredIndex); 763 } 764 765 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) { 766 // arrayType can be incomplete if we're initializing a flexible 767 // array member. There's nothing we can do with the completed 768 // type here, though. 769 770 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) { 771 if (!VerifyOnly) { 772 CheckStringInit(Str, ElemType, arrayType, SemaRef); 773 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 774 } 775 ++Index; 776 return; 777 } 778 779 // Fall through for subaggregate initialization. 780 781 } else if (SemaRef.getLangOptions().CPlusPlus) { 782 // C++ [dcl.init.aggr]p12: 783 // All implicit type conversions (clause 4) are considered when 784 // initializing the aggregate member with an initializer from 785 // an initializer-list. If the initializer can initialize a 786 // member, the member is initialized. [...] 787 788 // FIXME: Better EqualLoc? 789 InitializationKind Kind = 790 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation()); 791 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1); 792 793 if (Seq) { 794 if (!VerifyOnly) { 795 ExprResult Result = 796 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1)); 797 if (Result.isInvalid()) 798 hadError = true; 799 800 UpdateStructuredListElement(StructuredList, StructuredIndex, 801 Result.takeAs<Expr>()); 802 } 803 ++Index; 804 return; 805 } 806 807 // Fall through for subaggregate initialization 808 } else { 809 // C99 6.7.8p13: 810 // 811 // The initializer for a structure or union object that has 812 // automatic storage duration shall be either an initializer 813 // list as described below, or a single expression that has 814 // compatible structure or union type. In the latter case, the 815 // initial value of the object, including unnamed members, is 816 // that of the expression. 817 ExprResult ExprRes = SemaRef.Owned(expr); 818 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 819 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes, 820 !VerifyOnly) 821 == Sema::Compatible) { 822 if (ExprRes.isInvalid()) 823 hadError = true; 824 else { 825 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take()); 826 if (ExprRes.isInvalid()) 827 hadError = true; 828 } 829 UpdateStructuredListElement(StructuredList, StructuredIndex, 830 ExprRes.takeAs<Expr>()); 831 ++Index; 832 return; 833 } 834 ExprRes.release(); 835 // Fall through for subaggregate initialization 836 } 837 838 // C++ [dcl.init.aggr]p12: 839 // 840 // [...] Otherwise, if the member is itself a non-empty 841 // subaggregate, brace elision is assumed and the initializer is 842 // considered for the initialization of the first member of 843 // the subaggregate. 844 if (!SemaRef.getLangOptions().OpenCL && 845 (ElemType->isAggregateType() || ElemType->isVectorType())) { 846 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 847 StructuredIndex); 848 ++StructuredIndex; 849 } else { 850 if (!VerifyOnly) { 851 // We cannot initialize this element, so let 852 // PerformCopyInitialization produce the appropriate diagnostic. 853 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), 854 SemaRef.Owned(expr), 855 /*TopLevelOfInitList=*/true); 856 } 857 hadError = true; 858 ++Index; 859 ++StructuredIndex; 860 } 861} 862 863void InitListChecker::CheckComplexType(const InitializedEntity &Entity, 864 InitListExpr *IList, QualType DeclType, 865 unsigned &Index, 866 InitListExpr *StructuredList, 867 unsigned &StructuredIndex) { 868 assert(Index == 0 && "Index in explicit init list must be zero"); 869 870 // As an extension, clang supports complex initializers, which initialize 871 // a complex number component-wise. When an explicit initializer list for 872 // a complex number contains two two initializers, this extension kicks in: 873 // it exepcts the initializer list to contain two elements convertible to 874 // the element type of the complex type. The first element initializes 875 // the real part, and the second element intitializes the imaginary part. 876 877 if (IList->getNumInits() != 2) 878 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 879 StructuredIndex); 880 881 // This is an extension in C. (The builtin _Complex type does not exist 882 // in the C++ standard.) 883 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly) 884 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init) 885 << IList->getSourceRange(); 886 887 // Initialize the complex number. 888 QualType elementType = DeclType->getAs<ComplexType>()->getElementType(); 889 InitializedEntity ElementEntity = 890 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 891 892 for (unsigned i = 0; i < 2; ++i) { 893 ElementEntity.setElementIndex(Index); 894 CheckSubElementType(ElementEntity, IList, elementType, Index, 895 StructuredList, StructuredIndex); 896 } 897} 898 899 900void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 901 InitListExpr *IList, QualType DeclType, 902 unsigned &Index, 903 InitListExpr *StructuredList, 904 unsigned &StructuredIndex) { 905 if (Index >= IList->getNumInits()) { 906 if (!VerifyOnly) 907 SemaRef.Diag(IList->getLocStart(), 908 SemaRef.getLangOptions().CPlusPlus0x ? 909 diag::warn_cxx98_compat_empty_scalar_initializer : 910 diag::err_empty_scalar_initializer) 911 << IList->getSourceRange(); 912 hadError = !SemaRef.getLangOptions().CPlusPlus0x; 913 ++Index; 914 ++StructuredIndex; 915 return; 916 } 917 918 Expr *expr = IList->getInit(Index); 919 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 920 if (!VerifyOnly) 921 SemaRef.Diag(SubIList->getLocStart(), 922 diag::warn_many_braces_around_scalar_init) 923 << SubIList->getSourceRange(); 924 925 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 926 StructuredIndex); 927 return; 928 } else if (isa<DesignatedInitExpr>(expr)) { 929 if (!VerifyOnly) 930 SemaRef.Diag(expr->getSourceRange().getBegin(), 931 diag::err_designator_for_scalar_init) 932 << DeclType << expr->getSourceRange(); 933 hadError = true; 934 ++Index; 935 ++StructuredIndex; 936 return; 937 } 938 939 if (VerifyOnly) { 940 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr))) 941 hadError = true; 942 ++Index; 943 return; 944 } 945 946 ExprResult Result = 947 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 948 SemaRef.Owned(expr), 949 /*TopLevelOfInitList=*/true); 950 951 Expr *ResultExpr = 0; 952 953 if (Result.isInvalid()) 954 hadError = true; // types weren't compatible. 955 else { 956 ResultExpr = Result.takeAs<Expr>(); 957 958 if (ResultExpr != expr) { 959 // The type was promoted, update initializer list. 960 IList->setInit(Index, ResultExpr); 961 } 962 } 963 if (hadError) 964 ++StructuredIndex; 965 else 966 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 967 ++Index; 968} 969 970void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 971 InitListExpr *IList, QualType DeclType, 972 unsigned &Index, 973 InitListExpr *StructuredList, 974 unsigned &StructuredIndex) { 975 if (Index >= IList->getNumInits()) { 976 // FIXME: It would be wonderful if we could point at the actual member. In 977 // general, it would be useful to pass location information down the stack, 978 // so that we know the location (or decl) of the "current object" being 979 // initialized. 980 if (!VerifyOnly) 981 SemaRef.Diag(IList->getLocStart(), 982 diag::err_init_reference_member_uninitialized) 983 << DeclType 984 << IList->getSourceRange(); 985 hadError = true; 986 ++Index; 987 ++StructuredIndex; 988 return; 989 } 990 991 Expr *expr = IList->getInit(Index); 992 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) { 993 if (!VerifyOnly) 994 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 995 << DeclType << IList->getSourceRange(); 996 hadError = true; 997 ++Index; 998 ++StructuredIndex; 999 return; 1000 } 1001 1002 if (VerifyOnly) { 1003 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr))) 1004 hadError = true; 1005 ++Index; 1006 return; 1007 } 1008 1009 ExprResult Result = 1010 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 1011 SemaRef.Owned(expr), 1012 /*TopLevelOfInitList=*/true); 1013 1014 if (Result.isInvalid()) 1015 hadError = true; 1016 1017 expr = Result.takeAs<Expr>(); 1018 IList->setInit(Index, expr); 1019 1020 if (hadError) 1021 ++StructuredIndex; 1022 else 1023 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1024 ++Index; 1025} 1026 1027void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 1028 InitListExpr *IList, QualType DeclType, 1029 unsigned &Index, 1030 InitListExpr *StructuredList, 1031 unsigned &StructuredIndex) { 1032 const VectorType *VT = DeclType->getAs<VectorType>(); 1033 unsigned maxElements = VT->getNumElements(); 1034 unsigned numEltsInit = 0; 1035 QualType elementType = VT->getElementType(); 1036 1037 if (Index >= IList->getNumInits()) { 1038 // Make sure the element type can be value-initialized. 1039 if (VerifyOnly) 1040 CheckValueInitializable( 1041 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity)); 1042 return; 1043 } 1044 1045 if (!SemaRef.getLangOptions().OpenCL) { 1046 // If the initializing element is a vector, try to copy-initialize 1047 // instead of breaking it apart (which is doomed to failure anyway). 1048 Expr *Init = IList->getInit(Index); 1049 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 1050 if (VerifyOnly) { 1051 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init))) 1052 hadError = true; 1053 ++Index; 1054 return; 1055 } 1056 1057 ExprResult Result = 1058 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), 1059 SemaRef.Owned(Init), 1060 /*TopLevelOfInitList=*/true); 1061 1062 Expr *ResultExpr = 0; 1063 if (Result.isInvalid()) 1064 hadError = true; // types weren't compatible. 1065 else { 1066 ResultExpr = Result.takeAs<Expr>(); 1067 1068 if (ResultExpr != Init) { 1069 // The type was promoted, update initializer list. 1070 IList->setInit(Index, ResultExpr); 1071 } 1072 } 1073 if (hadError) 1074 ++StructuredIndex; 1075 else 1076 UpdateStructuredListElement(StructuredList, StructuredIndex, 1077 ResultExpr); 1078 ++Index; 1079 return; 1080 } 1081 1082 InitializedEntity ElementEntity = 1083 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1084 1085 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 1086 // Don't attempt to go past the end of the init list 1087 if (Index >= IList->getNumInits()) { 1088 if (VerifyOnly) 1089 CheckValueInitializable(ElementEntity); 1090 break; 1091 } 1092 1093 ElementEntity.setElementIndex(Index); 1094 CheckSubElementType(ElementEntity, IList, elementType, Index, 1095 StructuredList, StructuredIndex); 1096 } 1097 return; 1098 } 1099 1100 InitializedEntity ElementEntity = 1101 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1102 1103 // OpenCL initializers allows vectors to be constructed from vectors. 1104 for (unsigned i = 0; i < maxElements; ++i) { 1105 // Don't attempt to go past the end of the init list 1106 if (Index >= IList->getNumInits()) 1107 break; 1108 1109 ElementEntity.setElementIndex(Index); 1110 1111 QualType IType = IList->getInit(Index)->getType(); 1112 if (!IType->isVectorType()) { 1113 CheckSubElementType(ElementEntity, IList, elementType, Index, 1114 StructuredList, StructuredIndex); 1115 ++numEltsInit; 1116 } else { 1117 QualType VecType; 1118 const VectorType *IVT = IType->getAs<VectorType>(); 1119 unsigned numIElts = IVT->getNumElements(); 1120 1121 if (IType->isExtVectorType()) 1122 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 1123 else 1124 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 1125 IVT->getVectorKind()); 1126 CheckSubElementType(ElementEntity, IList, VecType, Index, 1127 StructuredList, StructuredIndex); 1128 numEltsInit += numIElts; 1129 } 1130 } 1131 1132 // OpenCL requires all elements to be initialized. 1133 if (numEltsInit != maxElements) { 1134 if (!VerifyOnly) 1135 SemaRef.Diag(IList->getSourceRange().getBegin(), 1136 diag::err_vector_incorrect_num_initializers) 1137 << (numEltsInit < maxElements) << maxElements << numEltsInit; 1138 hadError = true; 1139 } 1140} 1141 1142void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 1143 InitListExpr *IList, QualType &DeclType, 1144 llvm::APSInt elementIndex, 1145 bool SubobjectIsDesignatorContext, 1146 unsigned &Index, 1147 InitListExpr *StructuredList, 1148 unsigned &StructuredIndex) { 1149 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 1150 1151 // Check for the special-case of initializing an array with a string. 1152 if (Index < IList->getNumInits()) { 1153 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType, 1154 SemaRef.Context)) { 1155 // We place the string literal directly into the resulting 1156 // initializer list. This is the only place where the structure 1157 // of the structured initializer list doesn't match exactly, 1158 // because doing so would involve allocating one character 1159 // constant for each string. 1160 if (!VerifyOnly) { 1161 CheckStringInit(Str, DeclType, arrayType, SemaRef); 1162 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 1163 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1164 } 1165 ++Index; 1166 return; 1167 } 1168 } 1169 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1170 // Check for VLAs; in standard C it would be possible to check this 1171 // earlier, but I don't know where clang accepts VLAs (gcc accepts 1172 // them in all sorts of strange places). 1173 if (!VerifyOnly) 1174 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 1175 diag::err_variable_object_no_init) 1176 << VAT->getSizeExpr()->getSourceRange(); 1177 hadError = true; 1178 ++Index; 1179 ++StructuredIndex; 1180 return; 1181 } 1182 1183 // We might know the maximum number of elements in advance. 1184 llvm::APSInt maxElements(elementIndex.getBitWidth(), 1185 elementIndex.isUnsigned()); 1186 bool maxElementsKnown = false; 1187 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1188 maxElements = CAT->getSize(); 1189 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1190 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1191 maxElementsKnown = true; 1192 } 1193 1194 QualType elementType = arrayType->getElementType(); 1195 while (Index < IList->getNumInits()) { 1196 Expr *Init = IList->getInit(Index); 1197 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1198 // If we're not the subobject that matches up with the '{' for 1199 // the designator, we shouldn't be handling the 1200 // designator. Return immediately. 1201 if (!SubobjectIsDesignatorContext) 1202 return; 1203 1204 // Handle this designated initializer. elementIndex will be 1205 // updated to be the next array element we'll initialize. 1206 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1207 DeclType, 0, &elementIndex, Index, 1208 StructuredList, StructuredIndex, true, 1209 false)) { 1210 hadError = true; 1211 continue; 1212 } 1213 1214 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1215 maxElements = maxElements.extend(elementIndex.getBitWidth()); 1216 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1217 elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1218 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1219 1220 // If the array is of incomplete type, keep track of the number of 1221 // elements in the initializer. 1222 if (!maxElementsKnown && elementIndex > maxElements) 1223 maxElements = elementIndex; 1224 1225 continue; 1226 } 1227 1228 // If we know the maximum number of elements, and we've already 1229 // hit it, stop consuming elements in the initializer list. 1230 if (maxElementsKnown && elementIndex == maxElements) 1231 break; 1232 1233 InitializedEntity ElementEntity = 1234 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1235 Entity); 1236 // Check this element. 1237 CheckSubElementType(ElementEntity, IList, elementType, Index, 1238 StructuredList, StructuredIndex); 1239 ++elementIndex; 1240 1241 // If the array is of incomplete type, keep track of the number of 1242 // elements in the initializer. 1243 if (!maxElementsKnown && elementIndex > maxElements) 1244 maxElements = elementIndex; 1245 } 1246 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { 1247 // If this is an incomplete array type, the actual type needs to 1248 // be calculated here. 1249 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1250 if (maxElements == Zero) { 1251 // Sizing an array implicitly to zero is not allowed by ISO C, 1252 // but is supported by GNU. 1253 SemaRef.Diag(IList->getLocStart(), 1254 diag::ext_typecheck_zero_array_size); 1255 } 1256 1257 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1258 ArrayType::Normal, 0); 1259 } 1260 if (!hadError && VerifyOnly) { 1261 // Check if there are any members of the array that get value-initialized. 1262 // If so, check if doing that is possible. 1263 // FIXME: This needs to detect holes left by designated initializers too. 1264 if (maxElementsKnown && elementIndex < maxElements) 1265 CheckValueInitializable(InitializedEntity::InitializeElement( 1266 SemaRef.Context, 0, Entity)); 1267 } 1268} 1269 1270bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, 1271 Expr *InitExpr, 1272 FieldDecl *Field, 1273 bool TopLevelObject) { 1274 // Handle GNU flexible array initializers. 1275 unsigned FlexArrayDiag; 1276 if (isa<InitListExpr>(InitExpr) && 1277 cast<InitListExpr>(InitExpr)->getNumInits() == 0) { 1278 // Empty flexible array init always allowed as an extension 1279 FlexArrayDiag = diag::ext_flexible_array_init; 1280 } else if (SemaRef.getLangOptions().CPlusPlus) { 1281 // Disallow flexible array init in C++; it is not required for gcc 1282 // compatibility, and it needs work to IRGen correctly in general. 1283 FlexArrayDiag = diag::err_flexible_array_init; 1284 } else if (!TopLevelObject) { 1285 // Disallow flexible array init on non-top-level object 1286 FlexArrayDiag = diag::err_flexible_array_init; 1287 } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 1288 // Disallow flexible array init on anything which is not a variable. 1289 FlexArrayDiag = diag::err_flexible_array_init; 1290 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { 1291 // Disallow flexible array init on local variables. 1292 FlexArrayDiag = diag::err_flexible_array_init; 1293 } else { 1294 // Allow other cases. 1295 FlexArrayDiag = diag::ext_flexible_array_init; 1296 } 1297 1298 if (!VerifyOnly) { 1299 SemaRef.Diag(InitExpr->getSourceRange().getBegin(), 1300 FlexArrayDiag) 1301 << InitExpr->getSourceRange().getBegin(); 1302 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1303 << Field; 1304 } 1305 1306 return FlexArrayDiag != diag::ext_flexible_array_init; 1307} 1308 1309void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity, 1310 InitListExpr *IList, 1311 QualType DeclType, 1312 RecordDecl::field_iterator Field, 1313 bool SubobjectIsDesignatorContext, 1314 unsigned &Index, 1315 InitListExpr *StructuredList, 1316 unsigned &StructuredIndex, 1317 bool TopLevelObject) { 1318 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 1319 1320 // If the record is invalid, some of it's members are invalid. To avoid 1321 // confusion, we forgo checking the intializer for the entire record. 1322 if (structDecl->isInvalidDecl()) { 1323 hadError = true; 1324 return; 1325 } 1326 1327 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1328 // Value-initialize the first named member of the union. 1329 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1330 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1331 Field != FieldEnd; ++Field) { 1332 if (Field->getDeclName()) { 1333 if (VerifyOnly) 1334 CheckValueInitializable( 1335 InitializedEntity::InitializeMember(*Field, &Entity)); 1336 else 1337 StructuredList->setInitializedFieldInUnion(*Field); 1338 break; 1339 } 1340 } 1341 return; 1342 } 1343 1344 // If structDecl is a forward declaration, this loop won't do 1345 // anything except look at designated initializers; That's okay, 1346 // because an error should get printed out elsewhere. It might be 1347 // worthwhile to skip over the rest of the initializer, though. 1348 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1349 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1350 bool InitializedSomething = false; 1351 bool CheckForMissingFields = true; 1352 while (Index < IList->getNumInits()) { 1353 Expr *Init = IList->getInit(Index); 1354 1355 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1356 // If we're not the subobject that matches up with the '{' for 1357 // the designator, we shouldn't be handling the 1358 // designator. Return immediately. 1359 if (!SubobjectIsDesignatorContext) 1360 return; 1361 1362 // Handle this designated initializer. Field will be updated to 1363 // the next field that we'll be initializing. 1364 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1365 DeclType, &Field, 0, Index, 1366 StructuredList, StructuredIndex, 1367 true, TopLevelObject)) 1368 hadError = true; 1369 1370 InitializedSomething = true; 1371 1372 // Disable check for missing fields when designators are used. 1373 // This matches gcc behaviour. 1374 CheckForMissingFields = false; 1375 continue; 1376 } 1377 1378 if (Field == FieldEnd) { 1379 // We've run out of fields. We're done. 1380 break; 1381 } 1382 1383 // We've already initialized a member of a union. We're done. 1384 if (InitializedSomething && DeclType->isUnionType()) 1385 break; 1386 1387 // If we've hit the flexible array member at the end, we're done. 1388 if (Field->getType()->isIncompleteArrayType()) 1389 break; 1390 1391 if (Field->isUnnamedBitfield()) { 1392 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1393 ++Field; 1394 continue; 1395 } 1396 1397 // Make sure we can use this declaration. 1398 bool InvalidUse; 1399 if (VerifyOnly) 1400 InvalidUse = !SemaRef.CanUseDecl(*Field); 1401 else 1402 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, 1403 IList->getInit(Index)->getLocStart()); 1404 if (InvalidUse) { 1405 ++Index; 1406 ++Field; 1407 hadError = true; 1408 continue; 1409 } 1410 1411 InitializedEntity MemberEntity = 1412 InitializedEntity::InitializeMember(*Field, &Entity); 1413 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1414 StructuredList, StructuredIndex); 1415 InitializedSomething = true; 1416 1417 if (DeclType->isUnionType() && !VerifyOnly) { 1418 // Initialize the first field within the union. 1419 StructuredList->setInitializedFieldInUnion(*Field); 1420 } 1421 1422 ++Field; 1423 } 1424 1425 // Emit warnings for missing struct field initializers. 1426 if (!VerifyOnly && InitializedSomething && CheckForMissingFields && 1427 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && 1428 !DeclType->isUnionType()) { 1429 // It is possible we have one or more unnamed bitfields remaining. 1430 // Find first (if any) named field and emit warning. 1431 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 1432 it != end; ++it) { 1433 if (!it->isUnnamedBitfield()) { 1434 SemaRef.Diag(IList->getSourceRange().getEnd(), 1435 diag::warn_missing_field_initializers) << it->getName(); 1436 break; 1437 } 1438 } 1439 } 1440 1441 // Check that any remaining fields can be value-initialized. 1442 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() && 1443 !Field->getType()->isIncompleteArrayType()) { 1444 // FIXME: Should check for holes left by designated initializers too. 1445 for (; Field != FieldEnd && !hadError; ++Field) { 1446 if (!Field->isUnnamedBitfield()) 1447 CheckValueInitializable( 1448 InitializedEntity::InitializeMember(*Field, &Entity)); 1449 } 1450 } 1451 1452 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1453 Index >= IList->getNumInits()) 1454 return; 1455 1456 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, 1457 TopLevelObject)) { 1458 hadError = true; 1459 ++Index; 1460 return; 1461 } 1462 1463 InitializedEntity MemberEntity = 1464 InitializedEntity::InitializeMember(*Field, &Entity); 1465 1466 if (isa<InitListExpr>(IList->getInit(Index))) 1467 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1468 StructuredList, StructuredIndex); 1469 else 1470 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 1471 StructuredList, StructuredIndex); 1472} 1473 1474/// \brief Expand a field designator that refers to a member of an 1475/// anonymous struct or union into a series of field designators that 1476/// refers to the field within the appropriate subobject. 1477/// 1478static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1479 DesignatedInitExpr *DIE, 1480 unsigned DesigIdx, 1481 IndirectFieldDecl *IndirectField) { 1482 typedef DesignatedInitExpr::Designator Designator; 1483 1484 // Build the replacement designators. 1485 SmallVector<Designator, 4> Replacements; 1486 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 1487 PE = IndirectField->chain_end(); PI != PE; ++PI) { 1488 if (PI + 1 == PE) 1489 Replacements.push_back(Designator((IdentifierInfo *)0, 1490 DIE->getDesignator(DesigIdx)->getDotLoc(), 1491 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1492 else 1493 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1494 SourceLocation())); 1495 assert(isa<FieldDecl>(*PI)); 1496 Replacements.back().setField(cast<FieldDecl>(*PI)); 1497 } 1498 1499 // Expand the current designator into the set of replacement 1500 // designators, so we have a full subobject path down to where the 1501 // member of the anonymous struct/union is actually stored. 1502 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 1503 &Replacements[0] + Replacements.size()); 1504} 1505 1506/// \brief Given an implicit anonymous field, search the IndirectField that 1507/// corresponds to FieldName. 1508static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField, 1509 IdentifierInfo *FieldName) { 1510 assert(AnonField->isAnonymousStructOrUnion()); 1511 Decl *NextDecl = AnonField->getNextDeclInContext(); 1512 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) { 1513 if (FieldName && FieldName == IF->getAnonField()->getIdentifier()) 1514 return IF; 1515 NextDecl = NextDecl->getNextDeclInContext(); 1516 } 1517 return 0; 1518} 1519 1520static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, 1521 DesignatedInitExpr *DIE) { 1522 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; 1523 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); 1524 for (unsigned I = 0; I < NumIndexExprs; ++I) 1525 IndexExprs[I] = DIE->getSubExpr(I + 1); 1526 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(), 1527 DIE->size(), IndexExprs.data(), 1528 NumIndexExprs, DIE->getEqualOrColonLoc(), 1529 DIE->usesGNUSyntax(), DIE->getInit()); 1530} 1531 1532namespace { 1533 1534// Callback to only accept typo corrections that are for field members of 1535// the given struct or union. 1536class FieldInitializerValidatorCCC : public CorrectionCandidateCallback { 1537 public: 1538 explicit FieldInitializerValidatorCCC(RecordDecl *RD) 1539 : Record(RD) {} 1540 1541 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1542 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); 1543 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); 1544 } 1545 1546 private: 1547 RecordDecl *Record; 1548}; 1549 1550} 1551 1552/// @brief Check the well-formedness of a C99 designated initializer. 1553/// 1554/// Determines whether the designated initializer @p DIE, which 1555/// resides at the given @p Index within the initializer list @p 1556/// IList, is well-formed for a current object of type @p DeclType 1557/// (C99 6.7.8). The actual subobject that this designator refers to 1558/// within the current subobject is returned in either 1559/// @p NextField or @p NextElementIndex (whichever is appropriate). 1560/// 1561/// @param IList The initializer list in which this designated 1562/// initializer occurs. 1563/// 1564/// @param DIE The designated initializer expression. 1565/// 1566/// @param DesigIdx The index of the current designator. 1567/// 1568/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1569/// into which the designation in @p DIE should refer. 1570/// 1571/// @param NextField If non-NULL and the first designator in @p DIE is 1572/// a field, this will be set to the field declaration corresponding 1573/// to the field named by the designator. 1574/// 1575/// @param NextElementIndex If non-NULL and the first designator in @p 1576/// DIE is an array designator or GNU array-range designator, this 1577/// will be set to the last index initialized by this designator. 1578/// 1579/// @param Index Index into @p IList where the designated initializer 1580/// @p DIE occurs. 1581/// 1582/// @param StructuredList The initializer list expression that 1583/// describes all of the subobject initializers in the order they'll 1584/// actually be initialized. 1585/// 1586/// @returns true if there was an error, false otherwise. 1587bool 1588InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 1589 InitListExpr *IList, 1590 DesignatedInitExpr *DIE, 1591 unsigned DesigIdx, 1592 QualType &CurrentObjectType, 1593 RecordDecl::field_iterator *NextField, 1594 llvm::APSInt *NextElementIndex, 1595 unsigned &Index, 1596 InitListExpr *StructuredList, 1597 unsigned &StructuredIndex, 1598 bool FinishSubobjectInit, 1599 bool TopLevelObject) { 1600 if (DesigIdx == DIE->size()) { 1601 // Check the actual initialization for the designated object type. 1602 bool prevHadError = hadError; 1603 1604 // Temporarily remove the designator expression from the 1605 // initializer list that the child calls see, so that we don't try 1606 // to re-process the designator. 1607 unsigned OldIndex = Index; 1608 IList->setInit(OldIndex, DIE->getInit()); 1609 1610 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 1611 StructuredList, StructuredIndex); 1612 1613 // Restore the designated initializer expression in the syntactic 1614 // form of the initializer list. 1615 if (IList->getInit(OldIndex) != DIE->getInit()) 1616 DIE->setInit(IList->getInit(OldIndex)); 1617 IList->setInit(OldIndex, DIE); 1618 1619 return hadError && !prevHadError; 1620 } 1621 1622 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1623 bool IsFirstDesignator = (DesigIdx == 0); 1624 if (!VerifyOnly) { 1625 assert((IsFirstDesignator || StructuredList) && 1626 "Need a non-designated initializer list to start from"); 1627 1628 // Determine the structural initializer list that corresponds to the 1629 // current subobject. 1630 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1631 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1632 StructuredList, StructuredIndex, 1633 SourceRange(D->getStartLocation(), 1634 DIE->getSourceRange().getEnd())); 1635 assert(StructuredList && "Expected a structured initializer list"); 1636 } 1637 1638 if (D->isFieldDesignator()) { 1639 // C99 6.7.8p7: 1640 // 1641 // If a designator has the form 1642 // 1643 // . identifier 1644 // 1645 // then the current object (defined below) shall have 1646 // structure or union type and the identifier shall be the 1647 // name of a member of that type. 1648 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1649 if (!RT) { 1650 SourceLocation Loc = D->getDotLoc(); 1651 if (Loc.isInvalid()) 1652 Loc = D->getFieldLoc(); 1653 if (!VerifyOnly) 1654 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1655 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1656 ++Index; 1657 return true; 1658 } 1659 1660 // Note: we perform a linear search of the fields here, despite 1661 // the fact that we have a faster lookup method, because we always 1662 // need to compute the field's index. 1663 FieldDecl *KnownField = D->getField(); 1664 IdentifierInfo *FieldName = D->getFieldName(); 1665 unsigned FieldIndex = 0; 1666 RecordDecl::field_iterator 1667 Field = RT->getDecl()->field_begin(), 1668 FieldEnd = RT->getDecl()->field_end(); 1669 for (; Field != FieldEnd; ++Field) { 1670 if (Field->isUnnamedBitfield()) 1671 continue; 1672 1673 // If we find a field representing an anonymous field, look in the 1674 // IndirectFieldDecl that follow for the designated initializer. 1675 if (!KnownField && Field->isAnonymousStructOrUnion()) { 1676 if (IndirectFieldDecl *IF = 1677 FindIndirectFieldDesignator(*Field, FieldName)) { 1678 // In verify mode, don't modify the original. 1679 if (VerifyOnly) 1680 DIE = CloneDesignatedInitExpr(SemaRef, DIE); 1681 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF); 1682 D = DIE->getDesignator(DesigIdx); 1683 break; 1684 } 1685 } 1686 if (KnownField && KnownField == *Field) 1687 break; 1688 if (FieldName && FieldName == Field->getIdentifier()) 1689 break; 1690 1691 ++FieldIndex; 1692 } 1693 1694 if (Field == FieldEnd) { 1695 if (VerifyOnly) { 1696 ++Index; 1697 return true; // No typo correction when just trying this out. 1698 } 1699 1700 // There was no normal field in the struct with the designated 1701 // name. Perform another lookup for this name, which may find 1702 // something that we can't designate (e.g., a member function), 1703 // may find nothing, or may find a member of an anonymous 1704 // struct/union. 1705 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1706 FieldDecl *ReplacementField = 0; 1707 if (Lookup.first == Lookup.second) { 1708 // Name lookup didn't find anything. Determine whether this 1709 // was a typo for another field name. 1710 FieldInitializerValidatorCCC Validator(RT->getDecl()); 1711 TypoCorrection Corrected = SemaRef.CorrectTypo( 1712 DeclarationNameInfo(FieldName, D->getFieldLoc()), 1713 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, &Validator, 1714 RT->getDecl()); 1715 if (Corrected) { 1716 std::string CorrectedStr( 1717 Corrected.getAsString(SemaRef.getLangOptions())); 1718 std::string CorrectedQuotedStr( 1719 Corrected.getQuoted(SemaRef.getLangOptions())); 1720 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>(); 1721 SemaRef.Diag(D->getFieldLoc(), 1722 diag::err_field_designator_unknown_suggest) 1723 << FieldName << CurrentObjectType << CorrectedQuotedStr 1724 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr); 1725 SemaRef.Diag(ReplacementField->getLocation(), 1726 diag::note_previous_decl) << CorrectedQuotedStr; 1727 hadError = true; 1728 } else { 1729 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1730 << FieldName << CurrentObjectType; 1731 ++Index; 1732 return true; 1733 } 1734 } 1735 1736 if (!ReplacementField) { 1737 // Name lookup found something, but it wasn't a field. 1738 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1739 << FieldName; 1740 SemaRef.Diag((*Lookup.first)->getLocation(), 1741 diag::note_field_designator_found); 1742 ++Index; 1743 return true; 1744 } 1745 1746 if (!KnownField) { 1747 // The replacement field comes from typo correction; find it 1748 // in the list of fields. 1749 FieldIndex = 0; 1750 Field = RT->getDecl()->field_begin(); 1751 for (; Field != FieldEnd; ++Field) { 1752 if (Field->isUnnamedBitfield()) 1753 continue; 1754 1755 if (ReplacementField == *Field || 1756 Field->getIdentifier() == ReplacementField->getIdentifier()) 1757 break; 1758 1759 ++FieldIndex; 1760 } 1761 } 1762 } 1763 1764 // All of the fields of a union are located at the same place in 1765 // the initializer list. 1766 if (RT->getDecl()->isUnion()) { 1767 FieldIndex = 0; 1768 if (!VerifyOnly) 1769 StructuredList->setInitializedFieldInUnion(*Field); 1770 } 1771 1772 // Make sure we can use this declaration. 1773 bool InvalidUse; 1774 if (VerifyOnly) 1775 InvalidUse = !SemaRef.CanUseDecl(*Field); 1776 else 1777 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); 1778 if (InvalidUse) { 1779 ++Index; 1780 return true; 1781 } 1782 1783 if (!VerifyOnly) { 1784 // Update the designator with the field declaration. 1785 D->setField(*Field); 1786 1787 // Make sure that our non-designated initializer list has space 1788 // for a subobject corresponding to this field. 1789 if (FieldIndex >= StructuredList->getNumInits()) 1790 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1791 } 1792 1793 // This designator names a flexible array member. 1794 if (Field->getType()->isIncompleteArrayType()) { 1795 bool Invalid = false; 1796 if ((DesigIdx + 1) != DIE->size()) { 1797 // We can't designate an object within the flexible array 1798 // member (because GCC doesn't allow it). 1799 if (!VerifyOnly) { 1800 DesignatedInitExpr::Designator *NextD 1801 = DIE->getDesignator(DesigIdx + 1); 1802 SemaRef.Diag(NextD->getStartLocation(), 1803 diag::err_designator_into_flexible_array_member) 1804 << SourceRange(NextD->getStartLocation(), 1805 DIE->getSourceRange().getEnd()); 1806 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1807 << *Field; 1808 } 1809 Invalid = true; 1810 } 1811 1812 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 1813 !isa<StringLiteral>(DIE->getInit())) { 1814 // The initializer is not an initializer list. 1815 if (!VerifyOnly) { 1816 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1817 diag::err_flexible_array_init_needs_braces) 1818 << DIE->getInit()->getSourceRange(); 1819 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1820 << *Field; 1821 } 1822 Invalid = true; 1823 } 1824 1825 // Check GNU flexible array initializer. 1826 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, 1827 TopLevelObject)) 1828 Invalid = true; 1829 1830 if (Invalid) { 1831 ++Index; 1832 return true; 1833 } 1834 1835 // Initialize the array. 1836 bool prevHadError = hadError; 1837 unsigned newStructuredIndex = FieldIndex; 1838 unsigned OldIndex = Index; 1839 IList->setInit(Index, DIE->getInit()); 1840 1841 InitializedEntity MemberEntity = 1842 InitializedEntity::InitializeMember(*Field, &Entity); 1843 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1844 StructuredList, newStructuredIndex); 1845 1846 IList->setInit(OldIndex, DIE); 1847 if (hadError && !prevHadError) { 1848 ++Field; 1849 ++FieldIndex; 1850 if (NextField) 1851 *NextField = Field; 1852 StructuredIndex = FieldIndex; 1853 return true; 1854 } 1855 } else { 1856 // Recurse to check later designated subobjects. 1857 QualType FieldType = (*Field)->getType(); 1858 unsigned newStructuredIndex = FieldIndex; 1859 1860 InitializedEntity MemberEntity = 1861 InitializedEntity::InitializeMember(*Field, &Entity); 1862 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 1863 FieldType, 0, 0, Index, 1864 StructuredList, newStructuredIndex, 1865 true, false)) 1866 return true; 1867 } 1868 1869 // Find the position of the next field to be initialized in this 1870 // subobject. 1871 ++Field; 1872 ++FieldIndex; 1873 1874 // If this the first designator, our caller will continue checking 1875 // the rest of this struct/class/union subobject. 1876 if (IsFirstDesignator) { 1877 if (NextField) 1878 *NextField = Field; 1879 StructuredIndex = FieldIndex; 1880 return false; 1881 } 1882 1883 if (!FinishSubobjectInit) 1884 return false; 1885 1886 // We've already initialized something in the union; we're done. 1887 if (RT->getDecl()->isUnion()) 1888 return hadError; 1889 1890 // Check the remaining fields within this class/struct/union subobject. 1891 bool prevHadError = hadError; 1892 1893 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index, 1894 StructuredList, FieldIndex); 1895 return hadError && !prevHadError; 1896 } 1897 1898 // C99 6.7.8p6: 1899 // 1900 // If a designator has the form 1901 // 1902 // [ constant-expression ] 1903 // 1904 // then the current object (defined below) shall have array 1905 // type and the expression shall be an integer constant 1906 // expression. If the array is of unknown size, any 1907 // nonnegative value is valid. 1908 // 1909 // Additionally, cope with the GNU extension that permits 1910 // designators of the form 1911 // 1912 // [ constant-expression ... constant-expression ] 1913 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1914 if (!AT) { 1915 if (!VerifyOnly) 1916 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1917 << CurrentObjectType; 1918 ++Index; 1919 return true; 1920 } 1921 1922 Expr *IndexExpr = 0; 1923 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1924 if (D->isArrayDesignator()) { 1925 IndexExpr = DIE->getArrayIndex(*D); 1926 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); 1927 DesignatedEndIndex = DesignatedStartIndex; 1928 } else { 1929 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1930 1931 DesignatedStartIndex = 1932 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); 1933 DesignatedEndIndex = 1934 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); 1935 IndexExpr = DIE->getArrayRangeEnd(*D); 1936 1937 // Codegen can't handle evaluating array range designators that have side 1938 // effects, because we replicate the AST value for each initialized element. 1939 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 1940 // elements with something that has a side effect, so codegen can emit an 1941 // "error unsupported" error instead of miscompiling the app. 1942 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 1943 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) 1944 FullyStructuredList->sawArrayRangeDesignator(); 1945 } 1946 1947 if (isa<ConstantArrayType>(AT)) { 1948 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1949 DesignatedStartIndex 1950 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1951 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1952 DesignatedEndIndex 1953 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1954 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1955 if (DesignatedEndIndex >= MaxElements) { 1956 if (!VerifyOnly) 1957 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1958 diag::err_array_designator_too_large) 1959 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1960 << IndexExpr->getSourceRange(); 1961 ++Index; 1962 return true; 1963 } 1964 } else { 1965 // Make sure the bit-widths and signedness match. 1966 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1967 DesignatedEndIndex 1968 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1969 else if (DesignatedStartIndex.getBitWidth() < 1970 DesignatedEndIndex.getBitWidth()) 1971 DesignatedStartIndex 1972 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1973 DesignatedStartIndex.setIsUnsigned(true); 1974 DesignatedEndIndex.setIsUnsigned(true); 1975 } 1976 1977 // Make sure that our non-designated initializer list has space 1978 // for a subobject corresponding to this array element. 1979 if (!VerifyOnly && 1980 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1981 StructuredList->resizeInits(SemaRef.Context, 1982 DesignatedEndIndex.getZExtValue() + 1); 1983 1984 // Repeatedly perform subobject initializations in the range 1985 // [DesignatedStartIndex, DesignatedEndIndex]. 1986 1987 // Move to the next designator 1988 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1989 unsigned OldIndex = Index; 1990 1991 InitializedEntity ElementEntity = 1992 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1993 1994 while (DesignatedStartIndex <= DesignatedEndIndex) { 1995 // Recurse to check later designated subobjects. 1996 QualType ElementType = AT->getElementType(); 1997 Index = OldIndex; 1998 1999 ElementEntity.setElementIndex(ElementIndex); 2000 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1, 2001 ElementType, 0, 0, Index, 2002 StructuredList, ElementIndex, 2003 (DesignatedStartIndex == DesignatedEndIndex), 2004 false)) 2005 return true; 2006 2007 // Move to the next index in the array that we'll be initializing. 2008 ++DesignatedStartIndex; 2009 ElementIndex = DesignatedStartIndex.getZExtValue(); 2010 } 2011 2012 // If this the first designator, our caller will continue checking 2013 // the rest of this array subobject. 2014 if (IsFirstDesignator) { 2015 if (NextElementIndex) 2016 *NextElementIndex = DesignatedStartIndex; 2017 StructuredIndex = ElementIndex; 2018 return false; 2019 } 2020 2021 if (!FinishSubobjectInit) 2022 return false; 2023 2024 // Check the remaining elements within this array subobject. 2025 bool prevHadError = hadError; 2026 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 2027 /*SubobjectIsDesignatorContext=*/false, Index, 2028 StructuredList, ElementIndex); 2029 return hadError && !prevHadError; 2030} 2031 2032// Get the structured initializer list for a subobject of type 2033// @p CurrentObjectType. 2034InitListExpr * 2035InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 2036 QualType CurrentObjectType, 2037 InitListExpr *StructuredList, 2038 unsigned StructuredIndex, 2039 SourceRange InitRange) { 2040 if (VerifyOnly) 2041 return 0; // No structured list in verification-only mode. 2042 Expr *ExistingInit = 0; 2043 if (!StructuredList) 2044 ExistingInit = SyntacticToSemantic[IList]; 2045 else if (StructuredIndex < StructuredList->getNumInits()) 2046 ExistingInit = StructuredList->getInit(StructuredIndex); 2047 2048 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 2049 return Result; 2050 2051 if (ExistingInit) { 2052 // We are creating an initializer list that initializes the 2053 // subobjects of the current object, but there was already an 2054 // initialization that completely initialized the current 2055 // subobject, e.g., by a compound literal: 2056 // 2057 // struct X { int a, b; }; 2058 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2059 // 2060 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 2061 // designated initializer re-initializes the whole 2062 // subobject [0], overwriting previous initializers. 2063 SemaRef.Diag(InitRange.getBegin(), 2064 diag::warn_subobject_initializer_overrides) 2065 << InitRange; 2066 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 2067 diag::note_previous_initializer) 2068 << /*FIXME:has side effects=*/0 2069 << ExistingInit->getSourceRange(); 2070 } 2071 2072 InitListExpr *Result 2073 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 2074 InitRange.getBegin(), 0, 0, 2075 InitRange.getEnd()); 2076 2077 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context)); 2078 2079 // Pre-allocate storage for the structured initializer list. 2080 unsigned NumElements = 0; 2081 unsigned NumInits = 0; 2082 bool GotNumInits = false; 2083 if (!StructuredList) { 2084 NumInits = IList->getNumInits(); 2085 GotNumInits = true; 2086 } else if (Index < IList->getNumInits()) { 2087 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) { 2088 NumInits = SubList->getNumInits(); 2089 GotNumInits = true; 2090 } 2091 } 2092 2093 if (const ArrayType *AType 2094 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 2095 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 2096 NumElements = CAType->getSize().getZExtValue(); 2097 // Simple heuristic so that we don't allocate a very large 2098 // initializer with many empty entries at the end. 2099 if (GotNumInits && NumElements > NumInits) 2100 NumElements = 0; 2101 } 2102 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 2103 NumElements = VType->getNumElements(); 2104 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 2105 RecordDecl *RDecl = RType->getDecl(); 2106 if (RDecl->isUnion()) 2107 NumElements = 1; 2108 else 2109 NumElements = std::distance(RDecl->field_begin(), 2110 RDecl->field_end()); 2111 } 2112 2113 Result->reserveInits(SemaRef.Context, NumElements); 2114 2115 // Link this new initializer list into the structured initializer 2116 // lists. 2117 if (StructuredList) 2118 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 2119 else { 2120 Result->setSyntacticForm(IList); 2121 SyntacticToSemantic[IList] = Result; 2122 } 2123 2124 return Result; 2125} 2126 2127/// Update the initializer at index @p StructuredIndex within the 2128/// structured initializer list to the value @p expr. 2129void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 2130 unsigned &StructuredIndex, 2131 Expr *expr) { 2132 // No structured initializer list to update 2133 if (!StructuredList) 2134 return; 2135 2136 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 2137 StructuredIndex, expr)) { 2138 // This initializer overwrites a previous initializer. Warn. 2139 SemaRef.Diag(expr->getSourceRange().getBegin(), 2140 diag::warn_initializer_overrides) 2141 << expr->getSourceRange(); 2142 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 2143 diag::note_previous_initializer) 2144 << /*FIXME:has side effects=*/0 2145 << PrevInit->getSourceRange(); 2146 } 2147 2148 ++StructuredIndex; 2149} 2150 2151/// Check that the given Index expression is a valid array designator 2152/// value. This is essentailly just a wrapper around 2153/// VerifyIntegerConstantExpression that also checks for negative values 2154/// and produces a reasonable diagnostic if there is a 2155/// failure. Returns true if there was an error, false otherwise. If 2156/// everything went okay, Value will receive the value of the constant 2157/// expression. 2158static bool 2159CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 2160 SourceLocation Loc = Index->getSourceRange().getBegin(); 2161 2162 // Make sure this is an integer constant expression. 2163 if (S.VerifyIntegerConstantExpression(Index, &Value)) 2164 return true; 2165 2166 if (Value.isSigned() && Value.isNegative()) 2167 return S.Diag(Loc, diag::err_array_designator_negative) 2168 << Value.toString(10) << Index->getSourceRange(); 2169 2170 Value.setIsUnsigned(true); 2171 return false; 2172} 2173 2174ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 2175 SourceLocation Loc, 2176 bool GNUSyntax, 2177 ExprResult Init) { 2178 typedef DesignatedInitExpr::Designator ASTDesignator; 2179 2180 bool Invalid = false; 2181 SmallVector<ASTDesignator, 32> Designators; 2182 SmallVector<Expr *, 32> InitExpressions; 2183 2184 // Build designators and check array designator expressions. 2185 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 2186 const Designator &D = Desig.getDesignator(Idx); 2187 switch (D.getKind()) { 2188 case Designator::FieldDesignator: 2189 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 2190 D.getFieldLoc())); 2191 break; 2192 2193 case Designator::ArrayDesignator: { 2194 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 2195 llvm::APSInt IndexValue; 2196 if (!Index->isTypeDependent() && 2197 !Index->isValueDependent() && 2198 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 2199 Invalid = true; 2200 else { 2201 Designators.push_back(ASTDesignator(InitExpressions.size(), 2202 D.getLBracketLoc(), 2203 D.getRBracketLoc())); 2204 InitExpressions.push_back(Index); 2205 } 2206 break; 2207 } 2208 2209 case Designator::ArrayRangeDesignator: { 2210 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 2211 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 2212 llvm::APSInt StartValue; 2213 llvm::APSInt EndValue; 2214 bool StartDependent = StartIndex->isTypeDependent() || 2215 StartIndex->isValueDependent(); 2216 bool EndDependent = EndIndex->isTypeDependent() || 2217 EndIndex->isValueDependent(); 2218 if ((!StartDependent && 2219 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 2220 (!EndDependent && 2221 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 2222 Invalid = true; 2223 else { 2224 // Make sure we're comparing values with the same bit width. 2225 if (StartDependent || EndDependent) { 2226 // Nothing to compute. 2227 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 2228 EndValue = EndValue.extend(StartValue.getBitWidth()); 2229 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 2230 StartValue = StartValue.extend(EndValue.getBitWidth()); 2231 2232 if (!StartDependent && !EndDependent && EndValue < StartValue) { 2233 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 2234 << StartValue.toString(10) << EndValue.toString(10) 2235 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 2236 Invalid = true; 2237 } else { 2238 Designators.push_back(ASTDesignator(InitExpressions.size(), 2239 D.getLBracketLoc(), 2240 D.getEllipsisLoc(), 2241 D.getRBracketLoc())); 2242 InitExpressions.push_back(StartIndex); 2243 InitExpressions.push_back(EndIndex); 2244 } 2245 } 2246 break; 2247 } 2248 } 2249 } 2250 2251 if (Invalid || Init.isInvalid()) 2252 return ExprError(); 2253 2254 // Clear out the expressions within the designation. 2255 Desig.ClearExprs(*this); 2256 2257 DesignatedInitExpr *DIE 2258 = DesignatedInitExpr::Create(Context, 2259 Designators.data(), Designators.size(), 2260 InitExpressions.data(), InitExpressions.size(), 2261 Loc, GNUSyntax, Init.takeAs<Expr>()); 2262 2263 if (!getLangOptions().C99) 2264 Diag(DIE->getLocStart(), diag::ext_designated_init) 2265 << DIE->getSourceRange(); 2266 2267 return Owned(DIE); 2268} 2269 2270//===----------------------------------------------------------------------===// 2271// Initialization entity 2272//===----------------------------------------------------------------------===// 2273 2274InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 2275 const InitializedEntity &Parent) 2276 : Parent(&Parent), Index(Index) 2277{ 2278 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 2279 Kind = EK_ArrayElement; 2280 Type = AT->getElementType(); 2281 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 2282 Kind = EK_VectorElement; 2283 Type = VT->getElementType(); 2284 } else { 2285 const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 2286 assert(CT && "Unexpected type"); 2287 Kind = EK_ComplexElement; 2288 Type = CT->getElementType(); 2289 } 2290} 2291 2292InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 2293 CXXBaseSpecifier *Base, 2294 bool IsInheritedVirtualBase) 2295{ 2296 InitializedEntity Result; 2297 Result.Kind = EK_Base; 2298 Result.Base = reinterpret_cast<uintptr_t>(Base); 2299 if (IsInheritedVirtualBase) 2300 Result.Base |= 0x01; 2301 2302 Result.Type = Base->getType(); 2303 return Result; 2304} 2305 2306DeclarationName InitializedEntity::getName() const { 2307 switch (getKind()) { 2308 case EK_Parameter: { 2309 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2310 return (D ? D->getDeclName() : DeclarationName()); 2311 } 2312 2313 case EK_Variable: 2314 case EK_Member: 2315 return VariableOrMember->getDeclName(); 2316 2317 case EK_Result: 2318 case EK_Exception: 2319 case EK_New: 2320 case EK_Temporary: 2321 case EK_Base: 2322 case EK_Delegating: 2323 case EK_ArrayElement: 2324 case EK_VectorElement: 2325 case EK_ComplexElement: 2326 case EK_BlockElement: 2327 return DeclarationName(); 2328 } 2329 2330 llvm_unreachable("Invalid EntityKind!"); 2331} 2332 2333DeclaratorDecl *InitializedEntity::getDecl() const { 2334 switch (getKind()) { 2335 case EK_Variable: 2336 case EK_Member: 2337 return VariableOrMember; 2338 2339 case EK_Parameter: 2340 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2341 2342 case EK_Result: 2343 case EK_Exception: 2344 case EK_New: 2345 case EK_Temporary: 2346 case EK_Base: 2347 case EK_Delegating: 2348 case EK_ArrayElement: 2349 case EK_VectorElement: 2350 case EK_ComplexElement: 2351 case EK_BlockElement: 2352 return 0; 2353 } 2354 2355 llvm_unreachable("Invalid EntityKind!"); 2356} 2357 2358bool InitializedEntity::allowsNRVO() const { 2359 switch (getKind()) { 2360 case EK_Result: 2361 case EK_Exception: 2362 return LocAndNRVO.NRVO; 2363 2364 case EK_Variable: 2365 case EK_Parameter: 2366 case EK_Member: 2367 case EK_New: 2368 case EK_Temporary: 2369 case EK_Base: 2370 case EK_Delegating: 2371 case EK_ArrayElement: 2372 case EK_VectorElement: 2373 case EK_ComplexElement: 2374 case EK_BlockElement: 2375 break; 2376 } 2377 2378 return false; 2379} 2380 2381//===----------------------------------------------------------------------===// 2382// Initialization sequence 2383//===----------------------------------------------------------------------===// 2384 2385void InitializationSequence::Step::Destroy() { 2386 switch (Kind) { 2387 case SK_ResolveAddressOfOverloadedFunction: 2388 case SK_CastDerivedToBaseRValue: 2389 case SK_CastDerivedToBaseXValue: 2390 case SK_CastDerivedToBaseLValue: 2391 case SK_BindReference: 2392 case SK_BindReferenceToTemporary: 2393 case SK_ExtraneousCopyToTemporary: 2394 case SK_UserConversion: 2395 case SK_QualificationConversionRValue: 2396 case SK_QualificationConversionXValue: 2397 case SK_QualificationConversionLValue: 2398 case SK_ListInitialization: 2399 case SK_ListConstructorCall: 2400 case SK_UnwrapInitList: 2401 case SK_RewrapInitList: 2402 case SK_ConstructorInitialization: 2403 case SK_ZeroInitialization: 2404 case SK_CAssignment: 2405 case SK_StringInit: 2406 case SK_ObjCObjectConversion: 2407 case SK_ArrayInit: 2408 case SK_PassByIndirectCopyRestore: 2409 case SK_PassByIndirectRestore: 2410 case SK_ProduceObjCObject: 2411 break; 2412 2413 case SK_ConversionSequence: 2414 delete ICS; 2415 } 2416} 2417 2418bool InitializationSequence::isDirectReferenceBinding() const { 2419 return !Steps.empty() && Steps.back().Kind == SK_BindReference; 2420} 2421 2422bool InitializationSequence::isAmbiguous() const { 2423 if (!Failed()) 2424 return false; 2425 2426 switch (getFailureKind()) { 2427 case FK_TooManyInitsForReference: 2428 case FK_ArrayNeedsInitList: 2429 case FK_ArrayNeedsInitListOrStringLiteral: 2430 case FK_AddressOfOverloadFailed: // FIXME: Could do better 2431 case FK_NonConstLValueReferenceBindingToTemporary: 2432 case FK_NonConstLValueReferenceBindingToUnrelated: 2433 case FK_RValueReferenceBindingToLValue: 2434 case FK_ReferenceInitDropsQualifiers: 2435 case FK_ReferenceInitFailed: 2436 case FK_ConversionFailed: 2437 case FK_ConversionFromPropertyFailed: 2438 case FK_TooManyInitsForScalar: 2439 case FK_ReferenceBindingToInitList: 2440 case FK_InitListBadDestinationType: 2441 case FK_DefaultInitOfConst: 2442 case FK_Incomplete: 2443 case FK_ArrayTypeMismatch: 2444 case FK_NonConstantArrayInit: 2445 case FK_ListInitializationFailed: 2446 case FK_VariableLengthArrayHasInitializer: 2447 case FK_PlaceholderType: 2448 return false; 2449 2450 case FK_ReferenceInitOverloadFailed: 2451 case FK_UserConversionOverloadFailed: 2452 case FK_ConstructorOverloadFailed: 2453 case FK_ListConstructorOverloadFailed: 2454 return FailedOverloadResult == OR_Ambiguous; 2455 } 2456 2457 llvm_unreachable("Invalid EntityKind!"); 2458} 2459 2460bool InitializationSequence::isConstructorInitialization() const { 2461 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 2462} 2463 2464bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx, 2465 const Expr *Initializer, 2466 bool *isInitializerConstant, 2467 APValue *ConstantValue) const { 2468 if (Steps.empty() || Initializer->isValueDependent()) 2469 return false; 2470 2471 const Step &LastStep = Steps.back(); 2472 if (LastStep.Kind != SK_ConversionSequence) 2473 return false; 2474 2475 const ImplicitConversionSequence &ICS = *LastStep.ICS; 2476 const StandardConversionSequence *SCS = NULL; 2477 switch (ICS.getKind()) { 2478 case ImplicitConversionSequence::StandardConversion: 2479 SCS = &ICS.Standard; 2480 break; 2481 case ImplicitConversionSequence::UserDefinedConversion: 2482 SCS = &ICS.UserDefined.After; 2483 break; 2484 case ImplicitConversionSequence::AmbiguousConversion: 2485 case ImplicitConversionSequence::EllipsisConversion: 2486 case ImplicitConversionSequence::BadConversion: 2487 return false; 2488 } 2489 2490 // Check if SCS represents a narrowing conversion, according to C++0x 2491 // [dcl.init.list]p7: 2492 // 2493 // A narrowing conversion is an implicit conversion ... 2494 ImplicitConversionKind PossibleNarrowing = SCS->Second; 2495 QualType FromType = SCS->getToType(0); 2496 QualType ToType = SCS->getToType(1); 2497 switch (PossibleNarrowing) { 2498 // * from a floating-point type to an integer type, or 2499 // 2500 // * from an integer type or unscoped enumeration type to a floating-point 2501 // type, except where the source is a constant expression and the actual 2502 // value after conversion will fit into the target type and will produce 2503 // the original value when converted back to the original type, or 2504 case ICK_Floating_Integral: 2505 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 2506 *isInitializerConstant = false; 2507 return true; 2508 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 2509 llvm::APSInt IntConstantValue; 2510 if (Initializer && 2511 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 2512 // Convert the integer to the floating type. 2513 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 2514 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 2515 llvm::APFloat::rmNearestTiesToEven); 2516 // And back. 2517 llvm::APSInt ConvertedValue = IntConstantValue; 2518 bool ignored; 2519 Result.convertToInteger(ConvertedValue, 2520 llvm::APFloat::rmTowardZero, &ignored); 2521 // If the resulting value is different, this was a narrowing conversion. 2522 if (IntConstantValue != ConvertedValue) { 2523 *isInitializerConstant = true; 2524 *ConstantValue = APValue(IntConstantValue); 2525 return true; 2526 } 2527 } else { 2528 // Variables are always narrowings. 2529 *isInitializerConstant = false; 2530 return true; 2531 } 2532 } 2533 return false; 2534 2535 // * from long double to double or float, or from double to float, except 2536 // where the source is a constant expression and the actual value after 2537 // conversion is within the range of values that can be represented (even 2538 // if it cannot be represented exactly), or 2539 case ICK_Floating_Conversion: 2540 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) { 2541 // FromType is larger than ToType. 2542 Expr::EvalResult InitializerValue; 2543 // FIXME: Check whether Initializer is a constant expression according 2544 // to C++0x [expr.const], rather than just whether it can be folded. 2545 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) && 2546 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) { 2547 // Constant! (Except for FIXME above.) 2548 llvm::APFloat FloatVal = InitializerValue.Val.getFloat(); 2549 // Convert the source value into the target type. 2550 bool ignored; 2551 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 2552 Ctx.getFloatTypeSemantics(ToType), 2553 llvm::APFloat::rmNearestTiesToEven, &ignored); 2554 // If there was no overflow, the source value is within the range of 2555 // values that can be represented. 2556 if (ConvertStatus & llvm::APFloat::opOverflow) { 2557 *isInitializerConstant = true; 2558 *ConstantValue = InitializerValue.Val; 2559 return true; 2560 } 2561 } else { 2562 *isInitializerConstant = false; 2563 return true; 2564 } 2565 } 2566 return false; 2567 2568 // * from an integer type or unscoped enumeration type to an integer type 2569 // that cannot represent all the values of the original type, except where 2570 // the source is a constant expression and the actual value after 2571 // conversion will fit into the target type and will produce the original 2572 // value when converted back to the original type. 2573 case ICK_Boolean_Conversion: // Bools are integers too. 2574 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 2575 // Boolean conversions can be from pointers and pointers to members 2576 // [conv.bool], and those aren't considered narrowing conversions. 2577 return false; 2578 } // Otherwise, fall through to the integral case. 2579 case ICK_Integral_Conversion: { 2580 assert(FromType->isIntegralOrUnscopedEnumerationType()); 2581 assert(ToType->isIntegralOrUnscopedEnumerationType()); 2582 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 2583 const unsigned FromWidth = Ctx.getIntWidth(FromType); 2584 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 2585 const unsigned ToWidth = Ctx.getIntWidth(ToType); 2586 2587 if (FromWidth > ToWidth || 2588 (FromWidth == ToWidth && FromSigned != ToSigned)) { 2589 // Not all values of FromType can be represented in ToType. 2590 llvm::APSInt InitializerValue; 2591 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 2592 *isInitializerConstant = true; 2593 *ConstantValue = APValue(InitializerValue); 2594 2595 // Add a bit to the InitializerValue so we don't have to worry about 2596 // signed vs. unsigned comparisons. 2597 InitializerValue = InitializerValue.extend( 2598 InitializerValue.getBitWidth() + 1); 2599 // Convert the initializer to and from the target width and signed-ness. 2600 llvm::APSInt ConvertedValue = InitializerValue; 2601 ConvertedValue = ConvertedValue.trunc(ToWidth); 2602 ConvertedValue.setIsSigned(ToSigned); 2603 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 2604 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 2605 // If the result is different, this was a narrowing conversion. 2606 return ConvertedValue != InitializerValue; 2607 } else { 2608 // Variables are always narrowings. 2609 *isInitializerConstant = false; 2610 return true; 2611 } 2612 } 2613 return false; 2614 } 2615 2616 default: 2617 // Other kinds of conversions are not narrowings. 2618 return false; 2619 } 2620} 2621 2622void 2623InitializationSequence 2624::AddAddressOverloadResolutionStep(FunctionDecl *Function, 2625 DeclAccessPair Found, 2626 bool HadMultipleCandidates) { 2627 Step S; 2628 S.Kind = SK_ResolveAddressOfOverloadedFunction; 2629 S.Type = Function->getType(); 2630 S.Function.HadMultipleCandidates = HadMultipleCandidates; 2631 S.Function.Function = Function; 2632 S.Function.FoundDecl = Found; 2633 Steps.push_back(S); 2634} 2635 2636void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 2637 ExprValueKind VK) { 2638 Step S; 2639 switch (VK) { 2640 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 2641 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 2642 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 2643 } 2644 S.Type = BaseType; 2645 Steps.push_back(S); 2646} 2647 2648void InitializationSequence::AddReferenceBindingStep(QualType T, 2649 bool BindingTemporary) { 2650 Step S; 2651 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2652 S.Type = T; 2653 Steps.push_back(S); 2654} 2655 2656void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 2657 Step S; 2658 S.Kind = SK_ExtraneousCopyToTemporary; 2659 S.Type = T; 2660 Steps.push_back(S); 2661} 2662 2663void 2664InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2665 DeclAccessPair FoundDecl, 2666 QualType T, 2667 bool HadMultipleCandidates) { 2668 Step S; 2669 S.Kind = SK_UserConversion; 2670 S.Type = T; 2671 S.Function.HadMultipleCandidates = HadMultipleCandidates; 2672 S.Function.Function = Function; 2673 S.Function.FoundDecl = FoundDecl; 2674 Steps.push_back(S); 2675} 2676 2677void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2678 ExprValueKind VK) { 2679 Step S; 2680 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 2681 switch (VK) { 2682 case VK_RValue: 2683 S.Kind = SK_QualificationConversionRValue; 2684 break; 2685 case VK_XValue: 2686 S.Kind = SK_QualificationConversionXValue; 2687 break; 2688 case VK_LValue: 2689 S.Kind = SK_QualificationConversionLValue; 2690 break; 2691 } 2692 S.Type = Ty; 2693 Steps.push_back(S); 2694} 2695 2696void InitializationSequence::AddConversionSequenceStep( 2697 const ImplicitConversionSequence &ICS, 2698 QualType T) { 2699 Step S; 2700 S.Kind = SK_ConversionSequence; 2701 S.Type = T; 2702 S.ICS = new ImplicitConversionSequence(ICS); 2703 Steps.push_back(S); 2704} 2705 2706void InitializationSequence::AddListInitializationStep(QualType T) { 2707 Step S; 2708 S.Kind = SK_ListInitialization; 2709 S.Type = T; 2710 Steps.push_back(S); 2711} 2712 2713void 2714InitializationSequence 2715::AddConstructorInitializationStep(CXXConstructorDecl *Constructor, 2716 AccessSpecifier Access, 2717 QualType T, 2718 bool HadMultipleCandidates, 2719 bool FromInitList) { 2720 Step S; 2721 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization; 2722 S.Type = T; 2723 S.Function.HadMultipleCandidates = HadMultipleCandidates; 2724 S.Function.Function = Constructor; 2725 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access); 2726 Steps.push_back(S); 2727} 2728 2729void InitializationSequence::AddZeroInitializationStep(QualType T) { 2730 Step S; 2731 S.Kind = SK_ZeroInitialization; 2732 S.Type = T; 2733 Steps.push_back(S); 2734} 2735 2736void InitializationSequence::AddCAssignmentStep(QualType T) { 2737 Step S; 2738 S.Kind = SK_CAssignment; 2739 S.Type = T; 2740 Steps.push_back(S); 2741} 2742 2743void InitializationSequence::AddStringInitStep(QualType T) { 2744 Step S; 2745 S.Kind = SK_StringInit; 2746 S.Type = T; 2747 Steps.push_back(S); 2748} 2749 2750void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 2751 Step S; 2752 S.Kind = SK_ObjCObjectConversion; 2753 S.Type = T; 2754 Steps.push_back(S); 2755} 2756 2757void InitializationSequence::AddArrayInitStep(QualType T) { 2758 Step S; 2759 S.Kind = SK_ArrayInit; 2760 S.Type = T; 2761 Steps.push_back(S); 2762} 2763 2764void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 2765 bool shouldCopy) { 2766 Step s; 2767 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 2768 : SK_PassByIndirectRestore); 2769 s.Type = type; 2770 Steps.push_back(s); 2771} 2772 2773void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 2774 Step S; 2775 S.Kind = SK_ProduceObjCObject; 2776 S.Type = T; 2777 Steps.push_back(S); 2778} 2779 2780void InitializationSequence::RewrapReferenceInitList(QualType T, 2781 InitListExpr *Syntactic) { 2782 assert(Syntactic->getNumInits() == 1 && 2783 "Can only rewrap trivial init lists."); 2784 Step S; 2785 S.Kind = SK_UnwrapInitList; 2786 S.Type = Syntactic->getInit(0)->getType(); 2787 Steps.insert(Steps.begin(), S); 2788 2789 S.Kind = SK_RewrapInitList; 2790 S.Type = T; 2791 S.WrappingSyntacticList = Syntactic; 2792 Steps.push_back(S); 2793} 2794 2795void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2796 OverloadingResult Result) { 2797 setSequenceKind(FailedSequence); 2798 this->Failure = Failure; 2799 this->FailedOverloadResult = Result; 2800} 2801 2802//===----------------------------------------------------------------------===// 2803// Attempt initialization 2804//===----------------------------------------------------------------------===// 2805 2806static void MaybeProduceObjCObject(Sema &S, 2807 InitializationSequence &Sequence, 2808 const InitializedEntity &Entity) { 2809 if (!S.getLangOptions().ObjCAutoRefCount) return; 2810 2811 /// When initializing a parameter, produce the value if it's marked 2812 /// __attribute__((ns_consumed)). 2813 if (Entity.getKind() == InitializedEntity::EK_Parameter) { 2814 if (!Entity.isParameterConsumed()) 2815 return; 2816 2817 assert(Entity.getType()->isObjCRetainableType() && 2818 "consuming an object of unretainable type?"); 2819 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2820 2821 /// When initializing a return value, if the return type is a 2822 /// retainable type, then returns need to immediately retain the 2823 /// object. If an autorelease is required, it will be done at the 2824 /// last instant. 2825 } else if (Entity.getKind() == InitializedEntity::EK_Result) { 2826 if (!Entity.getType()->isObjCRetainableType()) 2827 return; 2828 2829 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2830 } 2831} 2832 2833/// \brief When initializing from init list via constructor, deal with the 2834/// empty init list and std::initializer_list special cases. 2835/// 2836/// \return True if this was a special case, false otherwise. 2837static bool TryListConstructionSpecialCases(Sema &S, 2838 Expr **Args, unsigned NumArgs, 2839 CXXRecordDecl *DestRecordDecl, 2840 QualType DestType, 2841 InitializationSequence &Sequence) { 2842 // C++0x [dcl.init.list]p3: 2843 // List-initialization of an object of type T is defined as follows: 2844 // - If the initializer list has no elements and T is a class type with 2845 // a default constructor, the object is value-initialized. 2846 if (NumArgs == 0) { 2847 if (CXXConstructorDecl *DefaultConstructor = 2848 S.LookupDefaultConstructor(DestRecordDecl)) { 2849 if (DefaultConstructor->isDeleted() || 2850 S.isFunctionConsideredUnavailable(DefaultConstructor)) { 2851 // Fake an overload resolution failure. 2852 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2853 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor, 2854 DefaultConstructor->getAccess()); 2855 if (FunctionTemplateDecl *ConstructorTmpl = 2856 dyn_cast<FunctionTemplateDecl>(DefaultConstructor)) 2857 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2858 /*ExplicitArgs*/ 0, 2859 Args, NumArgs, CandidateSet, 2860 /*SuppressUserConversions*/ false); 2861 else 2862 S.AddOverloadCandidate(DefaultConstructor, FoundDecl, 2863 Args, NumArgs, CandidateSet, 2864 /*SuppressUserConversions*/ false); 2865 Sequence.SetOverloadFailure( 2866 InitializationSequence::FK_ListConstructorOverloadFailed, 2867 OR_Deleted); 2868 } else 2869 Sequence.AddConstructorInitializationStep(DefaultConstructor, 2870 DefaultConstructor->getAccess(), 2871 DestType, 2872 /*MultipleCandidates=*/false, 2873 /*FromInitList=*/true); 2874 return true; 2875 } 2876 } 2877 2878 // - Otherwise, if T is a specialization of std::initializer_list, [...] 2879 // FIXME: Implement. 2880 2881 // Not a special case. 2882 return false; 2883} 2884 2885/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2886/// enumerates the constructors of the initialized entity and performs overload 2887/// resolution to select the best. 2888/// If FromInitList is true, this is list-initialization of a non-aggregate 2889/// class type. 2890static void TryConstructorInitialization(Sema &S, 2891 const InitializedEntity &Entity, 2892 const InitializationKind &Kind, 2893 Expr **Args, unsigned NumArgs, 2894 QualType DestType, 2895 InitializationSequence &Sequence, 2896 bool FromInitList = false) { 2897 // Check constructor arguments for self reference. 2898 if (DeclaratorDecl *DD = Entity.getDecl()) 2899 // Parameters arguments are occassionially constructed with itself, 2900 // for instance, in recursive functions. Skip them. 2901 if (!isa<ParmVarDecl>(DD)) 2902 for (unsigned i = 0; i < NumArgs; ++i) 2903 S.CheckSelfReference(DD, Args[i]); 2904 2905 // Build the candidate set directly in the initialization sequence 2906 // structure, so that it will persist if we fail. 2907 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2908 CandidateSet.clear(); 2909 2910 // Determine whether we are allowed to call explicit constructors or 2911 // explicit conversion operators. 2912 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct || 2913 Kind.getKind() == InitializationKind::IK_Value || 2914 Kind.getKind() == InitializationKind::IK_Default); 2915 2916 // The type we're constructing needs to be complete. 2917 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 2918 Sequence.SetFailed(InitializationSequence::FK_Incomplete); 2919 } 2920 2921 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2922 assert(DestRecordType && "Constructor initialization requires record type"); 2923 CXXRecordDecl *DestRecordDecl 2924 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2925 2926 if (FromInitList && 2927 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl, 2928 DestType, Sequence)) 2929 return; 2930 2931 // - Otherwise, if T is a class type, constructors are considered. The 2932 // applicable constructors are enumerated, and the best one is chosen 2933 // through overload resolution. 2934 DeclContext::lookup_iterator Con, ConEnd; 2935 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 2936 Con != ConEnd; ++Con) { 2937 NamedDecl *D = *Con; 2938 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2939 bool SuppressUserConversions = false; 2940 2941 // Find the constructor (which may be a template). 2942 CXXConstructorDecl *Constructor = 0; 2943 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2944 if (ConstructorTmpl) 2945 Constructor = cast<CXXConstructorDecl>( 2946 ConstructorTmpl->getTemplatedDecl()); 2947 else { 2948 Constructor = cast<CXXConstructorDecl>(D); 2949 2950 // If we're performing copy initialization using a copy constructor, we 2951 // suppress user-defined conversions on the arguments. 2952 // FIXME: Move constructors? 2953 if (Kind.getKind() == InitializationKind::IK_Copy && 2954 Constructor->isCopyConstructor()) 2955 SuppressUserConversions = true; 2956 } 2957 2958 if (!Constructor->isInvalidDecl() && 2959 (AllowExplicit || !Constructor->isExplicit())) { 2960 if (ConstructorTmpl) 2961 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2962 /*ExplicitArgs*/ 0, 2963 Args, NumArgs, CandidateSet, 2964 SuppressUserConversions); 2965 else 2966 S.AddOverloadCandidate(Constructor, FoundDecl, 2967 Args, NumArgs, CandidateSet, 2968 SuppressUserConversions); 2969 } 2970 } 2971 2972 SourceLocation DeclLoc = Kind.getLocation(); 2973 2974 // Perform overload resolution. If it fails, return the failed result. 2975 OverloadCandidateSet::iterator Best; 2976 if (OverloadingResult Result 2977 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 2978 Sequence.SetOverloadFailure(FromInitList ? 2979 InitializationSequence::FK_ListConstructorOverloadFailed : 2980 InitializationSequence::FK_ConstructorOverloadFailed, 2981 Result); 2982 return; 2983 } 2984 2985 // C++0x [dcl.init]p6: 2986 // If a program calls for the default initialization of an object 2987 // of a const-qualified type T, T shall be a class type with a 2988 // user-provided default constructor. 2989 if (Kind.getKind() == InitializationKind::IK_Default && 2990 Entity.getType().isConstQualified() && 2991 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) { 2992 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2993 return; 2994 } 2995 2996 // Add the constructor initialization step. Any cv-qualification conversion is 2997 // subsumed by the initialization. 2998 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2999 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 3000 Sequence.AddConstructorInitializationStep(CtorDecl, 3001 Best->FoundDecl.getAccess(), 3002 DestType, HadMultipleCandidates, 3003 FromInitList); 3004} 3005 3006static bool 3007ResolveOverloadedFunctionForReferenceBinding(Sema &S, 3008 Expr *Initializer, 3009 QualType &SourceType, 3010 QualType &UnqualifiedSourceType, 3011 QualType UnqualifiedTargetType, 3012 InitializationSequence &Sequence) { 3013 if (S.Context.getCanonicalType(UnqualifiedSourceType) == 3014 S.Context.OverloadTy) { 3015 DeclAccessPair Found; 3016 bool HadMultipleCandidates = false; 3017 if (FunctionDecl *Fn 3018 = S.ResolveAddressOfOverloadedFunction(Initializer, 3019 UnqualifiedTargetType, 3020 false, Found, 3021 &HadMultipleCandidates)) { 3022 Sequence.AddAddressOverloadResolutionStep(Fn, Found, 3023 HadMultipleCandidates); 3024 SourceType = Fn->getType(); 3025 UnqualifiedSourceType = SourceType.getUnqualifiedType(); 3026 } else if (!UnqualifiedTargetType->isRecordType()) { 3027 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3028 return true; 3029 } 3030 } 3031 return false; 3032} 3033 3034static void TryReferenceInitializationCore(Sema &S, 3035 const InitializedEntity &Entity, 3036 const InitializationKind &Kind, 3037 Expr *Initializer, 3038 QualType cv1T1, QualType T1, 3039 Qualifiers T1Quals, 3040 QualType cv2T2, QualType T2, 3041 Qualifiers T2Quals, 3042 InitializationSequence &Sequence); 3043 3044static void TryListInitialization(Sema &S, 3045 const InitializedEntity &Entity, 3046 const InitializationKind &Kind, 3047 InitListExpr *InitList, 3048 InitializationSequence &Sequence); 3049 3050/// \brief Attempt list initialization of a reference. 3051static void TryReferenceListInitialization(Sema &S, 3052 const InitializedEntity &Entity, 3053 const InitializationKind &Kind, 3054 InitListExpr *InitList, 3055 InitializationSequence &Sequence) 3056{ 3057 // First, catch C++03 where this isn't possible. 3058 if (!S.getLangOptions().CPlusPlus0x) { 3059 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 3060 return; 3061 } 3062 3063 QualType DestType = Entity.getType(); 3064 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3065 Qualifiers T1Quals; 3066 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 3067 3068 // Reference initialization via an initializer list works thus: 3069 // If the initializer list consists of a single element that is 3070 // reference-related to the referenced type, bind directly to that element 3071 // (possibly creating temporaries). 3072 // Otherwise, initialize a temporary with the initializer list and 3073 // bind to that. 3074 if (InitList->getNumInits() == 1) { 3075 Expr *Initializer = InitList->getInit(0); 3076 QualType cv2T2 = Initializer->getType(); 3077 Qualifiers T2Quals; 3078 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 3079 3080 // If this fails, creating a temporary wouldn't work either. 3081 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 3082 T1, Sequence)) 3083 return; 3084 3085 SourceLocation DeclLoc = Initializer->getLocStart(); 3086 bool dummy1, dummy2, dummy3; 3087 Sema::ReferenceCompareResult RefRelationship 3088 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1, 3089 dummy2, dummy3); 3090 if (RefRelationship >= Sema::Ref_Related) { 3091 // Try to bind the reference here. 3092 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 3093 T1Quals, cv2T2, T2, T2Quals, Sequence); 3094 if (Sequence) 3095 Sequence.RewrapReferenceInitList(cv1T1, InitList); 3096 return; 3097 } 3098 } 3099 3100 // Not reference-related. Create a temporary and bind to that. 3101 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 3102 3103 TryListInitialization(S, TempEntity, Kind, InitList, Sequence); 3104 if (Sequence) { 3105 if (DestType->isRValueReferenceType() || 3106 (T1Quals.hasConst() && !T1Quals.hasVolatile())) 3107 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 3108 else 3109 Sequence.SetFailed( 3110 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 3111 } 3112} 3113 3114/// \brief Attempt list initialization (C++0x [dcl.init.list]) 3115static void TryListInitialization(Sema &S, 3116 const InitializedEntity &Entity, 3117 const InitializationKind &Kind, 3118 InitListExpr *InitList, 3119 InitializationSequence &Sequence) { 3120 QualType DestType = Entity.getType(); 3121 3122 // C++ doesn't allow scalar initialization with more than one argument. 3123 // But C99 complex numbers are scalars and it makes sense there. 3124 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() && 3125 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 3126 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 3127 return; 3128 } 3129 if (DestType->isReferenceType()) { 3130 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence); 3131 return; 3132 } 3133 if (DestType->isRecordType() && !DestType->isAggregateType()) { 3134 if (S.getLangOptions().CPlusPlus0x) 3135 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(), 3136 InitList->getNumInits(), DestType, Sequence, 3137 /*FromInitList=*/true); 3138 else 3139 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 3140 return; 3141 } 3142 3143 InitListChecker CheckInitList(S, Entity, InitList, 3144 DestType, /*VerifyOnly=*/true, 3145 Kind.getKind() != InitializationKind::IK_Direct || 3146 !S.getLangOptions().CPlusPlus0x); 3147 if (CheckInitList.HadError()) { 3148 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 3149 return; 3150 } 3151 3152 // Add the list initialization step with the built init list. 3153 Sequence.AddListInitializationStep(DestType); 3154} 3155 3156/// \brief Try a reference initialization that involves calling a conversion 3157/// function. 3158static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 3159 const InitializedEntity &Entity, 3160 const InitializationKind &Kind, 3161 Expr *Initializer, 3162 bool AllowRValues, 3163 InitializationSequence &Sequence) { 3164 QualType DestType = Entity.getType(); 3165 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3166 QualType T1 = cv1T1.getUnqualifiedType(); 3167 QualType cv2T2 = Initializer->getType(); 3168 QualType T2 = cv2T2.getUnqualifiedType(); 3169 3170 bool DerivedToBase; 3171 bool ObjCConversion; 3172 bool ObjCLifetimeConversion; 3173 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 3174 T1, T2, DerivedToBase, 3175 ObjCConversion, 3176 ObjCLifetimeConversion) && 3177 "Must have incompatible references when binding via conversion"); 3178 (void)DerivedToBase; 3179 (void)ObjCConversion; 3180 (void)ObjCLifetimeConversion; 3181 3182 // Build the candidate set directly in the initialization sequence 3183 // structure, so that it will persist if we fail. 3184 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3185 CandidateSet.clear(); 3186 3187 // Determine whether we are allowed to call explicit constructors or 3188 // explicit conversion operators. 3189 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 3190 3191 const RecordType *T1RecordType = 0; 3192 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 3193 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) { 3194 // The type we're converting to is a class type. Enumerate its constructors 3195 // to see if there is a suitable conversion. 3196 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 3197 3198 DeclContext::lookup_iterator Con, ConEnd; 3199 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl); 3200 Con != ConEnd; ++Con) { 3201 NamedDecl *D = *Con; 3202 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3203 3204 // Find the constructor (which may be a template). 3205 CXXConstructorDecl *Constructor = 0; 3206 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 3207 if (ConstructorTmpl) 3208 Constructor = cast<CXXConstructorDecl>( 3209 ConstructorTmpl->getTemplatedDecl()); 3210 else 3211 Constructor = cast<CXXConstructorDecl>(D); 3212 3213 if (!Constructor->isInvalidDecl() && 3214 Constructor->isConvertingConstructor(AllowExplicit)) { 3215 if (ConstructorTmpl) 3216 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3217 /*ExplicitArgs*/ 0, 3218 &Initializer, 1, CandidateSet, 3219 /*SuppressUserConversions=*/true); 3220 else 3221 S.AddOverloadCandidate(Constructor, FoundDecl, 3222 &Initializer, 1, CandidateSet, 3223 /*SuppressUserConversions=*/true); 3224 } 3225 } 3226 } 3227 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 3228 return OR_No_Viable_Function; 3229 3230 const RecordType *T2RecordType = 0; 3231 if ((T2RecordType = T2->getAs<RecordType>()) && 3232 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) { 3233 // The type we're converting from is a class type, enumerate its conversion 3234 // functions. 3235 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 3236 3237 const UnresolvedSetImpl *Conversions 3238 = T2RecordDecl->getVisibleConversionFunctions(); 3239 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 3240 E = Conversions->end(); I != E; ++I) { 3241 NamedDecl *D = *I; 3242 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3243 if (isa<UsingShadowDecl>(D)) 3244 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3245 3246 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3247 CXXConversionDecl *Conv; 3248 if (ConvTemplate) 3249 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3250 else 3251 Conv = cast<CXXConversionDecl>(D); 3252 3253 // If the conversion function doesn't return a reference type, 3254 // it can't be considered for this conversion unless we're allowed to 3255 // consider rvalues. 3256 // FIXME: Do we need to make sure that we only consider conversion 3257 // candidates with reference-compatible results? That might be needed to 3258 // break recursion. 3259 if ((AllowExplicit || !Conv->isExplicit()) && 3260 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 3261 if (ConvTemplate) 3262 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 3263 ActingDC, Initializer, 3264 DestType, CandidateSet); 3265 else 3266 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 3267 Initializer, DestType, CandidateSet); 3268 } 3269 } 3270 } 3271 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 3272 return OR_No_Viable_Function; 3273 3274 SourceLocation DeclLoc = Initializer->getLocStart(); 3275 3276 // Perform overload resolution. If it fails, return the failed result. 3277 OverloadCandidateSet::iterator Best; 3278 if (OverloadingResult Result 3279 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) 3280 return Result; 3281 3282 FunctionDecl *Function = Best->Function; 3283 3284 // This is the overload that will actually be used for the initialization, so 3285 // mark it as used. 3286 S.MarkDeclarationReferenced(DeclLoc, Function); 3287 3288 // Compute the returned type of the conversion. 3289 if (isa<CXXConversionDecl>(Function)) 3290 T2 = Function->getResultType(); 3291 else 3292 T2 = cv1T1; 3293 3294 // Add the user-defined conversion step. 3295 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3296 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 3297 T2.getNonLValueExprType(S.Context), 3298 HadMultipleCandidates); 3299 3300 // Determine whether we need to perform derived-to-base or 3301 // cv-qualification adjustments. 3302 ExprValueKind VK = VK_RValue; 3303 if (T2->isLValueReferenceType()) 3304 VK = VK_LValue; 3305 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>()) 3306 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 3307 3308 bool NewDerivedToBase = false; 3309 bool NewObjCConversion = false; 3310 bool NewObjCLifetimeConversion = false; 3311 Sema::ReferenceCompareResult NewRefRelationship 3312 = S.CompareReferenceRelationship(DeclLoc, T1, 3313 T2.getNonLValueExprType(S.Context), 3314 NewDerivedToBase, NewObjCConversion, 3315 NewObjCLifetimeConversion); 3316 if (NewRefRelationship == Sema::Ref_Incompatible) { 3317 // If the type we've converted to is not reference-related to the 3318 // type we're looking for, then there is another conversion step 3319 // we need to perform to produce a temporary of the right type 3320 // that we'll be binding to. 3321 ImplicitConversionSequence ICS; 3322 ICS.setStandard(); 3323 ICS.Standard = Best->FinalConversion; 3324 T2 = ICS.Standard.getToType(2); 3325 Sequence.AddConversionSequenceStep(ICS, T2); 3326 } else if (NewDerivedToBase) 3327 Sequence.AddDerivedToBaseCastStep( 3328 S.Context.getQualifiedType(T1, 3329 T2.getNonReferenceType().getQualifiers()), 3330 VK); 3331 else if (NewObjCConversion) 3332 Sequence.AddObjCObjectConversionStep( 3333 S.Context.getQualifiedType(T1, 3334 T2.getNonReferenceType().getQualifiers())); 3335 3336 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 3337 Sequence.AddQualificationConversionStep(cv1T1, VK); 3338 3339 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 3340 return OR_Success; 3341} 3342 3343static void CheckCXX98CompatAccessibleCopy(Sema &S, 3344 const InitializedEntity &Entity, 3345 Expr *CurInitExpr); 3346 3347/// \brief Attempt reference initialization (C++0x [dcl.init.ref]) 3348static void TryReferenceInitialization(Sema &S, 3349 const InitializedEntity &Entity, 3350 const InitializationKind &Kind, 3351 Expr *Initializer, 3352 InitializationSequence &Sequence) { 3353 QualType DestType = Entity.getType(); 3354 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3355 Qualifiers T1Quals; 3356 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 3357 QualType cv2T2 = Initializer->getType(); 3358 Qualifiers T2Quals; 3359 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 3360 3361 // If the initializer is the address of an overloaded function, try 3362 // to resolve the overloaded function. If all goes well, T2 is the 3363 // type of the resulting function. 3364 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 3365 T1, Sequence)) 3366 return; 3367 3368 // Delegate everything else to a subfunction. 3369 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 3370 T1Quals, cv2T2, T2, T2Quals, Sequence); 3371} 3372 3373/// \brief Reference initialization without resolving overloaded functions. 3374static void TryReferenceInitializationCore(Sema &S, 3375 const InitializedEntity &Entity, 3376 const InitializationKind &Kind, 3377 Expr *Initializer, 3378 QualType cv1T1, QualType T1, 3379 Qualifiers T1Quals, 3380 QualType cv2T2, QualType T2, 3381 Qualifiers T2Quals, 3382 InitializationSequence &Sequence) { 3383 QualType DestType = Entity.getType(); 3384 SourceLocation DeclLoc = Initializer->getLocStart(); 3385 // Compute some basic properties of the types and the initializer. 3386 bool isLValueRef = DestType->isLValueReferenceType(); 3387 bool isRValueRef = !isLValueRef; 3388 bool DerivedToBase = false; 3389 bool ObjCConversion = false; 3390 bool ObjCLifetimeConversion = false; 3391 Expr::Classification InitCategory = Initializer->Classify(S.Context); 3392 Sema::ReferenceCompareResult RefRelationship 3393 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, 3394 ObjCConversion, ObjCLifetimeConversion); 3395 3396 // C++0x [dcl.init.ref]p5: 3397 // A reference to type "cv1 T1" is initialized by an expression of type 3398 // "cv2 T2" as follows: 3399 // 3400 // - If the reference is an lvalue reference and the initializer 3401 // expression 3402 // Note the analogous bullet points for rvlaue refs to functions. Because 3403 // there are no function rvalues in C++, rvalue refs to functions are treated 3404 // like lvalue refs. 3405 OverloadingResult ConvOvlResult = OR_Success; 3406 bool T1Function = T1->isFunctionType(); 3407 if (isLValueRef || T1Function) { 3408 if (InitCategory.isLValue() && 3409 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 3410 (Kind.isCStyleOrFunctionalCast() && 3411 RefRelationship == Sema::Ref_Related))) { 3412 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 3413 // reference-compatible with "cv2 T2," or 3414 // 3415 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a 3416 // bit-field when we're determining whether the reference initialization 3417 // can occur. However, we do pay attention to whether it is a bit-field 3418 // to decide whether we're actually binding to a temporary created from 3419 // the bit-field. 3420 if (DerivedToBase) 3421 Sequence.AddDerivedToBaseCastStep( 3422 S.Context.getQualifiedType(T1, T2Quals), 3423 VK_LValue); 3424 else if (ObjCConversion) 3425 Sequence.AddObjCObjectConversionStep( 3426 S.Context.getQualifiedType(T1, T2Quals)); 3427 3428 if (T1Quals != T2Quals) 3429 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue); 3430 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() && 3431 (Initializer->getBitField() || Initializer->refersToVectorElement()); 3432 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary); 3433 return; 3434 } 3435 3436 // - has a class type (i.e., T2 is a class type), where T1 is not 3437 // reference-related to T2, and can be implicitly converted to an 3438 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 3439 // with "cv3 T3" (this conversion is selected by enumerating the 3440 // applicable conversion functions (13.3.1.6) and choosing the best 3441 // one through overload resolution (13.3)), 3442 // If we have an rvalue ref to function type here, the rhs must be 3443 // an rvalue. 3444 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 3445 (isLValueRef || InitCategory.isRValue())) { 3446 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 3447 Initializer, 3448 /*AllowRValues=*/isRValueRef, 3449 Sequence); 3450 if (ConvOvlResult == OR_Success) 3451 return; 3452 if (ConvOvlResult != OR_No_Viable_Function) { 3453 Sequence.SetOverloadFailure( 3454 InitializationSequence::FK_ReferenceInitOverloadFailed, 3455 ConvOvlResult); 3456 } 3457 } 3458 } 3459 3460 // - Otherwise, the reference shall be an lvalue reference to a 3461 // non-volatile const type (i.e., cv1 shall be const), or the reference 3462 // shall be an rvalue reference. 3463 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) { 3464 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 3465 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3466 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 3467 Sequence.SetOverloadFailure( 3468 InitializationSequence::FK_ReferenceInitOverloadFailed, 3469 ConvOvlResult); 3470 else 3471 Sequence.SetFailed(InitCategory.isLValue() 3472 ? (RefRelationship == Sema::Ref_Related 3473 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 3474 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 3475 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 3476 3477 return; 3478 } 3479 3480 // - If the initializer expression 3481 // - is an xvalue, class prvalue, array prvalue, or function lvalue and 3482 // "cv1 T1" is reference-compatible with "cv2 T2" 3483 // Note: functions are handled below. 3484 if (!T1Function && 3485 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 3486 (Kind.isCStyleOrFunctionalCast() && 3487 RefRelationship == Sema::Ref_Related)) && 3488 (InitCategory.isXValue() || 3489 (InitCategory.isPRValue() && T2->isRecordType()) || 3490 (InitCategory.isPRValue() && T2->isArrayType()))) { 3491 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue; 3492 if (InitCategory.isPRValue() && T2->isRecordType()) { 3493 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 3494 // compiler the freedom to perform a copy here or bind to the 3495 // object, while C++0x requires that we bind directly to the 3496 // object. Hence, we always bind to the object without making an 3497 // extra copy. However, in C++03 requires that we check for the 3498 // presence of a suitable copy constructor: 3499 // 3500 // The constructor that would be used to make the copy shall 3501 // be callable whether or not the copy is actually done. 3502 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt) 3503 Sequence.AddExtraneousCopyToTemporary(cv2T2); 3504 else if (S.getLangOptions().CPlusPlus0x) 3505 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 3506 } 3507 3508 if (DerivedToBase) 3509 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals), 3510 ValueKind); 3511 else if (ObjCConversion) 3512 Sequence.AddObjCObjectConversionStep( 3513 S.Context.getQualifiedType(T1, T2Quals)); 3514 3515 if (T1Quals != T2Quals) 3516 Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 3517 Sequence.AddReferenceBindingStep(cv1T1, 3518 /*bindingTemporary=*/InitCategory.isPRValue()); 3519 return; 3520 } 3521 3522 // - has a class type (i.e., T2 is a class type), where T1 is not 3523 // reference-related to T2, and can be implicitly converted to an 3524 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 3525 // where "cv1 T1" is reference-compatible with "cv3 T3", 3526 if (T2->isRecordType()) { 3527 if (RefRelationship == Sema::Ref_Incompatible) { 3528 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 3529 Kind, Initializer, 3530 /*AllowRValues=*/true, 3531 Sequence); 3532 if (ConvOvlResult) 3533 Sequence.SetOverloadFailure( 3534 InitializationSequence::FK_ReferenceInitOverloadFailed, 3535 ConvOvlResult); 3536 3537 return; 3538 } 3539 3540 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 3541 return; 3542 } 3543 3544 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 3545 // from the initializer expression using the rules for a non-reference 3546 // copy initialization (8.5). The reference is then bound to the 3547 // temporary. [...] 3548 3549 // Determine whether we are allowed to call explicit constructors or 3550 // explicit conversion operators. 3551 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 3552 3553 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 3554 3555 ImplicitConversionSequence ICS 3556 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 3557 /*SuppressUserConversions*/ false, 3558 AllowExplicit, 3559 /*FIXME:InOverloadResolution=*/false, 3560 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 3561 /*AllowObjCWritebackConversion=*/false); 3562 3563 if (ICS.isBad()) { 3564 // FIXME: Use the conversion function set stored in ICS to turn 3565 // this into an overloading ambiguity diagnostic. However, we need 3566 // to keep that set as an OverloadCandidateSet rather than as some 3567 // other kind of set. 3568 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 3569 Sequence.SetOverloadFailure( 3570 InitializationSequence::FK_ReferenceInitOverloadFailed, 3571 ConvOvlResult); 3572 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 3573 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3574 else 3575 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 3576 return; 3577 } else { 3578 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 3579 } 3580 3581 // [...] If T1 is reference-related to T2, cv1 must be the 3582 // same cv-qualification as, or greater cv-qualification 3583 // than, cv2; otherwise, the program is ill-formed. 3584 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 3585 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 3586 if (RefRelationship == Sema::Ref_Related && 3587 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { 3588 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 3589 return; 3590 } 3591 3592 // [...] If T1 is reference-related to T2 and the reference is an rvalue 3593 // reference, the initializer expression shall not be an lvalue. 3594 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 3595 InitCategory.isLValue()) { 3596 Sequence.SetFailed( 3597 InitializationSequence::FK_RValueReferenceBindingToLValue); 3598 return; 3599 } 3600 3601 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 3602 return; 3603} 3604 3605/// \brief Attempt character array initialization from a string literal 3606/// (C++ [dcl.init.string], C99 6.7.8). 3607static void TryStringLiteralInitialization(Sema &S, 3608 const InitializedEntity &Entity, 3609 const InitializationKind &Kind, 3610 Expr *Initializer, 3611 InitializationSequence &Sequence) { 3612 Sequence.AddStringInitStep(Entity.getType()); 3613} 3614 3615/// \brief Attempt value initialization (C++ [dcl.init]p7). 3616static void TryValueInitialization(Sema &S, 3617 const InitializedEntity &Entity, 3618 const InitializationKind &Kind, 3619 InitializationSequence &Sequence) { 3620 // C++ [dcl.init]p5: 3621 // 3622 // To value-initialize an object of type T means: 3623 QualType T = Entity.getType(); 3624 3625 // -- if T is an array type, then each element is value-initialized; 3626 while (const ArrayType *AT = S.Context.getAsArrayType(T)) 3627 T = AT->getElementType(); 3628 3629 if (const RecordType *RT = T->getAs<RecordType>()) { 3630 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3631 // -- if T is a class type (clause 9) with a user-declared 3632 // constructor (12.1), then the default constructor for T is 3633 // called (and the initialization is ill-formed if T has no 3634 // accessible default constructor); 3635 // 3636 // FIXME: we really want to refer to a single subobject of the array, 3637 // but Entity doesn't have a way to capture that (yet). 3638 if (ClassDecl->hasUserDeclaredConstructor()) 3639 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 3640 3641 // -- if T is a (possibly cv-qualified) non-union class type 3642 // without a user-provided constructor, then the object is 3643 // zero-initialized and, if T's implicitly-declared default 3644 // constructor is non-trivial, that constructor is called. 3645 if ((ClassDecl->getTagKind() == TTK_Class || 3646 ClassDecl->getTagKind() == TTK_Struct)) { 3647 Sequence.AddZeroInitializationStep(Entity.getType()); 3648 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 3649 } 3650 } 3651 } 3652 3653 Sequence.AddZeroInitializationStep(Entity.getType()); 3654} 3655 3656/// \brief Attempt default initialization (C++ [dcl.init]p6). 3657static void TryDefaultInitialization(Sema &S, 3658 const InitializedEntity &Entity, 3659 const InitializationKind &Kind, 3660 InitializationSequence &Sequence) { 3661 assert(Kind.getKind() == InitializationKind::IK_Default); 3662 3663 // C++ [dcl.init]p6: 3664 // To default-initialize an object of type T means: 3665 // - if T is an array type, each element is default-initialized; 3666 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 3667 3668 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 3669 // constructor for T is called (and the initialization is ill-formed if 3670 // T has no accessible default constructor); 3671 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) { 3672 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence); 3673 return; 3674 } 3675 3676 // - otherwise, no initialization is performed. 3677 3678 // If a program calls for the default initialization of an object of 3679 // a const-qualified type T, T shall be a class type with a user-provided 3680 // default constructor. 3681 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) { 3682 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 3683 return; 3684 } 3685 3686 // If the destination type has a lifetime property, zero-initialize it. 3687 if (DestType.getQualifiers().hasObjCLifetime()) { 3688 Sequence.AddZeroInitializationStep(Entity.getType()); 3689 return; 3690 } 3691} 3692 3693/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 3694/// which enumerates all conversion functions and performs overload resolution 3695/// to select the best. 3696static void TryUserDefinedConversion(Sema &S, 3697 const InitializedEntity &Entity, 3698 const InitializationKind &Kind, 3699 Expr *Initializer, 3700 InitializationSequence &Sequence) { 3701 QualType DestType = Entity.getType(); 3702 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 3703 QualType SourceType = Initializer->getType(); 3704 assert((DestType->isRecordType() || SourceType->isRecordType()) && 3705 "Must have a class type to perform a user-defined conversion"); 3706 3707 // Build the candidate set directly in the initialization sequence 3708 // structure, so that it will persist if we fail. 3709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3710 CandidateSet.clear(); 3711 3712 // Determine whether we are allowed to call explicit constructors or 3713 // explicit conversion operators. 3714 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 3715 3716 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 3717 // The type we're converting to is a class type. Enumerate its constructors 3718 // to see if there is a suitable conversion. 3719 CXXRecordDecl *DestRecordDecl 3720 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 3721 3722 // Try to complete the type we're converting to. 3723 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 3724 DeclContext::lookup_iterator Con, ConEnd; 3725 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 3726 Con != ConEnd; ++Con) { 3727 NamedDecl *D = *Con; 3728 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3729 3730 // Find the constructor (which may be a template). 3731 CXXConstructorDecl *Constructor = 0; 3732 FunctionTemplateDecl *ConstructorTmpl 3733 = dyn_cast<FunctionTemplateDecl>(D); 3734 if (ConstructorTmpl) 3735 Constructor = cast<CXXConstructorDecl>( 3736 ConstructorTmpl->getTemplatedDecl()); 3737 else 3738 Constructor = cast<CXXConstructorDecl>(D); 3739 3740 if (!Constructor->isInvalidDecl() && 3741 Constructor->isConvertingConstructor(AllowExplicit)) { 3742 if (ConstructorTmpl) 3743 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3744 /*ExplicitArgs*/ 0, 3745 &Initializer, 1, CandidateSet, 3746 /*SuppressUserConversions=*/true); 3747 else 3748 S.AddOverloadCandidate(Constructor, FoundDecl, 3749 &Initializer, 1, CandidateSet, 3750 /*SuppressUserConversions=*/true); 3751 } 3752 } 3753 } 3754 } 3755 3756 SourceLocation DeclLoc = Initializer->getLocStart(); 3757 3758 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 3759 // The type we're converting from is a class type, enumerate its conversion 3760 // functions. 3761 3762 // We can only enumerate the conversion functions for a complete type; if 3763 // the type isn't complete, simply skip this step. 3764 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) { 3765 CXXRecordDecl *SourceRecordDecl 3766 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 3767 3768 const UnresolvedSetImpl *Conversions 3769 = SourceRecordDecl->getVisibleConversionFunctions(); 3770 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 3771 E = Conversions->end(); 3772 I != E; ++I) { 3773 NamedDecl *D = *I; 3774 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3775 if (isa<UsingShadowDecl>(D)) 3776 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3777 3778 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3779 CXXConversionDecl *Conv; 3780 if (ConvTemplate) 3781 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3782 else 3783 Conv = cast<CXXConversionDecl>(D); 3784 3785 if (AllowExplicit || !Conv->isExplicit()) { 3786 if (ConvTemplate) 3787 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 3788 ActingDC, Initializer, DestType, 3789 CandidateSet); 3790 else 3791 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 3792 Initializer, DestType, CandidateSet); 3793 } 3794 } 3795 } 3796 } 3797 3798 // Perform overload resolution. If it fails, return the failed result. 3799 OverloadCandidateSet::iterator Best; 3800 if (OverloadingResult Result 3801 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3802 Sequence.SetOverloadFailure( 3803 InitializationSequence::FK_UserConversionOverloadFailed, 3804 Result); 3805 return; 3806 } 3807 3808 FunctionDecl *Function = Best->Function; 3809 S.MarkDeclarationReferenced(DeclLoc, Function); 3810 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3811 3812 if (isa<CXXConstructorDecl>(Function)) { 3813 // Add the user-defined conversion step. Any cv-qualification conversion is 3814 // subsumed by the initialization. 3815 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType, 3816 HadMultipleCandidates); 3817 return; 3818 } 3819 3820 // Add the user-defined conversion step that calls the conversion function. 3821 QualType ConvType = Function->getCallResultType(); 3822 if (ConvType->getAs<RecordType>()) { 3823 // If we're converting to a class type, there may be an copy if 3824 // the resulting temporary object (possible to create an object of 3825 // a base class type). That copy is not a separate conversion, so 3826 // we just make a note of the actual destination type (possibly a 3827 // base class of the type returned by the conversion function) and 3828 // let the user-defined conversion step handle the conversion. 3829 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType, 3830 HadMultipleCandidates); 3831 return; 3832 } 3833 3834 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 3835 HadMultipleCandidates); 3836 3837 // If the conversion following the call to the conversion function 3838 // is interesting, add it as a separate step. 3839 if (Best->FinalConversion.First || Best->FinalConversion.Second || 3840 Best->FinalConversion.Third) { 3841 ImplicitConversionSequence ICS; 3842 ICS.setStandard(); 3843 ICS.Standard = Best->FinalConversion; 3844 Sequence.AddConversionSequenceStep(ICS, DestType); 3845 } 3846} 3847 3848/// The non-zero enum values here are indexes into diagnostic alternatives. 3849enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 3850 3851/// Determines whether this expression is an acceptable ICR source. 3852static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 3853 bool isAddressOf) { 3854 // Skip parens. 3855 e = e->IgnoreParens(); 3856 3857 // Skip address-of nodes. 3858 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 3859 if (op->getOpcode() == UO_AddrOf) 3860 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true); 3861 3862 // Skip certain casts. 3863 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 3864 switch (ce->getCastKind()) { 3865 case CK_Dependent: 3866 case CK_BitCast: 3867 case CK_LValueBitCast: 3868 case CK_NoOp: 3869 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf); 3870 3871 case CK_ArrayToPointerDecay: 3872 return IIK_nonscalar; 3873 3874 case CK_NullToPointer: 3875 return IIK_okay; 3876 3877 default: 3878 break; 3879 } 3880 3881 // If we have a declaration reference, it had better be a local variable. 3882 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) { 3883 if (!isAddressOf) return IIK_nonlocal; 3884 3885 VarDecl *var; 3886 if (isa<DeclRefExpr>(e)) { 3887 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 3888 if (!var) return IIK_nonlocal; 3889 } else { 3890 var = cast<BlockDeclRefExpr>(e)->getDecl(); 3891 } 3892 3893 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 3894 3895 // If we have a conditional operator, check both sides. 3896 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 3897 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf)) 3898 return iik; 3899 3900 return isInvalidICRSource(C, cond->getRHS(), isAddressOf); 3901 3902 // These are never scalar. 3903 } else if (isa<ArraySubscriptExpr>(e)) { 3904 return IIK_nonscalar; 3905 3906 // Otherwise, it needs to be a null pointer constant. 3907 } else { 3908 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 3909 ? IIK_okay : IIK_nonlocal); 3910 } 3911 3912 return IIK_nonlocal; 3913} 3914 3915/// Check whether the given expression is a valid operand for an 3916/// indirect copy/restore. 3917static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 3918 assert(src->isRValue()); 3919 3920 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false); 3921 if (iik == IIK_okay) return; 3922 3923 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 3924 << ((unsigned) iik - 1) // shift index into diagnostic explanations 3925 << src->getSourceRange(); 3926} 3927 3928/// \brief Determine whether we have compatible array types for the 3929/// purposes of GNU by-copy array initialization. 3930static bool hasCompatibleArrayTypes(ASTContext &Context, 3931 const ArrayType *Dest, 3932 const ArrayType *Source) { 3933 // If the source and destination array types are equivalent, we're 3934 // done. 3935 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 3936 return true; 3937 3938 // Make sure that the element types are the same. 3939 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 3940 return false; 3941 3942 // The only mismatch we allow is when the destination is an 3943 // incomplete array type and the source is a constant array type. 3944 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 3945} 3946 3947static bool tryObjCWritebackConversion(Sema &S, 3948 InitializationSequence &Sequence, 3949 const InitializedEntity &Entity, 3950 Expr *Initializer) { 3951 bool ArrayDecay = false; 3952 QualType ArgType = Initializer->getType(); 3953 QualType ArgPointee; 3954 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 3955 ArrayDecay = true; 3956 ArgPointee = ArgArrayType->getElementType(); 3957 ArgType = S.Context.getPointerType(ArgPointee); 3958 } 3959 3960 // Handle write-back conversion. 3961 QualType ConvertedArgType; 3962 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 3963 ConvertedArgType)) 3964 return false; 3965 3966 // We should copy unless we're passing to an argument explicitly 3967 // marked 'out'. 3968 bool ShouldCopy = true; 3969 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 3970 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 3971 3972 // Do we need an lvalue conversion? 3973 if (ArrayDecay || Initializer->isGLValue()) { 3974 ImplicitConversionSequence ICS; 3975 ICS.setStandard(); 3976 ICS.Standard.setAsIdentityConversion(); 3977 3978 QualType ResultType; 3979 if (ArrayDecay) { 3980 ICS.Standard.First = ICK_Array_To_Pointer; 3981 ResultType = S.Context.getPointerType(ArgPointee); 3982 } else { 3983 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 3984 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 3985 } 3986 3987 Sequence.AddConversionSequenceStep(ICS, ResultType); 3988 } 3989 3990 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 3991 return true; 3992} 3993 3994InitializationSequence::InitializationSequence(Sema &S, 3995 const InitializedEntity &Entity, 3996 const InitializationKind &Kind, 3997 Expr **Args, 3998 unsigned NumArgs) 3999 : FailedCandidateSet(Kind.getLocation()) { 4000 ASTContext &Context = S.Context; 4001 4002 // C++0x [dcl.init]p16: 4003 // The semantics of initializers are as follows. The destination type is 4004 // the type of the object or reference being initialized and the source 4005 // type is the type of the initializer expression. The source type is not 4006 // defined when the initializer is a braced-init-list or when it is a 4007 // parenthesized list of expressions. 4008 QualType DestType = Entity.getType(); 4009 4010 if (DestType->isDependentType() || 4011 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 4012 SequenceKind = DependentSequence; 4013 return; 4014 } 4015 4016 // Almost everything is a normal sequence. 4017 setSequenceKind(NormalSequence); 4018 4019 for (unsigned I = 0; I != NumArgs; ++I) 4020 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 4021 // FIXME: should we be doing this here? 4022 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 4023 if (result.isInvalid()) { 4024 SetFailed(FK_PlaceholderType); 4025 return; 4026 } 4027 Args[I] = result.take(); 4028 } 4029 4030 4031 QualType SourceType; 4032 Expr *Initializer = 0; 4033 if (NumArgs == 1) { 4034 Initializer = Args[0]; 4035 if (!isa<InitListExpr>(Initializer)) 4036 SourceType = Initializer->getType(); 4037 } 4038 4039 // - If the initializer is a braced-init-list, the object is 4040 // list-initialized (8.5.4). 4041 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 4042 TryListInitialization(S, Entity, Kind, InitList, *this); 4043 return; 4044 } 4045 4046 // - If the destination type is a reference type, see 8.5.3. 4047 if (DestType->isReferenceType()) { 4048 // C++0x [dcl.init.ref]p1: 4049 // A variable declared to be a T& or T&&, that is, "reference to type T" 4050 // (8.3.2), shall be initialized by an object, or function, of type T or 4051 // by an object that can be converted into a T. 4052 // (Therefore, multiple arguments are not permitted.) 4053 if (NumArgs != 1) 4054 SetFailed(FK_TooManyInitsForReference); 4055 else 4056 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 4057 return; 4058 } 4059 4060 // - If the initializer is (), the object is value-initialized. 4061 if (Kind.getKind() == InitializationKind::IK_Value || 4062 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) { 4063 TryValueInitialization(S, Entity, Kind, *this); 4064 return; 4065 } 4066 4067 // Handle default initialization. 4068 if (Kind.getKind() == InitializationKind::IK_Default) { 4069 TryDefaultInitialization(S, Entity, Kind, *this); 4070 return; 4071 } 4072 4073 // - If the destination type is an array of characters, an array of 4074 // char16_t, an array of char32_t, or an array of wchar_t, and the 4075 // initializer is a string literal, see 8.5.2. 4076 // - Otherwise, if the destination type is an array, the program is 4077 // ill-formed. 4078 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 4079 if (Initializer && isa<VariableArrayType>(DestAT)) { 4080 SetFailed(FK_VariableLengthArrayHasInitializer); 4081 return; 4082 } 4083 4084 if (Initializer && IsStringInit(Initializer, DestAT, Context)) { 4085 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 4086 return; 4087 } 4088 4089 // Note: as an GNU C extension, we allow initialization of an 4090 // array from a compound literal that creates an array of the same 4091 // type, so long as the initializer has no side effects. 4092 if (!S.getLangOptions().CPlusPlus && Initializer && 4093 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 4094 Initializer->getType()->isArrayType()) { 4095 const ArrayType *SourceAT 4096 = Context.getAsArrayType(Initializer->getType()); 4097 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 4098 SetFailed(FK_ArrayTypeMismatch); 4099 else if (Initializer->HasSideEffects(S.Context)) 4100 SetFailed(FK_NonConstantArrayInit); 4101 else { 4102 AddArrayInitStep(DestType); 4103 } 4104 } else if (DestAT->getElementType()->isAnyCharacterType()) 4105 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 4106 else 4107 SetFailed(FK_ArrayNeedsInitList); 4108 4109 return; 4110 } 4111 4112 // Determine whether we should consider writeback conversions for 4113 // Objective-C ARC. 4114 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount && 4115 Entity.getKind() == InitializedEntity::EK_Parameter; 4116 4117 // We're at the end of the line for C: it's either a write-back conversion 4118 // or it's a C assignment. There's no need to check anything else. 4119 if (!S.getLangOptions().CPlusPlus) { 4120 // If allowed, check whether this is an Objective-C writeback conversion. 4121 if (allowObjCWritebackConversion && 4122 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 4123 return; 4124 } 4125 4126 // Handle initialization in C 4127 AddCAssignmentStep(DestType); 4128 MaybeProduceObjCObject(S, *this, Entity); 4129 return; 4130 } 4131 4132 assert(S.getLangOptions().CPlusPlus); 4133 4134 // - If the destination type is a (possibly cv-qualified) class type: 4135 if (DestType->isRecordType()) { 4136 // - If the initialization is direct-initialization, or if it is 4137 // copy-initialization where the cv-unqualified version of the 4138 // source type is the same class as, or a derived class of, the 4139 // class of the destination, constructors are considered. [...] 4140 if (Kind.getKind() == InitializationKind::IK_Direct || 4141 (Kind.getKind() == InitializationKind::IK_Copy && 4142 (Context.hasSameUnqualifiedType(SourceType, DestType) || 4143 S.IsDerivedFrom(SourceType, DestType)))) 4144 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, 4145 Entity.getType(), *this); 4146 // - Otherwise (i.e., for the remaining copy-initialization cases), 4147 // user-defined conversion sequences that can convert from the source 4148 // type to the destination type or (when a conversion function is 4149 // used) to a derived class thereof are enumerated as described in 4150 // 13.3.1.4, and the best one is chosen through overload resolution 4151 // (13.3). 4152 else 4153 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 4154 return; 4155 } 4156 4157 if (NumArgs > 1) { 4158 SetFailed(FK_TooManyInitsForScalar); 4159 return; 4160 } 4161 assert(NumArgs == 1 && "Zero-argument case handled above"); 4162 4163 // - Otherwise, if the source type is a (possibly cv-qualified) class 4164 // type, conversion functions are considered. 4165 if (!SourceType.isNull() && SourceType->isRecordType()) { 4166 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 4167 MaybeProduceObjCObject(S, *this, Entity); 4168 return; 4169 } 4170 4171 // - Otherwise, the initial value of the object being initialized is the 4172 // (possibly converted) value of the initializer expression. Standard 4173 // conversions (Clause 4) will be used, if necessary, to convert the 4174 // initializer expression to the cv-unqualified version of the 4175 // destination type; no user-defined conversions are considered. 4176 4177 ImplicitConversionSequence ICS 4178 = S.TryImplicitConversion(Initializer, Entity.getType(), 4179 /*SuppressUserConversions*/true, 4180 /*AllowExplicitConversions*/ false, 4181 /*InOverloadResolution*/ false, 4182 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 4183 allowObjCWritebackConversion); 4184 4185 if (ICS.isStandard() && 4186 ICS.Standard.Second == ICK_Writeback_Conversion) { 4187 // Objective-C ARC writeback conversion. 4188 4189 // We should copy unless we're passing to an argument explicitly 4190 // marked 'out'. 4191 bool ShouldCopy = true; 4192 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 4193 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 4194 4195 // If there was an lvalue adjustment, add it as a separate conversion. 4196 if (ICS.Standard.First == ICK_Array_To_Pointer || 4197 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 4198 ImplicitConversionSequence LvalueICS; 4199 LvalueICS.setStandard(); 4200 LvalueICS.Standard.setAsIdentityConversion(); 4201 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 4202 LvalueICS.Standard.First = ICS.Standard.First; 4203 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 4204 } 4205 4206 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 4207 } else if (ICS.isBad()) { 4208 DeclAccessPair dap; 4209 if (Initializer->getType() == Context.OverloadTy && 4210 !S.ResolveAddressOfOverloadedFunction(Initializer 4211 , DestType, false, dap)) 4212 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4213 else 4214 SetFailed(InitializationSequence::FK_ConversionFailed); 4215 } else { 4216 AddConversionSequenceStep(ICS, Entity.getType()); 4217 4218 MaybeProduceObjCObject(S, *this, Entity); 4219 } 4220} 4221 4222InitializationSequence::~InitializationSequence() { 4223 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(), 4224 StepEnd = Steps.end(); 4225 Step != StepEnd; ++Step) 4226 Step->Destroy(); 4227} 4228 4229//===----------------------------------------------------------------------===// 4230// Perform initialization 4231//===----------------------------------------------------------------------===// 4232static Sema::AssignmentAction 4233getAssignmentAction(const InitializedEntity &Entity) { 4234 switch(Entity.getKind()) { 4235 case InitializedEntity::EK_Variable: 4236 case InitializedEntity::EK_New: 4237 case InitializedEntity::EK_Exception: 4238 case InitializedEntity::EK_Base: 4239 case InitializedEntity::EK_Delegating: 4240 return Sema::AA_Initializing; 4241 4242 case InitializedEntity::EK_Parameter: 4243 if (Entity.getDecl() && 4244 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 4245 return Sema::AA_Sending; 4246 4247 return Sema::AA_Passing; 4248 4249 case InitializedEntity::EK_Result: 4250 return Sema::AA_Returning; 4251 4252 case InitializedEntity::EK_Temporary: 4253 // FIXME: Can we tell apart casting vs. converting? 4254 return Sema::AA_Casting; 4255 4256 case InitializedEntity::EK_Member: 4257 case InitializedEntity::EK_ArrayElement: 4258 case InitializedEntity::EK_VectorElement: 4259 case InitializedEntity::EK_ComplexElement: 4260 case InitializedEntity::EK_BlockElement: 4261 return Sema::AA_Initializing; 4262 } 4263 4264 llvm_unreachable("Invalid EntityKind!"); 4265} 4266 4267/// \brief Whether we should binding a created object as a temporary when 4268/// initializing the given entity. 4269static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 4270 switch (Entity.getKind()) { 4271 case InitializedEntity::EK_ArrayElement: 4272 case InitializedEntity::EK_Member: 4273 case InitializedEntity::EK_Result: 4274 case InitializedEntity::EK_New: 4275 case InitializedEntity::EK_Variable: 4276 case InitializedEntity::EK_Base: 4277 case InitializedEntity::EK_Delegating: 4278 case InitializedEntity::EK_VectorElement: 4279 case InitializedEntity::EK_ComplexElement: 4280 case InitializedEntity::EK_Exception: 4281 case InitializedEntity::EK_BlockElement: 4282 return false; 4283 4284 case InitializedEntity::EK_Parameter: 4285 case InitializedEntity::EK_Temporary: 4286 return true; 4287 } 4288 4289 llvm_unreachable("missed an InitializedEntity kind?"); 4290} 4291 4292/// \brief Whether the given entity, when initialized with an object 4293/// created for that initialization, requires destruction. 4294static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 4295 switch (Entity.getKind()) { 4296 case InitializedEntity::EK_Member: 4297 case InitializedEntity::EK_Result: 4298 case InitializedEntity::EK_New: 4299 case InitializedEntity::EK_Base: 4300 case InitializedEntity::EK_Delegating: 4301 case InitializedEntity::EK_VectorElement: 4302 case InitializedEntity::EK_ComplexElement: 4303 case InitializedEntity::EK_BlockElement: 4304 return false; 4305 4306 case InitializedEntity::EK_Variable: 4307 case InitializedEntity::EK_Parameter: 4308 case InitializedEntity::EK_Temporary: 4309 case InitializedEntity::EK_ArrayElement: 4310 case InitializedEntity::EK_Exception: 4311 return true; 4312 } 4313 4314 llvm_unreachable("missed an InitializedEntity kind?"); 4315} 4316 4317/// \brief Look for copy and move constructors and constructor templates, for 4318/// copying an object via direct-initialization (per C++11 [dcl.init]p16). 4319static void LookupCopyAndMoveConstructors(Sema &S, 4320 OverloadCandidateSet &CandidateSet, 4321 CXXRecordDecl *Class, 4322 Expr *CurInitExpr) { 4323 DeclContext::lookup_iterator Con, ConEnd; 4324 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class); 4325 Con != ConEnd; ++Con) { 4326 CXXConstructorDecl *Constructor = 0; 4327 4328 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) { 4329 // Handle copy/moveconstructors, only. 4330 if (!Constructor || Constructor->isInvalidDecl() || 4331 !Constructor->isCopyOrMoveConstructor() || 4332 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 4333 continue; 4334 4335 DeclAccessPair FoundDecl 4336 = DeclAccessPair::make(Constructor, Constructor->getAccess()); 4337 S.AddOverloadCandidate(Constructor, FoundDecl, 4338 &CurInitExpr, 1, CandidateSet); 4339 continue; 4340 } 4341 4342 // Handle constructor templates. 4343 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con); 4344 if (ConstructorTmpl->isInvalidDecl()) 4345 continue; 4346 4347 Constructor = cast<CXXConstructorDecl>( 4348 ConstructorTmpl->getTemplatedDecl()); 4349 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 4350 continue; 4351 4352 // FIXME: Do we need to limit this to copy-constructor-like 4353 // candidates? 4354 DeclAccessPair FoundDecl 4355 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess()); 4356 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0, 4357 &CurInitExpr, 1, CandidateSet, true); 4358 } 4359} 4360 4361/// \brief Get the location at which initialization diagnostics should appear. 4362static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 4363 Expr *Initializer) { 4364 switch (Entity.getKind()) { 4365 case InitializedEntity::EK_Result: 4366 return Entity.getReturnLoc(); 4367 4368 case InitializedEntity::EK_Exception: 4369 return Entity.getThrowLoc(); 4370 4371 case InitializedEntity::EK_Variable: 4372 return Entity.getDecl()->getLocation(); 4373 4374 case InitializedEntity::EK_ArrayElement: 4375 case InitializedEntity::EK_Member: 4376 case InitializedEntity::EK_Parameter: 4377 case InitializedEntity::EK_Temporary: 4378 case InitializedEntity::EK_New: 4379 case InitializedEntity::EK_Base: 4380 case InitializedEntity::EK_Delegating: 4381 case InitializedEntity::EK_VectorElement: 4382 case InitializedEntity::EK_ComplexElement: 4383 case InitializedEntity::EK_BlockElement: 4384 return Initializer->getLocStart(); 4385 } 4386 llvm_unreachable("missed an InitializedEntity kind?"); 4387} 4388 4389/// \brief Make a (potentially elidable) temporary copy of the object 4390/// provided by the given initializer by calling the appropriate copy 4391/// constructor. 4392/// 4393/// \param S The Sema object used for type-checking. 4394/// 4395/// \param T The type of the temporary object, which must either be 4396/// the type of the initializer expression or a superclass thereof. 4397/// 4398/// \param Enter The entity being initialized. 4399/// 4400/// \param CurInit The initializer expression. 4401/// 4402/// \param IsExtraneousCopy Whether this is an "extraneous" copy that 4403/// is permitted in C++03 (but not C++0x) when binding a reference to 4404/// an rvalue. 4405/// 4406/// \returns An expression that copies the initializer expression into 4407/// a temporary object, or an error expression if a copy could not be 4408/// created. 4409static ExprResult CopyObject(Sema &S, 4410 QualType T, 4411 const InitializedEntity &Entity, 4412 ExprResult CurInit, 4413 bool IsExtraneousCopy) { 4414 // Determine which class type we're copying to. 4415 Expr *CurInitExpr = (Expr *)CurInit.get(); 4416 CXXRecordDecl *Class = 0; 4417 if (const RecordType *Record = T->getAs<RecordType>()) 4418 Class = cast<CXXRecordDecl>(Record->getDecl()); 4419 if (!Class) 4420 return move(CurInit); 4421 4422 // C++0x [class.copy]p32: 4423 // When certain criteria are met, an implementation is allowed to 4424 // omit the copy/move construction of a class object, even if the 4425 // copy/move constructor and/or destructor for the object have 4426 // side effects. [...] 4427 // - when a temporary class object that has not been bound to a 4428 // reference (12.2) would be copied/moved to a class object 4429 // with the same cv-unqualified type, the copy/move operation 4430 // can be omitted by constructing the temporary object 4431 // directly into the target of the omitted copy/move 4432 // 4433 // Note that the other three bullets are handled elsewhere. Copy 4434 // elision for return statements and throw expressions are handled as part 4435 // of constructor initialization, while copy elision for exception handlers 4436 // is handled by the run-time. 4437 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class); 4438 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 4439 4440 // Make sure that the type we are copying is complete. 4441 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete))) 4442 return move(CurInit); 4443 4444 // Perform overload resolution using the class's copy/move constructors. 4445 // Only consider constructors and constructor templates. Per 4446 // C++0x [dcl.init]p16, second bullet to class types, this initialization 4447 // is direct-initialization. 4448 OverloadCandidateSet CandidateSet(Loc); 4449 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr); 4450 4451 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4452 4453 OverloadCandidateSet::iterator Best; 4454 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 4455 case OR_Success: 4456 break; 4457 4458 case OR_No_Viable_Function: 4459 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 4460 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 4461 : diag::err_temp_copy_no_viable) 4462 << (int)Entity.getKind() << CurInitExpr->getType() 4463 << CurInitExpr->getSourceRange(); 4464 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1); 4465 if (!IsExtraneousCopy || S.isSFINAEContext()) 4466 return ExprError(); 4467 return move(CurInit); 4468 4469 case OR_Ambiguous: 4470 S.Diag(Loc, diag::err_temp_copy_ambiguous) 4471 << (int)Entity.getKind() << CurInitExpr->getType() 4472 << CurInitExpr->getSourceRange(); 4473 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1); 4474 return ExprError(); 4475 4476 case OR_Deleted: 4477 S.Diag(Loc, diag::err_temp_copy_deleted) 4478 << (int)Entity.getKind() << CurInitExpr->getType() 4479 << CurInitExpr->getSourceRange(); 4480 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4481 << 1 << Best->Function->isDeleted(); 4482 return ExprError(); 4483 } 4484 4485 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 4486 ASTOwningVector<Expr*> ConstructorArgs(S); 4487 CurInit.release(); // Ownership transferred into MultiExprArg, below. 4488 4489 S.CheckConstructorAccess(Loc, Constructor, Entity, 4490 Best->FoundDecl.getAccess(), IsExtraneousCopy); 4491 4492 if (IsExtraneousCopy) { 4493 // If this is a totally extraneous copy for C++03 reference 4494 // binding purposes, just return the original initialization 4495 // expression. We don't generate an (elided) copy operation here 4496 // because doing so would require us to pass down a flag to avoid 4497 // infinite recursion, where each step adds another extraneous, 4498 // elidable copy. 4499 4500 // Instantiate the default arguments of any extra parameters in 4501 // the selected copy constructor, as if we were going to create a 4502 // proper call to the copy constructor. 4503 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 4504 ParmVarDecl *Parm = Constructor->getParamDecl(I); 4505 if (S.RequireCompleteType(Loc, Parm->getType(), 4506 S.PDiag(diag::err_call_incomplete_argument))) 4507 break; 4508 4509 // Build the default argument expression; we don't actually care 4510 // if this succeeds or not, because this routine will complain 4511 // if there was a problem. 4512 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 4513 } 4514 4515 return S.Owned(CurInitExpr); 4516 } 4517 4518 S.MarkDeclarationReferenced(Loc, Constructor); 4519 4520 // Determine the arguments required to actually perform the 4521 // constructor call (we might have derived-to-base conversions, or 4522 // the copy constructor may have default arguments). 4523 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1), 4524 Loc, ConstructorArgs)) 4525 return ExprError(); 4526 4527 // Actually perform the constructor call. 4528 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable, 4529 move_arg(ConstructorArgs), 4530 HadMultipleCandidates, 4531 /*ZeroInit*/ false, 4532 CXXConstructExpr::CK_Complete, 4533 SourceRange()); 4534 4535 // If we're supposed to bind temporaries, do so. 4536 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 4537 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4538 return move(CurInit); 4539} 4540 4541/// \brief Check whether elidable copy construction for binding a reference to 4542/// a temporary would have succeeded if we were building in C++98 mode, for 4543/// -Wc++98-compat. 4544static void CheckCXX98CompatAccessibleCopy(Sema &S, 4545 const InitializedEntity &Entity, 4546 Expr *CurInitExpr) { 4547 assert(S.getLangOptions().CPlusPlus0x); 4548 4549 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 4550 if (!Record) 4551 return; 4552 4553 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 4554 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc) 4555 == DiagnosticsEngine::Ignored) 4556 return; 4557 4558 // Find constructors which would have been considered. 4559 OverloadCandidateSet CandidateSet(Loc); 4560 LookupCopyAndMoveConstructors( 4561 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr); 4562 4563 // Perform overload resolution. 4564 OverloadCandidateSet::iterator Best; 4565 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best); 4566 4567 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 4568 << OR << (int)Entity.getKind() << CurInitExpr->getType() 4569 << CurInitExpr->getSourceRange(); 4570 4571 switch (OR) { 4572 case OR_Success: 4573 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 4574 Best->FoundDecl.getAccess(), Diag); 4575 // FIXME: Check default arguments as far as that's possible. 4576 break; 4577 4578 case OR_No_Viable_Function: 4579 S.Diag(Loc, Diag); 4580 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1); 4581 break; 4582 4583 case OR_Ambiguous: 4584 S.Diag(Loc, Diag); 4585 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1); 4586 break; 4587 4588 case OR_Deleted: 4589 S.Diag(Loc, Diag); 4590 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4591 << 1 << Best->Function->isDeleted(); 4592 break; 4593 } 4594} 4595 4596void InitializationSequence::PrintInitLocationNote(Sema &S, 4597 const InitializedEntity &Entity) { 4598 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) { 4599 if (Entity.getDecl()->getLocation().isInvalid()) 4600 return; 4601 4602 if (Entity.getDecl()->getDeclName()) 4603 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 4604 << Entity.getDecl()->getDeclName(); 4605 else 4606 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 4607 } 4608} 4609 4610static bool isReferenceBinding(const InitializationSequence::Step &s) { 4611 return s.Kind == InitializationSequence::SK_BindReference || 4612 s.Kind == InitializationSequence::SK_BindReferenceToTemporary; 4613} 4614 4615static ExprResult 4616PerformConstructorInitialization(Sema &S, 4617 const InitializedEntity &Entity, 4618 const InitializationKind &Kind, 4619 MultiExprArg Args, 4620 const InitializationSequence::Step& Step, 4621 bool &ConstructorInitRequiresZeroInit) { 4622 unsigned NumArgs = Args.size(); 4623 CXXConstructorDecl *Constructor 4624 = cast<CXXConstructorDecl>(Step.Function.Function); 4625 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 4626 4627 // Build a call to the selected constructor. 4628 ASTOwningVector<Expr*> ConstructorArgs(S); 4629 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 4630 ? Kind.getEqualLoc() 4631 : Kind.getLocation(); 4632 4633 if (Kind.getKind() == InitializationKind::IK_Default) { 4634 // Force even a trivial, implicit default constructor to be 4635 // semantically checked. We do this explicitly because we don't build 4636 // the definition for completely trivial constructors. 4637 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4638 assert(ClassDecl && "No parent class for constructor."); 4639 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 4640 ClassDecl->hasTrivialDefaultConstructor() && 4641 !Constructor->isUsed(false)) 4642 S.DefineImplicitDefaultConstructor(Loc, Constructor); 4643 } 4644 4645 ExprResult CurInit = S.Owned((Expr *)0); 4646 4647 // Determine the arguments required to actually perform the constructor 4648 // call. 4649 if (S.CompleteConstructorCall(Constructor, move(Args), 4650 Loc, ConstructorArgs)) 4651 return ExprError(); 4652 4653 4654 if (Entity.getKind() == InitializedEntity::EK_Temporary && 4655 NumArgs != 1 && // FIXME: Hack to work around cast weirdness 4656 (Kind.getKind() == InitializationKind::IK_Direct || 4657 Kind.getKind() == InitializationKind::IK_Value)) { 4658 // An explicitly-constructed temporary, e.g., X(1, 2). 4659 unsigned NumExprs = ConstructorArgs.size(); 4660 Expr **Exprs = (Expr **)ConstructorArgs.take(); 4661 S.MarkDeclarationReferenced(Loc, Constructor); 4662 S.DiagnoseUseOfDecl(Constructor, Loc); 4663 4664 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 4665 if (!TSInfo) 4666 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 4667 4668 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context, 4669 Constructor, 4670 TSInfo, 4671 Exprs, 4672 NumExprs, 4673 Kind.getParenRange(), 4674 HadMultipleCandidates, 4675 ConstructorInitRequiresZeroInit)); 4676 } else { 4677 CXXConstructExpr::ConstructionKind ConstructKind = 4678 CXXConstructExpr::CK_Complete; 4679 4680 if (Entity.getKind() == InitializedEntity::EK_Base) { 4681 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 4682 CXXConstructExpr::CK_VirtualBase : 4683 CXXConstructExpr::CK_NonVirtualBase; 4684 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 4685 ConstructKind = CXXConstructExpr::CK_Delegating; 4686 } 4687 4688 // Only get the parenthesis range if it is a direct construction. 4689 SourceRange parenRange = 4690 Kind.getKind() == InitializationKind::IK_Direct ? 4691 Kind.getParenRange() : SourceRange(); 4692 4693 // If the entity allows NRVO, mark the construction as elidable 4694 // unconditionally. 4695 if (Entity.allowsNRVO()) 4696 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4697 Constructor, /*Elidable=*/true, 4698 move_arg(ConstructorArgs), 4699 HadMultipleCandidates, 4700 ConstructorInitRequiresZeroInit, 4701 ConstructKind, 4702 parenRange); 4703 else 4704 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4705 Constructor, 4706 move_arg(ConstructorArgs), 4707 HadMultipleCandidates, 4708 ConstructorInitRequiresZeroInit, 4709 ConstructKind, 4710 parenRange); 4711 } 4712 if (CurInit.isInvalid()) 4713 return ExprError(); 4714 4715 // Only check access if all of that succeeded. 4716 S.CheckConstructorAccess(Loc, Constructor, Entity, 4717 Step.Function.FoundDecl.getAccess()); 4718 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc); 4719 4720 if (shouldBindAsTemporary(Entity)) 4721 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4722 4723 return move(CurInit); 4724} 4725 4726ExprResult 4727InitializationSequence::Perform(Sema &S, 4728 const InitializedEntity &Entity, 4729 const InitializationKind &Kind, 4730 MultiExprArg Args, 4731 QualType *ResultType) { 4732 if (Failed()) { 4733 unsigned NumArgs = Args.size(); 4734 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 4735 return ExprError(); 4736 } 4737 4738 if (getKind() == DependentSequence) { 4739 // If the declaration is a non-dependent, incomplete array type 4740 // that has an initializer, then its type will be completed once 4741 // the initializer is instantiated. 4742 if (ResultType && !Entity.getType()->isDependentType() && 4743 Args.size() == 1) { 4744 QualType DeclType = Entity.getType(); 4745 if (const IncompleteArrayType *ArrayT 4746 = S.Context.getAsIncompleteArrayType(DeclType)) { 4747 // FIXME: We don't currently have the ability to accurately 4748 // compute the length of an initializer list without 4749 // performing full type-checking of the initializer list 4750 // (since we have to determine where braces are implicitly 4751 // introduced and such). So, we fall back to making the array 4752 // type a dependently-sized array type with no specified 4753 // bound. 4754 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 4755 SourceRange Brackets; 4756 4757 // Scavange the location of the brackets from the entity, if we can. 4758 if (DeclaratorDecl *DD = Entity.getDecl()) { 4759 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 4760 TypeLoc TL = TInfo->getTypeLoc(); 4761 if (IncompleteArrayTypeLoc *ArrayLoc 4762 = dyn_cast<IncompleteArrayTypeLoc>(&TL)) 4763 Brackets = ArrayLoc->getBracketsRange(); 4764 } 4765 } 4766 4767 *ResultType 4768 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 4769 /*NumElts=*/0, 4770 ArrayT->getSizeModifier(), 4771 ArrayT->getIndexTypeCVRQualifiers(), 4772 Brackets); 4773 } 4774 4775 } 4776 } 4777 assert(Kind.getKind() == InitializationKind::IK_Copy || 4778 Kind.isExplicitCast()); 4779 return ExprResult(Args.release()[0]); 4780 } 4781 4782 // No steps means no initialization. 4783 if (Steps.empty()) 4784 return S.Owned((Expr *)0); 4785 4786 QualType DestType = Entity.getType().getNonReferenceType(); 4787 // FIXME: Ugly hack around the fact that Entity.getType() is not 4788 // the same as Entity.getDecl()->getType() in cases involving type merging, 4789 // and we want latter when it makes sense. 4790 if (ResultType) 4791 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 4792 Entity.getType(); 4793 4794 ExprResult CurInit = S.Owned((Expr *)0); 4795 4796 // For initialization steps that start with a single initializer, 4797 // grab the only argument out the Args and place it into the "current" 4798 // initializer. 4799 switch (Steps.front().Kind) { 4800 case SK_ResolveAddressOfOverloadedFunction: 4801 case SK_CastDerivedToBaseRValue: 4802 case SK_CastDerivedToBaseXValue: 4803 case SK_CastDerivedToBaseLValue: 4804 case SK_BindReference: 4805 case SK_BindReferenceToTemporary: 4806 case SK_ExtraneousCopyToTemporary: 4807 case SK_UserConversion: 4808 case SK_QualificationConversionLValue: 4809 case SK_QualificationConversionXValue: 4810 case SK_QualificationConversionRValue: 4811 case SK_ConversionSequence: 4812 case SK_ListConstructorCall: 4813 case SK_ListInitialization: 4814 case SK_UnwrapInitList: 4815 case SK_RewrapInitList: 4816 case SK_CAssignment: 4817 case SK_StringInit: 4818 case SK_ObjCObjectConversion: 4819 case SK_ArrayInit: 4820 case SK_PassByIndirectCopyRestore: 4821 case SK_PassByIndirectRestore: 4822 case SK_ProduceObjCObject: { 4823 assert(Args.size() == 1); 4824 CurInit = Args.get()[0]; 4825 if (!CurInit.get()) return ExprError(); 4826 break; 4827 } 4828 4829 case SK_ConstructorInitialization: 4830 case SK_ZeroInitialization: 4831 break; 4832 } 4833 4834 // Walk through the computed steps for the initialization sequence, 4835 // performing the specified conversions along the way. 4836 bool ConstructorInitRequiresZeroInit = false; 4837 for (step_iterator Step = step_begin(), StepEnd = step_end(); 4838 Step != StepEnd; ++Step) { 4839 if (CurInit.isInvalid()) 4840 return ExprError(); 4841 4842 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 4843 4844 switch (Step->Kind) { 4845 case SK_ResolveAddressOfOverloadedFunction: 4846 // Overload resolution determined which function invoke; update the 4847 // initializer to reflect that choice. 4848 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 4849 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()); 4850 CurInit = S.FixOverloadedFunctionReference(move(CurInit), 4851 Step->Function.FoundDecl, 4852 Step->Function.Function); 4853 break; 4854 4855 case SK_CastDerivedToBaseRValue: 4856 case SK_CastDerivedToBaseXValue: 4857 case SK_CastDerivedToBaseLValue: { 4858 // We have a derived-to-base cast that produces either an rvalue or an 4859 // lvalue. Perform that cast. 4860 4861 CXXCastPath BasePath; 4862 4863 // Casts to inaccessible base classes are allowed with C-style casts. 4864 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 4865 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 4866 CurInit.get()->getLocStart(), 4867 CurInit.get()->getSourceRange(), 4868 &BasePath, IgnoreBaseAccess)) 4869 return ExprError(); 4870 4871 if (S.BasePathInvolvesVirtualBase(BasePath)) { 4872 QualType T = SourceType; 4873 if (const PointerType *Pointer = T->getAs<PointerType>()) 4874 T = Pointer->getPointeeType(); 4875 if (const RecordType *RecordTy = T->getAs<RecordType>()) 4876 S.MarkVTableUsed(CurInit.get()->getLocStart(), 4877 cast<CXXRecordDecl>(RecordTy->getDecl())); 4878 } 4879 4880 ExprValueKind VK = 4881 Step->Kind == SK_CastDerivedToBaseLValue ? 4882 VK_LValue : 4883 (Step->Kind == SK_CastDerivedToBaseXValue ? 4884 VK_XValue : 4885 VK_RValue); 4886 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 4887 Step->Type, 4888 CK_DerivedToBase, 4889 CurInit.get(), 4890 &BasePath, VK)); 4891 break; 4892 } 4893 4894 case SK_BindReference: 4895 if (FieldDecl *BitField = CurInit.get()->getBitField()) { 4896 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 4897 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 4898 << Entity.getType().isVolatileQualified() 4899 << BitField->getDeclName() 4900 << CurInit.get()->getSourceRange(); 4901 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 4902 return ExprError(); 4903 } 4904 4905 if (CurInit.get()->refersToVectorElement()) { 4906 // References cannot bind to vector elements. 4907 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 4908 << Entity.getType().isVolatileQualified() 4909 << CurInit.get()->getSourceRange(); 4910 PrintInitLocationNote(S, Entity); 4911 return ExprError(); 4912 } 4913 4914 // Reference binding does not have any corresponding ASTs. 4915 4916 // Check exception specifications 4917 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 4918 return ExprError(); 4919 4920 break; 4921 4922 case SK_BindReferenceToTemporary: 4923 // Check exception specifications 4924 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 4925 return ExprError(); 4926 4927 // Materialize the temporary into memory. 4928 CurInit = new (S.Context) MaterializeTemporaryExpr( 4929 Entity.getType().getNonReferenceType(), 4930 CurInit.get(), 4931 Entity.getType()->isLValueReferenceType()); 4932 4933 // If we're binding to an Objective-C object that has lifetime, we 4934 // need cleanups. 4935 if (S.getLangOptions().ObjCAutoRefCount && 4936 CurInit.get()->getType()->isObjCLifetimeType()) 4937 S.ExprNeedsCleanups = true; 4938 4939 break; 4940 4941 case SK_ExtraneousCopyToTemporary: 4942 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit), 4943 /*IsExtraneousCopy=*/true); 4944 break; 4945 4946 case SK_UserConversion: { 4947 // We have a user-defined conversion that invokes either a constructor 4948 // or a conversion function. 4949 CastKind CastKind; 4950 bool IsCopy = false; 4951 FunctionDecl *Fn = Step->Function.Function; 4952 DeclAccessPair FoundFn = Step->Function.FoundDecl; 4953 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 4954 bool CreatedObject = false; 4955 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 4956 // Build a call to the selected constructor. 4957 ASTOwningVector<Expr*> ConstructorArgs(S); 4958 SourceLocation Loc = CurInit.get()->getLocStart(); 4959 CurInit.release(); // Ownership transferred into MultiExprArg, below. 4960 4961 // Determine the arguments required to actually perform the constructor 4962 // call. 4963 Expr *Arg = CurInit.get(); 4964 if (S.CompleteConstructorCall(Constructor, 4965 MultiExprArg(&Arg, 1), 4966 Loc, ConstructorArgs)) 4967 return ExprError(); 4968 4969 // Build the an expression that constructs a temporary. 4970 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 4971 move_arg(ConstructorArgs), 4972 HadMultipleCandidates, 4973 /*ZeroInit*/ false, 4974 CXXConstructExpr::CK_Complete, 4975 SourceRange()); 4976 if (CurInit.isInvalid()) 4977 return ExprError(); 4978 4979 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity, 4980 FoundFn.getAccess()); 4981 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 4982 4983 CastKind = CK_ConstructorConversion; 4984 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 4985 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 4986 S.IsDerivedFrom(SourceType, Class)) 4987 IsCopy = true; 4988 4989 CreatedObject = true; 4990 } else { 4991 // Build a call to the conversion function. 4992 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 4993 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0, 4994 FoundFn); 4995 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 4996 4997 // FIXME: Should we move this initialization into a separate 4998 // derived-to-base conversion? I believe the answer is "no", because 4999 // we don't want to turn off access control here for c-style casts. 5000 ExprResult CurInitExprRes = 5001 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0, 5002 FoundFn, Conversion); 5003 if(CurInitExprRes.isInvalid()) 5004 return ExprError(); 5005 CurInit = move(CurInitExprRes); 5006 5007 // Build the actual call to the conversion function. 5008 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 5009 HadMultipleCandidates); 5010 if (CurInit.isInvalid() || !CurInit.get()) 5011 return ExprError(); 5012 5013 CastKind = CK_UserDefinedConversion; 5014 5015 CreatedObject = Conversion->getResultType()->isRecordType(); 5016 } 5017 5018 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back()); 5019 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity); 5020 5021 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) { 5022 QualType T = CurInit.get()->getType(); 5023 if (const RecordType *Record = T->getAs<RecordType>()) { 5024 CXXDestructorDecl *Destructor 5025 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 5026 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, 5027 S.PDiag(diag::err_access_dtor_temp) << T); 5028 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor); 5029 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()); 5030 } 5031 } 5032 5033 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 5034 CurInit.get()->getType(), 5035 CastKind, CurInit.get(), 0, 5036 CurInit.get()->getValueKind())); 5037 if (MaybeBindToTemp) 5038 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 5039 if (RequiresCopy) 5040 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 5041 move(CurInit), /*IsExtraneousCopy=*/false); 5042 break; 5043 } 5044 5045 case SK_QualificationConversionLValue: 5046 case SK_QualificationConversionXValue: 5047 case SK_QualificationConversionRValue: { 5048 // Perform a qualification conversion; these can never go wrong. 5049 ExprValueKind VK = 5050 Step->Kind == SK_QualificationConversionLValue ? 5051 VK_LValue : 5052 (Step->Kind == SK_QualificationConversionXValue ? 5053 VK_XValue : 5054 VK_RValue); 5055 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK); 5056 break; 5057 } 5058 5059 case SK_ConversionSequence: { 5060 Sema::CheckedConversionKind CCK 5061 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 5062 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 5063 : Kind.isExplicitCast()? Sema::CCK_OtherCast 5064 : Sema::CCK_ImplicitConversion; 5065 ExprResult CurInitExprRes = 5066 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 5067 getAssignmentAction(Entity), CCK); 5068 if (CurInitExprRes.isInvalid()) 5069 return ExprError(); 5070 CurInit = move(CurInitExprRes); 5071 break; 5072 } 5073 5074 case SK_ListInitialization: { 5075 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 5076 // Hack: We must pass *ResultType if available in order to set the type 5077 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 5078 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a 5079 // temporary, not a reference, so we should pass Ty. 5080 // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 5081 // Since this step is never used for a reference directly, we explicitly 5082 // unwrap references here and rewrap them afterwards. 5083 // We also need to create a InitializeTemporary entity for this. 5084 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type; 5085 bool IsTemporary = ResultType && (*ResultType)->isReferenceType(); 5086 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 5087 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity, 5088 InitList, Ty, /*VerifyOnly=*/false, 5089 Kind.getKind() != InitializationKind::IK_Direct || 5090 !S.getLangOptions().CPlusPlus0x); 5091 if (PerformInitList.HadError()) 5092 return ExprError(); 5093 5094 if (ResultType) { 5095 if ((*ResultType)->isRValueReferenceType()) 5096 Ty = S.Context.getRValueReferenceType(Ty); 5097 else if ((*ResultType)->isLValueReferenceType()) 5098 Ty = S.Context.getLValueReferenceType(Ty, 5099 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue()); 5100 *ResultType = Ty; 5101 } 5102 5103 InitListExpr *StructuredInitList = 5104 PerformInitList.getFullyStructuredList(); 5105 CurInit.release(); 5106 CurInit = S.Owned(StructuredInitList); 5107 break; 5108 } 5109 5110 case SK_ListConstructorCall: { 5111 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 5112 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 5113 CurInit = PerformConstructorInitialization(S, Entity, Kind, 5114 move(Arg), *Step, 5115 ConstructorInitRequiresZeroInit); 5116 break; 5117 } 5118 5119 case SK_UnwrapInitList: 5120 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0)); 5121 break; 5122 5123 case SK_RewrapInitList: { 5124 Expr *E = CurInit.take(); 5125 InitListExpr *Syntactic = Step->WrappingSyntacticList; 5126 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 5127 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc()); 5128 ILE->setSyntacticForm(Syntactic); 5129 ILE->setType(E->getType()); 5130 ILE->setValueKind(E->getValueKind()); 5131 CurInit = S.Owned(ILE); 5132 break; 5133 } 5134 5135 case SK_ConstructorInitialization: 5136 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args), 5137 *Step, 5138 ConstructorInitRequiresZeroInit); 5139 break; 5140 5141 case SK_ZeroInitialization: { 5142 step_iterator NextStep = Step; 5143 ++NextStep; 5144 if (NextStep != StepEnd && 5145 NextStep->Kind == SK_ConstructorInitialization) { 5146 // The need for zero-initialization is recorded directly into 5147 // the call to the object's constructor within the next step. 5148 ConstructorInitRequiresZeroInit = true; 5149 } else if (Kind.getKind() == InitializationKind::IK_Value && 5150 S.getLangOptions().CPlusPlus && 5151 !Kind.isImplicitValueInit()) { 5152 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 5153 if (!TSInfo) 5154 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 5155 Kind.getRange().getBegin()); 5156 5157 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr( 5158 TSInfo->getType().getNonLValueExprType(S.Context), 5159 TSInfo, 5160 Kind.getRange().getEnd())); 5161 } else { 5162 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 5163 } 5164 break; 5165 } 5166 5167 case SK_CAssignment: { 5168 QualType SourceType = CurInit.get()->getType(); 5169 ExprResult Result = move(CurInit); 5170 Sema::AssignConvertType ConvTy = 5171 S.CheckSingleAssignmentConstraints(Step->Type, Result); 5172 if (Result.isInvalid()) 5173 return ExprError(); 5174 CurInit = move(Result); 5175 5176 // If this is a call, allow conversion to a transparent union. 5177 ExprResult CurInitExprRes = move(CurInit); 5178 if (ConvTy != Sema::Compatible && 5179 Entity.getKind() == InitializedEntity::EK_Parameter && 5180 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 5181 == Sema::Compatible) 5182 ConvTy = Sema::Compatible; 5183 if (CurInitExprRes.isInvalid()) 5184 return ExprError(); 5185 CurInit = move(CurInitExprRes); 5186 5187 bool Complained; 5188 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 5189 Step->Type, SourceType, 5190 CurInit.get(), 5191 getAssignmentAction(Entity), 5192 &Complained)) { 5193 PrintInitLocationNote(S, Entity); 5194 return ExprError(); 5195 } else if (Complained) 5196 PrintInitLocationNote(S, Entity); 5197 break; 5198 } 5199 5200 case SK_StringInit: { 5201 QualType Ty = Step->Type; 5202 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, 5203 S.Context.getAsArrayType(Ty), S); 5204 break; 5205 } 5206 5207 case SK_ObjCObjectConversion: 5208 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, 5209 CK_ObjCObjectLValueCast, 5210 CurInit.get()->getValueKind()); 5211 break; 5212 5213 case SK_ArrayInit: 5214 // Okay: we checked everything before creating this step. Note that 5215 // this is a GNU extension. 5216 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 5217 << Step->Type << CurInit.get()->getType() 5218 << CurInit.get()->getSourceRange(); 5219 5220 // If the destination type is an incomplete array type, update the 5221 // type accordingly. 5222 if (ResultType) { 5223 if (const IncompleteArrayType *IncompleteDest 5224 = S.Context.getAsIncompleteArrayType(Step->Type)) { 5225 if (const ConstantArrayType *ConstantSource 5226 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 5227 *ResultType = S.Context.getConstantArrayType( 5228 IncompleteDest->getElementType(), 5229 ConstantSource->getSize(), 5230 ArrayType::Normal, 0); 5231 } 5232 } 5233 } 5234 break; 5235 5236 case SK_PassByIndirectCopyRestore: 5237 case SK_PassByIndirectRestore: 5238 checkIndirectCopyRestoreSource(S, CurInit.get()); 5239 CurInit = S.Owned(new (S.Context) 5240 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type, 5241 Step->Kind == SK_PassByIndirectCopyRestore)); 5242 break; 5243 5244 case SK_ProduceObjCObject: 5245 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type, 5246 CK_ARCProduceObject, 5247 CurInit.take(), 0, VK_RValue)); 5248 break; 5249 } 5250 } 5251 5252 // Diagnose non-fatal problems with the completed initialization. 5253 if (Entity.getKind() == InitializedEntity::EK_Member && 5254 cast<FieldDecl>(Entity.getDecl())->isBitField()) 5255 S.CheckBitFieldInitialization(Kind.getLocation(), 5256 cast<FieldDecl>(Entity.getDecl()), 5257 CurInit.get()); 5258 5259 return move(CurInit); 5260} 5261 5262//===----------------------------------------------------------------------===// 5263// Diagnose initialization failures 5264//===----------------------------------------------------------------------===// 5265bool InitializationSequence::Diagnose(Sema &S, 5266 const InitializedEntity &Entity, 5267 const InitializationKind &Kind, 5268 Expr **Args, unsigned NumArgs) { 5269 if (!Failed()) 5270 return false; 5271 5272 QualType DestType = Entity.getType(); 5273 switch (Failure) { 5274 case FK_TooManyInitsForReference: 5275 // FIXME: Customize for the initialized entity? 5276 if (NumArgs == 0) 5277 S.Diag(Kind.getLocation(), diag::err_reference_without_init) 5278 << DestType.getNonReferenceType(); 5279 else // FIXME: diagnostic below could be better! 5280 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 5281 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 5282 break; 5283 5284 case FK_ArrayNeedsInitList: 5285 case FK_ArrayNeedsInitListOrStringLiteral: 5286 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 5287 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 5288 break; 5289 5290 case FK_ArrayTypeMismatch: 5291 case FK_NonConstantArrayInit: 5292 S.Diag(Kind.getLocation(), 5293 (Failure == FK_ArrayTypeMismatch 5294 ? diag::err_array_init_different_type 5295 : diag::err_array_init_non_constant_array)) 5296 << DestType.getNonReferenceType() 5297 << Args[0]->getType() 5298 << Args[0]->getSourceRange(); 5299 break; 5300 5301 case FK_VariableLengthArrayHasInitializer: 5302 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 5303 << Args[0]->getSourceRange(); 5304 break; 5305 5306 case FK_AddressOfOverloadFailed: { 5307 DeclAccessPair Found; 5308 S.ResolveAddressOfOverloadedFunction(Args[0], 5309 DestType.getNonReferenceType(), 5310 true, 5311 Found); 5312 break; 5313 } 5314 5315 case FK_ReferenceInitOverloadFailed: 5316 case FK_UserConversionOverloadFailed: 5317 switch (FailedOverloadResult) { 5318 case OR_Ambiguous: 5319 if (Failure == FK_UserConversionOverloadFailed) 5320 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 5321 << Args[0]->getType() << DestType 5322 << Args[0]->getSourceRange(); 5323 else 5324 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 5325 << DestType << Args[0]->getType() 5326 << Args[0]->getSourceRange(); 5327 5328 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs); 5329 break; 5330 5331 case OR_No_Viable_Function: 5332 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 5333 << Args[0]->getType() << DestType.getNonReferenceType() 5334 << Args[0]->getSourceRange(); 5335 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 5336 break; 5337 5338 case OR_Deleted: { 5339 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 5340 << Args[0]->getType() << DestType.getNonReferenceType() 5341 << Args[0]->getSourceRange(); 5342 OverloadCandidateSet::iterator Best; 5343 OverloadingResult Ovl 5344 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, 5345 true); 5346 if (Ovl == OR_Deleted) { 5347 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 5348 << 1 << Best->Function->isDeleted(); 5349 } else { 5350 llvm_unreachable("Inconsistent overload resolution?"); 5351 } 5352 break; 5353 } 5354 5355 case OR_Success: 5356 llvm_unreachable("Conversion did not fail!"); 5357 } 5358 break; 5359 5360 case FK_NonConstLValueReferenceBindingToTemporary: 5361 if (isa<InitListExpr>(Args[0])) { 5362 S.Diag(Kind.getLocation(), 5363 diag::err_lvalue_reference_bind_to_initlist) 5364 << DestType.getNonReferenceType().isVolatileQualified() 5365 << DestType.getNonReferenceType() 5366 << Args[0]->getSourceRange(); 5367 break; 5368 } 5369 // Intentional fallthrough 5370 5371 case FK_NonConstLValueReferenceBindingToUnrelated: 5372 S.Diag(Kind.getLocation(), 5373 Failure == FK_NonConstLValueReferenceBindingToTemporary 5374 ? diag::err_lvalue_reference_bind_to_temporary 5375 : diag::err_lvalue_reference_bind_to_unrelated) 5376 << DestType.getNonReferenceType().isVolatileQualified() 5377 << DestType.getNonReferenceType() 5378 << Args[0]->getType() 5379 << Args[0]->getSourceRange(); 5380 break; 5381 5382 case FK_RValueReferenceBindingToLValue: 5383 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 5384 << DestType.getNonReferenceType() << Args[0]->getType() 5385 << Args[0]->getSourceRange(); 5386 break; 5387 5388 case FK_ReferenceInitDropsQualifiers: 5389 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 5390 << DestType.getNonReferenceType() 5391 << Args[0]->getType() 5392 << Args[0]->getSourceRange(); 5393 break; 5394 5395 case FK_ReferenceInitFailed: 5396 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 5397 << DestType.getNonReferenceType() 5398 << Args[0]->isLValue() 5399 << Args[0]->getType() 5400 << Args[0]->getSourceRange(); 5401 if (DestType.getNonReferenceType()->isObjCObjectPointerType() && 5402 Args[0]->getType()->isObjCObjectPointerType()) 5403 S.EmitRelatedResultTypeNote(Args[0]); 5404 break; 5405 5406 case FK_ConversionFailed: { 5407 QualType FromType = Args[0]->getType(); 5408 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 5409 << (int)Entity.getKind() 5410 << DestType 5411 << Args[0]->isLValue() 5412 << FromType 5413 << Args[0]->getSourceRange(); 5414 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 5415 S.Diag(Kind.getLocation(), PDiag); 5416 if (DestType.getNonReferenceType()->isObjCObjectPointerType() && 5417 Args[0]->getType()->isObjCObjectPointerType()) 5418 S.EmitRelatedResultTypeNote(Args[0]); 5419 break; 5420 } 5421 5422 case FK_ConversionFromPropertyFailed: 5423 // No-op. This error has already been reported. 5424 break; 5425 5426 case FK_TooManyInitsForScalar: { 5427 SourceRange R; 5428 5429 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 5430 R = SourceRange(InitList->getInit(0)->getLocEnd(), 5431 InitList->getLocEnd()); 5432 else 5433 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd()); 5434 5435 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin())); 5436 if (Kind.isCStyleOrFunctionalCast()) 5437 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 5438 << R; 5439 else 5440 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 5441 << /*scalar=*/2 << R; 5442 break; 5443 } 5444 5445 case FK_ReferenceBindingToInitList: 5446 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 5447 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 5448 break; 5449 5450 case FK_InitListBadDestinationType: 5451 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 5452 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 5453 break; 5454 5455 case FK_ListConstructorOverloadFailed: 5456 case FK_ConstructorOverloadFailed: { 5457 SourceRange ArgsRange; 5458 if (NumArgs) 5459 ArgsRange = SourceRange(Args[0]->getLocStart(), 5460 Args[NumArgs - 1]->getLocEnd()); 5461 5462 if (Failure == FK_ListConstructorOverloadFailed) { 5463 assert(NumArgs == 1 && "List construction from other than 1 argument."); 5464 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 5465 Args = InitList->getInits(); 5466 NumArgs = InitList->getNumInits(); 5467 } 5468 5469 // FIXME: Using "DestType" for the entity we're printing is probably 5470 // bad. 5471 switch (FailedOverloadResult) { 5472 case OR_Ambiguous: 5473 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 5474 << DestType << ArgsRange; 5475 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, 5476 Args, NumArgs); 5477 break; 5478 5479 case OR_No_Viable_Function: 5480 if (Kind.getKind() == InitializationKind::IK_Default && 5481 (Entity.getKind() == InitializedEntity::EK_Base || 5482 Entity.getKind() == InitializedEntity::EK_Member) && 5483 isa<CXXConstructorDecl>(S.CurContext)) { 5484 // This is implicit default initialization of a member or 5485 // base within a constructor. If no viable function was 5486 // found, notify the user that she needs to explicitly 5487 // initialize this base/member. 5488 CXXConstructorDecl *Constructor 5489 = cast<CXXConstructorDecl>(S.CurContext); 5490 if (Entity.getKind() == InitializedEntity::EK_Base) { 5491 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 5492 << Constructor->isImplicit() 5493 << S.Context.getTypeDeclType(Constructor->getParent()) 5494 << /*base=*/0 5495 << Entity.getType(); 5496 5497 RecordDecl *BaseDecl 5498 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 5499 ->getDecl(); 5500 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 5501 << S.Context.getTagDeclType(BaseDecl); 5502 } else { 5503 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 5504 << Constructor->isImplicit() 5505 << S.Context.getTypeDeclType(Constructor->getParent()) 5506 << /*member=*/1 5507 << Entity.getName(); 5508 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl); 5509 5510 if (const RecordType *Record 5511 = Entity.getType()->getAs<RecordType>()) 5512 S.Diag(Record->getDecl()->getLocation(), 5513 diag::note_previous_decl) 5514 << S.Context.getTagDeclType(Record->getDecl()); 5515 } 5516 break; 5517 } 5518 5519 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 5520 << DestType << ArgsRange; 5521 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 5522 break; 5523 5524 case OR_Deleted: { 5525 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 5526 << true << DestType << ArgsRange; 5527 OverloadCandidateSet::iterator Best; 5528 OverloadingResult Ovl 5529 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 5530 if (Ovl == OR_Deleted) { 5531 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 5532 << 1 << Best->Function->isDeleted(); 5533 } else { 5534 llvm_unreachable("Inconsistent overload resolution?"); 5535 } 5536 break; 5537 } 5538 5539 case OR_Success: 5540 llvm_unreachable("Conversion did not fail!"); 5541 } 5542 } 5543 5544 case FK_DefaultInitOfConst: 5545 if (Entity.getKind() == InitializedEntity::EK_Member && 5546 isa<CXXConstructorDecl>(S.CurContext)) { 5547 // This is implicit default-initialization of a const member in 5548 // a constructor. Complain that it needs to be explicitly 5549 // initialized. 5550 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 5551 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 5552 << Constructor->isImplicit() 5553 << S.Context.getTypeDeclType(Constructor->getParent()) 5554 << /*const=*/1 5555 << Entity.getName(); 5556 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 5557 << Entity.getName(); 5558 } else { 5559 S.Diag(Kind.getLocation(), diag::err_default_init_const) 5560 << DestType << (bool)DestType->getAs<RecordType>(); 5561 } 5562 break; 5563 5564 case FK_Incomplete: 5565 S.RequireCompleteType(Kind.getLocation(), DestType, 5566 diag::err_init_incomplete_type); 5567 break; 5568 5569 case FK_ListInitializationFailed: { 5570 // Run the init list checker again to emit diagnostics. 5571 InitListExpr* InitList = cast<InitListExpr>(Args[0]); 5572 QualType DestType = Entity.getType(); 5573 InitListChecker DiagnoseInitList(S, Entity, InitList, 5574 DestType, /*VerifyOnly=*/false, 5575 Kind.getKind() != InitializationKind::IK_Direct || 5576 !S.getLangOptions().CPlusPlus0x); 5577 assert(DiagnoseInitList.HadError() && 5578 "Inconsistent init list check result."); 5579 break; 5580 } 5581 5582 case FK_PlaceholderType: { 5583 // FIXME: Already diagnosed! 5584 break; 5585 } 5586 } 5587 5588 PrintInitLocationNote(S, Entity); 5589 return true; 5590} 5591 5592void InitializationSequence::dump(raw_ostream &OS) const { 5593 switch (SequenceKind) { 5594 case FailedSequence: { 5595 OS << "Failed sequence: "; 5596 switch (Failure) { 5597 case FK_TooManyInitsForReference: 5598 OS << "too many initializers for reference"; 5599 break; 5600 5601 case FK_ArrayNeedsInitList: 5602 OS << "array requires initializer list"; 5603 break; 5604 5605 case FK_ArrayNeedsInitListOrStringLiteral: 5606 OS << "array requires initializer list or string literal"; 5607 break; 5608 5609 case FK_ArrayTypeMismatch: 5610 OS << "array type mismatch"; 5611 break; 5612 5613 case FK_NonConstantArrayInit: 5614 OS << "non-constant array initializer"; 5615 break; 5616 5617 case FK_AddressOfOverloadFailed: 5618 OS << "address of overloaded function failed"; 5619 break; 5620 5621 case FK_ReferenceInitOverloadFailed: 5622 OS << "overload resolution for reference initialization failed"; 5623 break; 5624 5625 case FK_NonConstLValueReferenceBindingToTemporary: 5626 OS << "non-const lvalue reference bound to temporary"; 5627 break; 5628 5629 case FK_NonConstLValueReferenceBindingToUnrelated: 5630 OS << "non-const lvalue reference bound to unrelated type"; 5631 break; 5632 5633 case FK_RValueReferenceBindingToLValue: 5634 OS << "rvalue reference bound to an lvalue"; 5635 break; 5636 5637 case FK_ReferenceInitDropsQualifiers: 5638 OS << "reference initialization drops qualifiers"; 5639 break; 5640 5641 case FK_ReferenceInitFailed: 5642 OS << "reference initialization failed"; 5643 break; 5644 5645 case FK_ConversionFailed: 5646 OS << "conversion failed"; 5647 break; 5648 5649 case FK_ConversionFromPropertyFailed: 5650 OS << "conversion from property failed"; 5651 break; 5652 5653 case FK_TooManyInitsForScalar: 5654 OS << "too many initializers for scalar"; 5655 break; 5656 5657 case FK_ReferenceBindingToInitList: 5658 OS << "referencing binding to initializer list"; 5659 break; 5660 5661 case FK_InitListBadDestinationType: 5662 OS << "initializer list for non-aggregate, non-scalar type"; 5663 break; 5664 5665 case FK_UserConversionOverloadFailed: 5666 OS << "overloading failed for user-defined conversion"; 5667 break; 5668 5669 case FK_ConstructorOverloadFailed: 5670 OS << "constructor overloading failed"; 5671 break; 5672 5673 case FK_DefaultInitOfConst: 5674 OS << "default initialization of a const variable"; 5675 break; 5676 5677 case FK_Incomplete: 5678 OS << "initialization of incomplete type"; 5679 break; 5680 5681 case FK_ListInitializationFailed: 5682 OS << "list initialization checker failure"; 5683 break; 5684 5685 case FK_VariableLengthArrayHasInitializer: 5686 OS << "variable length array has an initializer"; 5687 break; 5688 5689 case FK_PlaceholderType: 5690 OS << "initializer expression isn't contextually valid"; 5691 break; 5692 5693 case FK_ListConstructorOverloadFailed: 5694 OS << "list constructor overloading failed"; 5695 break; 5696 } 5697 OS << '\n'; 5698 return; 5699 } 5700 5701 case DependentSequence: 5702 OS << "Dependent sequence\n"; 5703 return; 5704 5705 case NormalSequence: 5706 OS << "Normal sequence: "; 5707 break; 5708 } 5709 5710 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 5711 if (S != step_begin()) { 5712 OS << " -> "; 5713 } 5714 5715 switch (S->Kind) { 5716 case SK_ResolveAddressOfOverloadedFunction: 5717 OS << "resolve address of overloaded function"; 5718 break; 5719 5720 case SK_CastDerivedToBaseRValue: 5721 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 5722 break; 5723 5724 case SK_CastDerivedToBaseXValue: 5725 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 5726 break; 5727 5728 case SK_CastDerivedToBaseLValue: 5729 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 5730 break; 5731 5732 case SK_BindReference: 5733 OS << "bind reference to lvalue"; 5734 break; 5735 5736 case SK_BindReferenceToTemporary: 5737 OS << "bind reference to a temporary"; 5738 break; 5739 5740 case SK_ExtraneousCopyToTemporary: 5741 OS << "extraneous C++03 copy to temporary"; 5742 break; 5743 5744 case SK_UserConversion: 5745 OS << "user-defined conversion via " << *S->Function.Function; 5746 break; 5747 5748 case SK_QualificationConversionRValue: 5749 OS << "qualification conversion (rvalue)"; 5750 break; 5751 5752 case SK_QualificationConversionXValue: 5753 OS << "qualification conversion (xvalue)"; 5754 break; 5755 5756 case SK_QualificationConversionLValue: 5757 OS << "qualification conversion (lvalue)"; 5758 break; 5759 5760 case SK_ConversionSequence: 5761 OS << "implicit conversion sequence ("; 5762 S->ICS->DebugPrint(); // FIXME: use OS 5763 OS << ")"; 5764 break; 5765 5766 case SK_ListInitialization: 5767 OS << "list aggregate initialization"; 5768 break; 5769 5770 case SK_ListConstructorCall: 5771 OS << "list initialization via constructor"; 5772 break; 5773 5774 case SK_UnwrapInitList: 5775 OS << "unwrap reference initializer list"; 5776 break; 5777 5778 case SK_RewrapInitList: 5779 OS << "rewrap reference initializer list"; 5780 break; 5781 5782 case SK_ConstructorInitialization: 5783 OS << "constructor initialization"; 5784 break; 5785 5786 case SK_ZeroInitialization: 5787 OS << "zero initialization"; 5788 break; 5789 5790 case SK_CAssignment: 5791 OS << "C assignment"; 5792 break; 5793 5794 case SK_StringInit: 5795 OS << "string initialization"; 5796 break; 5797 5798 case SK_ObjCObjectConversion: 5799 OS << "Objective-C object conversion"; 5800 break; 5801 5802 case SK_ArrayInit: 5803 OS << "array initialization"; 5804 break; 5805 5806 case SK_PassByIndirectCopyRestore: 5807 OS << "pass by indirect copy and restore"; 5808 break; 5809 5810 case SK_PassByIndirectRestore: 5811 OS << "pass by indirect restore"; 5812 break; 5813 5814 case SK_ProduceObjCObject: 5815 OS << "Objective-C object retension"; 5816 break; 5817 } 5818 } 5819} 5820 5821void InitializationSequence::dump() const { 5822 dump(llvm::errs()); 5823} 5824 5825static void DiagnoseNarrowingInInitList( 5826 Sema& S, QualType EntityType, const Expr *InitE, 5827 bool Constant, const APValue &ConstantValue) { 5828 if (Constant) { 5829 S.Diag(InitE->getLocStart(), 5830 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt 5831 ? diag::err_init_list_constant_narrowing 5832 : diag::warn_init_list_constant_narrowing) 5833 << InitE->getSourceRange() 5834 << ConstantValue.getAsString(S.getASTContext(), EntityType) 5835 << EntityType.getLocalUnqualifiedType(); 5836 } else 5837 S.Diag(InitE->getLocStart(), 5838 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt 5839 ? diag::err_init_list_variable_narrowing 5840 : diag::warn_init_list_variable_narrowing) 5841 << InitE->getSourceRange() 5842 << InitE->getType().getLocalUnqualifiedType() 5843 << EntityType.getLocalUnqualifiedType(); 5844 5845 llvm::SmallString<128> StaticCast; 5846 llvm::raw_svector_ostream OS(StaticCast); 5847 OS << "static_cast<"; 5848 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 5849 // It's important to use the typedef's name if there is one so that the 5850 // fixit doesn't break code using types like int64_t. 5851 // 5852 // FIXME: This will break if the typedef requires qualification. But 5853 // getQualifiedNameAsString() includes non-machine-parsable components. 5854 OS << *TT->getDecl(); 5855 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 5856 OS << BT->getName(S.getLangOptions()); 5857 else { 5858 // Oops, we didn't find the actual type of the variable. Don't emit a fixit 5859 // with a broken cast. 5860 return; 5861 } 5862 OS << ">("; 5863 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override) 5864 << InitE->getSourceRange() 5865 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str()) 5866 << FixItHint::CreateInsertion( 5867 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")"); 5868} 5869 5870//===----------------------------------------------------------------------===// 5871// Initialization helper functions 5872//===----------------------------------------------------------------------===// 5873bool 5874Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 5875 ExprResult Init) { 5876 if (Init.isInvalid()) 5877 return false; 5878 5879 Expr *InitE = Init.get(); 5880 assert(InitE && "No initialization expression"); 5881 5882 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(), 5883 SourceLocation()); 5884 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 5885 return !Seq.Failed(); 5886} 5887 5888ExprResult 5889Sema::PerformCopyInitialization(const InitializedEntity &Entity, 5890 SourceLocation EqualLoc, 5891 ExprResult Init, 5892 bool TopLevelOfInitList) { 5893 if (Init.isInvalid()) 5894 return ExprError(); 5895 5896 Expr *InitE = Init.get(); 5897 assert(InitE && "No initialization expression?"); 5898 5899 if (EqualLoc.isInvalid()) 5900 EqualLoc = InitE->getLocStart(); 5901 5902 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 5903 EqualLoc); 5904 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 5905 Init.release(); 5906 5907 bool Constant = false; 5908 APValue Result; 5909 if (TopLevelOfInitList && 5910 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) { 5911 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE, 5912 Constant, Result); 5913 } 5914 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1)); 5915} 5916