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