1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for initializers. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Initialization.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/ExprObjC.h" 19 #include "clang/AST/TypeLoc.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "clang/Sema/Designator.h" 22 #include "clang/Sema/Lookup.h" 23 #include "clang/Sema/SemaInternal.h" 24 #include "llvm/ADT/APInt.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <map> 29 30 using namespace clang; 31 32 //===----------------------------------------------------------------------===// 33 // Sema Initialization Checking 34 //===----------------------------------------------------------------------===// 35 36 /// \brief Check whether T is compatible with a wide character type (wchar_t, 37 /// char16_t or char32_t). 38 static bool IsWideCharCompatible(QualType T, ASTContext &Context) { 39 if (Context.typesAreCompatible(Context.getWideCharType(), T)) 40 return true; 41 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { 42 return Context.typesAreCompatible(Context.Char16Ty, T) || 43 Context.typesAreCompatible(Context.Char32Ty, T); 44 } 45 return false; 46 } 47 48 enum StringInitFailureKind { 49 SIF_None, 50 SIF_NarrowStringIntoWideChar, 51 SIF_WideStringIntoChar, 52 SIF_IncompatWideStringIntoWideChar, 53 SIF_Other 54 }; 55 56 /// \brief Check whether the array of type AT can be initialized by the Init 57 /// expression by means of string initialization. Returns SIF_None if so, 58 /// otherwise returns a StringInitFailureKind that describes why the 59 /// initialization would not work. 60 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, 61 ASTContext &Context) { 62 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 63 return SIF_Other; 64 65 // See if this is a string literal or @encode. 66 Init = Init->IgnoreParens(); 67 68 // Handle @encode, which is a narrow string. 69 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 70 return SIF_None; 71 72 // Otherwise we can only handle string literals. 73 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 74 if (!SL) 75 return SIF_Other; 76 77 const QualType ElemTy = 78 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); 79 80 switch (SL->getKind()) { 81 case StringLiteral::Ascii: 82 case StringLiteral::UTF8: 83 // char array can be initialized with a narrow string. 84 // Only allow char x[] = "foo"; not char x[] = L"foo"; 85 if (ElemTy->isCharType()) 86 return SIF_None; 87 if (IsWideCharCompatible(ElemTy, Context)) 88 return SIF_NarrowStringIntoWideChar; 89 return SIF_Other; 90 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: 91 // "An array with element type compatible with a qualified or unqualified 92 // version of wchar_t, char16_t, or char32_t may be initialized by a wide 93 // string literal with the corresponding encoding prefix (L, u, or U, 94 // respectively), optionally enclosed in braces. 95 case StringLiteral::UTF16: 96 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) 97 return SIF_None; 98 if (ElemTy->isCharType()) 99 return SIF_WideStringIntoChar; 100 if (IsWideCharCompatible(ElemTy, Context)) 101 return SIF_IncompatWideStringIntoWideChar; 102 return SIF_Other; 103 case StringLiteral::UTF32: 104 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) 105 return SIF_None; 106 if (ElemTy->isCharType()) 107 return SIF_WideStringIntoChar; 108 if (IsWideCharCompatible(ElemTy, Context)) 109 return SIF_IncompatWideStringIntoWideChar; 110 return SIF_Other; 111 case StringLiteral::Wide: 112 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) 113 return SIF_None; 114 if (ElemTy->isCharType()) 115 return SIF_WideStringIntoChar; 116 if (IsWideCharCompatible(ElemTy, Context)) 117 return SIF_IncompatWideStringIntoWideChar; 118 return SIF_Other; 119 } 120 121 llvm_unreachable("missed a StringLiteral kind?"); 122 } 123 124 static StringInitFailureKind IsStringInit(Expr *init, QualType declType, 125 ASTContext &Context) { 126 const ArrayType *arrayType = Context.getAsArrayType(declType); 127 if (!arrayType) 128 return SIF_Other; 129 return IsStringInit(init, arrayType, Context); 130 } 131 132 /// Update the type of a string literal, including any surrounding parentheses, 133 /// to match the type of the object which it is initializing. 134 static void updateStringLiteralType(Expr *E, QualType Ty) { 135 while (true) { 136 E->setType(Ty); 137 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) 138 break; 139 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) 140 E = PE->getSubExpr(); 141 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 142 E = UO->getSubExpr(); 143 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) 144 E = GSE->getResultExpr(); 145 else 146 llvm_unreachable("unexpected expr in string literal init"); 147 } 148 } 149 150 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 151 Sema &S) { 152 // Get the length of the string as parsed. 153 auto *ConstantArrayTy = 154 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); 155 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); 156 157 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 158 // C99 6.7.8p14. We have an array of character type with unknown size 159 // being initialized to a string literal. 160 llvm::APInt ConstVal(32, StrLength); 161 // Return a new array type (C99 6.7.8p22). 162 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 163 ConstVal, 164 ArrayType::Normal, 0); 165 updateStringLiteralType(Str, DeclT); 166 return; 167 } 168 169 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 170 171 // We have an array of character type with known size. However, 172 // the size may be smaller or larger than the string we are initializing. 173 // FIXME: Avoid truncation for 64-bit length strings. 174 if (S.getLangOpts().CPlusPlus) { 175 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { 176 // For Pascal strings it's OK to strip off the terminating null character, 177 // so the example below is valid: 178 // 179 // unsigned char a[2] = "\pa"; 180 if (SL->isPascal()) 181 StrLength--; 182 } 183 184 // [dcl.init.string]p2 185 if (StrLength > CAT->getSize().getZExtValue()) 186 S.Diag(Str->getLocStart(), 187 diag::err_initializer_string_for_char_array_too_long) 188 << Str->getSourceRange(); 189 } else { 190 // C99 6.7.8p14. 191 if (StrLength-1 > CAT->getSize().getZExtValue()) 192 S.Diag(Str->getLocStart(), 193 diag::ext_initializer_string_for_char_array_too_long) 194 << Str->getSourceRange(); 195 } 196 197 // Set the type to the actual size that we are initializing. If we have 198 // something like: 199 // char x[1] = "foo"; 200 // then this will set the string literal's type to char[1]. 201 updateStringLiteralType(Str, DeclT); 202 } 203 204 //===----------------------------------------------------------------------===// 205 // Semantic checking for initializer lists. 206 //===----------------------------------------------------------------------===// 207 208 namespace { 209 210 /// @brief Semantic checking for initializer lists. 211 /// 212 /// The InitListChecker class contains a set of routines that each 213 /// handle the initialization of a certain kind of entity, e.g., 214 /// arrays, vectors, struct/union types, scalars, etc. The 215 /// InitListChecker itself performs a recursive walk of the subobject 216 /// structure of the type to be initialized, while stepping through 217 /// the initializer list one element at a time. The IList and Index 218 /// parameters to each of the Check* routines contain the active 219 /// (syntactic) initializer list and the index into that initializer 220 /// list that represents the current initializer. Each routine is 221 /// responsible for moving that Index forward as it consumes elements. 222 /// 223 /// Each Check* routine also has a StructuredList/StructuredIndex 224 /// arguments, which contains the current "structured" (semantic) 225 /// initializer list and the index into that initializer list where we 226 /// are copying initializers as we map them over to the semantic 227 /// list. Once we have completed our recursive walk of the subobject 228 /// structure, we will have constructed a full semantic initializer 229 /// list. 230 /// 231 /// C99 designators cause changes in the initializer list traversal, 232 /// because they make the initialization "jump" into a specific 233 /// subobject and then continue the initialization from that 234 /// point. CheckDesignatedInitializer() recursively steps into the 235 /// designated subobject and manages backing out the recursion to 236 /// initialize the subobjects after the one designated. 237 class InitListChecker { 238 Sema &SemaRef; 239 bool hadError; 240 bool VerifyOnly; // no diagnostics, no structure building 241 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. 242 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic; 243 InitListExpr *FullyStructuredList; 244 245 void CheckImplicitInitList(const InitializedEntity &Entity, 246 InitListExpr *ParentIList, QualType T, 247 unsigned &Index, InitListExpr *StructuredList, 248 unsigned &StructuredIndex); 249 void CheckExplicitInitList(const InitializedEntity &Entity, 250 InitListExpr *IList, QualType &T, 251 InitListExpr *StructuredList, 252 bool TopLevelObject = false); 253 void CheckListElementTypes(const InitializedEntity &Entity, 254 InitListExpr *IList, QualType &DeclType, 255 bool SubobjectIsDesignatorContext, 256 unsigned &Index, 257 InitListExpr *StructuredList, 258 unsigned &StructuredIndex, 259 bool TopLevelObject = false); 260 void CheckSubElementType(const InitializedEntity &Entity, 261 InitListExpr *IList, QualType ElemType, 262 unsigned &Index, 263 InitListExpr *StructuredList, 264 unsigned &StructuredIndex); 265 void CheckComplexType(const InitializedEntity &Entity, 266 InitListExpr *IList, QualType DeclType, 267 unsigned &Index, 268 InitListExpr *StructuredList, 269 unsigned &StructuredIndex); 270 void CheckScalarType(const InitializedEntity &Entity, 271 InitListExpr *IList, QualType DeclType, 272 unsigned &Index, 273 InitListExpr *StructuredList, 274 unsigned &StructuredIndex); 275 void CheckReferenceType(const InitializedEntity &Entity, 276 InitListExpr *IList, QualType DeclType, 277 unsigned &Index, 278 InitListExpr *StructuredList, 279 unsigned &StructuredIndex); 280 void CheckVectorType(const InitializedEntity &Entity, 281 InitListExpr *IList, QualType DeclType, unsigned &Index, 282 InitListExpr *StructuredList, 283 unsigned &StructuredIndex); 284 void CheckStructUnionTypes(const InitializedEntity &Entity, 285 InitListExpr *IList, QualType DeclType, 286 CXXRecordDecl::base_class_range Bases, 287 RecordDecl::field_iterator Field, 288 bool SubobjectIsDesignatorContext, unsigned &Index, 289 InitListExpr *StructuredList, 290 unsigned &StructuredIndex, 291 bool TopLevelObject = false); 292 void CheckArrayType(const InitializedEntity &Entity, 293 InitListExpr *IList, QualType &DeclType, 294 llvm::APSInt elementIndex, 295 bool SubobjectIsDesignatorContext, unsigned &Index, 296 InitListExpr *StructuredList, 297 unsigned &StructuredIndex); 298 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 299 InitListExpr *IList, DesignatedInitExpr *DIE, 300 unsigned DesigIdx, 301 QualType &CurrentObjectType, 302 RecordDecl::field_iterator *NextField, 303 llvm::APSInt *NextElementIndex, 304 unsigned &Index, 305 InitListExpr *StructuredList, 306 unsigned &StructuredIndex, 307 bool FinishSubobjectInit, 308 bool TopLevelObject); 309 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 310 QualType CurrentObjectType, 311 InitListExpr *StructuredList, 312 unsigned StructuredIndex, 313 SourceRange InitRange, 314 bool IsFullyOverwritten = false); 315 void UpdateStructuredListElement(InitListExpr *StructuredList, 316 unsigned &StructuredIndex, 317 Expr *expr); 318 int numArrayElements(QualType DeclType); 319 int numStructUnionElements(QualType DeclType); 320 321 static ExprResult PerformEmptyInit(Sema &SemaRef, 322 SourceLocation Loc, 323 const InitializedEntity &Entity, 324 bool VerifyOnly, 325 bool TreatUnavailableAsInvalid); 326 327 // Explanation on the "FillWithNoInit" mode: 328 // 329 // Assume we have the following definitions (Case#1): 330 // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; 331 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; 332 // 333 // l.lp.x[1][0..1] should not be filled with implicit initializers because the 334 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". 335 // 336 // But if we have (Case#2): 337 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; 338 // 339 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the 340 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". 341 // 342 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" 343 // in the InitListExpr, the "holes" in Case#1 are filled not with empty 344 // initializers but with special "NoInitExpr" place holders, which tells the 345 // CodeGen not to generate any initializers for these parts. 346 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, 347 const InitializedEntity &ParentEntity, 348 InitListExpr *ILE, bool &RequiresSecondPass, 349 bool FillWithNoInit); 350 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 351 const InitializedEntity &ParentEntity, 352 InitListExpr *ILE, bool &RequiresSecondPass, 353 bool FillWithNoInit = false); 354 void FillInEmptyInitializations(const InitializedEntity &Entity, 355 InitListExpr *ILE, bool &RequiresSecondPass, 356 bool FillWithNoInit = false); 357 bool CheckFlexibleArrayInit(const InitializedEntity &Entity, 358 Expr *InitExpr, FieldDecl *Field, 359 bool TopLevelObject); 360 void CheckEmptyInitializable(const InitializedEntity &Entity, 361 SourceLocation Loc); 362 363 public: 364 InitListChecker(Sema &S, const InitializedEntity &Entity, 365 InitListExpr *IL, QualType &T, bool VerifyOnly, 366 bool TreatUnavailableAsInvalid); 367 bool HadError() { return hadError; } 368 369 // @brief Retrieves the fully-structured initializer list used for 370 // semantic analysis and code generation. 371 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 372 }; 373 374 } // end anonymous namespace 375 376 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef, 377 SourceLocation Loc, 378 const InitializedEntity &Entity, 379 bool VerifyOnly, 380 bool TreatUnavailableAsInvalid) { 381 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 382 true); 383 MultiExprArg SubInit; 384 Expr *InitExpr; 385 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); 386 387 // C++ [dcl.init.aggr]p7: 388 // If there are fewer initializer-clauses in the list than there are 389 // members in the aggregate, then each member not explicitly initialized 390 // ... 391 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && 392 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); 393 if (EmptyInitList) { 394 // C++1y / DR1070: 395 // shall be initialized [...] from an empty initializer list. 396 // 397 // We apply the resolution of this DR to C++11 but not C++98, since C++98 398 // does not have useful semantics for initialization from an init list. 399 // We treat this as copy-initialization, because aggregate initialization 400 // always performs copy-initialization on its elements. 401 // 402 // Only do this if we're initializing a class type, to avoid filling in 403 // the initializer list where possible. 404 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) 405 InitListExpr(SemaRef.Context, Loc, None, Loc); 406 InitExpr->setType(SemaRef.Context.VoidTy); 407 SubInit = InitExpr; 408 Kind = InitializationKind::CreateCopy(Loc, Loc); 409 } else { 410 // C++03: 411 // shall be value-initialized. 412 } 413 414 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); 415 // libstdc++4.6 marks the vector default constructor as explicit in 416 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. 417 // stlport does so too. Look for std::__debug for libstdc++, and for 418 // std:: for stlport. This is effectively a compiler-side implementation of 419 // LWG2193. 420 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == 421 InitializationSequence::FK_ExplicitConstructor) { 422 OverloadCandidateSet::iterator Best; 423 OverloadingResult O = 424 InitSeq.getFailedCandidateSet() 425 .BestViableFunction(SemaRef, Kind.getLocation(), Best); 426 (void)O; 427 assert(O == OR_Success && "Inconsistent overload resolution"); 428 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 429 CXXRecordDecl *R = CtorDecl->getParent(); 430 431 if (CtorDecl->getMinRequiredArguments() == 0 && 432 CtorDecl->isExplicit() && R->getDeclName() && 433 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { 434 bool IsInStd = false; 435 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); 436 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { 437 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) 438 IsInStd = true; 439 } 440 441 if (IsInStd && llvm::StringSwitch<bool>(R->getName()) 442 .Cases("basic_string", "deque", "forward_list", true) 443 .Cases("list", "map", "multimap", "multiset", true) 444 .Cases("priority_queue", "queue", "set", "stack", true) 445 .Cases("unordered_map", "unordered_set", "vector", true) 446 .Default(false)) { 447 InitSeq.InitializeFrom( 448 SemaRef, Entity, 449 InitializationKind::CreateValue(Loc, Loc, Loc, true), 450 MultiExprArg(), /*TopLevelOfInitList=*/false, 451 TreatUnavailableAsInvalid); 452 // Emit a warning for this. System header warnings aren't shown 453 // by default, but people working on system headers should see it. 454 if (!VerifyOnly) { 455 SemaRef.Diag(CtorDecl->getLocation(), 456 diag::warn_invalid_initializer_from_system_header); 457 if (Entity.getKind() == InitializedEntity::EK_Member) 458 SemaRef.Diag(Entity.getDecl()->getLocation(), 459 diag::note_used_in_initialization_here); 460 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) 461 SemaRef.Diag(Loc, diag::note_used_in_initialization_here); 462 } 463 } 464 } 465 } 466 if (!InitSeq) { 467 if (!VerifyOnly) { 468 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); 469 if (Entity.getKind() == InitializedEntity::EK_Member) 470 SemaRef.Diag(Entity.getDecl()->getLocation(), 471 diag::note_in_omitted_aggregate_initializer) 472 << /*field*/1 << Entity.getDecl(); 473 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) 474 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) 475 << /*array element*/0 << Entity.getElementIndex(); 476 } 477 return ExprError(); 478 } 479 480 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr)) 481 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); 482 } 483 484 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, 485 SourceLocation Loc) { 486 assert(VerifyOnly && 487 "CheckEmptyInitializable is only inteded for verification mode."); 488 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true, 489 TreatUnavailableAsInvalid).isInvalid()) 490 hadError = true; 491 } 492 493 void InitListChecker::FillInEmptyInitForBase( 494 unsigned Init, const CXXBaseSpecifier &Base, 495 const InitializedEntity &ParentEntity, InitListExpr *ILE, 496 bool &RequiresSecondPass, bool FillWithNoInit) { 497 assert(Init < ILE->getNumInits() && "should have been expanded"); 498 499 InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 500 SemaRef.Context, &Base, false, &ParentEntity); 501 502 if (!ILE->getInit(Init)) { 503 ExprResult BaseInit = 504 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType()) 505 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity, 506 /*VerifyOnly*/ false, 507 TreatUnavailableAsInvalid); 508 if (BaseInit.isInvalid()) { 509 hadError = true; 510 return; 511 } 512 513 ILE->setInit(Init, BaseInit.getAs<Expr>()); 514 } else if (InitListExpr *InnerILE = 515 dyn_cast<InitListExpr>(ILE->getInit(Init))) { 516 FillInEmptyInitializations(BaseEntity, InnerILE, 517 RequiresSecondPass, FillWithNoInit); 518 } else if (DesignatedInitUpdateExpr *InnerDIUE = 519 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 520 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), 521 RequiresSecondPass, /*FillWithNoInit =*/true); 522 } 523 } 524 525 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 526 const InitializedEntity &ParentEntity, 527 InitListExpr *ILE, 528 bool &RequiresSecondPass, 529 bool FillWithNoInit) { 530 SourceLocation Loc = ILE->getLocEnd(); 531 unsigned NumInits = ILE->getNumInits(); 532 InitializedEntity MemberEntity 533 = InitializedEntity::InitializeMember(Field, &ParentEntity); 534 535 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) 536 if (!RType->getDecl()->isUnion()) 537 assert(Init < NumInits && "This ILE should have been expanded"); 538 539 if (Init >= NumInits || !ILE->getInit(Init)) { 540 if (FillWithNoInit) { 541 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); 542 if (Init < NumInits) 543 ILE->setInit(Init, Filler); 544 else 545 ILE->updateInit(SemaRef.Context, Init, Filler); 546 return; 547 } 548 // C++1y [dcl.init.aggr]p7: 549 // If there are fewer initializer-clauses in the list than there are 550 // members in the aggregate, then each member not explicitly initialized 551 // shall be initialized from its brace-or-equal-initializer [...] 552 if (Field->hasInClassInitializer()) { 553 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); 554 if (DIE.isInvalid()) { 555 hadError = true; 556 return; 557 } 558 if (Init < NumInits) 559 ILE->setInit(Init, DIE.get()); 560 else { 561 ILE->updateInit(SemaRef.Context, Init, DIE.get()); 562 RequiresSecondPass = true; 563 } 564 return; 565 } 566 567 if (Field->getType()->isReferenceType()) { 568 // C++ [dcl.init.aggr]p9: 569 // If an incomplete or empty initializer-list leaves a 570 // member of reference type uninitialized, the program is 571 // ill-formed. 572 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 573 << Field->getType() 574 << ILE->getSyntacticForm()->getSourceRange(); 575 SemaRef.Diag(Field->getLocation(), 576 diag::note_uninit_reference_member); 577 hadError = true; 578 return; 579 } 580 581 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity, 582 /*VerifyOnly*/false, 583 TreatUnavailableAsInvalid); 584 if (MemberInit.isInvalid()) { 585 hadError = true; 586 return; 587 } 588 589 if (hadError) { 590 // Do nothing 591 } else if (Init < NumInits) { 592 ILE->setInit(Init, MemberInit.getAs<Expr>()); 593 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { 594 // Empty initialization requires a constructor call, so 595 // extend the initializer list to include the constructor 596 // call and make a note that we'll need to take another pass 597 // through the initializer list. 598 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); 599 RequiresSecondPass = true; 600 } 601 } else if (InitListExpr *InnerILE 602 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 603 FillInEmptyInitializations(MemberEntity, InnerILE, 604 RequiresSecondPass, FillWithNoInit); 605 else if (DesignatedInitUpdateExpr *InnerDIUE 606 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) 607 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), 608 RequiresSecondPass, /*FillWithNoInit =*/ true); 609 } 610 611 /// Recursively replaces NULL values within the given initializer list 612 /// with expressions that perform value-initialization of the 613 /// appropriate type. 614 void 615 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, 616 InitListExpr *ILE, 617 bool &RequiresSecondPass, 618 bool FillWithNoInit) { 619 assert((ILE->getType() != SemaRef.Context.VoidTy) && 620 "Should not have void type"); 621 622 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 623 const RecordDecl *RDecl = RType->getDecl(); 624 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) 625 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), 626 Entity, ILE, RequiresSecondPass, FillWithNoInit); 627 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && 628 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { 629 for (auto *Field : RDecl->fields()) { 630 if (Field->hasInClassInitializer()) { 631 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, 632 FillWithNoInit); 633 break; 634 } 635 } 636 } else { 637 // The fields beyond ILE->getNumInits() are default initialized, so in 638 // order to leave them uninitialized, the ILE is expanded and the extra 639 // fields are then filled with NoInitExpr. 640 unsigned NumElems = numStructUnionElements(ILE->getType()); 641 if (RDecl->hasFlexibleArrayMember()) 642 ++NumElems; 643 if (ILE->getNumInits() < NumElems) 644 ILE->resizeInits(SemaRef.Context, NumElems); 645 646 unsigned Init = 0; 647 648 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { 649 for (auto &Base : CXXRD->bases()) { 650 if (hadError) 651 return; 652 653 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, 654 FillWithNoInit); 655 ++Init; 656 } 657 } 658 659 for (auto *Field : RDecl->fields()) { 660 if (Field->isUnnamedBitfield()) 661 continue; 662 663 if (hadError) 664 return; 665 666 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, 667 FillWithNoInit); 668 if (hadError) 669 return; 670 671 ++Init; 672 673 // Only look at the first initialization of a union. 674 if (RDecl->isUnion()) 675 break; 676 } 677 } 678 679 return; 680 } 681 682 QualType ElementType; 683 684 InitializedEntity ElementEntity = Entity; 685 unsigned NumInits = ILE->getNumInits(); 686 unsigned NumElements = NumInits; 687 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 688 ElementType = AType->getElementType(); 689 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 690 NumElements = CAType->getSize().getZExtValue(); 691 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 692 0, Entity); 693 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 694 ElementType = VType->getElementType(); 695 NumElements = VType->getNumElements(); 696 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 697 0, Entity); 698 } else 699 ElementType = ILE->getType(); 700 701 for (unsigned Init = 0; Init != NumElements; ++Init) { 702 if (hadError) 703 return; 704 705 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 706 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 707 ElementEntity.setElementIndex(Init); 708 709 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); 710 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) 711 ILE->setInit(Init, ILE->getArrayFiller()); 712 else if (!InitExpr && !ILE->hasArrayFiller()) { 713 Expr *Filler = nullptr; 714 715 if (FillWithNoInit) 716 Filler = new (SemaRef.Context) NoInitExpr(ElementType); 717 else { 718 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(), 719 ElementEntity, 720 /*VerifyOnly*/false, 721 TreatUnavailableAsInvalid); 722 if (ElementInit.isInvalid()) { 723 hadError = true; 724 return; 725 } 726 727 Filler = ElementInit.getAs<Expr>(); 728 } 729 730 if (hadError) { 731 // Do nothing 732 } else if (Init < NumInits) { 733 // For arrays, just set the expression used for value-initialization 734 // of the "holes" in the array. 735 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 736 ILE->setArrayFiller(Filler); 737 else 738 ILE->setInit(Init, Filler); 739 } else { 740 // For arrays, just set the expression used for value-initialization 741 // of the rest of elements and exit. 742 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 743 ILE->setArrayFiller(Filler); 744 return; 745 } 746 747 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { 748 // Empty initialization requires a constructor call, so 749 // extend the initializer list to include the constructor 750 // call and make a note that we'll need to take another pass 751 // through the initializer list. 752 ILE->updateInit(SemaRef.Context, Init, Filler); 753 RequiresSecondPass = true; 754 } 755 } 756 } else if (InitListExpr *InnerILE 757 = dyn_cast_or_null<InitListExpr>(InitExpr)) 758 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, 759 FillWithNoInit); 760 else if (DesignatedInitUpdateExpr *InnerDIUE 761 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) 762 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), 763 RequiresSecondPass, /*FillWithNoInit =*/ true); 764 } 765 } 766 767 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 768 InitListExpr *IL, QualType &T, 769 bool VerifyOnly, 770 bool TreatUnavailableAsInvalid) 771 : SemaRef(S), VerifyOnly(VerifyOnly), 772 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) { 773 // FIXME: Check that IL isn't already the semantic form of some other 774 // InitListExpr. If it is, we'd create a broken AST. 775 776 hadError = false; 777 778 FullyStructuredList = 779 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange()); 780 CheckExplicitInitList(Entity, IL, T, FullyStructuredList, 781 /*TopLevelObject=*/true); 782 783 if (!hadError && !VerifyOnly) { 784 bool RequiresSecondPass = false; 785 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass); 786 if (RequiresSecondPass && !hadError) 787 FillInEmptyInitializations(Entity, FullyStructuredList, 788 RequiresSecondPass); 789 } 790 } 791 792 int InitListChecker::numArrayElements(QualType DeclType) { 793 // FIXME: use a proper constant 794 int maxElements = 0x7FFFFFFF; 795 if (const ConstantArrayType *CAT = 796 SemaRef.Context.getAsConstantArrayType(DeclType)) { 797 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 798 } 799 return maxElements; 800 } 801 802 int InitListChecker::numStructUnionElements(QualType DeclType) { 803 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 804 int InitializableMembers = 0; 805 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) 806 InitializableMembers += CXXRD->getNumBases(); 807 for (const auto *Field : structDecl->fields()) 808 if (!Field->isUnnamedBitfield()) 809 ++InitializableMembers; 810 811 if (structDecl->isUnion()) 812 return std::min(InitializableMembers, 1); 813 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 814 } 815 816 /// Check whether the range of the initializer \p ParentIList from element 817 /// \p Index onwards can be used to initialize an object of type \p T. Update 818 /// \p Index to indicate how many elements of the list were consumed. 819 /// 820 /// This also fills in \p StructuredList, from element \p StructuredIndex 821 /// onwards, with the fully-braced, desugared form of the initialization. 822 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 823 InitListExpr *ParentIList, 824 QualType T, unsigned &Index, 825 InitListExpr *StructuredList, 826 unsigned &StructuredIndex) { 827 int maxElements = 0; 828 829 if (T->isArrayType()) 830 maxElements = numArrayElements(T); 831 else if (T->isRecordType()) 832 maxElements = numStructUnionElements(T); 833 else if (T->isVectorType()) 834 maxElements = T->getAs<VectorType>()->getNumElements(); 835 else 836 llvm_unreachable("CheckImplicitInitList(): Illegal type"); 837 838 if (maxElements == 0) { 839 if (!VerifyOnly) 840 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 841 diag::err_implicit_empty_initializer); 842 ++Index; 843 hadError = true; 844 return; 845 } 846 847 // Build a structured initializer list corresponding to this subobject. 848 InitListExpr *StructuredSubobjectInitList 849 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 850 StructuredIndex, 851 SourceRange(ParentIList->getInit(Index)->getLocStart(), 852 ParentIList->getSourceRange().getEnd())); 853 unsigned StructuredSubobjectInitIndex = 0; 854 855 // Check the element types and build the structural subobject. 856 unsigned StartIndex = Index; 857 CheckListElementTypes(Entity, ParentIList, T, 858 /*SubobjectIsDesignatorContext=*/false, Index, 859 StructuredSubobjectInitList, 860 StructuredSubobjectInitIndex); 861 862 if (!VerifyOnly) { 863 StructuredSubobjectInitList->setType(T); 864 865 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 866 // Update the structured sub-object initializer so that it's ending 867 // range corresponds with the end of the last initializer it used. 868 if (EndIndex < ParentIList->getNumInits() && 869 ParentIList->getInit(EndIndex)) { 870 SourceLocation EndLoc 871 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 872 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 873 } 874 875 // Complain about missing braces. 876 if (T->isArrayType() || T->isRecordType()) { 877 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), 878 diag::warn_missing_braces) 879 << StructuredSubobjectInitList->getSourceRange() 880 << FixItHint::CreateInsertion( 881 StructuredSubobjectInitList->getLocStart(), "{") 882 << FixItHint::CreateInsertion( 883 SemaRef.getLocForEndOfToken( 884 StructuredSubobjectInitList->getLocEnd()), 885 "}"); 886 } 887 } 888 } 889 890 /// Warn that \p Entity was of scalar type and was initialized by a 891 /// single-element braced initializer list. 892 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, 893 SourceRange Braces) { 894 // Don't warn during template instantiation. If the initialization was 895 // non-dependent, we warned during the initial parse; otherwise, the 896 // type might not be scalar in some uses of the template. 897 if (!S.ActiveTemplateInstantiations.empty()) 898 return; 899 900 unsigned DiagID = 0; 901 902 switch (Entity.getKind()) { 903 case InitializedEntity::EK_VectorElement: 904 case InitializedEntity::EK_ComplexElement: 905 case InitializedEntity::EK_ArrayElement: 906 case InitializedEntity::EK_Parameter: 907 case InitializedEntity::EK_Parameter_CF_Audited: 908 case InitializedEntity::EK_Result: 909 // Extra braces here are suspicious. 910 DiagID = diag::warn_braces_around_scalar_init; 911 break; 912 913 case InitializedEntity::EK_Member: 914 // Warn on aggregate initialization but not on ctor init list or 915 // default member initializer. 916 if (Entity.getParent()) 917 DiagID = diag::warn_braces_around_scalar_init; 918 break; 919 920 case InitializedEntity::EK_Variable: 921 case InitializedEntity::EK_LambdaCapture: 922 // No warning, might be direct-list-initialization. 923 // FIXME: Should we warn for copy-list-initialization in these cases? 924 break; 925 926 case InitializedEntity::EK_New: 927 case InitializedEntity::EK_Temporary: 928 case InitializedEntity::EK_CompoundLiteralInit: 929 // No warning, braces are part of the syntax of the underlying construct. 930 break; 931 932 case InitializedEntity::EK_RelatedResult: 933 // No warning, we already warned when initializing the result. 934 break; 935 936 case InitializedEntity::EK_Exception: 937 case InitializedEntity::EK_Base: 938 case InitializedEntity::EK_Delegating: 939 case InitializedEntity::EK_BlockElement: 940 llvm_unreachable("unexpected braced scalar init"); 941 } 942 943 if (DiagID) { 944 S.Diag(Braces.getBegin(), DiagID) 945 << Braces 946 << FixItHint::CreateRemoval(Braces.getBegin()) 947 << FixItHint::CreateRemoval(Braces.getEnd()); 948 } 949 } 950 951 /// Check whether the initializer \p IList (that was written with explicit 952 /// braces) can be used to initialize an object of type \p T. 953 /// 954 /// This also fills in \p StructuredList with the fully-braced, desugared 955 /// form of the initialization. 956 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 957 InitListExpr *IList, QualType &T, 958 InitListExpr *StructuredList, 959 bool TopLevelObject) { 960 if (!VerifyOnly) { 961 SyntacticToSemantic[IList] = StructuredList; 962 StructuredList->setSyntacticForm(IList); 963 } 964 965 unsigned Index = 0, StructuredIndex = 0; 966 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 967 Index, StructuredList, StructuredIndex, TopLevelObject); 968 if (!VerifyOnly) { 969 QualType ExprTy = T; 970 if (!ExprTy->isArrayType()) 971 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); 972 IList->setType(ExprTy); 973 StructuredList->setType(ExprTy); 974 } 975 if (hadError) 976 return; 977 978 if (Index < IList->getNumInits()) { 979 // We have leftover initializers 980 if (VerifyOnly) { 981 if (SemaRef.getLangOpts().CPlusPlus || 982 (SemaRef.getLangOpts().OpenCL && 983 IList->getType()->isVectorType())) { 984 hadError = true; 985 } 986 return; 987 } 988 989 if (StructuredIndex == 1 && 990 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == 991 SIF_None) { 992 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer; 993 if (SemaRef.getLangOpts().CPlusPlus) { 994 DK = diag::err_excess_initializers_in_char_array_initializer; 995 hadError = true; 996 } 997 // Special-case 998 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 999 << IList->getInit(Index)->getSourceRange(); 1000 } else if (!T->isIncompleteType()) { 1001 // Don't complain for incomplete types, since we'll get an error 1002 // elsewhere 1003 QualType CurrentObjectType = StructuredList->getType(); 1004 int initKind = 1005 CurrentObjectType->isArrayType()? 0 : 1006 CurrentObjectType->isVectorType()? 1 : 1007 CurrentObjectType->isScalarType()? 2 : 1008 CurrentObjectType->isUnionType()? 3 : 1009 4; 1010 1011 unsigned DK = diag::ext_excess_initializers; 1012 if (SemaRef.getLangOpts().CPlusPlus) { 1013 DK = diag::err_excess_initializers; 1014 hadError = true; 1015 } 1016 if (SemaRef.getLangOpts().OpenCL && initKind == 1) { 1017 DK = diag::err_excess_initializers; 1018 hadError = true; 1019 } 1020 1021 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 1022 << initKind << IList->getInit(Index)->getSourceRange(); 1023 } 1024 } 1025 1026 if (!VerifyOnly && T->isScalarType() && 1027 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0))) 1028 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); 1029 } 1030 1031 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 1032 InitListExpr *IList, 1033 QualType &DeclType, 1034 bool SubobjectIsDesignatorContext, 1035 unsigned &Index, 1036 InitListExpr *StructuredList, 1037 unsigned &StructuredIndex, 1038 bool TopLevelObject) { 1039 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { 1040 // Explicitly braced initializer for complex type can be real+imaginary 1041 // parts. 1042 CheckComplexType(Entity, IList, DeclType, Index, 1043 StructuredList, StructuredIndex); 1044 } else if (DeclType->isScalarType()) { 1045 CheckScalarType(Entity, IList, DeclType, Index, 1046 StructuredList, StructuredIndex); 1047 } else if (DeclType->isVectorType()) { 1048 CheckVectorType(Entity, IList, DeclType, Index, 1049 StructuredList, StructuredIndex); 1050 } else if (DeclType->isRecordType()) { 1051 assert(DeclType->isAggregateType() && 1052 "non-aggregate records should be handed in CheckSubElementType"); 1053 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1054 auto Bases = 1055 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 1056 CXXRecordDecl::base_class_iterator()); 1057 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1058 Bases = CXXRD->bases(); 1059 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), 1060 SubobjectIsDesignatorContext, Index, StructuredList, 1061 StructuredIndex, TopLevelObject); 1062 } else if (DeclType->isArrayType()) { 1063 llvm::APSInt Zero( 1064 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 1065 false); 1066 CheckArrayType(Entity, IList, DeclType, Zero, 1067 SubobjectIsDesignatorContext, Index, 1068 StructuredList, StructuredIndex); 1069 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 1070 // This type is invalid, issue a diagnostic. 1071 ++Index; 1072 if (!VerifyOnly) 1073 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 1074 << DeclType; 1075 hadError = true; 1076 } else if (DeclType->isReferenceType()) { 1077 CheckReferenceType(Entity, IList, DeclType, Index, 1078 StructuredList, StructuredIndex); 1079 } else if (DeclType->isObjCObjectType()) { 1080 if (!VerifyOnly) 1081 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class) 1082 << DeclType; 1083 hadError = true; 1084 } else { 1085 if (!VerifyOnly) 1086 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 1087 << DeclType; 1088 hadError = true; 1089 } 1090 } 1091 1092 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 1093 InitListExpr *IList, 1094 QualType ElemType, 1095 unsigned &Index, 1096 InitListExpr *StructuredList, 1097 unsigned &StructuredIndex) { 1098 Expr *expr = IList->getInit(Index); 1099 1100 if (ElemType->isReferenceType()) 1101 return CheckReferenceType(Entity, IList, ElemType, Index, 1102 StructuredList, StructuredIndex); 1103 1104 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 1105 if (SubInitList->getNumInits() == 1 && 1106 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == 1107 SIF_None) { 1108 expr = SubInitList->getInit(0); 1109 } else if (!SemaRef.getLangOpts().CPlusPlus) { 1110 InitListExpr *InnerStructuredList 1111 = getStructuredSubobjectInit(IList, Index, ElemType, 1112 StructuredList, StructuredIndex, 1113 SubInitList->getSourceRange(), true); 1114 CheckExplicitInitList(Entity, SubInitList, ElemType, 1115 InnerStructuredList); 1116 1117 if (!hadError && !VerifyOnly) { 1118 bool RequiresSecondPass = false; 1119 FillInEmptyInitializations(Entity, InnerStructuredList, 1120 RequiresSecondPass); 1121 if (RequiresSecondPass && !hadError) 1122 FillInEmptyInitializations(Entity, InnerStructuredList, 1123 RequiresSecondPass); 1124 } 1125 ++StructuredIndex; 1126 ++Index; 1127 return; 1128 } 1129 // C++ initialization is handled later. 1130 } else if (isa<ImplicitValueInitExpr>(expr)) { 1131 // This happens during template instantiation when we see an InitListExpr 1132 // that we've already checked once. 1133 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && 1134 "found implicit initialization for the wrong type"); 1135 if (!VerifyOnly) 1136 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1137 ++Index; 1138 return; 1139 } 1140 1141 if (SemaRef.getLangOpts().CPlusPlus) { 1142 // C++ [dcl.init.aggr]p2: 1143 // Each member is copy-initialized from the corresponding 1144 // initializer-clause. 1145 1146 // FIXME: Better EqualLoc? 1147 InitializationKind Kind = 1148 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation()); 1149 InitializationSequence Seq(SemaRef, Entity, Kind, expr, 1150 /*TopLevelOfInitList*/ true); 1151 1152 // C++14 [dcl.init.aggr]p13: 1153 // If the assignment-expression can initialize a member, the member is 1154 // initialized. Otherwise [...] brace elision is assumed 1155 // 1156 // Brace elision is never performed if the element is not an 1157 // assignment-expression. 1158 if (Seq || isa<InitListExpr>(expr)) { 1159 if (!VerifyOnly) { 1160 ExprResult Result = 1161 Seq.Perform(SemaRef, Entity, Kind, expr); 1162 if (Result.isInvalid()) 1163 hadError = true; 1164 1165 UpdateStructuredListElement(StructuredList, StructuredIndex, 1166 Result.getAs<Expr>()); 1167 } else if (!Seq) 1168 hadError = true; 1169 ++Index; 1170 return; 1171 } 1172 1173 // Fall through for subaggregate initialization 1174 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { 1175 // FIXME: Need to handle atomic aggregate types with implicit init lists. 1176 return CheckScalarType(Entity, IList, ElemType, Index, 1177 StructuredList, StructuredIndex); 1178 } else if (const ArrayType *arrayType = 1179 SemaRef.Context.getAsArrayType(ElemType)) { 1180 // arrayType can be incomplete if we're initializing a flexible 1181 // array member. There's nothing we can do with the completed 1182 // type here, though. 1183 1184 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { 1185 if (!VerifyOnly) { 1186 CheckStringInit(expr, ElemType, arrayType, SemaRef); 1187 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1188 } 1189 ++Index; 1190 return; 1191 } 1192 1193 // Fall through for subaggregate initialization. 1194 1195 } else { 1196 assert((ElemType->isRecordType() || ElemType->isVectorType()) && 1197 "Unexpected type"); 1198 1199 // C99 6.7.8p13: 1200 // 1201 // The initializer for a structure or union object that has 1202 // automatic storage duration shall be either an initializer 1203 // list as described below, or a single expression that has 1204 // compatible structure or union type. In the latter case, the 1205 // initial value of the object, including unnamed members, is 1206 // that of the expression. 1207 ExprResult ExprRes = expr; 1208 if (SemaRef.CheckSingleAssignmentConstraints( 1209 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { 1210 if (ExprRes.isInvalid()) 1211 hadError = true; 1212 else { 1213 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); 1214 if (ExprRes.isInvalid()) 1215 hadError = true; 1216 } 1217 UpdateStructuredListElement(StructuredList, StructuredIndex, 1218 ExprRes.getAs<Expr>()); 1219 ++Index; 1220 return; 1221 } 1222 ExprRes.get(); 1223 // Fall through for subaggregate initialization 1224 } 1225 1226 // C++ [dcl.init.aggr]p12: 1227 // 1228 // [...] Otherwise, if the member is itself a non-empty 1229 // subaggregate, brace elision is assumed and the initializer is 1230 // considered for the initialization of the first member of 1231 // the subaggregate. 1232 if (!SemaRef.getLangOpts().OpenCL && 1233 (ElemType->isAggregateType() || ElemType->isVectorType())) { 1234 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 1235 StructuredIndex); 1236 ++StructuredIndex; 1237 } else { 1238 if (!VerifyOnly) { 1239 // We cannot initialize this element, so let 1240 // PerformCopyInitialization produce the appropriate diagnostic. 1241 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, 1242 /*TopLevelOfInitList=*/true); 1243 } 1244 hadError = true; 1245 ++Index; 1246 ++StructuredIndex; 1247 } 1248 } 1249 1250 void InitListChecker::CheckComplexType(const InitializedEntity &Entity, 1251 InitListExpr *IList, QualType DeclType, 1252 unsigned &Index, 1253 InitListExpr *StructuredList, 1254 unsigned &StructuredIndex) { 1255 assert(Index == 0 && "Index in explicit init list must be zero"); 1256 1257 // As an extension, clang supports complex initializers, which initialize 1258 // a complex number component-wise. When an explicit initializer list for 1259 // a complex number contains two two initializers, this extension kicks in: 1260 // it exepcts the initializer list to contain two elements convertible to 1261 // the element type of the complex type. The first element initializes 1262 // the real part, and the second element intitializes the imaginary part. 1263 1264 if (IList->getNumInits() != 2) 1265 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1266 StructuredIndex); 1267 1268 // This is an extension in C. (The builtin _Complex type does not exist 1269 // in the C++ standard.) 1270 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) 1271 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init) 1272 << IList->getSourceRange(); 1273 1274 // Initialize the complex number. 1275 QualType elementType = DeclType->getAs<ComplexType>()->getElementType(); 1276 InitializedEntity ElementEntity = 1277 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1278 1279 for (unsigned i = 0; i < 2; ++i) { 1280 ElementEntity.setElementIndex(Index); 1281 CheckSubElementType(ElementEntity, IList, elementType, Index, 1282 StructuredList, StructuredIndex); 1283 } 1284 } 1285 1286 void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 1287 InitListExpr *IList, QualType DeclType, 1288 unsigned &Index, 1289 InitListExpr *StructuredList, 1290 unsigned &StructuredIndex) { 1291 if (Index >= IList->getNumInits()) { 1292 if (!VerifyOnly) 1293 SemaRef.Diag(IList->getLocStart(), 1294 SemaRef.getLangOpts().CPlusPlus11 ? 1295 diag::warn_cxx98_compat_empty_scalar_initializer : 1296 diag::err_empty_scalar_initializer) 1297 << IList->getSourceRange(); 1298 hadError = !SemaRef.getLangOpts().CPlusPlus11; 1299 ++Index; 1300 ++StructuredIndex; 1301 return; 1302 } 1303 1304 Expr *expr = IList->getInit(Index); 1305 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 1306 // FIXME: This is invalid, and accepting it causes overload resolution 1307 // to pick the wrong overload in some corner cases. 1308 if (!VerifyOnly) 1309 SemaRef.Diag(SubIList->getLocStart(), 1310 diag::ext_many_braces_around_scalar_init) 1311 << SubIList->getSourceRange(); 1312 1313 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 1314 StructuredIndex); 1315 return; 1316 } else if (isa<DesignatedInitExpr>(expr)) { 1317 if (!VerifyOnly) 1318 SemaRef.Diag(expr->getLocStart(), 1319 diag::err_designator_for_scalar_init) 1320 << DeclType << expr->getSourceRange(); 1321 hadError = true; 1322 ++Index; 1323 ++StructuredIndex; 1324 return; 1325 } 1326 1327 if (VerifyOnly) { 1328 if (!SemaRef.CanPerformCopyInitialization(Entity,expr)) 1329 hadError = true; 1330 ++Index; 1331 return; 1332 } 1333 1334 ExprResult Result = 1335 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr, 1336 /*TopLevelOfInitList=*/true); 1337 1338 Expr *ResultExpr = nullptr; 1339 1340 if (Result.isInvalid()) 1341 hadError = true; // types weren't compatible. 1342 else { 1343 ResultExpr = Result.getAs<Expr>(); 1344 1345 if (ResultExpr != expr) { 1346 // The type was promoted, update initializer list. 1347 IList->setInit(Index, ResultExpr); 1348 } 1349 } 1350 if (hadError) 1351 ++StructuredIndex; 1352 else 1353 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1354 ++Index; 1355 } 1356 1357 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 1358 InitListExpr *IList, QualType DeclType, 1359 unsigned &Index, 1360 InitListExpr *StructuredList, 1361 unsigned &StructuredIndex) { 1362 if (Index >= IList->getNumInits()) { 1363 // FIXME: It would be wonderful if we could point at the actual member. In 1364 // general, it would be useful to pass location information down the stack, 1365 // so that we know the location (or decl) of the "current object" being 1366 // initialized. 1367 if (!VerifyOnly) 1368 SemaRef.Diag(IList->getLocStart(), 1369 diag::err_init_reference_member_uninitialized) 1370 << DeclType 1371 << IList->getSourceRange(); 1372 hadError = true; 1373 ++Index; 1374 ++StructuredIndex; 1375 return; 1376 } 1377 1378 Expr *expr = IList->getInit(Index); 1379 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { 1380 if (!VerifyOnly) 1381 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 1382 << DeclType << IList->getSourceRange(); 1383 hadError = true; 1384 ++Index; 1385 ++StructuredIndex; 1386 return; 1387 } 1388 1389 if (VerifyOnly) { 1390 if (!SemaRef.CanPerformCopyInitialization(Entity,expr)) 1391 hadError = true; 1392 ++Index; 1393 return; 1394 } 1395 1396 ExprResult Result = 1397 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr, 1398 /*TopLevelOfInitList=*/true); 1399 1400 if (Result.isInvalid()) 1401 hadError = true; 1402 1403 expr = Result.getAs<Expr>(); 1404 IList->setInit(Index, expr); 1405 1406 if (hadError) 1407 ++StructuredIndex; 1408 else 1409 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1410 ++Index; 1411 } 1412 1413 void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 1414 InitListExpr *IList, QualType DeclType, 1415 unsigned &Index, 1416 InitListExpr *StructuredList, 1417 unsigned &StructuredIndex) { 1418 const VectorType *VT = DeclType->getAs<VectorType>(); 1419 unsigned maxElements = VT->getNumElements(); 1420 unsigned numEltsInit = 0; 1421 QualType elementType = VT->getElementType(); 1422 1423 if (Index >= IList->getNumInits()) { 1424 // Make sure the element type can be value-initialized. 1425 if (VerifyOnly) 1426 CheckEmptyInitializable( 1427 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1428 IList->getLocEnd()); 1429 return; 1430 } 1431 1432 if (!SemaRef.getLangOpts().OpenCL) { 1433 // If the initializing element is a vector, try to copy-initialize 1434 // instead of breaking it apart (which is doomed to failure anyway). 1435 Expr *Init = IList->getInit(Index); 1436 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 1437 if (VerifyOnly) { 1438 if (!SemaRef.CanPerformCopyInitialization(Entity, Init)) 1439 hadError = true; 1440 ++Index; 1441 return; 1442 } 1443 1444 ExprResult Result = 1445 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init, 1446 /*TopLevelOfInitList=*/true); 1447 1448 Expr *ResultExpr = nullptr; 1449 if (Result.isInvalid()) 1450 hadError = true; // types weren't compatible. 1451 else { 1452 ResultExpr = Result.getAs<Expr>(); 1453 1454 if (ResultExpr != Init) { 1455 // The type was promoted, update initializer list. 1456 IList->setInit(Index, ResultExpr); 1457 } 1458 } 1459 if (hadError) 1460 ++StructuredIndex; 1461 else 1462 UpdateStructuredListElement(StructuredList, StructuredIndex, 1463 ResultExpr); 1464 ++Index; 1465 return; 1466 } 1467 1468 InitializedEntity ElementEntity = 1469 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1470 1471 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 1472 // Don't attempt to go past the end of the init list 1473 if (Index >= IList->getNumInits()) { 1474 if (VerifyOnly) 1475 CheckEmptyInitializable(ElementEntity, IList->getLocEnd()); 1476 break; 1477 } 1478 1479 ElementEntity.setElementIndex(Index); 1480 CheckSubElementType(ElementEntity, IList, elementType, Index, 1481 StructuredList, StructuredIndex); 1482 } 1483 1484 if (VerifyOnly) 1485 return; 1486 1487 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); 1488 const VectorType *T = Entity.getType()->getAs<VectorType>(); 1489 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || 1490 T->getVectorKind() == VectorType::NeonPolyVector)) { 1491 // The ability to use vector initializer lists is a GNU vector extension 1492 // and is unrelated to the NEON intrinsics in arm_neon.h. On little 1493 // endian machines it works fine, however on big endian machines it 1494 // exhibits surprising behaviour: 1495 // 1496 // uint32x2_t x = {42, 64}; 1497 // return vget_lane_u32(x, 0); // Will return 64. 1498 // 1499 // Because of this, explicitly call out that it is non-portable. 1500 // 1501 SemaRef.Diag(IList->getLocStart(), 1502 diag::warn_neon_vector_initializer_non_portable); 1503 1504 const char *typeCode; 1505 unsigned typeSize = SemaRef.Context.getTypeSize(elementType); 1506 1507 if (elementType->isFloatingType()) 1508 typeCode = "f"; 1509 else if (elementType->isSignedIntegerType()) 1510 typeCode = "s"; 1511 else if (elementType->isUnsignedIntegerType()) 1512 typeCode = "u"; 1513 else 1514 llvm_unreachable("Invalid element type!"); 1515 1516 SemaRef.Diag(IList->getLocStart(), 1517 SemaRef.Context.getTypeSize(VT) > 64 ? 1518 diag::note_neon_vector_initializer_non_portable_q : 1519 diag::note_neon_vector_initializer_non_portable) 1520 << typeCode << typeSize; 1521 } 1522 1523 return; 1524 } 1525 1526 InitializedEntity ElementEntity = 1527 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1528 1529 // OpenCL initializers allows vectors to be constructed from vectors. 1530 for (unsigned i = 0; i < maxElements; ++i) { 1531 // Don't attempt to go past the end of the init list 1532 if (Index >= IList->getNumInits()) 1533 break; 1534 1535 ElementEntity.setElementIndex(Index); 1536 1537 QualType IType = IList->getInit(Index)->getType(); 1538 if (!IType->isVectorType()) { 1539 CheckSubElementType(ElementEntity, IList, elementType, Index, 1540 StructuredList, StructuredIndex); 1541 ++numEltsInit; 1542 } else { 1543 QualType VecType; 1544 const VectorType *IVT = IType->getAs<VectorType>(); 1545 unsigned numIElts = IVT->getNumElements(); 1546 1547 if (IType->isExtVectorType()) 1548 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 1549 else 1550 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 1551 IVT->getVectorKind()); 1552 CheckSubElementType(ElementEntity, IList, VecType, Index, 1553 StructuredList, StructuredIndex); 1554 numEltsInit += numIElts; 1555 } 1556 } 1557 1558 // OpenCL requires all elements to be initialized. 1559 if (numEltsInit != maxElements) { 1560 if (!VerifyOnly) 1561 SemaRef.Diag(IList->getLocStart(), 1562 diag::err_vector_incorrect_num_initializers) 1563 << (numEltsInit < maxElements) << maxElements << numEltsInit; 1564 hadError = true; 1565 } 1566 } 1567 1568 void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 1569 InitListExpr *IList, QualType &DeclType, 1570 llvm::APSInt elementIndex, 1571 bool SubobjectIsDesignatorContext, 1572 unsigned &Index, 1573 InitListExpr *StructuredList, 1574 unsigned &StructuredIndex) { 1575 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 1576 1577 // Check for the special-case of initializing an array with a string. 1578 if (Index < IList->getNumInits()) { 1579 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == 1580 SIF_None) { 1581 // We place the string literal directly into the resulting 1582 // initializer list. This is the only place where the structure 1583 // of the structured initializer list doesn't match exactly, 1584 // because doing so would involve allocating one character 1585 // constant for each string. 1586 if (!VerifyOnly) { 1587 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); 1588 UpdateStructuredListElement(StructuredList, StructuredIndex, 1589 IList->getInit(Index)); 1590 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1591 } 1592 ++Index; 1593 return; 1594 } 1595 } 1596 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1597 // Check for VLAs; in standard C it would be possible to check this 1598 // earlier, but I don't know where clang accepts VLAs (gcc accepts 1599 // them in all sorts of strange places). 1600 if (!VerifyOnly) 1601 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 1602 diag::err_variable_object_no_init) 1603 << VAT->getSizeExpr()->getSourceRange(); 1604 hadError = true; 1605 ++Index; 1606 ++StructuredIndex; 1607 return; 1608 } 1609 1610 // We might know the maximum number of elements in advance. 1611 llvm::APSInt maxElements(elementIndex.getBitWidth(), 1612 elementIndex.isUnsigned()); 1613 bool maxElementsKnown = false; 1614 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1615 maxElements = CAT->getSize(); 1616 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1617 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1618 maxElementsKnown = true; 1619 } 1620 1621 QualType elementType = arrayType->getElementType(); 1622 while (Index < IList->getNumInits()) { 1623 Expr *Init = IList->getInit(Index); 1624 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1625 // If we're not the subobject that matches up with the '{' for 1626 // the designator, we shouldn't be handling the 1627 // designator. Return immediately. 1628 if (!SubobjectIsDesignatorContext) 1629 return; 1630 1631 // Handle this designated initializer. elementIndex will be 1632 // updated to be the next array element we'll initialize. 1633 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1634 DeclType, nullptr, &elementIndex, Index, 1635 StructuredList, StructuredIndex, true, 1636 false)) { 1637 hadError = true; 1638 continue; 1639 } 1640 1641 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1642 maxElements = maxElements.extend(elementIndex.getBitWidth()); 1643 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1644 elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1645 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1646 1647 // If the array is of incomplete type, keep track of the number of 1648 // elements in the initializer. 1649 if (!maxElementsKnown && elementIndex > maxElements) 1650 maxElements = elementIndex; 1651 1652 continue; 1653 } 1654 1655 // If we know the maximum number of elements, and we've already 1656 // hit it, stop consuming elements in the initializer list. 1657 if (maxElementsKnown && elementIndex == maxElements) 1658 break; 1659 1660 InitializedEntity ElementEntity = 1661 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1662 Entity); 1663 // Check this element. 1664 CheckSubElementType(ElementEntity, IList, elementType, Index, 1665 StructuredList, StructuredIndex); 1666 ++elementIndex; 1667 1668 // If the array is of incomplete type, keep track of the number of 1669 // elements in the initializer. 1670 if (!maxElementsKnown && elementIndex > maxElements) 1671 maxElements = elementIndex; 1672 } 1673 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { 1674 // If this is an incomplete array type, the actual type needs to 1675 // be calculated here. 1676 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1677 if (maxElements == Zero) { 1678 // Sizing an array implicitly to zero is not allowed by ISO C, 1679 // but is supported by GNU. 1680 SemaRef.Diag(IList->getLocStart(), 1681 diag::ext_typecheck_zero_array_size); 1682 } 1683 1684 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1685 ArrayType::Normal, 0); 1686 } 1687 if (!hadError && VerifyOnly) { 1688 // Check if there are any members of the array that get value-initialized. 1689 // If so, check if doing that is possible. 1690 // FIXME: This needs to detect holes left by designated initializers too. 1691 if (maxElementsKnown && elementIndex < maxElements) 1692 CheckEmptyInitializable(InitializedEntity::InitializeElement( 1693 SemaRef.Context, 0, Entity), 1694 IList->getLocEnd()); 1695 } 1696 } 1697 1698 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, 1699 Expr *InitExpr, 1700 FieldDecl *Field, 1701 bool TopLevelObject) { 1702 // Handle GNU flexible array initializers. 1703 unsigned FlexArrayDiag; 1704 if (isa<InitListExpr>(InitExpr) && 1705 cast<InitListExpr>(InitExpr)->getNumInits() == 0) { 1706 // Empty flexible array init always allowed as an extension 1707 FlexArrayDiag = diag::ext_flexible_array_init; 1708 } else if (SemaRef.getLangOpts().CPlusPlus) { 1709 // Disallow flexible array init in C++; it is not required for gcc 1710 // compatibility, and it needs work to IRGen correctly in general. 1711 FlexArrayDiag = diag::err_flexible_array_init; 1712 } else if (!TopLevelObject) { 1713 // Disallow flexible array init on non-top-level object 1714 FlexArrayDiag = diag::err_flexible_array_init; 1715 } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 1716 // Disallow flexible array init on anything which is not a variable. 1717 FlexArrayDiag = diag::err_flexible_array_init; 1718 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { 1719 // Disallow flexible array init on local variables. 1720 FlexArrayDiag = diag::err_flexible_array_init; 1721 } else { 1722 // Allow other cases. 1723 FlexArrayDiag = diag::ext_flexible_array_init; 1724 } 1725 1726 if (!VerifyOnly) { 1727 SemaRef.Diag(InitExpr->getLocStart(), 1728 FlexArrayDiag) 1729 << InitExpr->getLocStart(); 1730 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1731 << Field; 1732 } 1733 1734 return FlexArrayDiag != diag::ext_flexible_array_init; 1735 } 1736 1737 void InitListChecker::CheckStructUnionTypes( 1738 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, 1739 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, 1740 bool SubobjectIsDesignatorContext, unsigned &Index, 1741 InitListExpr *StructuredList, unsigned &StructuredIndex, 1742 bool TopLevelObject) { 1743 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 1744 1745 // If the record is invalid, some of it's members are invalid. To avoid 1746 // confusion, we forgo checking the intializer for the entire record. 1747 if (structDecl->isInvalidDecl()) { 1748 // Assume it was supposed to consume a single initializer. 1749 ++Index; 1750 hadError = true; 1751 return; 1752 } 1753 1754 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1755 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1756 1757 // If there's a default initializer, use it. 1758 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { 1759 if (VerifyOnly) 1760 return; 1761 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1762 Field != FieldEnd; ++Field) { 1763 if (Field->hasInClassInitializer()) { 1764 StructuredList->setInitializedFieldInUnion(*Field); 1765 // FIXME: Actually build a CXXDefaultInitExpr? 1766 return; 1767 } 1768 } 1769 } 1770 1771 // Value-initialize the first member of the union that isn't an unnamed 1772 // bitfield. 1773 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1774 Field != FieldEnd; ++Field) { 1775 if (!Field->isUnnamedBitfield()) { 1776 if (VerifyOnly) 1777 CheckEmptyInitializable( 1778 InitializedEntity::InitializeMember(*Field, &Entity), 1779 IList->getLocEnd()); 1780 else 1781 StructuredList->setInitializedFieldInUnion(*Field); 1782 break; 1783 } 1784 } 1785 return; 1786 } 1787 1788 bool InitializedSomething = false; 1789 1790 // If we have any base classes, they are initialized prior to the fields. 1791 for (auto &Base : Bases) { 1792 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; 1793 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd(); 1794 1795 // Designated inits always initialize fields, so if we see one, all 1796 // remaining base classes have no explicit initializer. 1797 if (Init && isa<DesignatedInitExpr>(Init)) 1798 Init = nullptr; 1799 1800 InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 1801 SemaRef.Context, &Base, false, &Entity); 1802 if (Init) { 1803 CheckSubElementType(BaseEntity, IList, Base.getType(), Index, 1804 StructuredList, StructuredIndex); 1805 InitializedSomething = true; 1806 } else if (VerifyOnly) { 1807 CheckEmptyInitializable(BaseEntity, InitLoc); 1808 } 1809 } 1810 1811 // If structDecl is a forward declaration, this loop won't do 1812 // anything except look at designated initializers; That's okay, 1813 // because an error should get printed out elsewhere. It might be 1814 // worthwhile to skip over the rest of the initializer, though. 1815 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1816 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1817 bool CheckForMissingFields = true; 1818 while (Index < IList->getNumInits()) { 1819 Expr *Init = IList->getInit(Index); 1820 1821 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1822 // If we're not the subobject that matches up with the '{' for 1823 // the designator, we shouldn't be handling the 1824 // designator. Return immediately. 1825 if (!SubobjectIsDesignatorContext) 1826 return; 1827 1828 // Handle this designated initializer. Field will be updated to 1829 // the next field that we'll be initializing. 1830 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1831 DeclType, &Field, nullptr, Index, 1832 StructuredList, StructuredIndex, 1833 true, TopLevelObject)) 1834 hadError = true; 1835 1836 InitializedSomething = true; 1837 1838 // Disable check for missing fields when designators are used. 1839 // This matches gcc behaviour. 1840 CheckForMissingFields = false; 1841 continue; 1842 } 1843 1844 if (Field == FieldEnd) { 1845 // We've run out of fields. We're done. 1846 break; 1847 } 1848 1849 // We've already initialized a member of a union. We're done. 1850 if (InitializedSomething && DeclType->isUnionType()) 1851 break; 1852 1853 // If we've hit the flexible array member at the end, we're done. 1854 if (Field->getType()->isIncompleteArrayType()) 1855 break; 1856 1857 if (Field->isUnnamedBitfield()) { 1858 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1859 ++Field; 1860 continue; 1861 } 1862 1863 // Make sure we can use this declaration. 1864 bool InvalidUse; 1865 if (VerifyOnly) 1866 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 1867 else 1868 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, 1869 IList->getInit(Index)->getLocStart()); 1870 if (InvalidUse) { 1871 ++Index; 1872 ++Field; 1873 hadError = true; 1874 continue; 1875 } 1876 1877 InitializedEntity MemberEntity = 1878 InitializedEntity::InitializeMember(*Field, &Entity); 1879 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1880 StructuredList, StructuredIndex); 1881 InitializedSomething = true; 1882 1883 if (DeclType->isUnionType() && !VerifyOnly) { 1884 // Initialize the first field within the union. 1885 StructuredList->setInitializedFieldInUnion(*Field); 1886 } 1887 1888 ++Field; 1889 } 1890 1891 // Emit warnings for missing struct field initializers. 1892 if (!VerifyOnly && InitializedSomething && CheckForMissingFields && 1893 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && 1894 !DeclType->isUnionType()) { 1895 // It is possible we have one or more unnamed bitfields remaining. 1896 // Find first (if any) named field and emit warning. 1897 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 1898 it != end; ++it) { 1899 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { 1900 SemaRef.Diag(IList->getSourceRange().getEnd(), 1901 diag::warn_missing_field_initializers) << *it; 1902 break; 1903 } 1904 } 1905 } 1906 1907 // Check that any remaining fields can be value-initialized. 1908 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() && 1909 !Field->getType()->isIncompleteArrayType()) { 1910 // FIXME: Should check for holes left by designated initializers too. 1911 for (; Field != FieldEnd && !hadError; ++Field) { 1912 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) 1913 CheckEmptyInitializable( 1914 InitializedEntity::InitializeMember(*Field, &Entity), 1915 IList->getLocEnd()); 1916 } 1917 } 1918 1919 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1920 Index >= IList->getNumInits()) 1921 return; 1922 1923 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, 1924 TopLevelObject)) { 1925 hadError = true; 1926 ++Index; 1927 return; 1928 } 1929 1930 InitializedEntity MemberEntity = 1931 InitializedEntity::InitializeMember(*Field, &Entity); 1932 1933 if (isa<InitListExpr>(IList->getInit(Index))) 1934 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1935 StructuredList, StructuredIndex); 1936 else 1937 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 1938 StructuredList, StructuredIndex); 1939 } 1940 1941 /// \brief Expand a field designator that refers to a member of an 1942 /// anonymous struct or union into a series of field designators that 1943 /// refers to the field within the appropriate subobject. 1944 /// 1945 static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1946 DesignatedInitExpr *DIE, 1947 unsigned DesigIdx, 1948 IndirectFieldDecl *IndirectField) { 1949 typedef DesignatedInitExpr::Designator Designator; 1950 1951 // Build the replacement designators. 1952 SmallVector<Designator, 4> Replacements; 1953 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 1954 PE = IndirectField->chain_end(); PI != PE; ++PI) { 1955 if (PI + 1 == PE) 1956 Replacements.push_back(Designator((IdentifierInfo *)nullptr, 1957 DIE->getDesignator(DesigIdx)->getDotLoc(), 1958 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1959 else 1960 Replacements.push_back(Designator((IdentifierInfo *)nullptr, 1961 SourceLocation(), SourceLocation())); 1962 assert(isa<FieldDecl>(*PI)); 1963 Replacements.back().setField(cast<FieldDecl>(*PI)); 1964 } 1965 1966 // Expand the current designator into the set of replacement 1967 // designators, so we have a full subobject path down to where the 1968 // member of the anonymous struct/union is actually stored. 1969 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 1970 &Replacements[0] + Replacements.size()); 1971 } 1972 1973 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, 1974 DesignatedInitExpr *DIE) { 1975 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; 1976 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); 1977 for (unsigned I = 0; I < NumIndexExprs; ++I) 1978 IndexExprs[I] = DIE->getSubExpr(I + 1); 1979 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(), 1980 DIE->size(), IndexExprs, 1981 DIE->getEqualOrColonLoc(), 1982 DIE->usesGNUSyntax(), DIE->getInit()); 1983 } 1984 1985 namespace { 1986 1987 // Callback to only accept typo corrections that are for field members of 1988 // the given struct or union. 1989 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback { 1990 public: 1991 explicit FieldInitializerValidatorCCC(RecordDecl *RD) 1992 : Record(RD) {} 1993 1994 bool ValidateCandidate(const TypoCorrection &candidate) override { 1995 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); 1996 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); 1997 } 1998 1999 private: 2000 RecordDecl *Record; 2001 }; 2002 2003 } // end anonymous namespace 2004 2005 /// @brief Check the well-formedness of a C99 designated initializer. 2006 /// 2007 /// Determines whether the designated initializer @p DIE, which 2008 /// resides at the given @p Index within the initializer list @p 2009 /// IList, is well-formed for a current object of type @p DeclType 2010 /// (C99 6.7.8). The actual subobject that this designator refers to 2011 /// within the current subobject is returned in either 2012 /// @p NextField or @p NextElementIndex (whichever is appropriate). 2013 /// 2014 /// @param IList The initializer list in which this designated 2015 /// initializer occurs. 2016 /// 2017 /// @param DIE The designated initializer expression. 2018 /// 2019 /// @param DesigIdx The index of the current designator. 2020 /// 2021 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), 2022 /// into which the designation in @p DIE should refer. 2023 /// 2024 /// @param NextField If non-NULL and the first designator in @p DIE is 2025 /// a field, this will be set to the field declaration corresponding 2026 /// to the field named by the designator. 2027 /// 2028 /// @param NextElementIndex If non-NULL and the first designator in @p 2029 /// DIE is an array designator or GNU array-range designator, this 2030 /// will be set to the last index initialized by this designator. 2031 /// 2032 /// @param Index Index into @p IList where the designated initializer 2033 /// @p DIE occurs. 2034 /// 2035 /// @param StructuredList The initializer list expression that 2036 /// describes all of the subobject initializers in the order they'll 2037 /// actually be initialized. 2038 /// 2039 /// @returns true if there was an error, false otherwise. 2040 bool 2041 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 2042 InitListExpr *IList, 2043 DesignatedInitExpr *DIE, 2044 unsigned DesigIdx, 2045 QualType &CurrentObjectType, 2046 RecordDecl::field_iterator *NextField, 2047 llvm::APSInt *NextElementIndex, 2048 unsigned &Index, 2049 InitListExpr *StructuredList, 2050 unsigned &StructuredIndex, 2051 bool FinishSubobjectInit, 2052 bool TopLevelObject) { 2053 if (DesigIdx == DIE->size()) { 2054 // Check the actual initialization for the designated object type. 2055 bool prevHadError = hadError; 2056 2057 // Temporarily remove the designator expression from the 2058 // initializer list that the child calls see, so that we don't try 2059 // to re-process the designator. 2060 unsigned OldIndex = Index; 2061 IList->setInit(OldIndex, DIE->getInit()); 2062 2063 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 2064 StructuredList, StructuredIndex); 2065 2066 // Restore the designated initializer expression in the syntactic 2067 // form of the initializer list. 2068 if (IList->getInit(OldIndex) != DIE->getInit()) 2069 DIE->setInit(IList->getInit(OldIndex)); 2070 IList->setInit(OldIndex, DIE); 2071 2072 return hadError && !prevHadError; 2073 } 2074 2075 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 2076 bool IsFirstDesignator = (DesigIdx == 0); 2077 if (!VerifyOnly) { 2078 assert((IsFirstDesignator || StructuredList) && 2079 "Need a non-designated initializer list to start from"); 2080 2081 // Determine the structural initializer list that corresponds to the 2082 // current subobject. 2083 if (IsFirstDesignator) 2084 StructuredList = SyntacticToSemantic.lookup(IList); 2085 else { 2086 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? 2087 StructuredList->getInit(StructuredIndex) : nullptr; 2088 if (!ExistingInit && StructuredList->hasArrayFiller()) 2089 ExistingInit = StructuredList->getArrayFiller(); 2090 2091 if (!ExistingInit) 2092 StructuredList = 2093 getStructuredSubobjectInit(IList, Index, CurrentObjectType, 2094 StructuredList, StructuredIndex, 2095 SourceRange(D->getLocStart(), 2096 DIE->getLocEnd())); 2097 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) 2098 StructuredList = Result; 2099 else { 2100 if (DesignatedInitUpdateExpr *E = 2101 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) 2102 StructuredList = E->getUpdater(); 2103 else { 2104 DesignatedInitUpdateExpr *DIUE = 2105 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context, 2106 D->getLocStart(), ExistingInit, 2107 DIE->getLocEnd()); 2108 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); 2109 StructuredList = DIUE->getUpdater(); 2110 } 2111 2112 // We need to check on source range validity because the previous 2113 // initializer does not have to be an explicit initializer. e.g., 2114 // 2115 // struct P { int a, b; }; 2116 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; 2117 // 2118 // There is an overwrite taking place because the first braced initializer 2119 // list "{ .a = 2 }" already provides value for .p.b (which is zero). 2120 if (ExistingInit->getSourceRange().isValid()) { 2121 // We are creating an initializer list that initializes the 2122 // subobjects of the current object, but there was already an 2123 // initialization that completely initialized the current 2124 // subobject, e.g., by a compound literal: 2125 // 2126 // struct X { int a, b; }; 2127 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2128 // 2129 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 2130 // designated initializer re-initializes the whole 2131 // subobject [0], overwriting previous initializers. 2132 SemaRef.Diag(D->getLocStart(), 2133 diag::warn_subobject_initializer_overrides) 2134 << SourceRange(D->getLocStart(), DIE->getLocEnd()); 2135 2136 SemaRef.Diag(ExistingInit->getLocStart(), 2137 diag::note_previous_initializer) 2138 << /*FIXME:has side effects=*/0 2139 << ExistingInit->getSourceRange(); 2140 } 2141 } 2142 } 2143 assert(StructuredList && "Expected a structured initializer list"); 2144 } 2145 2146 if (D->isFieldDesignator()) { 2147 // C99 6.7.8p7: 2148 // 2149 // If a designator has the form 2150 // 2151 // . identifier 2152 // 2153 // then the current object (defined below) shall have 2154 // structure or union type and the identifier shall be the 2155 // name of a member of that type. 2156 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 2157 if (!RT) { 2158 SourceLocation Loc = D->getDotLoc(); 2159 if (Loc.isInvalid()) 2160 Loc = D->getFieldLoc(); 2161 if (!VerifyOnly) 2162 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 2163 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; 2164 ++Index; 2165 return true; 2166 } 2167 2168 FieldDecl *KnownField = D->getField(); 2169 if (!KnownField) { 2170 IdentifierInfo *FieldName = D->getFieldName(); 2171 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 2172 for (NamedDecl *ND : Lookup) { 2173 if (auto *FD = dyn_cast<FieldDecl>(ND)) { 2174 KnownField = FD; 2175 break; 2176 } 2177 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { 2178 // In verify mode, don't modify the original. 2179 if (VerifyOnly) 2180 DIE = CloneDesignatedInitExpr(SemaRef, DIE); 2181 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); 2182 D = DIE->getDesignator(DesigIdx); 2183 KnownField = cast<FieldDecl>(*IFD->chain_begin()); 2184 break; 2185 } 2186 } 2187 if (!KnownField) { 2188 if (VerifyOnly) { 2189 ++Index; 2190 return true; // No typo correction when just trying this out. 2191 } 2192 2193 // Name lookup found something, but it wasn't a field. 2194 if (!Lookup.empty()) { 2195 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 2196 << FieldName; 2197 SemaRef.Diag(Lookup.front()->getLocation(), 2198 diag::note_field_designator_found); 2199 ++Index; 2200 return true; 2201 } 2202 2203 // Name lookup didn't find anything. 2204 // Determine whether this was a typo for another field name. 2205 if (TypoCorrection Corrected = SemaRef.CorrectTypo( 2206 DeclarationNameInfo(FieldName, D->getFieldLoc()), 2207 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, 2208 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()), 2209 Sema::CTK_ErrorRecovery, RT->getDecl())) { 2210 SemaRef.diagnoseTypo( 2211 Corrected, 2212 SemaRef.PDiag(diag::err_field_designator_unknown_suggest) 2213 << FieldName << CurrentObjectType); 2214 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); 2215 hadError = true; 2216 } else { 2217 // Typo correction didn't find anything. 2218 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 2219 << FieldName << CurrentObjectType; 2220 ++Index; 2221 return true; 2222 } 2223 } 2224 } 2225 2226 unsigned FieldIndex = 0; 2227 for (auto *FI : RT->getDecl()->fields()) { 2228 if (FI->isUnnamedBitfield()) 2229 continue; 2230 if (declaresSameEntity(KnownField, FI)) { 2231 KnownField = FI; 2232 break; 2233 } 2234 ++FieldIndex; 2235 } 2236 2237 RecordDecl::field_iterator Field = 2238 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); 2239 2240 // All of the fields of a union are located at the same place in 2241 // the initializer list. 2242 if (RT->getDecl()->isUnion()) { 2243 FieldIndex = 0; 2244 if (!VerifyOnly) { 2245 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); 2246 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { 2247 assert(StructuredList->getNumInits() == 1 2248 && "A union should never have more than one initializer!"); 2249 2250 // We're about to throw away an initializer, emit warning. 2251 SemaRef.Diag(D->getFieldLoc(), 2252 diag::warn_initializer_overrides) 2253 << D->getSourceRange(); 2254 Expr *ExistingInit = StructuredList->getInit(0); 2255 SemaRef.Diag(ExistingInit->getLocStart(), 2256 diag::note_previous_initializer) 2257 << /*FIXME:has side effects=*/0 2258 << ExistingInit->getSourceRange(); 2259 2260 // remove existing initializer 2261 StructuredList->resizeInits(SemaRef.Context, 0); 2262 StructuredList->setInitializedFieldInUnion(nullptr); 2263 } 2264 2265 StructuredList->setInitializedFieldInUnion(*Field); 2266 } 2267 } 2268 2269 // Make sure we can use this declaration. 2270 bool InvalidUse; 2271 if (VerifyOnly) 2272 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2273 else 2274 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); 2275 if (InvalidUse) { 2276 ++Index; 2277 return true; 2278 } 2279 2280 if (!VerifyOnly) { 2281 // Update the designator with the field declaration. 2282 D->setField(*Field); 2283 2284 // Make sure that our non-designated initializer list has space 2285 // for a subobject corresponding to this field. 2286 if (FieldIndex >= StructuredList->getNumInits()) 2287 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 2288 } 2289 2290 // This designator names a flexible array member. 2291 if (Field->getType()->isIncompleteArrayType()) { 2292 bool Invalid = false; 2293 if ((DesigIdx + 1) != DIE->size()) { 2294 // We can't designate an object within the flexible array 2295 // member (because GCC doesn't allow it). 2296 if (!VerifyOnly) { 2297 DesignatedInitExpr::Designator *NextD 2298 = DIE->getDesignator(DesigIdx + 1); 2299 SemaRef.Diag(NextD->getLocStart(), 2300 diag::err_designator_into_flexible_array_member) 2301 << SourceRange(NextD->getLocStart(), 2302 DIE->getLocEnd()); 2303 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2304 << *Field; 2305 } 2306 Invalid = true; 2307 } 2308 2309 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 2310 !isa<StringLiteral>(DIE->getInit())) { 2311 // The initializer is not an initializer list. 2312 if (!VerifyOnly) { 2313 SemaRef.Diag(DIE->getInit()->getLocStart(), 2314 diag::err_flexible_array_init_needs_braces) 2315 << DIE->getInit()->getSourceRange(); 2316 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2317 << *Field; 2318 } 2319 Invalid = true; 2320 } 2321 2322 // Check GNU flexible array initializer. 2323 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, 2324 TopLevelObject)) 2325 Invalid = true; 2326 2327 if (Invalid) { 2328 ++Index; 2329 return true; 2330 } 2331 2332 // Initialize the array. 2333 bool prevHadError = hadError; 2334 unsigned newStructuredIndex = FieldIndex; 2335 unsigned OldIndex = Index; 2336 IList->setInit(Index, DIE->getInit()); 2337 2338 InitializedEntity MemberEntity = 2339 InitializedEntity::InitializeMember(*Field, &Entity); 2340 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2341 StructuredList, newStructuredIndex); 2342 2343 IList->setInit(OldIndex, DIE); 2344 if (hadError && !prevHadError) { 2345 ++Field; 2346 ++FieldIndex; 2347 if (NextField) 2348 *NextField = Field; 2349 StructuredIndex = FieldIndex; 2350 return true; 2351 } 2352 } else { 2353 // Recurse to check later designated subobjects. 2354 QualType FieldType = Field->getType(); 2355 unsigned newStructuredIndex = FieldIndex; 2356 2357 InitializedEntity MemberEntity = 2358 InitializedEntity::InitializeMember(*Field, &Entity); 2359 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 2360 FieldType, nullptr, nullptr, Index, 2361 StructuredList, newStructuredIndex, 2362 FinishSubobjectInit, false)) 2363 return true; 2364 } 2365 2366 // Find the position of the next field to be initialized in this 2367 // subobject. 2368 ++Field; 2369 ++FieldIndex; 2370 2371 // If this the first designator, our caller will continue checking 2372 // the rest of this struct/class/union subobject. 2373 if (IsFirstDesignator) { 2374 if (NextField) 2375 *NextField = Field; 2376 StructuredIndex = FieldIndex; 2377 return false; 2378 } 2379 2380 if (!FinishSubobjectInit) 2381 return false; 2382 2383 // We've already initialized something in the union; we're done. 2384 if (RT->getDecl()->isUnion()) 2385 return hadError; 2386 2387 // Check the remaining fields within this class/struct/union subobject. 2388 bool prevHadError = hadError; 2389 2390 auto NoBases = 2391 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 2392 CXXRecordDecl::base_class_iterator()); 2393 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, 2394 false, Index, StructuredList, FieldIndex); 2395 return hadError && !prevHadError; 2396 } 2397 2398 // C99 6.7.8p6: 2399 // 2400 // If a designator has the form 2401 // 2402 // [ constant-expression ] 2403 // 2404 // then the current object (defined below) shall have array 2405 // type and the expression shall be an integer constant 2406 // expression. If the array is of unknown size, any 2407 // nonnegative value is valid. 2408 // 2409 // Additionally, cope with the GNU extension that permits 2410 // designators of the form 2411 // 2412 // [ constant-expression ... constant-expression ] 2413 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 2414 if (!AT) { 2415 if (!VerifyOnly) 2416 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 2417 << CurrentObjectType; 2418 ++Index; 2419 return true; 2420 } 2421 2422 Expr *IndexExpr = nullptr; 2423 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 2424 if (D->isArrayDesignator()) { 2425 IndexExpr = DIE->getArrayIndex(*D); 2426 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); 2427 DesignatedEndIndex = DesignatedStartIndex; 2428 } else { 2429 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 2430 2431 DesignatedStartIndex = 2432 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); 2433 DesignatedEndIndex = 2434 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); 2435 IndexExpr = DIE->getArrayRangeEnd(*D); 2436 2437 // Codegen can't handle evaluating array range designators that have side 2438 // effects, because we replicate the AST value for each initialized element. 2439 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 2440 // elements with something that has a side effect, so codegen can emit an 2441 // "error unsupported" error instead of miscompiling the app. 2442 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 2443 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) 2444 FullyStructuredList->sawArrayRangeDesignator(); 2445 } 2446 2447 if (isa<ConstantArrayType>(AT)) { 2448 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 2449 DesignatedStartIndex 2450 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 2451 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 2452 DesignatedEndIndex 2453 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 2454 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 2455 if (DesignatedEndIndex >= MaxElements) { 2456 if (!VerifyOnly) 2457 SemaRef.Diag(IndexExpr->getLocStart(), 2458 diag::err_array_designator_too_large) 2459 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 2460 << IndexExpr->getSourceRange(); 2461 ++Index; 2462 return true; 2463 } 2464 } else { 2465 unsigned DesignatedIndexBitWidth = 2466 ConstantArrayType::getMaxSizeBits(SemaRef.Context); 2467 DesignatedStartIndex = 2468 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); 2469 DesignatedEndIndex = 2470 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); 2471 DesignatedStartIndex.setIsUnsigned(true); 2472 DesignatedEndIndex.setIsUnsigned(true); 2473 } 2474 2475 if (!VerifyOnly && StructuredList->isStringLiteralInit()) { 2476 // We're modifying a string literal init; we have to decompose the string 2477 // so we can modify the individual characters. 2478 ASTContext &Context = SemaRef.Context; 2479 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); 2480 2481 // Compute the character type 2482 QualType CharTy = AT->getElementType(); 2483 2484 // Compute the type of the integer literals. 2485 QualType PromotedCharTy = CharTy; 2486 if (CharTy->isPromotableIntegerType()) 2487 PromotedCharTy = Context.getPromotedIntegerType(CharTy); 2488 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); 2489 2490 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { 2491 // Get the length of the string. 2492 uint64_t StrLen = SL->getLength(); 2493 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2494 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2495 StructuredList->resizeInits(Context, StrLen); 2496 2497 // Build a literal for each character in the string, and put them into 2498 // the init list. 2499 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2500 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); 2501 Expr *Init = new (Context) IntegerLiteral( 2502 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2503 if (CharTy != PromotedCharTy) 2504 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, 2505 Init, nullptr, VK_RValue); 2506 StructuredList->updateInit(Context, i, Init); 2507 } 2508 } else { 2509 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); 2510 std::string Str; 2511 Context.getObjCEncodingForType(E->getEncodedType(), Str); 2512 2513 // Get the length of the string. 2514 uint64_t StrLen = Str.size(); 2515 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2516 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2517 StructuredList->resizeInits(Context, StrLen); 2518 2519 // Build a literal for each character in the string, and put them into 2520 // the init list. 2521 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2522 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); 2523 Expr *Init = new (Context) IntegerLiteral( 2524 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2525 if (CharTy != PromotedCharTy) 2526 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, 2527 Init, nullptr, VK_RValue); 2528 StructuredList->updateInit(Context, i, Init); 2529 } 2530 } 2531 } 2532 2533 // Make sure that our non-designated initializer list has space 2534 // for a subobject corresponding to this array element. 2535 if (!VerifyOnly && 2536 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 2537 StructuredList->resizeInits(SemaRef.Context, 2538 DesignatedEndIndex.getZExtValue() + 1); 2539 2540 // Repeatedly perform subobject initializations in the range 2541 // [DesignatedStartIndex, DesignatedEndIndex]. 2542 2543 // Move to the next designator 2544 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 2545 unsigned OldIndex = Index; 2546 2547 InitializedEntity ElementEntity = 2548 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 2549 2550 while (DesignatedStartIndex <= DesignatedEndIndex) { 2551 // Recurse to check later designated subobjects. 2552 QualType ElementType = AT->getElementType(); 2553 Index = OldIndex; 2554 2555 ElementEntity.setElementIndex(ElementIndex); 2556 if (CheckDesignatedInitializer( 2557 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, 2558 nullptr, Index, StructuredList, ElementIndex, 2559 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), 2560 false)) 2561 return true; 2562 2563 // Move to the next index in the array that we'll be initializing. 2564 ++DesignatedStartIndex; 2565 ElementIndex = DesignatedStartIndex.getZExtValue(); 2566 } 2567 2568 // If this the first designator, our caller will continue checking 2569 // the rest of this array subobject. 2570 if (IsFirstDesignator) { 2571 if (NextElementIndex) 2572 *NextElementIndex = DesignatedStartIndex; 2573 StructuredIndex = ElementIndex; 2574 return false; 2575 } 2576 2577 if (!FinishSubobjectInit) 2578 return false; 2579 2580 // Check the remaining elements within this array subobject. 2581 bool prevHadError = hadError; 2582 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 2583 /*SubobjectIsDesignatorContext=*/false, Index, 2584 StructuredList, ElementIndex); 2585 return hadError && !prevHadError; 2586 } 2587 2588 // Get the structured initializer list for a subobject of type 2589 // @p CurrentObjectType. 2590 InitListExpr * 2591 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 2592 QualType CurrentObjectType, 2593 InitListExpr *StructuredList, 2594 unsigned StructuredIndex, 2595 SourceRange InitRange, 2596 bool IsFullyOverwritten) { 2597 if (VerifyOnly) 2598 return nullptr; // No structured list in verification-only mode. 2599 Expr *ExistingInit = nullptr; 2600 if (!StructuredList) 2601 ExistingInit = SyntacticToSemantic.lookup(IList); 2602 else if (StructuredIndex < StructuredList->getNumInits()) 2603 ExistingInit = StructuredList->getInit(StructuredIndex); 2604 2605 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 2606 // There might have already been initializers for subobjects of the current 2607 // object, but a subsequent initializer list will overwrite the entirety 2608 // of the current object. (See DR 253 and C99 6.7.8p21). e.g., 2609 // 2610 // struct P { char x[6]; }; 2611 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; 2612 // 2613 // The first designated initializer is ignored, and l.x is just "f". 2614 if (!IsFullyOverwritten) 2615 return Result; 2616 2617 if (ExistingInit) { 2618 // We are creating an initializer list that initializes the 2619 // subobjects of the current object, but there was already an 2620 // initialization that completely initialized the current 2621 // subobject, e.g., by a compound literal: 2622 // 2623 // struct X { int a, b; }; 2624 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2625 // 2626 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 2627 // designated initializer re-initializes the whole 2628 // subobject [0], overwriting previous initializers. 2629 SemaRef.Diag(InitRange.getBegin(), 2630 diag::warn_subobject_initializer_overrides) 2631 << InitRange; 2632 SemaRef.Diag(ExistingInit->getLocStart(), 2633 diag::note_previous_initializer) 2634 << /*FIXME:has side effects=*/0 2635 << ExistingInit->getSourceRange(); 2636 } 2637 2638 InitListExpr *Result 2639 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 2640 InitRange.getBegin(), None, 2641 InitRange.getEnd()); 2642 2643 QualType ResultType = CurrentObjectType; 2644 if (!ResultType->isArrayType()) 2645 ResultType = ResultType.getNonLValueExprType(SemaRef.Context); 2646 Result->setType(ResultType); 2647 2648 // Pre-allocate storage for the structured initializer list. 2649 unsigned NumElements = 0; 2650 unsigned NumInits = 0; 2651 bool GotNumInits = false; 2652 if (!StructuredList) { 2653 NumInits = IList->getNumInits(); 2654 GotNumInits = true; 2655 } else if (Index < IList->getNumInits()) { 2656 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) { 2657 NumInits = SubList->getNumInits(); 2658 GotNumInits = true; 2659 } 2660 } 2661 2662 if (const ArrayType *AType 2663 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 2664 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 2665 NumElements = CAType->getSize().getZExtValue(); 2666 // Simple heuristic so that we don't allocate a very large 2667 // initializer with many empty entries at the end. 2668 if (GotNumInits && NumElements > NumInits) 2669 NumElements = 0; 2670 } 2671 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 2672 NumElements = VType->getNumElements(); 2673 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 2674 RecordDecl *RDecl = RType->getDecl(); 2675 if (RDecl->isUnion()) 2676 NumElements = 1; 2677 else 2678 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end()); 2679 } 2680 2681 Result->reserveInits(SemaRef.Context, NumElements); 2682 2683 // Link this new initializer list into the structured initializer 2684 // lists. 2685 if (StructuredList) 2686 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 2687 else { 2688 Result->setSyntacticForm(IList); 2689 SyntacticToSemantic[IList] = Result; 2690 } 2691 2692 return Result; 2693 } 2694 2695 /// Update the initializer at index @p StructuredIndex within the 2696 /// structured initializer list to the value @p expr. 2697 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 2698 unsigned &StructuredIndex, 2699 Expr *expr) { 2700 // No structured initializer list to update 2701 if (!StructuredList) 2702 return; 2703 2704 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 2705 StructuredIndex, expr)) { 2706 // This initializer overwrites a previous initializer. Warn. 2707 // We need to check on source range validity because the previous 2708 // initializer does not have to be an explicit initializer. 2709 // struct P { int a, b; }; 2710 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; 2711 // There is an overwrite taking place because the first braced initializer 2712 // list "{ .a = 2 }' already provides value for .p.b (which is zero). 2713 if (PrevInit->getSourceRange().isValid()) { 2714 SemaRef.Diag(expr->getLocStart(), 2715 diag::warn_initializer_overrides) 2716 << expr->getSourceRange(); 2717 2718 SemaRef.Diag(PrevInit->getLocStart(), 2719 diag::note_previous_initializer) 2720 << /*FIXME:has side effects=*/0 2721 << PrevInit->getSourceRange(); 2722 } 2723 } 2724 2725 ++StructuredIndex; 2726 } 2727 2728 /// Check that the given Index expression is a valid array designator 2729 /// value. This is essentially just a wrapper around 2730 /// VerifyIntegerConstantExpression that also checks for negative values 2731 /// and produces a reasonable diagnostic if there is a 2732 /// failure. Returns the index expression, possibly with an implicit cast 2733 /// added, on success. If everything went okay, Value will receive the 2734 /// value of the constant expression. 2735 static ExprResult 2736 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 2737 SourceLocation Loc = Index->getLocStart(); 2738 2739 // Make sure this is an integer constant expression. 2740 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value); 2741 if (Result.isInvalid()) 2742 return Result; 2743 2744 if (Value.isSigned() && Value.isNegative()) 2745 return S.Diag(Loc, diag::err_array_designator_negative) 2746 << Value.toString(10) << Index->getSourceRange(); 2747 2748 Value.setIsUnsigned(true); 2749 return Result; 2750 } 2751 2752 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 2753 SourceLocation Loc, 2754 bool GNUSyntax, 2755 ExprResult Init) { 2756 typedef DesignatedInitExpr::Designator ASTDesignator; 2757 2758 bool Invalid = false; 2759 SmallVector<ASTDesignator, 32> Designators; 2760 SmallVector<Expr *, 32> InitExpressions; 2761 2762 // Build designators and check array designator expressions. 2763 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 2764 const Designator &D = Desig.getDesignator(Idx); 2765 switch (D.getKind()) { 2766 case Designator::FieldDesignator: 2767 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 2768 D.getFieldLoc())); 2769 break; 2770 2771 case Designator::ArrayDesignator: { 2772 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 2773 llvm::APSInt IndexValue; 2774 if (!Index->isTypeDependent() && !Index->isValueDependent()) 2775 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); 2776 if (!Index) 2777 Invalid = true; 2778 else { 2779 Designators.push_back(ASTDesignator(InitExpressions.size(), 2780 D.getLBracketLoc(), 2781 D.getRBracketLoc())); 2782 InitExpressions.push_back(Index); 2783 } 2784 break; 2785 } 2786 2787 case Designator::ArrayRangeDesignator: { 2788 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 2789 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 2790 llvm::APSInt StartValue; 2791 llvm::APSInt EndValue; 2792 bool StartDependent = StartIndex->isTypeDependent() || 2793 StartIndex->isValueDependent(); 2794 bool EndDependent = EndIndex->isTypeDependent() || 2795 EndIndex->isValueDependent(); 2796 if (!StartDependent) 2797 StartIndex = 2798 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); 2799 if (!EndDependent) 2800 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); 2801 2802 if (!StartIndex || !EndIndex) 2803 Invalid = true; 2804 else { 2805 // Make sure we're comparing values with the same bit width. 2806 if (StartDependent || EndDependent) { 2807 // Nothing to compute. 2808 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 2809 EndValue = EndValue.extend(StartValue.getBitWidth()); 2810 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 2811 StartValue = StartValue.extend(EndValue.getBitWidth()); 2812 2813 if (!StartDependent && !EndDependent && EndValue < StartValue) { 2814 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 2815 << StartValue.toString(10) << EndValue.toString(10) 2816 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 2817 Invalid = true; 2818 } else { 2819 Designators.push_back(ASTDesignator(InitExpressions.size(), 2820 D.getLBracketLoc(), 2821 D.getEllipsisLoc(), 2822 D.getRBracketLoc())); 2823 InitExpressions.push_back(StartIndex); 2824 InitExpressions.push_back(EndIndex); 2825 } 2826 } 2827 break; 2828 } 2829 } 2830 } 2831 2832 if (Invalid || Init.isInvalid()) 2833 return ExprError(); 2834 2835 // Clear out the expressions within the designation. 2836 Desig.ClearExprs(*this); 2837 2838 DesignatedInitExpr *DIE 2839 = DesignatedInitExpr::Create(Context, 2840 Designators.data(), Designators.size(), 2841 InitExpressions, Loc, GNUSyntax, 2842 Init.getAs<Expr>()); 2843 2844 if (!getLangOpts().C99) 2845 Diag(DIE->getLocStart(), diag::ext_designated_init) 2846 << DIE->getSourceRange(); 2847 2848 return DIE; 2849 } 2850 2851 //===----------------------------------------------------------------------===// 2852 // Initialization entity 2853 //===----------------------------------------------------------------------===// 2854 2855 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 2856 const InitializedEntity &Parent) 2857 : Parent(&Parent), Index(Index) 2858 { 2859 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 2860 Kind = EK_ArrayElement; 2861 Type = AT->getElementType(); 2862 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 2863 Kind = EK_VectorElement; 2864 Type = VT->getElementType(); 2865 } else { 2866 const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 2867 assert(CT && "Unexpected type"); 2868 Kind = EK_ComplexElement; 2869 Type = CT->getElementType(); 2870 } 2871 } 2872 2873 InitializedEntity 2874 InitializedEntity::InitializeBase(ASTContext &Context, 2875 const CXXBaseSpecifier *Base, 2876 bool IsInheritedVirtualBase, 2877 const InitializedEntity *Parent) { 2878 InitializedEntity Result; 2879 Result.Kind = EK_Base; 2880 Result.Parent = Parent; 2881 Result.Base = reinterpret_cast<uintptr_t>(Base); 2882 if (IsInheritedVirtualBase) 2883 Result.Base |= 0x01; 2884 2885 Result.Type = Base->getType(); 2886 return Result; 2887 } 2888 2889 DeclarationName InitializedEntity::getName() const { 2890 switch (getKind()) { 2891 case EK_Parameter: 2892 case EK_Parameter_CF_Audited: { 2893 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2894 return (D ? D->getDeclName() : DeclarationName()); 2895 } 2896 2897 case EK_Variable: 2898 case EK_Member: 2899 return VariableOrMember->getDeclName(); 2900 2901 case EK_LambdaCapture: 2902 return DeclarationName(Capture.VarID); 2903 2904 case EK_Result: 2905 case EK_Exception: 2906 case EK_New: 2907 case EK_Temporary: 2908 case EK_Base: 2909 case EK_Delegating: 2910 case EK_ArrayElement: 2911 case EK_VectorElement: 2912 case EK_ComplexElement: 2913 case EK_BlockElement: 2914 case EK_CompoundLiteralInit: 2915 case EK_RelatedResult: 2916 return DeclarationName(); 2917 } 2918 2919 llvm_unreachable("Invalid EntityKind!"); 2920 } 2921 2922 DeclaratorDecl *InitializedEntity::getDecl() const { 2923 switch (getKind()) { 2924 case EK_Variable: 2925 case EK_Member: 2926 return VariableOrMember; 2927 2928 case EK_Parameter: 2929 case EK_Parameter_CF_Audited: 2930 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2931 2932 case EK_Result: 2933 case EK_Exception: 2934 case EK_New: 2935 case EK_Temporary: 2936 case EK_Base: 2937 case EK_Delegating: 2938 case EK_ArrayElement: 2939 case EK_VectorElement: 2940 case EK_ComplexElement: 2941 case EK_BlockElement: 2942 case EK_LambdaCapture: 2943 case EK_CompoundLiteralInit: 2944 case EK_RelatedResult: 2945 return nullptr; 2946 } 2947 2948 llvm_unreachable("Invalid EntityKind!"); 2949 } 2950 2951 bool InitializedEntity::allowsNRVO() const { 2952 switch (getKind()) { 2953 case EK_Result: 2954 case EK_Exception: 2955 return LocAndNRVO.NRVO; 2956 2957 case EK_Variable: 2958 case EK_Parameter: 2959 case EK_Parameter_CF_Audited: 2960 case EK_Member: 2961 case EK_New: 2962 case EK_Temporary: 2963 case EK_CompoundLiteralInit: 2964 case EK_Base: 2965 case EK_Delegating: 2966 case EK_ArrayElement: 2967 case EK_VectorElement: 2968 case EK_ComplexElement: 2969 case EK_BlockElement: 2970 case EK_LambdaCapture: 2971 case EK_RelatedResult: 2972 break; 2973 } 2974 2975 return false; 2976 } 2977 2978 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { 2979 assert(getParent() != this); 2980 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; 2981 for (unsigned I = 0; I != Depth; ++I) 2982 OS << "`-"; 2983 2984 switch (getKind()) { 2985 case EK_Variable: OS << "Variable"; break; 2986 case EK_Parameter: OS << "Parameter"; break; 2987 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; 2988 break; 2989 case EK_Result: OS << "Result"; break; 2990 case EK_Exception: OS << "Exception"; break; 2991 case EK_Member: OS << "Member"; break; 2992 case EK_New: OS << "New"; break; 2993 case EK_Temporary: OS << "Temporary"; break; 2994 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; 2995 case EK_RelatedResult: OS << "RelatedResult"; break; 2996 case EK_Base: OS << "Base"; break; 2997 case EK_Delegating: OS << "Delegating"; break; 2998 case EK_ArrayElement: OS << "ArrayElement " << Index; break; 2999 case EK_VectorElement: OS << "VectorElement " << Index; break; 3000 case EK_ComplexElement: OS << "ComplexElement " << Index; break; 3001 case EK_BlockElement: OS << "Block"; break; 3002 case EK_LambdaCapture: 3003 OS << "LambdaCapture "; 3004 OS << DeclarationName(Capture.VarID); 3005 break; 3006 } 3007 3008 if (Decl *D = getDecl()) { 3009 OS << " "; 3010 cast<NamedDecl>(D)->printQualifiedName(OS); 3011 } 3012 3013 OS << " '" << getType().getAsString() << "'\n"; 3014 3015 return Depth + 1; 3016 } 3017 3018 LLVM_DUMP_METHOD void InitializedEntity::dump() const { 3019 dumpImpl(llvm::errs()); 3020 } 3021 3022 //===----------------------------------------------------------------------===// 3023 // Initialization sequence 3024 //===----------------------------------------------------------------------===// 3025 3026 void InitializationSequence::Step::Destroy() { 3027 switch (Kind) { 3028 case SK_ResolveAddressOfOverloadedFunction: 3029 case SK_CastDerivedToBaseRValue: 3030 case SK_CastDerivedToBaseXValue: 3031 case SK_CastDerivedToBaseLValue: 3032 case SK_BindReference: 3033 case SK_BindReferenceToTemporary: 3034 case SK_ExtraneousCopyToTemporary: 3035 case SK_UserConversion: 3036 case SK_QualificationConversionRValue: 3037 case SK_QualificationConversionXValue: 3038 case SK_QualificationConversionLValue: 3039 case SK_AtomicConversion: 3040 case SK_LValueToRValue: 3041 case SK_ListInitialization: 3042 case SK_UnwrapInitList: 3043 case SK_RewrapInitList: 3044 case SK_ConstructorInitialization: 3045 case SK_ConstructorInitializationFromList: 3046 case SK_ZeroInitialization: 3047 case SK_CAssignment: 3048 case SK_StringInit: 3049 case SK_ObjCObjectConversion: 3050 case SK_ArrayInit: 3051 case SK_ParenthesizedArrayInit: 3052 case SK_PassByIndirectCopyRestore: 3053 case SK_PassByIndirectRestore: 3054 case SK_ProduceObjCObject: 3055 case SK_StdInitializerList: 3056 case SK_StdInitializerListConstructorCall: 3057 case SK_OCLSamplerInit: 3058 case SK_OCLZeroEvent: 3059 break; 3060 3061 case SK_ConversionSequence: 3062 case SK_ConversionSequenceNoNarrowing: 3063 delete ICS; 3064 } 3065 } 3066 3067 bool InitializationSequence::isDirectReferenceBinding() const { 3068 return !Steps.empty() && Steps.back().Kind == SK_BindReference; 3069 } 3070 3071 bool InitializationSequence::isAmbiguous() const { 3072 if (!Failed()) 3073 return false; 3074 3075 switch (getFailureKind()) { 3076 case FK_TooManyInitsForReference: 3077 case FK_ArrayNeedsInitList: 3078 case FK_ArrayNeedsInitListOrStringLiteral: 3079 case FK_ArrayNeedsInitListOrWideStringLiteral: 3080 case FK_NarrowStringIntoWideCharArray: 3081 case FK_WideStringIntoCharArray: 3082 case FK_IncompatWideStringIntoWideChar: 3083 case FK_AddressOfOverloadFailed: // FIXME: Could do better 3084 case FK_NonConstLValueReferenceBindingToTemporary: 3085 case FK_NonConstLValueReferenceBindingToUnrelated: 3086 case FK_RValueReferenceBindingToLValue: 3087 case FK_ReferenceInitDropsQualifiers: 3088 case FK_ReferenceInitFailed: 3089 case FK_ConversionFailed: 3090 case FK_ConversionFromPropertyFailed: 3091 case FK_TooManyInitsForScalar: 3092 case FK_ReferenceBindingToInitList: 3093 case FK_InitListBadDestinationType: 3094 case FK_DefaultInitOfConst: 3095 case FK_Incomplete: 3096 case FK_ArrayTypeMismatch: 3097 case FK_NonConstantArrayInit: 3098 case FK_ListInitializationFailed: 3099 case FK_VariableLengthArrayHasInitializer: 3100 case FK_PlaceholderType: 3101 case FK_ExplicitConstructor: 3102 case FK_AddressOfUnaddressableFunction: 3103 return false; 3104 3105 case FK_ReferenceInitOverloadFailed: 3106 case FK_UserConversionOverloadFailed: 3107 case FK_ConstructorOverloadFailed: 3108 case FK_ListConstructorOverloadFailed: 3109 return FailedOverloadResult == OR_Ambiguous; 3110 } 3111 3112 llvm_unreachable("Invalid EntityKind!"); 3113 } 3114 3115 bool InitializationSequence::isConstructorInitialization() const { 3116 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 3117 } 3118 3119 void 3120 InitializationSequence 3121 ::AddAddressOverloadResolutionStep(FunctionDecl *Function, 3122 DeclAccessPair Found, 3123 bool HadMultipleCandidates) { 3124 Step S; 3125 S.Kind = SK_ResolveAddressOfOverloadedFunction; 3126 S.Type = Function->getType(); 3127 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3128 S.Function.Function = Function; 3129 S.Function.FoundDecl = Found; 3130 Steps.push_back(S); 3131 } 3132 3133 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 3134 ExprValueKind VK) { 3135 Step S; 3136 switch (VK) { 3137 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 3138 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 3139 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 3140 } 3141 S.Type = BaseType; 3142 Steps.push_back(S); 3143 } 3144 3145 void InitializationSequence::AddReferenceBindingStep(QualType T, 3146 bool BindingTemporary) { 3147 Step S; 3148 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 3149 S.Type = T; 3150 Steps.push_back(S); 3151 } 3152 3153 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 3154 Step S; 3155 S.Kind = SK_ExtraneousCopyToTemporary; 3156 S.Type = T; 3157 Steps.push_back(S); 3158 } 3159 3160 void 3161 InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 3162 DeclAccessPair FoundDecl, 3163 QualType T, 3164 bool HadMultipleCandidates) { 3165 Step S; 3166 S.Kind = SK_UserConversion; 3167 S.Type = T; 3168 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3169 S.Function.Function = Function; 3170 S.Function.FoundDecl = FoundDecl; 3171 Steps.push_back(S); 3172 } 3173 3174 void InitializationSequence::AddQualificationConversionStep(QualType Ty, 3175 ExprValueKind VK) { 3176 Step S; 3177 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 3178 switch (VK) { 3179 case VK_RValue: 3180 S.Kind = SK_QualificationConversionRValue; 3181 break; 3182 case VK_XValue: 3183 S.Kind = SK_QualificationConversionXValue; 3184 break; 3185 case VK_LValue: 3186 S.Kind = SK_QualificationConversionLValue; 3187 break; 3188 } 3189 S.Type = Ty; 3190 Steps.push_back(S); 3191 } 3192 3193 void InitializationSequence::AddAtomicConversionStep(QualType Ty) { 3194 Step S; 3195 S.Kind = SK_AtomicConversion; 3196 S.Type = Ty; 3197 Steps.push_back(S); 3198 } 3199 3200 void InitializationSequence::AddLValueToRValueStep(QualType Ty) { 3201 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers"); 3202 3203 Step S; 3204 S.Kind = SK_LValueToRValue; 3205 S.Type = Ty; 3206 Steps.push_back(S); 3207 } 3208 3209 void InitializationSequence::AddConversionSequenceStep( 3210 const ImplicitConversionSequence &ICS, QualType T, 3211 bool TopLevelOfInitList) { 3212 Step S; 3213 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing 3214 : SK_ConversionSequence; 3215 S.Type = T; 3216 S.ICS = new ImplicitConversionSequence(ICS); 3217 Steps.push_back(S); 3218 } 3219 3220 void InitializationSequence::AddListInitializationStep(QualType T) { 3221 Step S; 3222 S.Kind = SK_ListInitialization; 3223 S.Type = T; 3224 Steps.push_back(S); 3225 } 3226 3227 void 3228 InitializationSequence 3229 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor, 3230 AccessSpecifier Access, 3231 QualType T, 3232 bool HadMultipleCandidates, 3233 bool FromInitList, bool AsInitList) { 3234 Step S; 3235 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall 3236 : SK_ConstructorInitializationFromList 3237 : SK_ConstructorInitialization; 3238 S.Type = T; 3239 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3240 S.Function.Function = Constructor; 3241 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access); 3242 Steps.push_back(S); 3243 } 3244 3245 void InitializationSequence::AddZeroInitializationStep(QualType T) { 3246 Step S; 3247 S.Kind = SK_ZeroInitialization; 3248 S.Type = T; 3249 Steps.push_back(S); 3250 } 3251 3252 void InitializationSequence::AddCAssignmentStep(QualType T) { 3253 Step S; 3254 S.Kind = SK_CAssignment; 3255 S.Type = T; 3256 Steps.push_back(S); 3257 } 3258 3259 void InitializationSequence::AddStringInitStep(QualType T) { 3260 Step S; 3261 S.Kind = SK_StringInit; 3262 S.Type = T; 3263 Steps.push_back(S); 3264 } 3265 3266 void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 3267 Step S; 3268 S.Kind = SK_ObjCObjectConversion; 3269 S.Type = T; 3270 Steps.push_back(S); 3271 } 3272 3273 void InitializationSequence::AddArrayInitStep(QualType T) { 3274 Step S; 3275 S.Kind = SK_ArrayInit; 3276 S.Type = T; 3277 Steps.push_back(S); 3278 } 3279 3280 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { 3281 Step S; 3282 S.Kind = SK_ParenthesizedArrayInit; 3283 S.Type = T; 3284 Steps.push_back(S); 3285 } 3286 3287 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 3288 bool shouldCopy) { 3289 Step s; 3290 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 3291 : SK_PassByIndirectRestore); 3292 s.Type = type; 3293 Steps.push_back(s); 3294 } 3295 3296 void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 3297 Step S; 3298 S.Kind = SK_ProduceObjCObject; 3299 S.Type = T; 3300 Steps.push_back(S); 3301 } 3302 3303 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { 3304 Step S; 3305 S.Kind = SK_StdInitializerList; 3306 S.Type = T; 3307 Steps.push_back(S); 3308 } 3309 3310 void InitializationSequence::AddOCLSamplerInitStep(QualType T) { 3311 Step S; 3312 S.Kind = SK_OCLSamplerInit; 3313 S.Type = T; 3314 Steps.push_back(S); 3315 } 3316 3317 void InitializationSequence::AddOCLZeroEventStep(QualType T) { 3318 Step S; 3319 S.Kind = SK_OCLZeroEvent; 3320 S.Type = T; 3321 Steps.push_back(S); 3322 } 3323 3324 void InitializationSequence::RewrapReferenceInitList(QualType T, 3325 InitListExpr *Syntactic) { 3326 assert(Syntactic->getNumInits() == 1 && 3327 "Can only rewrap trivial init lists."); 3328 Step S; 3329 S.Kind = SK_UnwrapInitList; 3330 S.Type = Syntactic->getInit(0)->getType(); 3331 Steps.insert(Steps.begin(), S); 3332 3333 S.Kind = SK_RewrapInitList; 3334 S.Type = T; 3335 S.WrappingSyntacticList = Syntactic; 3336 Steps.push_back(S); 3337 } 3338 3339 void InitializationSequence::SetOverloadFailure(FailureKind Failure, 3340 OverloadingResult Result) { 3341 setSequenceKind(FailedSequence); 3342 this->Failure = Failure; 3343 this->FailedOverloadResult = Result; 3344 } 3345 3346 //===----------------------------------------------------------------------===// 3347 // Attempt initialization 3348 //===----------------------------------------------------------------------===// 3349 3350 /// Tries to add a zero initializer. Returns true if that worked. 3351 static bool 3352 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, 3353 const InitializedEntity &Entity) { 3354 if (Entity.getKind() != InitializedEntity::EK_Variable) 3355 return false; 3356 3357 VarDecl *VD = cast<VarDecl>(Entity.getDecl()); 3358 if (VD->getInit() || VD->getLocEnd().isMacroID()) 3359 return false; 3360 3361 QualType VariableTy = VD->getType().getCanonicalType(); 3362 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd()); 3363 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 3364 if (!Init.empty()) { 3365 Sequence.AddZeroInitializationStep(Entity.getType()); 3366 Sequence.SetZeroInitializationFixit(Init, Loc); 3367 return true; 3368 } 3369 return false; 3370 } 3371 3372 static void MaybeProduceObjCObject(Sema &S, 3373 InitializationSequence &Sequence, 3374 const InitializedEntity &Entity) { 3375 if (!S.getLangOpts().ObjCAutoRefCount) return; 3376 3377 /// When initializing a parameter, produce the value if it's marked 3378 /// __attribute__((ns_consumed)). 3379 if (Entity.isParameterKind()) { 3380 if (!Entity.isParameterConsumed()) 3381 return; 3382 3383 assert(Entity.getType()->isObjCRetainableType() && 3384 "consuming an object of unretainable type?"); 3385 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3386 3387 /// When initializing a return value, if the return type is a 3388 /// retainable type, then returns need to immediately retain the 3389 /// object. If an autorelease is required, it will be done at the 3390 /// last instant. 3391 } else if (Entity.getKind() == InitializedEntity::EK_Result) { 3392 if (!Entity.getType()->isObjCRetainableType()) 3393 return; 3394 3395 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3396 } 3397 } 3398 3399 static void TryListInitialization(Sema &S, 3400 const InitializedEntity &Entity, 3401 const InitializationKind &Kind, 3402 InitListExpr *InitList, 3403 InitializationSequence &Sequence, 3404 bool TreatUnavailableAsInvalid); 3405 3406 /// \brief When initializing from init list via constructor, handle 3407 /// initialization of an object of type std::initializer_list<T>. 3408 /// 3409 /// \return true if we have handled initialization of an object of type 3410 /// std::initializer_list<T>, false otherwise. 3411 static bool TryInitializerListConstruction(Sema &S, 3412 InitListExpr *List, 3413 QualType DestType, 3414 InitializationSequence &Sequence, 3415 bool TreatUnavailableAsInvalid) { 3416 QualType E; 3417 if (!S.isStdInitializerList(DestType, &E)) 3418 return false; 3419 3420 if (!S.isCompleteType(List->getExprLoc(), E)) { 3421 Sequence.setIncompleteTypeFailure(E); 3422 return true; 3423 } 3424 3425 // Try initializing a temporary array from the init list. 3426 QualType ArrayType = S.Context.getConstantArrayType( 3427 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 3428 List->getNumInits()), 3429 clang::ArrayType::Normal, 0); 3430 InitializedEntity HiddenArray = 3431 InitializedEntity::InitializeTemporary(ArrayType); 3432 InitializationKind Kind = 3433 InitializationKind::CreateDirectList(List->getExprLoc()); 3434 TryListInitialization(S, HiddenArray, Kind, List, Sequence, 3435 TreatUnavailableAsInvalid); 3436 if (Sequence) 3437 Sequence.AddStdInitializerListConstructionStep(DestType); 3438 return true; 3439 } 3440 3441 static OverloadingResult 3442 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, 3443 MultiExprArg Args, 3444 OverloadCandidateSet &CandidateSet, 3445 DeclContext::lookup_result Ctors, 3446 OverloadCandidateSet::iterator &Best, 3447 bool CopyInitializing, bool AllowExplicit, 3448 bool OnlyListConstructors, bool IsListInit) { 3449 CandidateSet.clear(); 3450 3451 for (NamedDecl *D : Ctors) { 3452 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3453 bool SuppressUserConversions = false; 3454 3455 // Find the constructor (which may be a template). 3456 CXXConstructorDecl *Constructor = nullptr; 3457 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 3458 if (ConstructorTmpl) 3459 Constructor = cast<CXXConstructorDecl>( 3460 ConstructorTmpl->getTemplatedDecl()); 3461 else { 3462 Constructor = cast<CXXConstructorDecl>(D); 3463 3464 // C++11 [over.best.ics]p4: 3465 // ... and the constructor or user-defined conversion function is a 3466 // candidate by 3467 // - 13.3.1.3, when the argument is the temporary in the second step 3468 // of a class copy-initialization, or 3469 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), 3470 // user-defined conversion sequences are not considered. 3471 // FIXME: This breaks backward compatibility, e.g. PR12117. As a 3472 // temporary fix, let's re-instate the third bullet above until 3473 // there is a resolution in the standard, i.e., 3474 // - 13.3.1.7 when the initializer list has exactly one element that is 3475 // itself an initializer list and a conversion to some class X or 3476 // reference to (possibly cv-qualified) X is considered for the first 3477 // parameter of a constructor of X. 3478 if ((CopyInitializing || 3479 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 3480 Constructor->isCopyOrMoveConstructor()) 3481 SuppressUserConversions = true; 3482 } 3483 3484 if (!Constructor->isInvalidDecl() && 3485 (AllowExplicit || !Constructor->isExplicit()) && 3486 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) { 3487 if (ConstructorTmpl) 3488 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3489 /*ExplicitArgs*/ nullptr, Args, 3490 CandidateSet, SuppressUserConversions); 3491 else { 3492 // C++ [over.match.copy]p1: 3493 // - When initializing a temporary to be bound to the first parameter 3494 // of a constructor that takes a reference to possibly cv-qualified 3495 // T as its first argument, called with a single argument in the 3496 // context of direct-initialization, explicit conversion functions 3497 // are also considered. 3498 bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 3499 Args.size() == 1 && 3500 Constructor->isCopyOrMoveConstructor(); 3501 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet, 3502 SuppressUserConversions, 3503 /*PartialOverloading=*/false, 3504 /*AllowExplicit=*/AllowExplicitConv); 3505 } 3506 } 3507 } 3508 3509 // Perform overload resolution and return the result. 3510 return CandidateSet.BestViableFunction(S, DeclLoc, Best); 3511 } 3512 3513 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which 3514 /// enumerates the constructors of the initialized entity and performs overload 3515 /// resolution to select the best. 3516 /// \param IsListInit Is this list-initialization? 3517 /// \param IsInitListCopy Is this non-list-initialization resulting from a 3518 /// list-initialization from {x} where x is the same 3519 /// type as the entity? 3520 static void TryConstructorInitialization(Sema &S, 3521 const InitializedEntity &Entity, 3522 const InitializationKind &Kind, 3523 MultiExprArg Args, QualType DestType, 3524 InitializationSequence &Sequence, 3525 bool IsListInit = false, 3526 bool IsInitListCopy = false) { 3527 assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 3528 "IsListInit must come with a single initializer list argument."); 3529 3530 // The type we're constructing needs to be complete. 3531 if (!S.isCompleteType(Kind.getLocation(), DestType)) { 3532 Sequence.setIncompleteTypeFailure(DestType); 3533 return; 3534 } 3535 3536 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 3537 assert(DestRecordType && "Constructor initialization requires record type"); 3538 CXXRecordDecl *DestRecordDecl 3539 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 3540 3541 // Build the candidate set directly in the initialization sequence 3542 // structure, so that it will persist if we fail. 3543 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3544 3545 // Determine whether we are allowed to call explicit constructors or 3546 // explicit conversion operators. 3547 bool AllowExplicit = Kind.AllowExplicit() || IsListInit; 3548 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; 3549 3550 // - Otherwise, if T is a class type, constructors are considered. The 3551 // applicable constructors are enumerated, and the best one is chosen 3552 // through overload resolution. 3553 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); 3554 3555 OverloadingResult Result = OR_No_Viable_Function; 3556 OverloadCandidateSet::iterator Best; 3557 bool AsInitializerList = false; 3558 3559 // C++11 [over.match.list]p1, per DR1467: 3560 // When objects of non-aggregate type T are list-initialized, such that 3561 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed 3562 // according to the rules in this section, overload resolution selects 3563 // the constructor in two phases: 3564 // 3565 // - Initially, the candidate functions are the initializer-list 3566 // constructors of the class T and the argument list consists of the 3567 // initializer list as a single argument. 3568 if (IsListInit) { 3569 InitListExpr *ILE = cast<InitListExpr>(Args[0]); 3570 AsInitializerList = true; 3571 3572 // If the initializer list has no elements and T has a default constructor, 3573 // the first phase is omitted. 3574 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor()) 3575 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 3576 CandidateSet, Ctors, Best, 3577 CopyInitialization, AllowExplicit, 3578 /*OnlyListConstructor=*/true, 3579 IsListInit); 3580 3581 // Time to unwrap the init list. 3582 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits()); 3583 } 3584 3585 // C++11 [over.match.list]p1: 3586 // - If no viable initializer-list constructor is found, overload resolution 3587 // is performed again, where the candidate functions are all the 3588 // constructors of the class T and the argument list consists of the 3589 // elements of the initializer list. 3590 if (Result == OR_No_Viable_Function) { 3591 AsInitializerList = false; 3592 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 3593 CandidateSet, Ctors, Best, 3594 CopyInitialization, AllowExplicit, 3595 /*OnlyListConstructors=*/false, 3596 IsListInit); 3597 } 3598 if (Result) { 3599 Sequence.SetOverloadFailure(IsListInit ? 3600 InitializationSequence::FK_ListConstructorOverloadFailed : 3601 InitializationSequence::FK_ConstructorOverloadFailed, 3602 Result); 3603 return; 3604 } 3605 3606 // C++11 [dcl.init]p6: 3607 // If a program calls for the default initialization of an object 3608 // of a const-qualified type T, T shall be a class type with a 3609 // user-provided default constructor. 3610 // C++ core issue 253 proposal: 3611 // If the implicit default constructor initializes all subobjects, no 3612 // initializer should be required. 3613 // The 253 proposal is for example needed to process libstdc++ headers in 5.x. 3614 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 3615 if (Kind.getKind() == InitializationKind::IK_Default && 3616 Entity.getType().isConstQualified()) { 3617 if (!CtorDecl->getParent()->allowConstDefaultInit()) { 3618 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 3619 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 3620 return; 3621 } 3622 } 3623 3624 // C++11 [over.match.list]p1: 3625 // In copy-list-initialization, if an explicit constructor is chosen, the 3626 // initializer is ill-formed. 3627 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { 3628 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); 3629 return; 3630 } 3631 3632 // Add the constructor initialization step. Any cv-qualification conversion is 3633 // subsumed by the initialization. 3634 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3635 Sequence.AddConstructorInitializationStep( 3636 CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates, 3637 IsListInit | IsInitListCopy, AsInitializerList); 3638 } 3639 3640 static bool 3641 ResolveOverloadedFunctionForReferenceBinding(Sema &S, 3642 Expr *Initializer, 3643 QualType &SourceType, 3644 QualType &UnqualifiedSourceType, 3645 QualType UnqualifiedTargetType, 3646 InitializationSequence &Sequence) { 3647 if (S.Context.getCanonicalType(UnqualifiedSourceType) == 3648 S.Context.OverloadTy) { 3649 DeclAccessPair Found; 3650 bool HadMultipleCandidates = false; 3651 if (FunctionDecl *Fn 3652 = S.ResolveAddressOfOverloadedFunction(Initializer, 3653 UnqualifiedTargetType, 3654 false, Found, 3655 &HadMultipleCandidates)) { 3656 Sequence.AddAddressOverloadResolutionStep(Fn, Found, 3657 HadMultipleCandidates); 3658 SourceType = Fn->getType(); 3659 UnqualifiedSourceType = SourceType.getUnqualifiedType(); 3660 } else if (!UnqualifiedTargetType->isRecordType()) { 3661 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3662 return true; 3663 } 3664 } 3665 return false; 3666 } 3667 3668 static void TryReferenceInitializationCore(Sema &S, 3669 const InitializedEntity &Entity, 3670 const InitializationKind &Kind, 3671 Expr *Initializer, 3672 QualType cv1T1, QualType T1, 3673 Qualifiers T1Quals, 3674 QualType cv2T2, QualType T2, 3675 Qualifiers T2Quals, 3676 InitializationSequence &Sequence); 3677 3678 static void TryValueInitialization(Sema &S, 3679 const InitializedEntity &Entity, 3680 const InitializationKind &Kind, 3681 InitializationSequence &Sequence, 3682 InitListExpr *InitList = nullptr); 3683 3684 /// \brief Attempt list initialization of a reference. 3685 static void TryReferenceListInitialization(Sema &S, 3686 const InitializedEntity &Entity, 3687 const InitializationKind &Kind, 3688 InitListExpr *InitList, 3689 InitializationSequence &Sequence, 3690 bool TreatUnavailableAsInvalid) { 3691 // First, catch C++03 where this isn't possible. 3692 if (!S.getLangOpts().CPlusPlus11) { 3693 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 3694 return; 3695 } 3696 // Can't reference initialize a compound literal. 3697 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { 3698 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 3699 return; 3700 } 3701 3702 QualType DestType = Entity.getType(); 3703 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3704 Qualifiers T1Quals; 3705 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 3706 3707 // Reference initialization via an initializer list works thus: 3708 // If the initializer list consists of a single element that is 3709 // reference-related to the referenced type, bind directly to that element 3710 // (possibly creating temporaries). 3711 // Otherwise, initialize a temporary with the initializer list and 3712 // bind to that. 3713 if (InitList->getNumInits() == 1) { 3714 Expr *Initializer = InitList->getInit(0); 3715 QualType cv2T2 = Initializer->getType(); 3716 Qualifiers T2Quals; 3717 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 3718 3719 // If this fails, creating a temporary wouldn't work either. 3720 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 3721 T1, Sequence)) 3722 return; 3723 3724 SourceLocation DeclLoc = Initializer->getLocStart(); 3725 bool dummy1, dummy2, dummy3; 3726 Sema::ReferenceCompareResult RefRelationship 3727 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1, 3728 dummy2, dummy3); 3729 if (RefRelationship >= Sema::Ref_Related) { 3730 // Try to bind the reference here. 3731 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 3732 T1Quals, cv2T2, T2, T2Quals, Sequence); 3733 if (Sequence) 3734 Sequence.RewrapReferenceInitList(cv1T1, InitList); 3735 return; 3736 } 3737 3738 // Update the initializer if we've resolved an overloaded function. 3739 if (Sequence.step_begin() != Sequence.step_end()) 3740 Sequence.RewrapReferenceInitList(cv1T1, InitList); 3741 } 3742 3743 // Not reference-related. Create a temporary and bind to that. 3744 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 3745 3746 TryListInitialization(S, TempEntity, Kind, InitList, Sequence, 3747 TreatUnavailableAsInvalid); 3748 if (Sequence) { 3749 if (DestType->isRValueReferenceType() || 3750 (T1Quals.hasConst() && !T1Quals.hasVolatile())) 3751 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 3752 else 3753 Sequence.SetFailed( 3754 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 3755 } 3756 } 3757 3758 /// \brief Attempt list initialization (C++0x [dcl.init.list]) 3759 static void TryListInitialization(Sema &S, 3760 const InitializedEntity &Entity, 3761 const InitializationKind &Kind, 3762 InitListExpr *InitList, 3763 InitializationSequence &Sequence, 3764 bool TreatUnavailableAsInvalid) { 3765 QualType DestType = Entity.getType(); 3766 3767 // C++ doesn't allow scalar initialization with more than one argument. 3768 // But C99 complex numbers are scalars and it makes sense there. 3769 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && 3770 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 3771 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 3772 return; 3773 } 3774 if (DestType->isReferenceType()) { 3775 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, 3776 TreatUnavailableAsInvalid); 3777 return; 3778 } 3779 3780 if (DestType->isRecordType() && 3781 !S.isCompleteType(InitList->getLocStart(), DestType)) { 3782 Sequence.setIncompleteTypeFailure(DestType); 3783 return; 3784 } 3785 3786 // C++11 [dcl.init.list]p3, per DR1467: 3787 // - If T is a class type and the initializer list has a single element of 3788 // type cv U, where U is T or a class derived from T, the object is 3789 // initialized from that element (by copy-initialization for 3790 // copy-list-initialization, or by direct-initialization for 3791 // direct-list-initialization). 3792 // - Otherwise, if T is a character array and the initializer list has a 3793 // single element that is an appropriately-typed string literal 3794 // (8.5.2 [dcl.init.string]), initialization is performed as described 3795 // in that section. 3796 // - Otherwise, if T is an aggregate, [...] (continue below). 3797 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { 3798 if (DestType->isRecordType()) { 3799 QualType InitType = InitList->getInit(0)->getType(); 3800 if (S.Context.hasSameUnqualifiedType(InitType, DestType) || 3801 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) { 3802 Expr *InitAsExpr = InitList->getInit(0); 3803 TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType, 3804 Sequence, /*InitListSyntax*/ false, 3805 /*IsInitListCopy*/ true); 3806 return; 3807 } 3808 } 3809 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { 3810 Expr *SubInit[1] = {InitList->getInit(0)}; 3811 if (!isa<VariableArrayType>(DestAT) && 3812 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { 3813 InitializationKind SubKind = 3814 Kind.getKind() == InitializationKind::IK_DirectList 3815 ? InitializationKind::CreateDirect(Kind.getLocation(), 3816 InitList->getLBraceLoc(), 3817 InitList->getRBraceLoc()) 3818 : Kind; 3819 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 3820 /*TopLevelOfInitList*/ true, 3821 TreatUnavailableAsInvalid); 3822 3823 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if 3824 // the element is not an appropriately-typed string literal, in which 3825 // case we should proceed as in C++11 (below). 3826 if (Sequence) { 3827 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 3828 return; 3829 } 3830 } 3831 } 3832 } 3833 3834 // C++11 [dcl.init.list]p3: 3835 // - If T is an aggregate, aggregate initialization is performed. 3836 if ((DestType->isRecordType() && !DestType->isAggregateType()) || 3837 (S.getLangOpts().CPlusPlus11 && 3838 S.isStdInitializerList(DestType, nullptr))) { 3839 if (S.getLangOpts().CPlusPlus11) { 3840 // - Otherwise, if the initializer list has no elements and T is a 3841 // class type with a default constructor, the object is 3842 // value-initialized. 3843 if (InitList->getNumInits() == 0) { 3844 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); 3845 if (RD->hasDefaultConstructor()) { 3846 TryValueInitialization(S, Entity, Kind, Sequence, InitList); 3847 return; 3848 } 3849 } 3850 3851 // - Otherwise, if T is a specialization of std::initializer_list<E>, 3852 // an initializer_list object constructed [...] 3853 if (TryInitializerListConstruction(S, InitList, DestType, Sequence, 3854 TreatUnavailableAsInvalid)) 3855 return; 3856 3857 // - Otherwise, if T is a class type, constructors are considered. 3858 Expr *InitListAsExpr = InitList; 3859 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 3860 Sequence, /*InitListSyntax*/ true); 3861 } else 3862 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 3863 return; 3864 } 3865 3866 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && 3867 InitList->getNumInits() == 1) { 3868 Expr *E = InitList->getInit(0); 3869 3870 // - Otherwise, if T is an enumeration with a fixed underlying type, 3871 // the initializer-list has a single element v, and the initialization 3872 // is direct-list-initialization, the object is initialized with the 3873 // value T(v); if a narrowing conversion is required to convert v to 3874 // the underlying type of T, the program is ill-formed. 3875 auto *ET = DestType->getAs<EnumType>(); 3876 if (S.getLangOpts().CPlusPlus1z && 3877 Kind.getKind() == InitializationKind::IK_DirectList && 3878 ET && ET->getDecl()->isFixed() && 3879 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && 3880 (E->getType()->isIntegralOrEnumerationType() || 3881 E->getType()->isFloatingType())) { 3882 // There are two ways that T(v) can work when T is an enumeration type. 3883 // If there is either an implicit conversion sequence from v to T or 3884 // a conversion function that can convert from v to T, then we use that. 3885 // Otherwise, if v is of integral, enumeration, or floating-point type, 3886 // it is converted to the enumeration type via its underlying type. 3887 // There is no overlap possible between these two cases (except when the 3888 // source value is already of the destination type), and the first 3889 // case is handled by the general case for single-element lists below. 3890 ImplicitConversionSequence ICS; 3891 ICS.setStandard(); 3892 ICS.Standard.setAsIdentityConversion(); 3893 // If E is of a floating-point type, then the conversion is ill-formed 3894 // due to narrowing, but go through the motions in order to produce the 3895 // right diagnostic. 3896 ICS.Standard.Second = E->getType()->isFloatingType() 3897 ? ICK_Floating_Integral 3898 : ICK_Integral_Conversion; 3899 ICS.Standard.setFromType(E->getType()); 3900 ICS.Standard.setToType(0, E->getType()); 3901 ICS.Standard.setToType(1, DestType); 3902 ICS.Standard.setToType(2, DestType); 3903 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), 3904 /*TopLevelOfInitList*/true); 3905 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 3906 return; 3907 } 3908 3909 // - Otherwise, if the initializer list has a single element of type E 3910 // [...references are handled above...], the object or reference is 3911 // initialized from that element (by copy-initialization for 3912 // copy-list-initialization, or by direct-initialization for 3913 // direct-list-initialization); if a narrowing conversion is required 3914 // to convert the element to T, the program is ill-formed. 3915 // 3916 // Per core-24034, this is direct-initialization if we were performing 3917 // direct-list-initialization and copy-initialization otherwise. 3918 // We can't use InitListChecker for this, because it always performs 3919 // copy-initialization. This only matters if we might use an 'explicit' 3920 // conversion operator, so we only need to handle the cases where the source 3921 // is of record type. 3922 if (InitList->getInit(0)->getType()->isRecordType()) { 3923 InitializationKind SubKind = 3924 Kind.getKind() == InitializationKind::IK_DirectList 3925 ? InitializationKind::CreateDirect(Kind.getLocation(), 3926 InitList->getLBraceLoc(), 3927 InitList->getRBraceLoc()) 3928 : Kind; 3929 Expr *SubInit[1] = { InitList->getInit(0) }; 3930 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 3931 /*TopLevelOfInitList*/true, 3932 TreatUnavailableAsInvalid); 3933 if (Sequence) 3934 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 3935 return; 3936 } 3937 } 3938 3939 InitListChecker CheckInitList(S, Entity, InitList, 3940 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); 3941 if (CheckInitList.HadError()) { 3942 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 3943 return; 3944 } 3945 3946 // Add the list initialization step with the built init list. 3947 Sequence.AddListInitializationStep(DestType); 3948 } 3949 3950 /// \brief Try a reference initialization that involves calling a conversion 3951 /// function. 3952 static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 3953 const InitializedEntity &Entity, 3954 const InitializationKind &Kind, 3955 Expr *Initializer, 3956 bool AllowRValues, 3957 InitializationSequence &Sequence) { 3958 QualType DestType = Entity.getType(); 3959 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 3960 QualType T1 = cv1T1.getUnqualifiedType(); 3961 QualType cv2T2 = Initializer->getType(); 3962 QualType T2 = cv2T2.getUnqualifiedType(); 3963 3964 bool DerivedToBase; 3965 bool ObjCConversion; 3966 bool ObjCLifetimeConversion; 3967 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 3968 T1, T2, DerivedToBase, 3969 ObjCConversion, 3970 ObjCLifetimeConversion) && 3971 "Must have incompatible references when binding via conversion"); 3972 (void)DerivedToBase; 3973 (void)ObjCConversion; 3974 (void)ObjCLifetimeConversion; 3975 3976 // Build the candidate set directly in the initialization sequence 3977 // structure, so that it will persist if we fail. 3978 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3979 CandidateSet.clear(); 3980 3981 // Determine whether we are allowed to call explicit constructors or 3982 // explicit conversion operators. 3983 bool AllowExplicit = Kind.AllowExplicit(); 3984 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); 3985 3986 const RecordType *T1RecordType = nullptr; 3987 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 3988 S.isCompleteType(Kind.getLocation(), T1)) { 3989 // The type we're converting to is a class type. Enumerate its constructors 3990 // to see if there is a suitable conversion. 3991 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 3992 3993 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { 3994 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3995 3996 // Find the constructor (which may be a template). 3997 CXXConstructorDecl *Constructor = nullptr; 3998 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 3999 if (ConstructorTmpl) 4000 Constructor = cast<CXXConstructorDecl>( 4001 ConstructorTmpl->getTemplatedDecl()); 4002 else 4003 Constructor = cast<CXXConstructorDecl>(D); 4004 4005 if (!Constructor->isInvalidDecl() && 4006 Constructor->isConvertingConstructor(AllowExplicit)) { 4007 if (ConstructorTmpl) 4008 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 4009 /*ExplicitArgs*/ nullptr, 4010 Initializer, CandidateSet, 4011 /*SuppressUserConversions=*/true); 4012 else 4013 S.AddOverloadCandidate(Constructor, FoundDecl, 4014 Initializer, CandidateSet, 4015 /*SuppressUserConversions=*/true); 4016 } 4017 } 4018 } 4019 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 4020 return OR_No_Viable_Function; 4021 4022 const RecordType *T2RecordType = nullptr; 4023 if ((T2RecordType = T2->getAs<RecordType>()) && 4024 S.isCompleteType(Kind.getLocation(), T2)) { 4025 // The type we're converting from is a class type, enumerate its conversion 4026 // functions. 4027 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 4028 4029 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4030 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4031 NamedDecl *D = *I; 4032 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4033 if (isa<UsingShadowDecl>(D)) 4034 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4035 4036 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4037 CXXConversionDecl *Conv; 4038 if (ConvTemplate) 4039 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4040 else 4041 Conv = cast<CXXConversionDecl>(D); 4042 4043 // If the conversion function doesn't return a reference type, 4044 // it can't be considered for this conversion unless we're allowed to 4045 // consider rvalues. 4046 // FIXME: Do we need to make sure that we only consider conversion 4047 // candidates with reference-compatible results? That might be needed to 4048 // break recursion. 4049 if ((AllowExplicitConvs || !Conv->isExplicit()) && 4050 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 4051 if (ConvTemplate) 4052 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 4053 ActingDC, Initializer, 4054 DestType, CandidateSet, 4055 /*AllowObjCConversionOnExplicit=*/ 4056 false); 4057 else 4058 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 4059 Initializer, DestType, CandidateSet, 4060 /*AllowObjCConversionOnExplicit=*/false); 4061 } 4062 } 4063 } 4064 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 4065 return OR_No_Viable_Function; 4066 4067 SourceLocation DeclLoc = Initializer->getLocStart(); 4068 4069 // Perform overload resolution. If it fails, return the failed result. 4070 OverloadCandidateSet::iterator Best; 4071 if (OverloadingResult Result 4072 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) 4073 return Result; 4074 4075 FunctionDecl *Function = Best->Function; 4076 // This is the overload that will be used for this initialization step if we 4077 // use this initialization. Mark it as referenced. 4078 Function->setReferenced(); 4079 4080 // Compute the returned type of the conversion. 4081 if (isa<CXXConversionDecl>(Function)) 4082 T2 = Function->getReturnType(); 4083 else 4084 T2 = cv1T1; 4085 4086 // Add the user-defined conversion step. 4087 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4088 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 4089 T2.getNonLValueExprType(S.Context), 4090 HadMultipleCandidates); 4091 4092 // Determine whether we need to perform derived-to-base or 4093 // cv-qualification adjustments. 4094 ExprValueKind VK = VK_RValue; 4095 if (T2->isLValueReferenceType()) 4096 VK = VK_LValue; 4097 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>()) 4098 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 4099 4100 bool NewDerivedToBase = false; 4101 bool NewObjCConversion = false; 4102 bool NewObjCLifetimeConversion = false; 4103 Sema::ReferenceCompareResult NewRefRelationship 4104 = S.CompareReferenceRelationship(DeclLoc, T1, 4105 T2.getNonLValueExprType(S.Context), 4106 NewDerivedToBase, NewObjCConversion, 4107 NewObjCLifetimeConversion); 4108 if (NewRefRelationship == Sema::Ref_Incompatible) { 4109 // If the type we've converted to is not reference-related to the 4110 // type we're looking for, then there is another conversion step 4111 // we need to perform to produce a temporary of the right type 4112 // that we'll be binding to. 4113 ImplicitConversionSequence ICS; 4114 ICS.setStandard(); 4115 ICS.Standard = Best->FinalConversion; 4116 T2 = ICS.Standard.getToType(2); 4117 Sequence.AddConversionSequenceStep(ICS, T2); 4118 } else if (NewDerivedToBase) 4119 Sequence.AddDerivedToBaseCastStep( 4120 S.Context.getQualifiedType(T1, 4121 T2.getNonReferenceType().getQualifiers()), 4122 VK); 4123 else if (NewObjCConversion) 4124 Sequence.AddObjCObjectConversionStep( 4125 S.Context.getQualifiedType(T1, 4126 T2.getNonReferenceType().getQualifiers())); 4127 4128 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 4129 Sequence.AddQualificationConversionStep(cv1T1, VK); 4130 4131 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 4132 return OR_Success; 4133 } 4134 4135 static void CheckCXX98CompatAccessibleCopy(Sema &S, 4136 const InitializedEntity &Entity, 4137 Expr *CurInitExpr); 4138 4139 /// \brief Attempt reference initialization (C++0x [dcl.init.ref]) 4140 static void TryReferenceInitialization(Sema &S, 4141 const InitializedEntity &Entity, 4142 const InitializationKind &Kind, 4143 Expr *Initializer, 4144 InitializationSequence &Sequence) { 4145 QualType DestType = Entity.getType(); 4146 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 4147 Qualifiers T1Quals; 4148 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4149 QualType cv2T2 = Initializer->getType(); 4150 Qualifiers T2Quals; 4151 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4152 4153 // If the initializer is the address of an overloaded function, try 4154 // to resolve the overloaded function. If all goes well, T2 is the 4155 // type of the resulting function. 4156 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4157 T1, Sequence)) 4158 return; 4159 4160 // Delegate everything else to a subfunction. 4161 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4162 T1Quals, cv2T2, T2, T2Quals, Sequence); 4163 } 4164 4165 /// Converts the target of reference initialization so that it has the 4166 /// appropriate qualifiers and value kind. 4167 /// 4168 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'. 4169 /// \code 4170 /// int x; 4171 /// const int &r = x; 4172 /// \endcode 4173 /// 4174 /// In this case the reference is binding to a bitfield lvalue, which isn't 4175 /// valid. Perform a load to create a lifetime-extended temporary instead. 4176 /// \code 4177 /// const int &r = someStruct.bitfield; 4178 /// \endcode 4179 static ExprValueKind 4180 convertQualifiersAndValueKindIfNecessary(Sema &S, 4181 InitializationSequence &Sequence, 4182 Expr *Initializer, 4183 QualType cv1T1, 4184 Qualifiers T1Quals, 4185 Qualifiers T2Quals, 4186 bool IsLValueRef) { 4187 bool IsNonAddressableType = Initializer->refersToBitField() || 4188 Initializer->refersToVectorElement(); 4189 4190 if (IsNonAddressableType) { 4191 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an 4192 // lvalue reference to a non-volatile const type, or the reference shall be 4193 // an rvalue reference. 4194 // 4195 // If not, we can't make a temporary and bind to that. Give up and allow the 4196 // error to be diagnosed later. 4197 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) { 4198 assert(Initializer->isGLValue()); 4199 return Initializer->getValueKind(); 4200 } 4201 4202 // Force a load so we can materialize a temporary. 4203 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType()); 4204 return VK_RValue; 4205 } 4206 4207 if (T1Quals != T2Quals) { 4208 Sequence.AddQualificationConversionStep(cv1T1, 4209 Initializer->getValueKind()); 4210 } 4211 4212 return Initializer->getValueKind(); 4213 } 4214 4215 /// \brief Reference initialization without resolving overloaded functions. 4216 static void TryReferenceInitializationCore(Sema &S, 4217 const InitializedEntity &Entity, 4218 const InitializationKind &Kind, 4219 Expr *Initializer, 4220 QualType cv1T1, QualType T1, 4221 Qualifiers T1Quals, 4222 QualType cv2T2, QualType T2, 4223 Qualifiers T2Quals, 4224 InitializationSequence &Sequence) { 4225 QualType DestType = Entity.getType(); 4226 SourceLocation DeclLoc = Initializer->getLocStart(); 4227 // Compute some basic properties of the types and the initializer. 4228 bool isLValueRef = DestType->isLValueReferenceType(); 4229 bool isRValueRef = !isLValueRef; 4230 bool DerivedToBase = false; 4231 bool ObjCConversion = false; 4232 bool ObjCLifetimeConversion = false; 4233 Expr::Classification InitCategory = Initializer->Classify(S.Context); 4234 Sema::ReferenceCompareResult RefRelationship 4235 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, 4236 ObjCConversion, ObjCLifetimeConversion); 4237 4238 // C++0x [dcl.init.ref]p5: 4239 // A reference to type "cv1 T1" is initialized by an expression of type 4240 // "cv2 T2" as follows: 4241 // 4242 // - If the reference is an lvalue reference and the initializer 4243 // expression 4244 // Note the analogous bullet points for rvalue refs to functions. Because 4245 // there are no function rvalues in C++, rvalue refs to functions are treated 4246 // like lvalue refs. 4247 OverloadingResult ConvOvlResult = OR_Success; 4248 bool T1Function = T1->isFunctionType(); 4249 if (isLValueRef || T1Function) { 4250 if (InitCategory.isLValue() && 4251 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 4252 (Kind.isCStyleOrFunctionalCast() && 4253 RefRelationship == Sema::Ref_Related))) { 4254 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 4255 // reference-compatible with "cv2 T2," or 4256 // 4257 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a 4258 // bit-field when we're determining whether the reference initialization 4259 // can occur. However, we do pay attention to whether it is a bit-field 4260 // to decide whether we're actually binding to a temporary created from 4261 // the bit-field. 4262 if (DerivedToBase) 4263 Sequence.AddDerivedToBaseCastStep( 4264 S.Context.getQualifiedType(T1, T2Quals), 4265 VK_LValue); 4266 else if (ObjCConversion) 4267 Sequence.AddObjCObjectConversionStep( 4268 S.Context.getQualifiedType(T1, T2Quals)); 4269 4270 ExprValueKind ValueKind = 4271 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer, 4272 cv1T1, T1Quals, T2Quals, 4273 isLValueRef); 4274 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue); 4275 return; 4276 } 4277 4278 // - has a class type (i.e., T2 is a class type), where T1 is not 4279 // reference-related to T2, and can be implicitly converted to an 4280 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 4281 // with "cv3 T3" (this conversion is selected by enumerating the 4282 // applicable conversion functions (13.3.1.6) and choosing the best 4283 // one through overload resolution (13.3)), 4284 // If we have an rvalue ref to function type here, the rhs must be 4285 // an rvalue. DR1287 removed the "implicitly" here. 4286 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 4287 (isLValueRef || InitCategory.isRValue())) { 4288 ConvOvlResult = TryRefInitWithConversionFunction( 4289 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence); 4290 if (ConvOvlResult == OR_Success) 4291 return; 4292 if (ConvOvlResult != OR_No_Viable_Function) 4293 Sequence.SetOverloadFailure( 4294 InitializationSequence::FK_ReferenceInitOverloadFailed, 4295 ConvOvlResult); 4296 } 4297 } 4298 4299 // - Otherwise, the reference shall be an lvalue reference to a 4300 // non-volatile const type (i.e., cv1 shall be const), or the reference 4301 // shall be an rvalue reference. 4302 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) { 4303 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4304 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4305 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4306 Sequence.SetOverloadFailure( 4307 InitializationSequence::FK_ReferenceInitOverloadFailed, 4308 ConvOvlResult); 4309 else 4310 Sequence.SetFailed(InitCategory.isLValue() 4311 ? (RefRelationship == Sema::Ref_Related 4312 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 4313 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 4314 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 4315 4316 return; 4317 } 4318 4319 // - If the initializer expression 4320 // - is an xvalue, class prvalue, array prvalue, or function lvalue and 4321 // "cv1 T1" is reference-compatible with "cv2 T2" 4322 // Note: functions are handled below. 4323 if (!T1Function && 4324 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 4325 (Kind.isCStyleOrFunctionalCast() && 4326 RefRelationship == Sema::Ref_Related)) && 4327 (InitCategory.isXValue() || 4328 (InitCategory.isPRValue() && T2->isRecordType()) || 4329 (InitCategory.isPRValue() && T2->isArrayType()))) { 4330 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue; 4331 if (InitCategory.isPRValue() && T2->isRecordType()) { 4332 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 4333 // compiler the freedom to perform a copy here or bind to the 4334 // object, while C++0x requires that we bind directly to the 4335 // object. Hence, we always bind to the object without making an 4336 // extra copy. However, in C++03 requires that we check for the 4337 // presence of a suitable copy constructor: 4338 // 4339 // The constructor that would be used to make the copy shall 4340 // be callable whether or not the copy is actually done. 4341 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) 4342 Sequence.AddExtraneousCopyToTemporary(cv2T2); 4343 else if (S.getLangOpts().CPlusPlus11) 4344 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 4345 } 4346 4347 if (DerivedToBase) 4348 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals), 4349 ValueKind); 4350 else if (ObjCConversion) 4351 Sequence.AddObjCObjectConversionStep( 4352 S.Context.getQualifiedType(T1, T2Quals)); 4353 4354 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence, 4355 Initializer, cv1T1, 4356 T1Quals, T2Quals, 4357 isLValueRef); 4358 4359 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue); 4360 return; 4361 } 4362 4363 // - has a class type (i.e., T2 is a class type), where T1 is not 4364 // reference-related to T2, and can be implicitly converted to an 4365 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 4366 // where "cv1 T1" is reference-compatible with "cv3 T3", 4367 // 4368 // DR1287 removes the "implicitly" here. 4369 if (T2->isRecordType()) { 4370 if (RefRelationship == Sema::Ref_Incompatible) { 4371 ConvOvlResult = TryRefInitWithConversionFunction( 4372 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence); 4373 if (ConvOvlResult) 4374 Sequence.SetOverloadFailure( 4375 InitializationSequence::FK_ReferenceInitOverloadFailed, 4376 ConvOvlResult); 4377 4378 return; 4379 } 4380 4381 if ((RefRelationship == Sema::Ref_Compatible || 4382 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) && 4383 isRValueRef && InitCategory.isLValue()) { 4384 Sequence.SetFailed( 4385 InitializationSequence::FK_RValueReferenceBindingToLValue); 4386 return; 4387 } 4388 4389 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 4390 return; 4391 } 4392 4393 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 4394 // from the initializer expression using the rules for a non-reference 4395 // copy-initialization (8.5). The reference is then bound to the 4396 // temporary. [...] 4397 4398 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 4399 4400 // FIXME: Why do we use an implicit conversion here rather than trying 4401 // copy-initialization? 4402 ImplicitConversionSequence ICS 4403 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 4404 /*SuppressUserConversions=*/false, 4405 /*AllowExplicit=*/false, 4406 /*FIXME:InOverloadResolution=*/false, 4407 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 4408 /*AllowObjCWritebackConversion=*/false); 4409 4410 if (ICS.isBad()) { 4411 // FIXME: Use the conversion function set stored in ICS to turn 4412 // this into an overloading ambiguity diagnostic. However, we need 4413 // to keep that set as an OverloadCandidateSet rather than as some 4414 // other kind of set. 4415 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4416 Sequence.SetOverloadFailure( 4417 InitializationSequence::FK_ReferenceInitOverloadFailed, 4418 ConvOvlResult); 4419 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4420 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4421 else 4422 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 4423 return; 4424 } else { 4425 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 4426 } 4427 4428 // [...] If T1 is reference-related to T2, cv1 must be the 4429 // same cv-qualification as, or greater cv-qualification 4430 // than, cv2; otherwise, the program is ill-formed. 4431 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 4432 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 4433 if (RefRelationship == Sema::Ref_Related && 4434 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { 4435 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 4436 return; 4437 } 4438 4439 // [...] If T1 is reference-related to T2 and the reference is an rvalue 4440 // reference, the initializer expression shall not be an lvalue. 4441 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 4442 InitCategory.isLValue()) { 4443 Sequence.SetFailed( 4444 InitializationSequence::FK_RValueReferenceBindingToLValue); 4445 return; 4446 } 4447 4448 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 4449 } 4450 4451 /// \brief Attempt character array initialization from a string literal 4452 /// (C++ [dcl.init.string], C99 6.7.8). 4453 static void TryStringLiteralInitialization(Sema &S, 4454 const InitializedEntity &Entity, 4455 const InitializationKind &Kind, 4456 Expr *Initializer, 4457 InitializationSequence &Sequence) { 4458 Sequence.AddStringInitStep(Entity.getType()); 4459 } 4460 4461 /// \brief Attempt value initialization (C++ [dcl.init]p7). 4462 static void TryValueInitialization(Sema &S, 4463 const InitializedEntity &Entity, 4464 const InitializationKind &Kind, 4465 InitializationSequence &Sequence, 4466 InitListExpr *InitList) { 4467 assert((!InitList || InitList->getNumInits() == 0) && 4468 "Shouldn't use value-init for non-empty init lists"); 4469 4470 // C++98 [dcl.init]p5, C++11 [dcl.init]p7: 4471 // 4472 // To value-initialize an object of type T means: 4473 QualType T = Entity.getType(); 4474 4475 // -- if T is an array type, then each element is value-initialized; 4476 T = S.Context.getBaseElementType(T); 4477 4478 if (const RecordType *RT = T->getAs<RecordType>()) { 4479 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 4480 bool NeedZeroInitialization = true; 4481 if (!S.getLangOpts().CPlusPlus11) { 4482 // C++98: 4483 // -- if T is a class type (clause 9) with a user-declared constructor 4484 // (12.1), then the default constructor for T is called (and the 4485 // initialization is ill-formed if T has no accessible default 4486 // constructor); 4487 if (ClassDecl->hasUserDeclaredConstructor()) 4488 NeedZeroInitialization = false; 4489 } else { 4490 // C++11: 4491 // -- if T is a class type (clause 9) with either no default constructor 4492 // (12.1 [class.ctor]) or a default constructor that is user-provided 4493 // or deleted, then the object is default-initialized; 4494 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); 4495 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) 4496 NeedZeroInitialization = false; 4497 } 4498 4499 // -- if T is a (possibly cv-qualified) non-union class type without a 4500 // user-provided or deleted default constructor, then the object is 4501 // zero-initialized and, if T has a non-trivial default constructor, 4502 // default-initialized; 4503 // The 'non-union' here was removed by DR1502. The 'non-trivial default 4504 // constructor' part was removed by DR1507. 4505 if (NeedZeroInitialization) 4506 Sequence.AddZeroInitializationStep(Entity.getType()); 4507 4508 // C++03: 4509 // -- if T is a non-union class type without a user-declared constructor, 4510 // then every non-static data member and base class component of T is 4511 // value-initialized; 4512 // [...] A program that calls for [...] value-initialization of an 4513 // entity of reference type is ill-formed. 4514 // 4515 // C++11 doesn't need this handling, because value-initialization does not 4516 // occur recursively there, and the implicit default constructor is 4517 // defined as deleted in the problematic cases. 4518 if (!S.getLangOpts().CPlusPlus11 && 4519 ClassDecl->hasUninitializedReferenceMember()) { 4520 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); 4521 return; 4522 } 4523 4524 // If this is list-value-initialization, pass the empty init list on when 4525 // building the constructor call. This affects the semantics of a few 4526 // things (such as whether an explicit default constructor can be called). 4527 Expr *InitListAsExpr = InitList; 4528 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); 4529 bool InitListSyntax = InitList; 4530 4531 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence, 4532 InitListSyntax); 4533 } 4534 } 4535 4536 Sequence.AddZeroInitializationStep(Entity.getType()); 4537 } 4538 4539 /// \brief Attempt default initialization (C++ [dcl.init]p6). 4540 static void TryDefaultInitialization(Sema &S, 4541 const InitializedEntity &Entity, 4542 const InitializationKind &Kind, 4543 InitializationSequence &Sequence) { 4544 assert(Kind.getKind() == InitializationKind::IK_Default); 4545 4546 // C++ [dcl.init]p6: 4547 // To default-initialize an object of type T means: 4548 // - if T is an array type, each element is default-initialized; 4549 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 4550 4551 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 4552 // constructor for T is called (and the initialization is ill-formed if 4553 // T has no accessible default constructor); 4554 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { 4555 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence); 4556 return; 4557 } 4558 4559 // - otherwise, no initialization is performed. 4560 4561 // If a program calls for the default initialization of an object of 4562 // a const-qualified type T, T shall be a class type with a user-provided 4563 // default constructor. 4564 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { 4565 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 4566 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 4567 return; 4568 } 4569 4570 // If the destination type has a lifetime property, zero-initialize it. 4571 if (DestType.getQualifiers().hasObjCLifetime()) { 4572 Sequence.AddZeroInitializationStep(Entity.getType()); 4573 return; 4574 } 4575 } 4576 4577 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 4578 /// which enumerates all conversion functions and performs overload resolution 4579 /// to select the best. 4580 static void TryUserDefinedConversion(Sema &S, 4581 QualType DestType, 4582 const InitializationKind &Kind, 4583 Expr *Initializer, 4584 InitializationSequence &Sequence, 4585 bool TopLevelOfInitList) { 4586 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 4587 QualType SourceType = Initializer->getType(); 4588 assert((DestType->isRecordType() || SourceType->isRecordType()) && 4589 "Must have a class type to perform a user-defined conversion"); 4590 4591 // Build the candidate set directly in the initialization sequence 4592 // structure, so that it will persist if we fail. 4593 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4594 CandidateSet.clear(); 4595 4596 // Determine whether we are allowed to call explicit constructors or 4597 // explicit conversion operators. 4598 bool AllowExplicit = Kind.AllowExplicit(); 4599 4600 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 4601 // The type we're converting to is a class type. Enumerate its constructors 4602 // to see if there is a suitable conversion. 4603 CXXRecordDecl *DestRecordDecl 4604 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 4605 4606 // Try to complete the type we're converting to. 4607 if (S.isCompleteType(Kind.getLocation(), DestType)) { 4608 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl); 4609 // The container holding the constructors can under certain conditions 4610 // be changed while iterating. To be safe we copy the lookup results 4611 // to a new container. 4612 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end()); 4613 for (SmallVectorImpl<NamedDecl *>::iterator 4614 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end(); 4615 Con != ConEnd; ++Con) { 4616 NamedDecl *D = *Con; 4617 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 4618 4619 // Find the constructor (which may be a template). 4620 CXXConstructorDecl *Constructor = nullptr; 4621 FunctionTemplateDecl *ConstructorTmpl 4622 = dyn_cast<FunctionTemplateDecl>(D); 4623 if (ConstructorTmpl) 4624 Constructor = cast<CXXConstructorDecl>( 4625 ConstructorTmpl->getTemplatedDecl()); 4626 else 4627 Constructor = cast<CXXConstructorDecl>(D); 4628 4629 if (!Constructor->isInvalidDecl() && 4630 Constructor->isConvertingConstructor(AllowExplicit)) { 4631 if (ConstructorTmpl) 4632 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 4633 /*ExplicitArgs*/ nullptr, 4634 Initializer, CandidateSet, 4635 /*SuppressUserConversions=*/true); 4636 else 4637 S.AddOverloadCandidate(Constructor, FoundDecl, 4638 Initializer, CandidateSet, 4639 /*SuppressUserConversions=*/true); 4640 } 4641 } 4642 } 4643 } 4644 4645 SourceLocation DeclLoc = Initializer->getLocStart(); 4646 4647 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 4648 // The type we're converting from is a class type, enumerate its conversion 4649 // functions. 4650 4651 // We can only enumerate the conversion functions for a complete type; if 4652 // the type isn't complete, simply skip this step. 4653 if (S.isCompleteType(DeclLoc, SourceType)) { 4654 CXXRecordDecl *SourceRecordDecl 4655 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 4656 4657 const auto &Conversions = 4658 SourceRecordDecl->getVisibleConversionFunctions(); 4659 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4660 NamedDecl *D = *I; 4661 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4662 if (isa<UsingShadowDecl>(D)) 4663 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4664 4665 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4666 CXXConversionDecl *Conv; 4667 if (ConvTemplate) 4668 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4669 else 4670 Conv = cast<CXXConversionDecl>(D); 4671 4672 if (AllowExplicit || !Conv->isExplicit()) { 4673 if (ConvTemplate) 4674 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 4675 ActingDC, Initializer, DestType, 4676 CandidateSet, AllowExplicit); 4677 else 4678 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 4679 Initializer, DestType, CandidateSet, 4680 AllowExplicit); 4681 } 4682 } 4683 } 4684 } 4685 4686 // Perform overload resolution. If it fails, return the failed result. 4687 OverloadCandidateSet::iterator Best; 4688 if (OverloadingResult Result 4689 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4690 Sequence.SetOverloadFailure( 4691 InitializationSequence::FK_UserConversionOverloadFailed, 4692 Result); 4693 return; 4694 } 4695 4696 FunctionDecl *Function = Best->Function; 4697 Function->setReferenced(); 4698 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4699 4700 if (isa<CXXConstructorDecl>(Function)) { 4701 // Add the user-defined conversion step. Any cv-qualification conversion is 4702 // subsumed by the initialization. Per DR5, the created temporary is of the 4703 // cv-unqualified type of the destination. 4704 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 4705 DestType.getUnqualifiedType(), 4706 HadMultipleCandidates); 4707 return; 4708 } 4709 4710 // Add the user-defined conversion step that calls the conversion function. 4711 QualType ConvType = Function->getCallResultType(); 4712 if (ConvType->getAs<RecordType>()) { 4713 // If we're converting to a class type, there may be an copy of 4714 // the resulting temporary object (possible to create an object of 4715 // a base class type). That copy is not a separate conversion, so 4716 // we just make a note of the actual destination type (possibly a 4717 // base class of the type returned by the conversion function) and 4718 // let the user-defined conversion step handle the conversion. 4719 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType, 4720 HadMultipleCandidates); 4721 return; 4722 } 4723 4724 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 4725 HadMultipleCandidates); 4726 4727 // If the conversion following the call to the conversion function 4728 // is interesting, add it as a separate step. 4729 if (Best->FinalConversion.First || Best->FinalConversion.Second || 4730 Best->FinalConversion.Third) { 4731 ImplicitConversionSequence ICS; 4732 ICS.setStandard(); 4733 ICS.Standard = Best->FinalConversion; 4734 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 4735 } 4736 } 4737 4738 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, 4739 /// a function with a pointer return type contains a 'return false;' statement. 4740 /// In C++11, 'false' is not a null pointer, so this breaks the build of any 4741 /// code using that header. 4742 /// 4743 /// Work around this by treating 'return false;' as zero-initializing the result 4744 /// if it's used in a pointer-returning function in a system header. 4745 static bool isLibstdcxxPointerReturnFalseHack(Sema &S, 4746 const InitializedEntity &Entity, 4747 const Expr *Init) { 4748 return S.getLangOpts().CPlusPlus11 && 4749 Entity.getKind() == InitializedEntity::EK_Result && 4750 Entity.getType()->isPointerType() && 4751 isa<CXXBoolLiteralExpr>(Init) && 4752 !cast<CXXBoolLiteralExpr>(Init)->getValue() && 4753 S.getSourceManager().isInSystemHeader(Init->getExprLoc()); 4754 } 4755 4756 /// The non-zero enum values here are indexes into diagnostic alternatives. 4757 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 4758 4759 /// Determines whether this expression is an acceptable ICR source. 4760 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 4761 bool isAddressOf, bool &isWeakAccess) { 4762 // Skip parens. 4763 e = e->IgnoreParens(); 4764 4765 // Skip address-of nodes. 4766 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 4767 if (op->getOpcode() == UO_AddrOf) 4768 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, 4769 isWeakAccess); 4770 4771 // Skip certain casts. 4772 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 4773 switch (ce->getCastKind()) { 4774 case CK_Dependent: 4775 case CK_BitCast: 4776 case CK_LValueBitCast: 4777 case CK_NoOp: 4778 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); 4779 4780 case CK_ArrayToPointerDecay: 4781 return IIK_nonscalar; 4782 4783 case CK_NullToPointer: 4784 return IIK_okay; 4785 4786 default: 4787 break; 4788 } 4789 4790 // If we have a declaration reference, it had better be a local variable. 4791 } else if (isa<DeclRefExpr>(e)) { 4792 // set isWeakAccess to true, to mean that there will be an implicit 4793 // load which requires a cleanup. 4794 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 4795 isWeakAccess = true; 4796 4797 if (!isAddressOf) return IIK_nonlocal; 4798 4799 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 4800 if (!var) return IIK_nonlocal; 4801 4802 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 4803 4804 // If we have a conditional operator, check both sides. 4805 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 4806 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, 4807 isWeakAccess)) 4808 return iik; 4809 4810 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); 4811 4812 // These are never scalar. 4813 } else if (isa<ArraySubscriptExpr>(e)) { 4814 return IIK_nonscalar; 4815 4816 // Otherwise, it needs to be a null pointer constant. 4817 } else { 4818 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 4819 ? IIK_okay : IIK_nonlocal); 4820 } 4821 4822 return IIK_nonlocal; 4823 } 4824 4825 /// Check whether the given expression is a valid operand for an 4826 /// indirect copy/restore. 4827 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 4828 assert(src->isRValue()); 4829 bool isWeakAccess = false; 4830 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); 4831 // If isWeakAccess to true, there will be an implicit 4832 // load which requires a cleanup. 4833 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) 4834 S.ExprNeedsCleanups = true; 4835 4836 if (iik == IIK_okay) return; 4837 4838 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 4839 << ((unsigned) iik - 1) // shift index into diagnostic explanations 4840 << src->getSourceRange(); 4841 } 4842 4843 /// \brief Determine whether we have compatible array types for the 4844 /// purposes of GNU by-copy array initialization. 4845 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, 4846 const ArrayType *Source) { 4847 // If the source and destination array types are equivalent, we're 4848 // done. 4849 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 4850 return true; 4851 4852 // Make sure that the element types are the same. 4853 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 4854 return false; 4855 4856 // The only mismatch we allow is when the destination is an 4857 // incomplete array type and the source is a constant array type. 4858 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 4859 } 4860 4861 static bool tryObjCWritebackConversion(Sema &S, 4862 InitializationSequence &Sequence, 4863 const InitializedEntity &Entity, 4864 Expr *Initializer) { 4865 bool ArrayDecay = false; 4866 QualType ArgType = Initializer->getType(); 4867 QualType ArgPointee; 4868 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 4869 ArrayDecay = true; 4870 ArgPointee = ArgArrayType->getElementType(); 4871 ArgType = S.Context.getPointerType(ArgPointee); 4872 } 4873 4874 // Handle write-back conversion. 4875 QualType ConvertedArgType; 4876 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 4877 ConvertedArgType)) 4878 return false; 4879 4880 // We should copy unless we're passing to an argument explicitly 4881 // marked 'out'. 4882 bool ShouldCopy = true; 4883 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 4884 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 4885 4886 // Do we need an lvalue conversion? 4887 if (ArrayDecay || Initializer->isGLValue()) { 4888 ImplicitConversionSequence ICS; 4889 ICS.setStandard(); 4890 ICS.Standard.setAsIdentityConversion(); 4891 4892 QualType ResultType; 4893 if (ArrayDecay) { 4894 ICS.Standard.First = ICK_Array_To_Pointer; 4895 ResultType = S.Context.getPointerType(ArgPointee); 4896 } else { 4897 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 4898 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 4899 } 4900 4901 Sequence.AddConversionSequenceStep(ICS, ResultType); 4902 } 4903 4904 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 4905 return true; 4906 } 4907 4908 static bool TryOCLSamplerInitialization(Sema &S, 4909 InitializationSequence &Sequence, 4910 QualType DestType, 4911 Expr *Initializer) { 4912 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || 4913 !Initializer->isIntegerConstantExpr(S.getASTContext())) 4914 return false; 4915 4916 Sequence.AddOCLSamplerInitStep(DestType); 4917 return true; 4918 } 4919 4920 // 4921 // OpenCL 1.2 spec, s6.12.10 4922 // 4923 // The event argument can also be used to associate the 4924 // async_work_group_copy with a previous async copy allowing 4925 // an event to be shared by multiple async copies; otherwise 4926 // event should be zero. 4927 // 4928 static bool TryOCLZeroEventInitialization(Sema &S, 4929 InitializationSequence &Sequence, 4930 QualType DestType, 4931 Expr *Initializer) { 4932 if (!S.getLangOpts().OpenCL || !DestType->isEventT() || 4933 !Initializer->isIntegerConstantExpr(S.getASTContext()) || 4934 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0)) 4935 return false; 4936 4937 Sequence.AddOCLZeroEventStep(DestType); 4938 return true; 4939 } 4940 4941 InitializationSequence::InitializationSequence(Sema &S, 4942 const InitializedEntity &Entity, 4943 const InitializationKind &Kind, 4944 MultiExprArg Args, 4945 bool TopLevelOfInitList, 4946 bool TreatUnavailableAsInvalid) 4947 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { 4948 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, 4949 TreatUnavailableAsInvalid); 4950 } 4951 4952 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the 4953 /// address of that function, this returns true. Otherwise, it returns false. 4954 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { 4955 auto *DRE = dyn_cast<DeclRefExpr>(E); 4956 if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) 4957 return false; 4958 4959 return !S.checkAddressOfFunctionIsAvailable( 4960 cast<FunctionDecl>(DRE->getDecl())); 4961 } 4962 4963 void InitializationSequence::InitializeFrom(Sema &S, 4964 const InitializedEntity &Entity, 4965 const InitializationKind &Kind, 4966 MultiExprArg Args, 4967 bool TopLevelOfInitList, 4968 bool TreatUnavailableAsInvalid) { 4969 ASTContext &Context = S.Context; 4970 4971 // Eliminate non-overload placeholder types in the arguments. We 4972 // need to do this before checking whether types are dependent 4973 // because lowering a pseudo-object expression might well give us 4974 // something of dependent type. 4975 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4976 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 4977 // FIXME: should we be doing this here? 4978 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 4979 if (result.isInvalid()) { 4980 SetFailed(FK_PlaceholderType); 4981 return; 4982 } 4983 Args[I] = result.get(); 4984 } 4985 4986 // C++0x [dcl.init]p16: 4987 // The semantics of initializers are as follows. The destination type is 4988 // the type of the object or reference being initialized and the source 4989 // type is the type of the initializer expression. The source type is not 4990 // defined when the initializer is a braced-init-list or when it is a 4991 // parenthesized list of expressions. 4992 QualType DestType = Entity.getType(); 4993 4994 if (DestType->isDependentType() || 4995 Expr::hasAnyTypeDependentArguments(Args)) { 4996 SequenceKind = DependentSequence; 4997 return; 4998 } 4999 5000 // Almost everything is a normal sequence. 5001 setSequenceKind(NormalSequence); 5002 5003 QualType SourceType; 5004 Expr *Initializer = nullptr; 5005 if (Args.size() == 1) { 5006 Initializer = Args[0]; 5007 if (S.getLangOpts().ObjC1) { 5008 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(), 5009 DestType, Initializer->getType(), 5010 Initializer) || 5011 S.ConversionToObjCStringLiteralCheck(DestType, Initializer)) 5012 Args[0] = Initializer; 5013 } 5014 if (!isa<InitListExpr>(Initializer)) 5015 SourceType = Initializer->getType(); 5016 } 5017 5018 // - If the initializer is a (non-parenthesized) braced-init-list, the 5019 // object is list-initialized (8.5.4). 5020 if (Kind.getKind() != InitializationKind::IK_Direct) { 5021 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 5022 TryListInitialization(S, Entity, Kind, InitList, *this, 5023 TreatUnavailableAsInvalid); 5024 return; 5025 } 5026 } 5027 5028 // - If the destination type is a reference type, see 8.5.3. 5029 if (DestType->isReferenceType()) { 5030 // C++0x [dcl.init.ref]p1: 5031 // A variable declared to be a T& or T&&, that is, "reference to type T" 5032 // (8.3.2), shall be initialized by an object, or function, of type T or 5033 // by an object that can be converted into a T. 5034 // (Therefore, multiple arguments are not permitted.) 5035 if (Args.size() != 1) 5036 SetFailed(FK_TooManyInitsForReference); 5037 else 5038 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 5039 return; 5040 } 5041 5042 // - If the initializer is (), the object is value-initialized. 5043 if (Kind.getKind() == InitializationKind::IK_Value || 5044 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 5045 TryValueInitialization(S, Entity, Kind, *this); 5046 return; 5047 } 5048 5049 // Handle default initialization. 5050 if (Kind.getKind() == InitializationKind::IK_Default) { 5051 TryDefaultInitialization(S, Entity, Kind, *this); 5052 return; 5053 } 5054 5055 // - If the destination type is an array of characters, an array of 5056 // char16_t, an array of char32_t, or an array of wchar_t, and the 5057 // initializer is a string literal, see 8.5.2. 5058 // - Otherwise, if the destination type is an array, the program is 5059 // ill-formed. 5060 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 5061 if (Initializer && isa<VariableArrayType>(DestAT)) { 5062 SetFailed(FK_VariableLengthArrayHasInitializer); 5063 return; 5064 } 5065 5066 if (Initializer) { 5067 switch (IsStringInit(Initializer, DestAT, Context)) { 5068 case SIF_None: 5069 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 5070 return; 5071 case SIF_NarrowStringIntoWideChar: 5072 SetFailed(FK_NarrowStringIntoWideCharArray); 5073 return; 5074 case SIF_WideStringIntoChar: 5075 SetFailed(FK_WideStringIntoCharArray); 5076 return; 5077 case SIF_IncompatWideStringIntoWideChar: 5078 SetFailed(FK_IncompatWideStringIntoWideChar); 5079 return; 5080 case SIF_Other: 5081 break; 5082 } 5083 } 5084 5085 // Note: as an GNU C extension, we allow initialization of an 5086 // array from a compound literal that creates an array of the same 5087 // type, so long as the initializer has no side effects. 5088 if (!S.getLangOpts().CPlusPlus && Initializer && 5089 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 5090 Initializer->getType()->isArrayType()) { 5091 const ArrayType *SourceAT 5092 = Context.getAsArrayType(Initializer->getType()); 5093 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 5094 SetFailed(FK_ArrayTypeMismatch); 5095 else if (Initializer->HasSideEffects(S.Context)) 5096 SetFailed(FK_NonConstantArrayInit); 5097 else { 5098 AddArrayInitStep(DestType); 5099 } 5100 } 5101 // Note: as a GNU C++ extension, we allow list-initialization of a 5102 // class member of array type from a parenthesized initializer list. 5103 else if (S.getLangOpts().CPlusPlus && 5104 Entity.getKind() == InitializedEntity::EK_Member && 5105 Initializer && isa<InitListExpr>(Initializer)) { 5106 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 5107 *this, TreatUnavailableAsInvalid); 5108 AddParenthesizedArrayInitStep(DestType); 5109 } else if (DestAT->getElementType()->isCharType()) 5110 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 5111 else if (IsWideCharCompatible(DestAT->getElementType(), Context)) 5112 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); 5113 else 5114 SetFailed(FK_ArrayNeedsInitList); 5115 5116 return; 5117 } 5118 5119 // Determine whether we should consider writeback conversions for 5120 // Objective-C ARC. 5121 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 5122 Entity.isParameterKind(); 5123 5124 // We're at the end of the line for C: it's either a write-back conversion 5125 // or it's a C assignment. There's no need to check anything else. 5126 if (!S.getLangOpts().CPlusPlus) { 5127 // If allowed, check whether this is an Objective-C writeback conversion. 5128 if (allowObjCWritebackConversion && 5129 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 5130 return; 5131 } 5132 5133 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 5134 return; 5135 5136 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer)) 5137 return; 5138 5139 // Handle initialization in C 5140 AddCAssignmentStep(DestType); 5141 MaybeProduceObjCObject(S, *this, Entity); 5142 return; 5143 } 5144 5145 assert(S.getLangOpts().CPlusPlus); 5146 5147 // - If the destination type is a (possibly cv-qualified) class type: 5148 if (DestType->isRecordType()) { 5149 // - If the initialization is direct-initialization, or if it is 5150 // copy-initialization where the cv-unqualified version of the 5151 // source type is the same class as, or a derived class of, the 5152 // class of the destination, constructors are considered. [...] 5153 if (Kind.getKind() == InitializationKind::IK_Direct || 5154 (Kind.getKind() == InitializationKind::IK_Copy && 5155 (Context.hasSameUnqualifiedType(SourceType, DestType) || 5156 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType)))) 5157 TryConstructorInitialization(S, Entity, Kind, Args, 5158 DestType, *this); 5159 // - Otherwise (i.e., for the remaining copy-initialization cases), 5160 // user-defined conversion sequences that can convert from the source 5161 // type to the destination type or (when a conversion function is 5162 // used) to a derived class thereof are enumerated as described in 5163 // 13.3.1.4, and the best one is chosen through overload resolution 5164 // (13.3). 5165 else 5166 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5167 TopLevelOfInitList); 5168 return; 5169 } 5170 5171 if (Args.size() > 1) { 5172 SetFailed(FK_TooManyInitsForScalar); 5173 return; 5174 } 5175 assert(Args.size() == 1 && "Zero-argument case handled above"); 5176 5177 // - Otherwise, if the source type is a (possibly cv-qualified) class 5178 // type, conversion functions are considered. 5179 if (!SourceType.isNull() && SourceType->isRecordType()) { 5180 // For a conversion to _Atomic(T) from either T or a class type derived 5181 // from T, initialize the T object then convert to _Atomic type. 5182 bool NeedAtomicConversion = false; 5183 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { 5184 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || 5185 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, 5186 Atomic->getValueType())) { 5187 DestType = Atomic->getValueType(); 5188 NeedAtomicConversion = true; 5189 } 5190 } 5191 5192 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5193 TopLevelOfInitList); 5194 MaybeProduceObjCObject(S, *this, Entity); 5195 if (!Failed() && NeedAtomicConversion) 5196 AddAtomicConversionStep(Entity.getType()); 5197 return; 5198 } 5199 5200 // - Otherwise, the initial value of the object being initialized is the 5201 // (possibly converted) value of the initializer expression. Standard 5202 // conversions (Clause 4) will be used, if necessary, to convert the 5203 // initializer expression to the cv-unqualified version of the 5204 // destination type; no user-defined conversions are considered. 5205 5206 ImplicitConversionSequence ICS 5207 = S.TryImplicitConversion(Initializer, DestType, 5208 /*SuppressUserConversions*/true, 5209 /*AllowExplicitConversions*/ false, 5210 /*InOverloadResolution*/ false, 5211 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5212 allowObjCWritebackConversion); 5213 5214 if (ICS.isStandard() && 5215 ICS.Standard.Second == ICK_Writeback_Conversion) { 5216 // Objective-C ARC writeback conversion. 5217 5218 // We should copy unless we're passing to an argument explicitly 5219 // marked 'out'. 5220 bool ShouldCopy = true; 5221 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5222 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5223 5224 // If there was an lvalue adjustment, add it as a separate conversion. 5225 if (ICS.Standard.First == ICK_Array_To_Pointer || 5226 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5227 ImplicitConversionSequence LvalueICS; 5228 LvalueICS.setStandard(); 5229 LvalueICS.Standard.setAsIdentityConversion(); 5230 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 5231 LvalueICS.Standard.First = ICS.Standard.First; 5232 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 5233 } 5234 5235 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); 5236 } else if (ICS.isBad()) { 5237 DeclAccessPair dap; 5238 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { 5239 AddZeroInitializationStep(Entity.getType()); 5240 } else if (Initializer->getType() == Context.OverloadTy && 5241 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, 5242 false, dap)) 5243 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 5244 else if (Initializer->getType()->isFunctionType() && 5245 isExprAnUnaddressableFunction(S, Initializer)) 5246 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); 5247 else 5248 SetFailed(InitializationSequence::FK_ConversionFailed); 5249 } else { 5250 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5251 5252 MaybeProduceObjCObject(S, *this, Entity); 5253 } 5254 } 5255 5256 InitializationSequence::~InitializationSequence() { 5257 for (auto &S : Steps) 5258 S.Destroy(); 5259 } 5260 5261 //===----------------------------------------------------------------------===// 5262 // Perform initialization 5263 //===----------------------------------------------------------------------===// 5264 static Sema::AssignmentAction 5265 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { 5266 switch(Entity.getKind()) { 5267 case InitializedEntity::EK_Variable: 5268 case InitializedEntity::EK_New: 5269 case InitializedEntity::EK_Exception: 5270 case InitializedEntity::EK_Base: 5271 case InitializedEntity::EK_Delegating: 5272 return Sema::AA_Initializing; 5273 5274 case InitializedEntity::EK_Parameter: 5275 if (Entity.getDecl() && 5276 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5277 return Sema::AA_Sending; 5278 5279 return Sema::AA_Passing; 5280 5281 case InitializedEntity::EK_Parameter_CF_Audited: 5282 if (Entity.getDecl() && 5283 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5284 return Sema::AA_Sending; 5285 5286 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; 5287 5288 case InitializedEntity::EK_Result: 5289 return Sema::AA_Returning; 5290 5291 case InitializedEntity::EK_Temporary: 5292 case InitializedEntity::EK_RelatedResult: 5293 // FIXME: Can we tell apart casting vs. converting? 5294 return Sema::AA_Casting; 5295 5296 case InitializedEntity::EK_Member: 5297 case InitializedEntity::EK_ArrayElement: 5298 case InitializedEntity::EK_VectorElement: 5299 case InitializedEntity::EK_ComplexElement: 5300 case InitializedEntity::EK_BlockElement: 5301 case InitializedEntity::EK_LambdaCapture: 5302 case InitializedEntity::EK_CompoundLiteralInit: 5303 return Sema::AA_Initializing; 5304 } 5305 5306 llvm_unreachable("Invalid EntityKind!"); 5307 } 5308 5309 /// \brief Whether we should bind a created object as a temporary when 5310 /// initializing the given entity. 5311 static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 5312 switch (Entity.getKind()) { 5313 case InitializedEntity::EK_ArrayElement: 5314 case InitializedEntity::EK_Member: 5315 case InitializedEntity::EK_Result: 5316 case InitializedEntity::EK_New: 5317 case InitializedEntity::EK_Variable: 5318 case InitializedEntity::EK_Base: 5319 case InitializedEntity::EK_Delegating: 5320 case InitializedEntity::EK_VectorElement: 5321 case InitializedEntity::EK_ComplexElement: 5322 case InitializedEntity::EK_Exception: 5323 case InitializedEntity::EK_BlockElement: 5324 case InitializedEntity::EK_LambdaCapture: 5325 case InitializedEntity::EK_CompoundLiteralInit: 5326 return false; 5327 5328 case InitializedEntity::EK_Parameter: 5329 case InitializedEntity::EK_Parameter_CF_Audited: 5330 case InitializedEntity::EK_Temporary: 5331 case InitializedEntity::EK_RelatedResult: 5332 return true; 5333 } 5334 5335 llvm_unreachable("missed an InitializedEntity kind?"); 5336 } 5337 5338 /// \brief Whether the given entity, when initialized with an object 5339 /// created for that initialization, requires destruction. 5340 static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 5341 switch (Entity.getKind()) { 5342 case InitializedEntity::EK_Result: 5343 case InitializedEntity::EK_New: 5344 case InitializedEntity::EK_Base: 5345 case InitializedEntity::EK_Delegating: 5346 case InitializedEntity::EK_VectorElement: 5347 case InitializedEntity::EK_ComplexElement: 5348 case InitializedEntity::EK_BlockElement: 5349 case InitializedEntity::EK_LambdaCapture: 5350 return false; 5351 5352 case InitializedEntity::EK_Member: 5353 case InitializedEntity::EK_Variable: 5354 case InitializedEntity::EK_Parameter: 5355 case InitializedEntity::EK_Parameter_CF_Audited: 5356 case InitializedEntity::EK_Temporary: 5357 case InitializedEntity::EK_ArrayElement: 5358 case InitializedEntity::EK_Exception: 5359 case InitializedEntity::EK_CompoundLiteralInit: 5360 case InitializedEntity::EK_RelatedResult: 5361 return true; 5362 } 5363 5364 llvm_unreachable("missed an InitializedEntity kind?"); 5365 } 5366 5367 /// \brief Look for copy and move constructors and constructor templates, for 5368 /// copying an object via direct-initialization (per C++11 [dcl.init]p16). 5369 static void LookupCopyAndMoveConstructors(Sema &S, 5370 OverloadCandidateSet &CandidateSet, 5371 CXXRecordDecl *Class, 5372 Expr *CurInitExpr) { 5373 DeclContext::lookup_result R = S.LookupConstructors(Class); 5374 // The container holding the constructors can under certain conditions 5375 // be changed while iterating (e.g. because of deserialization). 5376 // To be safe we copy the lookup results to a new container. 5377 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end()); 5378 for (SmallVectorImpl<NamedDecl *>::iterator 5379 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) { 5380 NamedDecl *D = *CI; 5381 CXXConstructorDecl *Constructor = nullptr; 5382 5383 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) { 5384 // Handle copy/moveconstructors, only. 5385 if (!Constructor || Constructor->isInvalidDecl() || 5386 !Constructor->isCopyOrMoveConstructor() || 5387 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 5388 continue; 5389 5390 DeclAccessPair FoundDecl 5391 = DeclAccessPair::make(Constructor, Constructor->getAccess()); 5392 S.AddOverloadCandidate(Constructor, FoundDecl, 5393 CurInitExpr, CandidateSet); 5394 continue; 5395 } 5396 5397 // Handle constructor templates. 5398 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D); 5399 if (ConstructorTmpl->isInvalidDecl()) 5400 continue; 5401 5402 Constructor = cast<CXXConstructorDecl>( 5403 ConstructorTmpl->getTemplatedDecl()); 5404 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 5405 continue; 5406 5407 // FIXME: Do we need to limit this to copy-constructor-like 5408 // candidates? 5409 DeclAccessPair FoundDecl 5410 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess()); 5411 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr, 5412 CurInitExpr, CandidateSet, true); 5413 } 5414 } 5415 5416 /// \brief Get the location at which initialization diagnostics should appear. 5417 static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 5418 Expr *Initializer) { 5419 switch (Entity.getKind()) { 5420 case InitializedEntity::EK_Result: 5421 return Entity.getReturnLoc(); 5422 5423 case InitializedEntity::EK_Exception: 5424 return Entity.getThrowLoc(); 5425 5426 case InitializedEntity::EK_Variable: 5427 return Entity.getDecl()->getLocation(); 5428 5429 case InitializedEntity::EK_LambdaCapture: 5430 return Entity.getCaptureLoc(); 5431 5432 case InitializedEntity::EK_ArrayElement: 5433 case InitializedEntity::EK_Member: 5434 case InitializedEntity::EK_Parameter: 5435 case InitializedEntity::EK_Parameter_CF_Audited: 5436 case InitializedEntity::EK_Temporary: 5437 case InitializedEntity::EK_New: 5438 case InitializedEntity::EK_Base: 5439 case InitializedEntity::EK_Delegating: 5440 case InitializedEntity::EK_VectorElement: 5441 case InitializedEntity::EK_ComplexElement: 5442 case InitializedEntity::EK_BlockElement: 5443 case InitializedEntity::EK_CompoundLiteralInit: 5444 case InitializedEntity::EK_RelatedResult: 5445 return Initializer->getLocStart(); 5446 } 5447 llvm_unreachable("missed an InitializedEntity kind?"); 5448 } 5449 5450 /// \brief Make a (potentially elidable) temporary copy of the object 5451 /// provided by the given initializer by calling the appropriate copy 5452 /// constructor. 5453 /// 5454 /// \param S The Sema object used for type-checking. 5455 /// 5456 /// \param T The type of the temporary object, which must either be 5457 /// the type of the initializer expression or a superclass thereof. 5458 /// 5459 /// \param Entity The entity being initialized. 5460 /// 5461 /// \param CurInit The initializer expression. 5462 /// 5463 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that 5464 /// is permitted in C++03 (but not C++0x) when binding a reference to 5465 /// an rvalue. 5466 /// 5467 /// \returns An expression that copies the initializer expression into 5468 /// a temporary object, or an error expression if a copy could not be 5469 /// created. 5470 static ExprResult CopyObject(Sema &S, 5471 QualType T, 5472 const InitializedEntity &Entity, 5473 ExprResult CurInit, 5474 bool IsExtraneousCopy) { 5475 if (CurInit.isInvalid()) 5476 return CurInit; 5477 // Determine which class type we're copying to. 5478 Expr *CurInitExpr = (Expr *)CurInit.get(); 5479 CXXRecordDecl *Class = nullptr; 5480 if (const RecordType *Record = T->getAs<RecordType>()) 5481 Class = cast<CXXRecordDecl>(Record->getDecl()); 5482 if (!Class) 5483 return CurInit; 5484 5485 // C++0x [class.copy]p32: 5486 // When certain criteria are met, an implementation is allowed to 5487 // omit the copy/move construction of a class object, even if the 5488 // copy/move constructor and/or destructor for the object have 5489 // side effects. [...] 5490 // - when a temporary class object that has not been bound to a 5491 // reference (12.2) would be copied/moved to a class object 5492 // with the same cv-unqualified type, the copy/move operation 5493 // can be omitted by constructing the temporary object 5494 // directly into the target of the omitted copy/move 5495 // 5496 // Note that the other three bullets are handled elsewhere. Copy 5497 // elision for return statements and throw expressions are handled as part 5498 // of constructor initialization, while copy elision for exception handlers 5499 // is handled by the run-time. 5500 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class); 5501 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 5502 5503 // Make sure that the type we are copying is complete. 5504 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 5505 return CurInit; 5506 5507 // Perform overload resolution using the class's copy/move constructors. 5508 // Only consider constructors and constructor templates. Per 5509 // C++0x [dcl.init]p16, second bullet to class types, this initialization 5510 // is direct-initialization. 5511 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5512 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr); 5513 5514 bool HadMultipleCandidates = (CandidateSet.size() > 1); 5515 5516 OverloadCandidateSet::iterator Best; 5517 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 5518 case OR_Success: 5519 break; 5520 5521 case OR_No_Viable_Function: 5522 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 5523 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 5524 : diag::err_temp_copy_no_viable) 5525 << (int)Entity.getKind() << CurInitExpr->getType() 5526 << CurInitExpr->getSourceRange(); 5527 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); 5528 if (!IsExtraneousCopy || S.isSFINAEContext()) 5529 return ExprError(); 5530 return CurInit; 5531 5532 case OR_Ambiguous: 5533 S.Diag(Loc, diag::err_temp_copy_ambiguous) 5534 << (int)Entity.getKind() << CurInitExpr->getType() 5535 << CurInitExpr->getSourceRange(); 5536 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); 5537 return ExprError(); 5538 5539 case OR_Deleted: 5540 S.Diag(Loc, diag::err_temp_copy_deleted) 5541 << (int)Entity.getKind() << CurInitExpr->getType() 5542 << CurInitExpr->getSourceRange(); 5543 S.NoteDeletedFunction(Best->Function); 5544 return ExprError(); 5545 } 5546 5547 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 5548 SmallVector<Expr*, 8> ConstructorArgs; 5549 CurInit.get(); // Ownership transferred into MultiExprArg, below. 5550 5551 S.CheckConstructorAccess(Loc, Constructor, Entity, 5552 Best->FoundDecl.getAccess(), IsExtraneousCopy); 5553 5554 if (IsExtraneousCopy) { 5555 // If this is a totally extraneous copy for C++03 reference 5556 // binding purposes, just return the original initialization 5557 // expression. We don't generate an (elided) copy operation here 5558 // because doing so would require us to pass down a flag to avoid 5559 // infinite recursion, where each step adds another extraneous, 5560 // elidable copy. 5561 5562 // Instantiate the default arguments of any extra parameters in 5563 // the selected copy constructor, as if we were going to create a 5564 // proper call to the copy constructor. 5565 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 5566 ParmVarDecl *Parm = Constructor->getParamDecl(I); 5567 if (S.RequireCompleteType(Loc, Parm->getType(), 5568 diag::err_call_incomplete_argument)) 5569 break; 5570 5571 // Build the default argument expression; we don't actually care 5572 // if this succeeds or not, because this routine will complain 5573 // if there was a problem. 5574 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 5575 } 5576 5577 return CurInitExpr; 5578 } 5579 5580 // Determine the arguments required to actually perform the 5581 // constructor call (we might have derived-to-base conversions, or 5582 // the copy constructor may have default arguments). 5583 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) 5584 return ExprError(); 5585 5586 // Actually perform the constructor call. 5587 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable, 5588 ConstructorArgs, 5589 HadMultipleCandidates, 5590 /*ListInit*/ false, 5591 /*StdInitListInit*/ false, 5592 /*ZeroInit*/ false, 5593 CXXConstructExpr::CK_Complete, 5594 SourceRange()); 5595 5596 // If we're supposed to bind temporaries, do so. 5597 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 5598 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 5599 return CurInit; 5600 } 5601 5602 /// \brief Check whether elidable copy construction for binding a reference to 5603 /// a temporary would have succeeded if we were building in C++98 mode, for 5604 /// -Wc++98-compat. 5605 static void CheckCXX98CompatAccessibleCopy(Sema &S, 5606 const InitializedEntity &Entity, 5607 Expr *CurInitExpr) { 5608 assert(S.getLangOpts().CPlusPlus11); 5609 5610 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 5611 if (!Record) 5612 return; 5613 5614 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 5615 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) 5616 return; 5617 5618 // Find constructors which would have been considered. 5619 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5620 LookupCopyAndMoveConstructors( 5621 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr); 5622 5623 // Perform overload resolution. 5624 OverloadCandidateSet::iterator Best; 5625 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best); 5626 5627 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 5628 << OR << (int)Entity.getKind() << CurInitExpr->getType() 5629 << CurInitExpr->getSourceRange(); 5630 5631 switch (OR) { 5632 case OR_Success: 5633 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 5634 Entity, Best->FoundDecl.getAccess(), Diag); 5635 // FIXME: Check default arguments as far as that's possible. 5636 break; 5637 5638 case OR_No_Viable_Function: 5639 S.Diag(Loc, Diag); 5640 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); 5641 break; 5642 5643 case OR_Ambiguous: 5644 S.Diag(Loc, Diag); 5645 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); 5646 break; 5647 5648 case OR_Deleted: 5649 S.Diag(Loc, Diag); 5650 S.NoteDeletedFunction(Best->Function); 5651 break; 5652 } 5653 } 5654 5655 void InitializationSequence::PrintInitLocationNote(Sema &S, 5656 const InitializedEntity &Entity) { 5657 if (Entity.isParameterKind() && Entity.getDecl()) { 5658 if (Entity.getDecl()->getLocation().isInvalid()) 5659 return; 5660 5661 if (Entity.getDecl()->getDeclName()) 5662 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 5663 << Entity.getDecl()->getDeclName(); 5664 else 5665 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 5666 } 5667 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && 5668 Entity.getMethodDecl()) 5669 S.Diag(Entity.getMethodDecl()->getLocation(), 5670 diag::note_method_return_type_change) 5671 << Entity.getMethodDecl()->getDeclName(); 5672 } 5673 5674 static bool isReferenceBinding(const InitializationSequence::Step &s) { 5675 return s.Kind == InitializationSequence::SK_BindReference || 5676 s.Kind == InitializationSequence::SK_BindReferenceToTemporary; 5677 } 5678 5679 /// Returns true if the parameters describe a constructor initialization of 5680 /// an explicit temporary object, e.g. "Point(x, y)". 5681 static bool isExplicitTemporary(const InitializedEntity &Entity, 5682 const InitializationKind &Kind, 5683 unsigned NumArgs) { 5684 switch (Entity.getKind()) { 5685 case InitializedEntity::EK_Temporary: 5686 case InitializedEntity::EK_CompoundLiteralInit: 5687 case InitializedEntity::EK_RelatedResult: 5688 break; 5689 default: 5690 return false; 5691 } 5692 5693 switch (Kind.getKind()) { 5694 case InitializationKind::IK_DirectList: 5695 return true; 5696 // FIXME: Hack to work around cast weirdness. 5697 case InitializationKind::IK_Direct: 5698 case InitializationKind::IK_Value: 5699 return NumArgs != 1; 5700 default: 5701 return false; 5702 } 5703 } 5704 5705 static ExprResult 5706 PerformConstructorInitialization(Sema &S, 5707 const InitializedEntity &Entity, 5708 const InitializationKind &Kind, 5709 MultiExprArg Args, 5710 const InitializationSequence::Step& Step, 5711 bool &ConstructorInitRequiresZeroInit, 5712 bool IsListInitialization, 5713 bool IsStdInitListInitialization, 5714 SourceLocation LBraceLoc, 5715 SourceLocation RBraceLoc) { 5716 unsigned NumArgs = Args.size(); 5717 CXXConstructorDecl *Constructor 5718 = cast<CXXConstructorDecl>(Step.Function.Function); 5719 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 5720 5721 // Build a call to the selected constructor. 5722 SmallVector<Expr*, 8> ConstructorArgs; 5723 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 5724 ? Kind.getEqualLoc() 5725 : Kind.getLocation(); 5726 5727 if (Kind.getKind() == InitializationKind::IK_Default) { 5728 // Force even a trivial, implicit default constructor to be 5729 // semantically checked. We do this explicitly because we don't build 5730 // the definition for completely trivial constructors. 5731 assert(Constructor->getParent() && "No parent class for constructor."); 5732 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 5733 Constructor->isTrivial() && !Constructor->isUsed(false)) 5734 S.DefineImplicitDefaultConstructor(Loc, Constructor); 5735 } 5736 5737 ExprResult CurInit((Expr *)nullptr); 5738 5739 // C++ [over.match.copy]p1: 5740 // - When initializing a temporary to be bound to the first parameter 5741 // of a constructor that takes a reference to possibly cv-qualified 5742 // T as its first argument, called with a single argument in the 5743 // context of direct-initialization, explicit conversion functions 5744 // are also considered. 5745 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() && 5746 Args.size() == 1 && 5747 Constructor->isCopyOrMoveConstructor(); 5748 5749 // Determine the arguments required to actually perform the constructor 5750 // call. 5751 if (S.CompleteConstructorCall(Constructor, Args, 5752 Loc, ConstructorArgs, 5753 AllowExplicitConv, 5754 IsListInitialization)) 5755 return ExprError(); 5756 5757 5758 if (isExplicitTemporary(Entity, Kind, NumArgs)) { 5759 // An explicitly-constructed temporary, e.g., X(1, 2). 5760 S.MarkFunctionReferenced(Loc, Constructor); 5761 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 5762 return ExprError(); 5763 5764 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 5765 if (!TSInfo) 5766 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 5767 SourceRange ParenOrBraceRange = 5768 (Kind.getKind() == InitializationKind::IK_DirectList) 5769 ? SourceRange(LBraceLoc, RBraceLoc) 5770 : Kind.getParenRange(); 5771 5772 CurInit = new (S.Context) CXXTemporaryObjectExpr( 5773 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange, 5774 HadMultipleCandidates, IsListInitialization, 5775 IsStdInitListInitialization, ConstructorInitRequiresZeroInit); 5776 } else { 5777 CXXConstructExpr::ConstructionKind ConstructKind = 5778 CXXConstructExpr::CK_Complete; 5779 5780 if (Entity.getKind() == InitializedEntity::EK_Base) { 5781 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 5782 CXXConstructExpr::CK_VirtualBase : 5783 CXXConstructExpr::CK_NonVirtualBase; 5784 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 5785 ConstructKind = CXXConstructExpr::CK_Delegating; 5786 } 5787 5788 // Only get the parenthesis or brace range if it is a list initialization or 5789 // direct construction. 5790 SourceRange ParenOrBraceRange; 5791 if (IsListInitialization) 5792 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); 5793 else if (Kind.getKind() == InitializationKind::IK_Direct) 5794 ParenOrBraceRange = Kind.getParenRange(); 5795 5796 // If the entity allows NRVO, mark the construction as elidable 5797 // unconditionally. 5798 if (Entity.allowsNRVO()) 5799 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 5800 Constructor, /*Elidable=*/true, 5801 ConstructorArgs, 5802 HadMultipleCandidates, 5803 IsListInitialization, 5804 IsStdInitListInitialization, 5805 ConstructorInitRequiresZeroInit, 5806 ConstructKind, 5807 ParenOrBraceRange); 5808 else 5809 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 5810 Constructor, 5811 ConstructorArgs, 5812 HadMultipleCandidates, 5813 IsListInitialization, 5814 IsStdInitListInitialization, 5815 ConstructorInitRequiresZeroInit, 5816 ConstructKind, 5817 ParenOrBraceRange); 5818 } 5819 if (CurInit.isInvalid()) 5820 return ExprError(); 5821 5822 // Only check access if all of that succeeded. 5823 S.CheckConstructorAccess(Loc, Constructor, Entity, 5824 Step.Function.FoundDecl.getAccess()); 5825 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 5826 return ExprError(); 5827 5828 if (shouldBindAsTemporary(Entity)) 5829 CurInit = S.MaybeBindToTemporary(CurInit.get()); 5830 5831 return CurInit; 5832 } 5833 5834 /// Determine whether the specified InitializedEntity definitely has a lifetime 5835 /// longer than the current full-expression. Conservatively returns false if 5836 /// it's unclear. 5837 static bool 5838 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) { 5839 const InitializedEntity *Top = &Entity; 5840 while (Top->getParent()) 5841 Top = Top->getParent(); 5842 5843 switch (Top->getKind()) { 5844 case InitializedEntity::EK_Variable: 5845 case InitializedEntity::EK_Result: 5846 case InitializedEntity::EK_Exception: 5847 case InitializedEntity::EK_Member: 5848 case InitializedEntity::EK_New: 5849 case InitializedEntity::EK_Base: 5850 case InitializedEntity::EK_Delegating: 5851 return true; 5852 5853 case InitializedEntity::EK_ArrayElement: 5854 case InitializedEntity::EK_VectorElement: 5855 case InitializedEntity::EK_BlockElement: 5856 case InitializedEntity::EK_ComplexElement: 5857 // Could not determine what the full initialization is. Assume it might not 5858 // outlive the full-expression. 5859 return false; 5860 5861 case InitializedEntity::EK_Parameter: 5862 case InitializedEntity::EK_Parameter_CF_Audited: 5863 case InitializedEntity::EK_Temporary: 5864 case InitializedEntity::EK_LambdaCapture: 5865 case InitializedEntity::EK_CompoundLiteralInit: 5866 case InitializedEntity::EK_RelatedResult: 5867 // The entity being initialized might not outlive the full-expression. 5868 return false; 5869 } 5870 5871 llvm_unreachable("unknown entity kind"); 5872 } 5873 5874 /// Determine the declaration which an initialized entity ultimately refers to, 5875 /// for the purpose of lifetime-extending a temporary bound to a reference in 5876 /// the initialization of \p Entity. 5877 static const InitializedEntity *getEntityForTemporaryLifetimeExtension( 5878 const InitializedEntity *Entity, 5879 const InitializedEntity *FallbackDecl = nullptr) { 5880 // C++11 [class.temporary]p5: 5881 switch (Entity->getKind()) { 5882 case InitializedEntity::EK_Variable: 5883 // The temporary [...] persists for the lifetime of the reference 5884 return Entity; 5885 5886 case InitializedEntity::EK_Member: 5887 // For subobjects, we look at the complete object. 5888 if (Entity->getParent()) 5889 return getEntityForTemporaryLifetimeExtension(Entity->getParent(), 5890 Entity); 5891 5892 // except: 5893 // -- A temporary bound to a reference member in a constructor's 5894 // ctor-initializer persists until the constructor exits. 5895 return Entity; 5896 5897 case InitializedEntity::EK_Parameter: 5898 case InitializedEntity::EK_Parameter_CF_Audited: 5899 // -- A temporary bound to a reference parameter in a function call 5900 // persists until the completion of the full-expression containing 5901 // the call. 5902 case InitializedEntity::EK_Result: 5903 // -- The lifetime of a temporary bound to the returned value in a 5904 // function return statement is not extended; the temporary is 5905 // destroyed at the end of the full-expression in the return statement. 5906 case InitializedEntity::EK_New: 5907 // -- A temporary bound to a reference in a new-initializer persists 5908 // until the completion of the full-expression containing the 5909 // new-initializer. 5910 return nullptr; 5911 5912 case InitializedEntity::EK_Temporary: 5913 case InitializedEntity::EK_CompoundLiteralInit: 5914 case InitializedEntity::EK_RelatedResult: 5915 // We don't yet know the storage duration of the surrounding temporary. 5916 // Assume it's got full-expression duration for now, it will patch up our 5917 // storage duration if that's not correct. 5918 return nullptr; 5919 5920 case InitializedEntity::EK_ArrayElement: 5921 // For subobjects, we look at the complete object. 5922 return getEntityForTemporaryLifetimeExtension(Entity->getParent(), 5923 FallbackDecl); 5924 5925 case InitializedEntity::EK_Base: 5926 // For subobjects, we look at the complete object. 5927 if (Entity->getParent()) 5928 return getEntityForTemporaryLifetimeExtension(Entity->getParent(), 5929 Entity); 5930 // Fall through. 5931 case InitializedEntity::EK_Delegating: 5932 // We can reach this case for aggregate initialization in a constructor: 5933 // struct A { int &&r; }; 5934 // struct B : A { B() : A{0} {} }; 5935 // In this case, use the innermost field decl as the context. 5936 return FallbackDecl; 5937 5938 case InitializedEntity::EK_BlockElement: 5939 case InitializedEntity::EK_LambdaCapture: 5940 case InitializedEntity::EK_Exception: 5941 case InitializedEntity::EK_VectorElement: 5942 case InitializedEntity::EK_ComplexElement: 5943 return nullptr; 5944 } 5945 llvm_unreachable("unknown entity kind"); 5946 } 5947 5948 static void performLifetimeExtension(Expr *Init, 5949 const InitializedEntity *ExtendingEntity); 5950 5951 /// Update a glvalue expression that is used as the initializer of a reference 5952 /// to note that its lifetime is extended. 5953 /// \return \c true if any temporary had its lifetime extended. 5954 static bool 5955 performReferenceExtension(Expr *Init, 5956 const InitializedEntity *ExtendingEntity) { 5957 // Walk past any constructs which we can lifetime-extend across. 5958 Expr *Old; 5959 do { 5960 Old = Init; 5961 5962 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 5963 if (ILE->getNumInits() == 1 && ILE->isGLValue()) { 5964 // This is just redundant braces around an initializer. Step over it. 5965 Init = ILE->getInit(0); 5966 } 5967 } 5968 5969 // Step over any subobject adjustments; we may have a materialized 5970 // temporary inside them. 5971 SmallVector<const Expr *, 2> CommaLHSs; 5972 SmallVector<SubobjectAdjustment, 2> Adjustments; 5973 Init = const_cast<Expr *>( 5974 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 5975 5976 // Per current approach for DR1376, look through casts to reference type 5977 // when performing lifetime extension. 5978 if (CastExpr *CE = dyn_cast<CastExpr>(Init)) 5979 if (CE->getSubExpr()->isGLValue()) 5980 Init = CE->getSubExpr(); 5981 5982 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue. 5983 // It's unclear if binding a reference to that xvalue extends the array 5984 // temporary. 5985 } while (Init != Old); 5986 5987 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) { 5988 // Update the storage duration of the materialized temporary. 5989 // FIXME: Rebuild the expression instead of mutating it. 5990 ME->setExtendingDecl(ExtendingEntity->getDecl(), 5991 ExtendingEntity->allocateManglingNumber()); 5992 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity); 5993 return true; 5994 } 5995 5996 return false; 5997 } 5998 5999 /// Update a prvalue expression that is going to be materialized as a 6000 /// lifetime-extended temporary. 6001 static void performLifetimeExtension(Expr *Init, 6002 const InitializedEntity *ExtendingEntity) { 6003 // Dig out the expression which constructs the extended temporary. 6004 SmallVector<const Expr *, 2> CommaLHSs; 6005 SmallVector<SubobjectAdjustment, 2> Adjustments; 6006 Init = const_cast<Expr *>( 6007 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 6008 6009 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) 6010 Init = BTE->getSubExpr(); 6011 6012 if (CXXStdInitializerListExpr *ILE = 6013 dyn_cast<CXXStdInitializerListExpr>(Init)) { 6014 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity); 6015 return; 6016 } 6017 6018 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 6019 if (ILE->getType()->isArrayType()) { 6020 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) 6021 performLifetimeExtension(ILE->getInit(I), ExtendingEntity); 6022 return; 6023 } 6024 6025 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { 6026 assert(RD->isAggregate() && "aggregate init on non-aggregate"); 6027 6028 // If we lifetime-extend a braced initializer which is initializing an 6029 // aggregate, and that aggregate contains reference members which are 6030 // bound to temporaries, those temporaries are also lifetime-extended. 6031 if (RD->isUnion() && ILE->getInitializedFieldInUnion() && 6032 ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) 6033 performReferenceExtension(ILE->getInit(0), ExtendingEntity); 6034 else { 6035 unsigned Index = 0; 6036 for (const auto *I : RD->fields()) { 6037 if (Index >= ILE->getNumInits()) 6038 break; 6039 if (I->isUnnamedBitfield()) 6040 continue; 6041 Expr *SubInit = ILE->getInit(Index); 6042 if (I->getType()->isReferenceType()) 6043 performReferenceExtension(SubInit, ExtendingEntity); 6044 else if (isa<InitListExpr>(SubInit) || 6045 isa<CXXStdInitializerListExpr>(SubInit)) 6046 // This may be either aggregate-initialization of a member or 6047 // initialization of a std::initializer_list object. Either way, 6048 // we should recursively lifetime-extend that initializer. 6049 performLifetimeExtension(SubInit, ExtendingEntity); 6050 ++Index; 6051 } 6052 } 6053 } 6054 } 6055 } 6056 6057 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity, 6058 const Expr *Init, bool IsInitializerList, 6059 const ValueDecl *ExtendingDecl) { 6060 // Warn if a field lifetime-extends a temporary. 6061 if (isa<FieldDecl>(ExtendingDecl)) { 6062 if (IsInitializerList) { 6063 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list) 6064 << /*at end of constructor*/true; 6065 return; 6066 } 6067 6068 bool IsSubobjectMember = false; 6069 for (const InitializedEntity *Ent = Entity.getParent(); Ent; 6070 Ent = Ent->getParent()) { 6071 if (Ent->getKind() != InitializedEntity::EK_Base) { 6072 IsSubobjectMember = true; 6073 break; 6074 } 6075 } 6076 S.Diag(Init->getExprLoc(), 6077 diag::warn_bind_ref_member_to_temporary) 6078 << ExtendingDecl << Init->getSourceRange() 6079 << IsSubobjectMember << IsInitializerList; 6080 if (IsSubobjectMember) 6081 S.Diag(ExtendingDecl->getLocation(), 6082 diag::note_ref_subobject_of_member_declared_here); 6083 else 6084 S.Diag(ExtendingDecl->getLocation(), 6085 diag::note_ref_or_ptr_member_declared_here) 6086 << /*is pointer*/false; 6087 } 6088 } 6089 6090 static void DiagnoseNarrowingInInitList(Sema &S, 6091 const ImplicitConversionSequence &ICS, 6092 QualType PreNarrowingType, 6093 QualType EntityType, 6094 const Expr *PostInit); 6095 6096 /// Provide warnings when std::move is used on construction. 6097 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, 6098 bool IsReturnStmt) { 6099 if (!InitExpr) 6100 return; 6101 6102 if (!S.ActiveTemplateInstantiations.empty()) 6103 return; 6104 6105 QualType DestType = InitExpr->getType(); 6106 if (!DestType->isRecordType()) 6107 return; 6108 6109 unsigned DiagID = 0; 6110 if (IsReturnStmt) { 6111 const CXXConstructExpr *CCE = 6112 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); 6113 if (!CCE || CCE->getNumArgs() != 1) 6114 return; 6115 6116 if (!CCE->getConstructor()->isCopyOrMoveConstructor()) 6117 return; 6118 6119 InitExpr = CCE->getArg(0)->IgnoreImpCasts(); 6120 } 6121 6122 // Find the std::move call and get the argument. 6123 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); 6124 if (!CE || CE->getNumArgs() != 1) 6125 return; 6126 6127 const FunctionDecl *MoveFunction = CE->getDirectCallee(); 6128 if (!MoveFunction || !MoveFunction->isInStdNamespace() || 6129 !MoveFunction->getIdentifier() || 6130 !MoveFunction->getIdentifier()->isStr("move")) 6131 return; 6132 6133 const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); 6134 6135 if (IsReturnStmt) { 6136 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); 6137 if (!DRE || DRE->refersToEnclosingVariableOrCapture()) 6138 return; 6139 6140 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); 6141 if (!VD || !VD->hasLocalStorage()) 6142 return; 6143 6144 QualType SourceType = VD->getType(); 6145 if (!SourceType->isRecordType()) 6146 return; 6147 6148 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { 6149 return; 6150 } 6151 6152 // If we're returning a function parameter, copy elision 6153 // is not possible. 6154 if (isa<ParmVarDecl>(VD)) 6155 DiagID = diag::warn_redundant_move_on_return; 6156 else 6157 DiagID = diag::warn_pessimizing_move_on_return; 6158 } else { 6159 DiagID = diag::warn_pessimizing_move_on_initialization; 6160 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); 6161 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) 6162 return; 6163 } 6164 6165 S.Diag(CE->getLocStart(), DiagID); 6166 6167 // Get all the locations for a fix-it. Don't emit the fix-it if any location 6168 // is within a macro. 6169 SourceLocation CallBegin = CE->getCallee()->getLocStart(); 6170 if (CallBegin.isMacroID()) 6171 return; 6172 SourceLocation RParen = CE->getRParenLoc(); 6173 if (RParen.isMacroID()) 6174 return; 6175 SourceLocation LParen; 6176 SourceLocation ArgLoc = Arg->getLocStart(); 6177 6178 // Special testing for the argument location. Since the fix-it needs the 6179 // location right before the argument, the argument location can be in a 6180 // macro only if it is at the beginning of the macro. 6181 while (ArgLoc.isMacroID() && 6182 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { 6183 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first; 6184 } 6185 6186 if (LParen.isMacroID()) 6187 return; 6188 6189 LParen = ArgLoc.getLocWithOffset(-1); 6190 6191 S.Diag(CE->getLocStart(), diag::note_remove_move) 6192 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) 6193 << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); 6194 } 6195 6196 ExprResult 6197 InitializationSequence::Perform(Sema &S, 6198 const InitializedEntity &Entity, 6199 const InitializationKind &Kind, 6200 MultiExprArg Args, 6201 QualType *ResultType) { 6202 if (Failed()) { 6203 Diagnose(S, Entity, Kind, Args); 6204 return ExprError(); 6205 } 6206 if (!ZeroInitializationFixit.empty()) { 6207 unsigned DiagID = diag::err_default_init_const; 6208 if (Decl *D = Entity.getDecl()) 6209 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) 6210 DiagID = diag::ext_default_init_const; 6211 6212 // The initialization would have succeeded with this fixit. Since the fixit 6213 // is on the error, we need to build a valid AST in this case, so this isn't 6214 // handled in the Failed() branch above. 6215 QualType DestType = Entity.getType(); 6216 S.Diag(Kind.getLocation(), DiagID) 6217 << DestType << (bool)DestType->getAs<RecordType>() 6218 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, 6219 ZeroInitializationFixit); 6220 } 6221 6222 if (getKind() == DependentSequence) { 6223 // If the declaration is a non-dependent, incomplete array type 6224 // that has an initializer, then its type will be completed once 6225 // the initializer is instantiated. 6226 if (ResultType && !Entity.getType()->isDependentType() && 6227 Args.size() == 1) { 6228 QualType DeclType = Entity.getType(); 6229 if (const IncompleteArrayType *ArrayT 6230 = S.Context.getAsIncompleteArrayType(DeclType)) { 6231 // FIXME: We don't currently have the ability to accurately 6232 // compute the length of an initializer list without 6233 // performing full type-checking of the initializer list 6234 // (since we have to determine where braces are implicitly 6235 // introduced and such). So, we fall back to making the array 6236 // type a dependently-sized array type with no specified 6237 // bound. 6238 if (isa<InitListExpr>((Expr *)Args[0])) { 6239 SourceRange Brackets; 6240 6241 // Scavange the location of the brackets from the entity, if we can. 6242 if (DeclaratorDecl *DD = Entity.getDecl()) { 6243 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 6244 TypeLoc TL = TInfo->getTypeLoc(); 6245 if (IncompleteArrayTypeLoc ArrayLoc = 6246 TL.getAs<IncompleteArrayTypeLoc>()) 6247 Brackets = ArrayLoc.getBracketsRange(); 6248 } 6249 } 6250 6251 *ResultType 6252 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 6253 /*NumElts=*/nullptr, 6254 ArrayT->getSizeModifier(), 6255 ArrayT->getIndexTypeCVRQualifiers(), 6256 Brackets); 6257 } 6258 6259 } 6260 } 6261 if (Kind.getKind() == InitializationKind::IK_Direct && 6262 !Kind.isExplicitCast()) { 6263 // Rebuild the ParenListExpr. 6264 SourceRange ParenRange = Kind.getParenRange(); 6265 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), 6266 Args); 6267 } 6268 assert(Kind.getKind() == InitializationKind::IK_Copy || 6269 Kind.isExplicitCast() || 6270 Kind.getKind() == InitializationKind::IK_DirectList); 6271 return ExprResult(Args[0]); 6272 } 6273 6274 // No steps means no initialization. 6275 if (Steps.empty()) 6276 return ExprResult((Expr *)nullptr); 6277 6278 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && 6279 Args.size() == 1 && isa<InitListExpr>(Args[0]) && 6280 !Entity.isParameterKind()) { 6281 // Produce a C++98 compatibility warning if we are initializing a reference 6282 // from an initializer list. For parameters, we produce a better warning 6283 // elsewhere. 6284 Expr *Init = Args[0]; 6285 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init) 6286 << Init->getSourceRange(); 6287 } 6288 6289 // Diagnose cases where we initialize a pointer to an array temporary, and the 6290 // pointer obviously outlives the temporary. 6291 if (Args.size() == 1 && Args[0]->getType()->isArrayType() && 6292 Entity.getType()->isPointerType() && 6293 InitializedEntityOutlivesFullExpression(Entity)) { 6294 Expr *Init = Args[0]; 6295 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context); 6296 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary) 6297 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay) 6298 << Init->getSourceRange(); 6299 } 6300 6301 QualType DestType = Entity.getType().getNonReferenceType(); 6302 // FIXME: Ugly hack around the fact that Entity.getType() is not 6303 // the same as Entity.getDecl()->getType() in cases involving type merging, 6304 // and we want latter when it makes sense. 6305 if (ResultType) 6306 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 6307 Entity.getType(); 6308 6309 ExprResult CurInit((Expr *)nullptr); 6310 6311 // For initialization steps that start with a single initializer, 6312 // grab the only argument out the Args and place it into the "current" 6313 // initializer. 6314 switch (Steps.front().Kind) { 6315 case SK_ResolveAddressOfOverloadedFunction: 6316 case SK_CastDerivedToBaseRValue: 6317 case SK_CastDerivedToBaseXValue: 6318 case SK_CastDerivedToBaseLValue: 6319 case SK_BindReference: 6320 case SK_BindReferenceToTemporary: 6321 case SK_ExtraneousCopyToTemporary: 6322 case SK_UserConversion: 6323 case SK_QualificationConversionLValue: 6324 case SK_QualificationConversionXValue: 6325 case SK_QualificationConversionRValue: 6326 case SK_AtomicConversion: 6327 case SK_LValueToRValue: 6328 case SK_ConversionSequence: 6329 case SK_ConversionSequenceNoNarrowing: 6330 case SK_ListInitialization: 6331 case SK_UnwrapInitList: 6332 case SK_RewrapInitList: 6333 case SK_CAssignment: 6334 case SK_StringInit: 6335 case SK_ObjCObjectConversion: 6336 case SK_ArrayInit: 6337 case SK_ParenthesizedArrayInit: 6338 case SK_PassByIndirectCopyRestore: 6339 case SK_PassByIndirectRestore: 6340 case SK_ProduceObjCObject: 6341 case SK_StdInitializerList: 6342 case SK_OCLSamplerInit: 6343 case SK_OCLZeroEvent: { 6344 assert(Args.size() == 1); 6345 CurInit = Args[0]; 6346 if (!CurInit.get()) return ExprError(); 6347 break; 6348 } 6349 6350 case SK_ConstructorInitialization: 6351 case SK_ConstructorInitializationFromList: 6352 case SK_StdInitializerListConstructorCall: 6353 case SK_ZeroInitialization: 6354 break; 6355 } 6356 6357 // Walk through the computed steps for the initialization sequence, 6358 // performing the specified conversions along the way. 6359 bool ConstructorInitRequiresZeroInit = false; 6360 for (step_iterator Step = step_begin(), StepEnd = step_end(); 6361 Step != StepEnd; ++Step) { 6362 if (CurInit.isInvalid()) 6363 return ExprError(); 6364 6365 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 6366 6367 switch (Step->Kind) { 6368 case SK_ResolveAddressOfOverloadedFunction: 6369 // Overload resolution determined which function invoke; update the 6370 // initializer to reflect that choice. 6371 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 6372 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) 6373 return ExprError(); 6374 CurInit = S.FixOverloadedFunctionReference(CurInit, 6375 Step->Function.FoundDecl, 6376 Step->Function.Function); 6377 break; 6378 6379 case SK_CastDerivedToBaseRValue: 6380 case SK_CastDerivedToBaseXValue: 6381 case SK_CastDerivedToBaseLValue: { 6382 // We have a derived-to-base cast that produces either an rvalue or an 6383 // lvalue. Perform that cast. 6384 6385 CXXCastPath BasePath; 6386 6387 // Casts to inaccessible base classes are allowed with C-style casts. 6388 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 6389 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 6390 CurInit.get()->getLocStart(), 6391 CurInit.get()->getSourceRange(), 6392 &BasePath, IgnoreBaseAccess)) 6393 return ExprError(); 6394 6395 ExprValueKind VK = 6396 Step->Kind == SK_CastDerivedToBaseLValue ? 6397 VK_LValue : 6398 (Step->Kind == SK_CastDerivedToBaseXValue ? 6399 VK_XValue : 6400 VK_RValue); 6401 CurInit = 6402 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase, 6403 CurInit.get(), &BasePath, VK); 6404 break; 6405 } 6406 6407 case SK_BindReference: 6408 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5). 6409 if (CurInit.get()->refersToBitField()) { 6410 // We don't necessarily have an unambiguous source bit-field. 6411 FieldDecl *BitField = CurInit.get()->getSourceBitField(); 6412 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 6413 << Entity.getType().isVolatileQualified() 6414 << (BitField ? BitField->getDeclName() : DeclarationName()) 6415 << (BitField != nullptr) 6416 << CurInit.get()->getSourceRange(); 6417 if (BitField) 6418 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 6419 6420 return ExprError(); 6421 } 6422 6423 if (CurInit.get()->refersToVectorElement()) { 6424 // References cannot bind to vector elements. 6425 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 6426 << Entity.getType().isVolatileQualified() 6427 << CurInit.get()->getSourceRange(); 6428 PrintInitLocationNote(S, Entity); 6429 return ExprError(); 6430 } 6431 6432 // Reference binding does not have any corresponding ASTs. 6433 6434 // Check exception specifications 6435 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 6436 return ExprError(); 6437 6438 // Even though we didn't materialize a temporary, the binding may still 6439 // extend the lifetime of a temporary. This happens if we bind a reference 6440 // to the result of a cast to reference type. 6441 if (const InitializedEntity *ExtendingEntity = 6442 getEntityForTemporaryLifetimeExtension(&Entity)) 6443 if (performReferenceExtension(CurInit.get(), ExtendingEntity)) 6444 warnOnLifetimeExtension(S, Entity, CurInit.get(), 6445 /*IsInitializerList=*/false, 6446 ExtendingEntity->getDecl()); 6447 6448 break; 6449 6450 case SK_BindReferenceToTemporary: { 6451 // Make sure the "temporary" is actually an rvalue. 6452 assert(CurInit.get()->isRValue() && "not a temporary"); 6453 6454 // Check exception specifications 6455 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 6456 return ExprError(); 6457 6458 // Materialize the temporary into memory. 6459 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr( 6460 Entity.getType().getNonReferenceType(), CurInit.get(), 6461 Entity.getType()->isLValueReferenceType()); 6462 6463 // Maybe lifetime-extend the temporary's subobjects to match the 6464 // entity's lifetime. 6465 if (const InitializedEntity *ExtendingEntity = 6466 getEntityForTemporaryLifetimeExtension(&Entity)) 6467 if (performReferenceExtension(MTE, ExtendingEntity)) 6468 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false, 6469 ExtendingEntity->getDecl()); 6470 6471 // If we're binding to an Objective-C object that has lifetime, we 6472 // need cleanups. Likewise if we're extending this temporary to automatic 6473 // storage duration -- we need to register its cleanup during the 6474 // full-expression's cleanups. 6475 if ((S.getLangOpts().ObjCAutoRefCount && 6476 MTE->getType()->isObjCLifetimeType()) || 6477 (MTE->getStorageDuration() == SD_Automatic && 6478 MTE->getType().isDestructedType())) 6479 S.ExprNeedsCleanups = true; 6480 6481 CurInit = MTE; 6482 break; 6483 } 6484 6485 case SK_ExtraneousCopyToTemporary: 6486 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 6487 /*IsExtraneousCopy=*/true); 6488 break; 6489 6490 case SK_UserConversion: { 6491 // We have a user-defined conversion that invokes either a constructor 6492 // or a conversion function. 6493 CastKind CastKind; 6494 bool IsCopy = false; 6495 FunctionDecl *Fn = Step->Function.Function; 6496 DeclAccessPair FoundFn = Step->Function.FoundDecl; 6497 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 6498 bool CreatedObject = false; 6499 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 6500 // Build a call to the selected constructor. 6501 SmallVector<Expr*, 8> ConstructorArgs; 6502 SourceLocation Loc = CurInit.get()->getLocStart(); 6503 CurInit.get(); // Ownership transferred into MultiExprArg, below. 6504 6505 // Determine the arguments required to actually perform the constructor 6506 // call. 6507 Expr *Arg = CurInit.get(); 6508 if (S.CompleteConstructorCall(Constructor, 6509 MultiExprArg(&Arg, 1), 6510 Loc, ConstructorArgs)) 6511 return ExprError(); 6512 6513 // Build an expression that constructs a temporary. 6514 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 6515 ConstructorArgs, 6516 HadMultipleCandidates, 6517 /*ListInit*/ false, 6518 /*StdInitListInit*/ false, 6519 /*ZeroInit*/ false, 6520 CXXConstructExpr::CK_Complete, 6521 SourceRange()); 6522 if (CurInit.isInvalid()) 6523 return ExprError(); 6524 6525 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity, 6526 FoundFn.getAccess()); 6527 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 6528 return ExprError(); 6529 6530 CastKind = CK_ConstructorConversion; 6531 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 6532 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 6533 S.IsDerivedFrom(Loc, SourceType, Class)) 6534 IsCopy = true; 6535 6536 CreatedObject = true; 6537 } else { 6538 // Build a call to the conversion function. 6539 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 6540 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, 6541 FoundFn); 6542 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 6543 return ExprError(); 6544 6545 // FIXME: Should we move this initialization into a separate 6546 // derived-to-base conversion? I believe the answer is "no", because 6547 // we don't want to turn off access control here for c-style casts. 6548 ExprResult CurInitExprRes = 6549 S.PerformObjectArgumentInitialization(CurInit.get(), 6550 /*Qualifier=*/nullptr, 6551 FoundFn, Conversion); 6552 if(CurInitExprRes.isInvalid()) 6553 return ExprError(); 6554 CurInit = CurInitExprRes; 6555 6556 // Build the actual call to the conversion function. 6557 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 6558 HadMultipleCandidates); 6559 if (CurInit.isInvalid() || !CurInit.get()) 6560 return ExprError(); 6561 6562 CastKind = CK_UserDefinedConversion; 6563 6564 CreatedObject = Conversion->getReturnType()->isRecordType(); 6565 } 6566 6567 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back()); 6568 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity); 6569 6570 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) { 6571 QualType T = CurInit.get()->getType(); 6572 if (const RecordType *Record = T->getAs<RecordType>()) { 6573 CXXDestructorDecl *Destructor 6574 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 6575 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, 6576 S.PDiag(diag::err_access_dtor_temp) << T); 6577 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor); 6578 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart())) 6579 return ExprError(); 6580 } 6581 } 6582 6583 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(), 6584 CastKind, CurInit.get(), nullptr, 6585 CurInit.get()->getValueKind()); 6586 if (MaybeBindToTemp) 6587 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 6588 if (RequiresCopy) 6589 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 6590 CurInit, /*IsExtraneousCopy=*/false); 6591 break; 6592 } 6593 6594 case SK_QualificationConversionLValue: 6595 case SK_QualificationConversionXValue: 6596 case SK_QualificationConversionRValue: { 6597 // Perform a qualification conversion; these can never go wrong. 6598 ExprValueKind VK = 6599 Step->Kind == SK_QualificationConversionLValue ? 6600 VK_LValue : 6601 (Step->Kind == SK_QualificationConversionXValue ? 6602 VK_XValue : 6603 VK_RValue); 6604 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK); 6605 break; 6606 } 6607 6608 case SK_AtomicConversion: { 6609 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic"); 6610 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 6611 CK_NonAtomicToAtomic, VK_RValue); 6612 break; 6613 } 6614 6615 case SK_LValueToRValue: { 6616 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue"); 6617 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, 6618 CK_LValueToRValue, CurInit.get(), 6619 /*BasePath=*/nullptr, VK_RValue); 6620 break; 6621 } 6622 6623 case SK_ConversionSequence: 6624 case SK_ConversionSequenceNoNarrowing: { 6625 Sema::CheckedConversionKind CCK 6626 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 6627 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 6628 : Kind.isExplicitCast()? Sema::CCK_OtherCast 6629 : Sema::CCK_ImplicitConversion; 6630 ExprResult CurInitExprRes = 6631 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 6632 getAssignmentAction(Entity), CCK); 6633 if (CurInitExprRes.isInvalid()) 6634 return ExprError(); 6635 CurInit = CurInitExprRes; 6636 6637 if (Step->Kind == SK_ConversionSequenceNoNarrowing && 6638 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent()) 6639 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), 6640 CurInit.get()); 6641 break; 6642 } 6643 6644 case SK_ListInitialization: { 6645 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 6646 // If we're not initializing the top-level entity, we need to create an 6647 // InitializeTemporary entity for our target type. 6648 QualType Ty = Step->Type; 6649 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); 6650 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 6651 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; 6652 InitListChecker PerformInitList(S, InitEntity, 6653 InitList, Ty, /*VerifyOnly=*/false, 6654 /*TreatUnavailableAsInvalid=*/false); 6655 if (PerformInitList.HadError()) 6656 return ExprError(); 6657 6658 // Hack: We must update *ResultType if available in order to set the 6659 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 6660 // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 6661 if (ResultType && 6662 ResultType->getNonReferenceType()->isIncompleteArrayType()) { 6663 if ((*ResultType)->isRValueReferenceType()) 6664 Ty = S.Context.getRValueReferenceType(Ty); 6665 else if ((*ResultType)->isLValueReferenceType()) 6666 Ty = S.Context.getLValueReferenceType(Ty, 6667 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue()); 6668 *ResultType = Ty; 6669 } 6670 6671 InitListExpr *StructuredInitList = 6672 PerformInitList.getFullyStructuredList(); 6673 CurInit.get(); 6674 CurInit = shouldBindAsTemporary(InitEntity) 6675 ? S.MaybeBindToTemporary(StructuredInitList) 6676 : StructuredInitList; 6677 break; 6678 } 6679 6680 case SK_ConstructorInitializationFromList: { 6681 // When an initializer list is passed for a parameter of type "reference 6682 // to object", we don't get an EK_Temporary entity, but instead an 6683 // EK_Parameter entity with reference type. 6684 // FIXME: This is a hack. What we really should do is create a user 6685 // conversion step for this case, but this makes it considerably more 6686 // complicated. For now, this will do. 6687 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 6688 Entity.getType().getNonReferenceType()); 6689 bool UseTemporary = Entity.getType()->isReferenceType(); 6690 assert(Args.size() == 1 && "expected a single argument for list init"); 6691 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 6692 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) 6693 << InitList->getSourceRange(); 6694 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 6695 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : 6696 Entity, 6697 Kind, Arg, *Step, 6698 ConstructorInitRequiresZeroInit, 6699 /*IsListInitialization*/true, 6700 /*IsStdInitListInit*/false, 6701 InitList->getLBraceLoc(), 6702 InitList->getRBraceLoc()); 6703 break; 6704 } 6705 6706 case SK_UnwrapInitList: 6707 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); 6708 break; 6709 6710 case SK_RewrapInitList: { 6711 Expr *E = CurInit.get(); 6712 InitListExpr *Syntactic = Step->WrappingSyntacticList; 6713 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 6714 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); 6715 ILE->setSyntacticForm(Syntactic); 6716 ILE->setType(E->getType()); 6717 ILE->setValueKind(E->getValueKind()); 6718 CurInit = ILE; 6719 break; 6720 } 6721 6722 case SK_ConstructorInitialization: 6723 case SK_StdInitializerListConstructorCall: { 6724 // When an initializer list is passed for a parameter of type "reference 6725 // to object", we don't get an EK_Temporary entity, but instead an 6726 // EK_Parameter entity with reference type. 6727 // FIXME: This is a hack. What we really should do is create a user 6728 // conversion step for this case, but this makes it considerably more 6729 // complicated. For now, this will do. 6730 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 6731 Entity.getType().getNonReferenceType()); 6732 bool UseTemporary = Entity.getType()->isReferenceType(); 6733 bool IsStdInitListInit = 6734 Step->Kind == SK_StdInitializerListConstructorCall; 6735 CurInit = PerformConstructorInitialization( 6736 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step, 6737 ConstructorInitRequiresZeroInit, 6738 /*IsListInitialization*/IsStdInitListInit, 6739 /*IsStdInitListInitialization*/IsStdInitListInit, 6740 /*LBraceLoc*/SourceLocation(), 6741 /*RBraceLoc*/SourceLocation()); 6742 break; 6743 } 6744 6745 case SK_ZeroInitialization: { 6746 step_iterator NextStep = Step; 6747 ++NextStep; 6748 if (NextStep != StepEnd && 6749 (NextStep->Kind == SK_ConstructorInitialization || 6750 NextStep->Kind == SK_ConstructorInitializationFromList)) { 6751 // The need for zero-initialization is recorded directly into 6752 // the call to the object's constructor within the next step. 6753 ConstructorInitRequiresZeroInit = true; 6754 } else if (Kind.getKind() == InitializationKind::IK_Value && 6755 S.getLangOpts().CPlusPlus && 6756 !Kind.isImplicitValueInit()) { 6757 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 6758 if (!TSInfo) 6759 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 6760 Kind.getRange().getBegin()); 6761 6762 CurInit = new (S.Context) CXXScalarValueInitExpr( 6763 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo, 6764 Kind.getRange().getEnd()); 6765 } else { 6766 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); 6767 } 6768 break; 6769 } 6770 6771 case SK_CAssignment: { 6772 QualType SourceType = CurInit.get()->getType(); 6773 // Save off the initial CurInit in case we need to emit a diagnostic 6774 ExprResult InitialCurInit = CurInit; 6775 ExprResult Result = CurInit; 6776 Sema::AssignConvertType ConvTy = 6777 S.CheckSingleAssignmentConstraints(Step->Type, Result, true, 6778 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); 6779 if (Result.isInvalid()) 6780 return ExprError(); 6781 CurInit = Result; 6782 6783 // If this is a call, allow conversion to a transparent union. 6784 ExprResult CurInitExprRes = CurInit; 6785 if (ConvTy != Sema::Compatible && 6786 Entity.isParameterKind() && 6787 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 6788 == Sema::Compatible) 6789 ConvTy = Sema::Compatible; 6790 if (CurInitExprRes.isInvalid()) 6791 return ExprError(); 6792 CurInit = CurInitExprRes; 6793 6794 bool Complained; 6795 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 6796 Step->Type, SourceType, 6797 InitialCurInit.get(), 6798 getAssignmentAction(Entity, true), 6799 &Complained)) { 6800 PrintInitLocationNote(S, Entity); 6801 return ExprError(); 6802 } else if (Complained) 6803 PrintInitLocationNote(S, Entity); 6804 break; 6805 } 6806 6807 case SK_StringInit: { 6808 QualType Ty = Step->Type; 6809 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, 6810 S.Context.getAsArrayType(Ty), S); 6811 break; 6812 } 6813 6814 case SK_ObjCObjectConversion: 6815 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 6816 CK_ObjCObjectLValueCast, 6817 CurInit.get()->getValueKind()); 6818 break; 6819 6820 case SK_ArrayInit: 6821 // Okay: we checked everything before creating this step. Note that 6822 // this is a GNU extension. 6823 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 6824 << Step->Type << CurInit.get()->getType() 6825 << CurInit.get()->getSourceRange(); 6826 6827 // If the destination type is an incomplete array type, update the 6828 // type accordingly. 6829 if (ResultType) { 6830 if (const IncompleteArrayType *IncompleteDest 6831 = S.Context.getAsIncompleteArrayType(Step->Type)) { 6832 if (const ConstantArrayType *ConstantSource 6833 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 6834 *ResultType = S.Context.getConstantArrayType( 6835 IncompleteDest->getElementType(), 6836 ConstantSource->getSize(), 6837 ArrayType::Normal, 0); 6838 } 6839 } 6840 } 6841 break; 6842 6843 case SK_ParenthesizedArrayInit: 6844 // Okay: we checked everything before creating this step. Note that 6845 // this is a GNU extension. 6846 S.Diag(Kind.getLocation(), diag::ext_array_init_parens) 6847 << CurInit.get()->getSourceRange(); 6848 break; 6849 6850 case SK_PassByIndirectCopyRestore: 6851 case SK_PassByIndirectRestore: 6852 checkIndirectCopyRestoreSource(S, CurInit.get()); 6853 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( 6854 CurInit.get(), Step->Type, 6855 Step->Kind == SK_PassByIndirectCopyRestore); 6856 break; 6857 6858 case SK_ProduceObjCObject: 6859 CurInit = 6860 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject, 6861 CurInit.get(), nullptr, VK_RValue); 6862 break; 6863 6864 case SK_StdInitializerList: { 6865 S.Diag(CurInit.get()->getExprLoc(), 6866 diag::warn_cxx98_compat_initializer_list_init) 6867 << CurInit.get()->getSourceRange(); 6868 6869 // Materialize the temporary into memory. 6870 MaterializeTemporaryExpr *MTE = new (S.Context) 6871 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(), 6872 /*BoundToLvalueReference=*/false); 6873 6874 // Maybe lifetime-extend the array temporary's subobjects to match the 6875 // entity's lifetime. 6876 if (const InitializedEntity *ExtendingEntity = 6877 getEntityForTemporaryLifetimeExtension(&Entity)) 6878 if (performReferenceExtension(MTE, ExtendingEntity)) 6879 warnOnLifetimeExtension(S, Entity, CurInit.get(), 6880 /*IsInitializerList=*/true, 6881 ExtendingEntity->getDecl()); 6882 6883 // Wrap it in a construction of a std::initializer_list<T>. 6884 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); 6885 6886 // Bind the result, in case the library has given initializer_list a 6887 // non-trivial destructor. 6888 if (shouldBindAsTemporary(Entity)) 6889 CurInit = S.MaybeBindToTemporary(CurInit.get()); 6890 break; 6891 } 6892 6893 case SK_OCLSamplerInit: { 6894 assert(Step->Type->isSamplerT() && 6895 "Sampler initialization on non-sampler type."); 6896 6897 QualType SourceType = CurInit.get()->getType(); 6898 6899 if (Entity.isParameterKind()) { 6900 if (!SourceType->isSamplerT()) 6901 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) 6902 << SourceType; 6903 } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 6904 llvm_unreachable("Invalid EntityKind!"); 6905 } 6906 6907 break; 6908 } 6909 case SK_OCLZeroEvent: { 6910 assert(Step->Type->isEventT() && 6911 "Event initialization on non-event type."); 6912 6913 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 6914 CK_ZeroToOCLEvent, 6915 CurInit.get()->getValueKind()); 6916 break; 6917 } 6918 } 6919 } 6920 6921 // Diagnose non-fatal problems with the completed initialization. 6922 if (Entity.getKind() == InitializedEntity::EK_Member && 6923 cast<FieldDecl>(Entity.getDecl())->isBitField()) 6924 S.CheckBitFieldInitialization(Kind.getLocation(), 6925 cast<FieldDecl>(Entity.getDecl()), 6926 CurInit.get()); 6927 6928 // Check for std::move on construction. 6929 if (const Expr *E = CurInit.get()) { 6930 CheckMoveOnConstruction(S, E, 6931 Entity.getKind() == InitializedEntity::EK_Result); 6932 } 6933 6934 return CurInit; 6935 } 6936 6937 /// Somewhere within T there is an uninitialized reference subobject. 6938 /// Dig it out and diagnose it. 6939 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, 6940 QualType T) { 6941 if (T->isReferenceType()) { 6942 S.Diag(Loc, diag::err_reference_without_init) 6943 << T.getNonReferenceType(); 6944 return true; 6945 } 6946 6947 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6948 if (!RD || !RD->hasUninitializedReferenceMember()) 6949 return false; 6950 6951 for (const auto *FI : RD->fields()) { 6952 if (FI->isUnnamedBitfield()) 6953 continue; 6954 6955 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { 6956 S.Diag(Loc, diag::note_value_initialization_here) << RD; 6957 return true; 6958 } 6959 } 6960 6961 for (const auto &BI : RD->bases()) { 6962 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) { 6963 S.Diag(Loc, diag::note_value_initialization_here) << RD; 6964 return true; 6965 } 6966 } 6967 6968 return false; 6969 } 6970 6971 6972 //===----------------------------------------------------------------------===// 6973 // Diagnose initialization failures 6974 //===----------------------------------------------------------------------===// 6975 6976 /// Emit notes associated with an initialization that failed due to a 6977 /// "simple" conversion failure. 6978 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, 6979 Expr *op) { 6980 QualType destType = entity.getType(); 6981 if (destType.getNonReferenceType()->isObjCObjectPointerType() && 6982 op->getType()->isObjCObjectPointerType()) { 6983 6984 // Emit a possible note about the conversion failing because the 6985 // operand is a message send with a related result type. 6986 S.EmitRelatedResultTypeNote(op); 6987 6988 // Emit a possible note about a return failing because we're 6989 // expecting a related result type. 6990 if (entity.getKind() == InitializedEntity::EK_Result) 6991 S.EmitRelatedResultTypeNoteForReturn(destType); 6992 } 6993 } 6994 6995 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, 6996 InitListExpr *InitList) { 6997 QualType DestType = Entity.getType(); 6998 6999 QualType E; 7000 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { 7001 QualType ArrayType = S.Context.getConstantArrayType( 7002 E.withConst(), 7003 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 7004 InitList->getNumInits()), 7005 clang::ArrayType::Normal, 0); 7006 InitializedEntity HiddenArray = 7007 InitializedEntity::InitializeTemporary(ArrayType); 7008 return diagnoseListInit(S, HiddenArray, InitList); 7009 } 7010 7011 if (DestType->isReferenceType()) { 7012 // A list-initialization failure for a reference means that we tried to 7013 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the 7014 // inner initialization failed. 7015 QualType T = DestType->getAs<ReferenceType>()->getPointeeType(); 7016 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); 7017 SourceLocation Loc = InitList->getLocStart(); 7018 if (auto *D = Entity.getDecl()) 7019 Loc = D->getLocation(); 7020 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; 7021 return; 7022 } 7023 7024 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, 7025 /*VerifyOnly=*/false, 7026 /*TreatUnavailableAsInvalid=*/false); 7027 assert(DiagnoseInitList.HadError() && 7028 "Inconsistent init list check result."); 7029 } 7030 7031 bool InitializationSequence::Diagnose(Sema &S, 7032 const InitializedEntity &Entity, 7033 const InitializationKind &Kind, 7034 ArrayRef<Expr *> Args) { 7035 if (!Failed()) 7036 return false; 7037 7038 QualType DestType = Entity.getType(); 7039 switch (Failure) { 7040 case FK_TooManyInitsForReference: 7041 // FIXME: Customize for the initialized entity? 7042 if (Args.empty()) { 7043 // Dig out the reference subobject which is uninitialized and diagnose it. 7044 // If this is value-initialization, this could be nested some way within 7045 // the target type. 7046 assert(Kind.getKind() == InitializationKind::IK_Value || 7047 DestType->isReferenceType()); 7048 bool Diagnosed = 7049 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); 7050 assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); 7051 (void)Diagnosed; 7052 } else // FIXME: diagnostic below could be better! 7053 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 7054 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd()); 7055 break; 7056 7057 case FK_ArrayNeedsInitList: 7058 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; 7059 break; 7060 case FK_ArrayNeedsInitListOrStringLiteral: 7061 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; 7062 break; 7063 case FK_ArrayNeedsInitListOrWideStringLiteral: 7064 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; 7065 break; 7066 case FK_NarrowStringIntoWideCharArray: 7067 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); 7068 break; 7069 case FK_WideStringIntoCharArray: 7070 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); 7071 break; 7072 case FK_IncompatWideStringIntoWideChar: 7073 S.Diag(Kind.getLocation(), 7074 diag::err_array_init_incompat_wide_string_into_wchar); 7075 break; 7076 case FK_ArrayTypeMismatch: 7077 case FK_NonConstantArrayInit: 7078 S.Diag(Kind.getLocation(), 7079 (Failure == FK_ArrayTypeMismatch 7080 ? diag::err_array_init_different_type 7081 : diag::err_array_init_non_constant_array)) 7082 << DestType.getNonReferenceType() 7083 << Args[0]->getType() 7084 << Args[0]->getSourceRange(); 7085 break; 7086 7087 case FK_VariableLengthArrayHasInitializer: 7088 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 7089 << Args[0]->getSourceRange(); 7090 break; 7091 7092 case FK_AddressOfOverloadFailed: { 7093 DeclAccessPair Found; 7094 S.ResolveAddressOfOverloadedFunction(Args[0], 7095 DestType.getNonReferenceType(), 7096 true, 7097 Found); 7098 break; 7099 } 7100 7101 case FK_AddressOfUnaddressableFunction: { 7102 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl()); 7103 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 7104 Args[0]->getLocStart()); 7105 break; 7106 } 7107 7108 case FK_ReferenceInitOverloadFailed: 7109 case FK_UserConversionOverloadFailed: 7110 switch (FailedOverloadResult) { 7111 case OR_Ambiguous: 7112 if (Failure == FK_UserConversionOverloadFailed) 7113 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 7114 << Args[0]->getType() << DestType 7115 << Args[0]->getSourceRange(); 7116 else 7117 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 7118 << DestType << Args[0]->getType() 7119 << Args[0]->getSourceRange(); 7120 7121 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); 7122 break; 7123 7124 case OR_No_Viable_Function: 7125 if (!S.RequireCompleteType(Kind.getLocation(), 7126 DestType.getNonReferenceType(), 7127 diag::err_typecheck_nonviable_condition_incomplete, 7128 Args[0]->getType(), Args[0]->getSourceRange())) 7129 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 7130 << (Entity.getKind() == InitializedEntity::EK_Result) 7131 << Args[0]->getType() << Args[0]->getSourceRange() 7132 << DestType.getNonReferenceType(); 7133 7134 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); 7135 break; 7136 7137 case OR_Deleted: { 7138 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 7139 << Args[0]->getType() << DestType.getNonReferenceType() 7140 << Args[0]->getSourceRange(); 7141 OverloadCandidateSet::iterator Best; 7142 OverloadingResult Ovl 7143 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, 7144 true); 7145 if (Ovl == OR_Deleted) { 7146 S.NoteDeletedFunction(Best->Function); 7147 } else { 7148 llvm_unreachable("Inconsistent overload resolution?"); 7149 } 7150 break; 7151 } 7152 7153 case OR_Success: 7154 llvm_unreachable("Conversion did not fail!"); 7155 } 7156 break; 7157 7158 case FK_NonConstLValueReferenceBindingToTemporary: 7159 if (isa<InitListExpr>(Args[0])) { 7160 S.Diag(Kind.getLocation(), 7161 diag::err_lvalue_reference_bind_to_initlist) 7162 << DestType.getNonReferenceType().isVolatileQualified() 7163 << DestType.getNonReferenceType() 7164 << Args[0]->getSourceRange(); 7165 break; 7166 } 7167 // Intentional fallthrough 7168 7169 case FK_NonConstLValueReferenceBindingToUnrelated: 7170 S.Diag(Kind.getLocation(), 7171 Failure == FK_NonConstLValueReferenceBindingToTemporary 7172 ? diag::err_lvalue_reference_bind_to_temporary 7173 : diag::err_lvalue_reference_bind_to_unrelated) 7174 << DestType.getNonReferenceType().isVolatileQualified() 7175 << DestType.getNonReferenceType() 7176 << Args[0]->getType() 7177 << Args[0]->getSourceRange(); 7178 break; 7179 7180 case FK_RValueReferenceBindingToLValue: 7181 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 7182 << DestType.getNonReferenceType() << Args[0]->getType() 7183 << Args[0]->getSourceRange(); 7184 break; 7185 7186 case FK_ReferenceInitDropsQualifiers: { 7187 QualType SourceType = Args[0]->getType(); 7188 QualType NonRefType = DestType.getNonReferenceType(); 7189 Qualifiers DroppedQualifiers = 7190 SourceType.getQualifiers() - NonRefType.getQualifiers(); 7191 7192 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 7193 << SourceType 7194 << NonRefType 7195 << DroppedQualifiers.getCVRQualifiers() 7196 << Args[0]->getSourceRange(); 7197 break; 7198 } 7199 7200 case FK_ReferenceInitFailed: 7201 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 7202 << DestType.getNonReferenceType() 7203 << Args[0]->isLValue() 7204 << Args[0]->getType() 7205 << Args[0]->getSourceRange(); 7206 emitBadConversionNotes(S, Entity, Args[0]); 7207 break; 7208 7209 case FK_ConversionFailed: { 7210 QualType FromType = Args[0]->getType(); 7211 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 7212 << (int)Entity.getKind() 7213 << DestType 7214 << Args[0]->isLValue() 7215 << FromType 7216 << Args[0]->getSourceRange(); 7217 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 7218 S.Diag(Kind.getLocation(), PDiag); 7219 emitBadConversionNotes(S, Entity, Args[0]); 7220 break; 7221 } 7222 7223 case FK_ConversionFromPropertyFailed: 7224 // No-op. This error has already been reported. 7225 break; 7226 7227 case FK_TooManyInitsForScalar: { 7228 SourceRange R; 7229 7230 auto *InitList = dyn_cast<InitListExpr>(Args[0]); 7231 if (InitList && InitList->getNumInits() >= 1) { 7232 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd()); 7233 } else { 7234 assert(Args.size() > 1 && "Expected multiple initializers!"); 7235 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd()); 7236 } 7237 7238 R.setBegin(S.getLocForEndOfToken(R.getBegin())); 7239 if (Kind.isCStyleOrFunctionalCast()) 7240 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 7241 << R; 7242 else 7243 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 7244 << /*scalar=*/2 << R; 7245 break; 7246 } 7247 7248 case FK_ReferenceBindingToInitList: 7249 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 7250 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 7251 break; 7252 7253 case FK_InitListBadDestinationType: 7254 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 7255 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 7256 break; 7257 7258 case FK_ListConstructorOverloadFailed: 7259 case FK_ConstructorOverloadFailed: { 7260 SourceRange ArgsRange; 7261 if (Args.size()) 7262 ArgsRange = SourceRange(Args.front()->getLocStart(), 7263 Args.back()->getLocEnd()); 7264 7265 if (Failure == FK_ListConstructorOverloadFailed) { 7266 assert(Args.size() == 1 && 7267 "List construction from other than 1 argument."); 7268 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 7269 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 7270 } 7271 7272 // FIXME: Using "DestType" for the entity we're printing is probably 7273 // bad. 7274 switch (FailedOverloadResult) { 7275 case OR_Ambiguous: 7276 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 7277 << DestType << ArgsRange; 7278 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); 7279 break; 7280 7281 case OR_No_Viable_Function: 7282 if (Kind.getKind() == InitializationKind::IK_Default && 7283 (Entity.getKind() == InitializedEntity::EK_Base || 7284 Entity.getKind() == InitializedEntity::EK_Member) && 7285 isa<CXXConstructorDecl>(S.CurContext)) { 7286 // This is implicit default initialization of a member or 7287 // base within a constructor. If no viable function was 7288 // found, notify the user that she needs to explicitly 7289 // initialize this base/member. 7290 CXXConstructorDecl *Constructor 7291 = cast<CXXConstructorDecl>(S.CurContext); 7292 if (Entity.getKind() == InitializedEntity::EK_Base) { 7293 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 7294 << (Constructor->getInheritedConstructor() ? 2 : 7295 Constructor->isImplicit() ? 1 : 0) 7296 << S.Context.getTypeDeclType(Constructor->getParent()) 7297 << /*base=*/0 7298 << Entity.getType(); 7299 7300 RecordDecl *BaseDecl 7301 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 7302 ->getDecl(); 7303 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 7304 << S.Context.getTagDeclType(BaseDecl); 7305 } else { 7306 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 7307 << (Constructor->getInheritedConstructor() ? 2 : 7308 Constructor->isImplicit() ? 1 : 0) 7309 << S.Context.getTypeDeclType(Constructor->getParent()) 7310 << /*member=*/1 7311 << Entity.getName(); 7312 S.Diag(Entity.getDecl()->getLocation(), 7313 diag::note_member_declared_at); 7314 7315 if (const RecordType *Record 7316 = Entity.getType()->getAs<RecordType>()) 7317 S.Diag(Record->getDecl()->getLocation(), 7318 diag::note_previous_decl) 7319 << S.Context.getTagDeclType(Record->getDecl()); 7320 } 7321 break; 7322 } 7323 7324 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 7325 << DestType << ArgsRange; 7326 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); 7327 break; 7328 7329 case OR_Deleted: { 7330 OverloadCandidateSet::iterator Best; 7331 OverloadingResult Ovl 7332 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 7333 if (Ovl != OR_Deleted) { 7334 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 7335 << true << DestType << ArgsRange; 7336 llvm_unreachable("Inconsistent overload resolution?"); 7337 break; 7338 } 7339 7340 // If this is a defaulted or implicitly-declared function, then 7341 // it was implicitly deleted. Make it clear that the deletion was 7342 // implicit. 7343 if (S.isImplicitlyDeleted(Best->Function)) 7344 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) 7345 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) 7346 << DestType << ArgsRange; 7347 else 7348 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 7349 << true << DestType << ArgsRange; 7350 7351 S.NoteDeletedFunction(Best->Function); 7352 break; 7353 } 7354 7355 case OR_Success: 7356 llvm_unreachable("Conversion did not fail!"); 7357 } 7358 } 7359 break; 7360 7361 case FK_DefaultInitOfConst: 7362 if (Entity.getKind() == InitializedEntity::EK_Member && 7363 isa<CXXConstructorDecl>(S.CurContext)) { 7364 // This is implicit default-initialization of a const member in 7365 // a constructor. Complain that it needs to be explicitly 7366 // initialized. 7367 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 7368 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 7369 << (Constructor->getInheritedConstructor() ? 2 : 7370 Constructor->isImplicit() ? 1 : 0) 7371 << S.Context.getTypeDeclType(Constructor->getParent()) 7372 << /*const=*/1 7373 << Entity.getName(); 7374 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 7375 << Entity.getName(); 7376 } else { 7377 S.Diag(Kind.getLocation(), diag::err_default_init_const) 7378 << DestType << (bool)DestType->getAs<RecordType>(); 7379 } 7380 break; 7381 7382 case FK_Incomplete: 7383 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, 7384 diag::err_init_incomplete_type); 7385 break; 7386 7387 case FK_ListInitializationFailed: { 7388 // Run the init list checker again to emit diagnostics. 7389 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 7390 diagnoseListInit(S, Entity, InitList); 7391 break; 7392 } 7393 7394 case FK_PlaceholderType: { 7395 // FIXME: Already diagnosed! 7396 break; 7397 } 7398 7399 case FK_ExplicitConstructor: { 7400 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) 7401 << Args[0]->getSourceRange(); 7402 OverloadCandidateSet::iterator Best; 7403 OverloadingResult Ovl 7404 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 7405 (void)Ovl; 7406 assert(Ovl == OR_Success && "Inconsistent overload resolution"); 7407 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 7408 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here); 7409 break; 7410 } 7411 } 7412 7413 PrintInitLocationNote(S, Entity); 7414 return true; 7415 } 7416 7417 void InitializationSequence::dump(raw_ostream &OS) const { 7418 switch (SequenceKind) { 7419 case FailedSequence: { 7420 OS << "Failed sequence: "; 7421 switch (Failure) { 7422 case FK_TooManyInitsForReference: 7423 OS << "too many initializers for reference"; 7424 break; 7425 7426 case FK_ArrayNeedsInitList: 7427 OS << "array requires initializer list"; 7428 break; 7429 7430 case FK_AddressOfUnaddressableFunction: 7431 OS << "address of unaddressable function was taken"; 7432 break; 7433 7434 case FK_ArrayNeedsInitListOrStringLiteral: 7435 OS << "array requires initializer list or string literal"; 7436 break; 7437 7438 case FK_ArrayNeedsInitListOrWideStringLiteral: 7439 OS << "array requires initializer list or wide string literal"; 7440 break; 7441 7442 case FK_NarrowStringIntoWideCharArray: 7443 OS << "narrow string into wide char array"; 7444 break; 7445 7446 case FK_WideStringIntoCharArray: 7447 OS << "wide string into char array"; 7448 break; 7449 7450 case FK_IncompatWideStringIntoWideChar: 7451 OS << "incompatible wide string into wide char array"; 7452 break; 7453 7454 case FK_ArrayTypeMismatch: 7455 OS << "array type mismatch"; 7456 break; 7457 7458 case FK_NonConstantArrayInit: 7459 OS << "non-constant array initializer"; 7460 break; 7461 7462 case FK_AddressOfOverloadFailed: 7463 OS << "address of overloaded function failed"; 7464 break; 7465 7466 case FK_ReferenceInitOverloadFailed: 7467 OS << "overload resolution for reference initialization failed"; 7468 break; 7469 7470 case FK_NonConstLValueReferenceBindingToTemporary: 7471 OS << "non-const lvalue reference bound to temporary"; 7472 break; 7473 7474 case FK_NonConstLValueReferenceBindingToUnrelated: 7475 OS << "non-const lvalue reference bound to unrelated type"; 7476 break; 7477 7478 case FK_RValueReferenceBindingToLValue: 7479 OS << "rvalue reference bound to an lvalue"; 7480 break; 7481 7482 case FK_ReferenceInitDropsQualifiers: 7483 OS << "reference initialization drops qualifiers"; 7484 break; 7485 7486 case FK_ReferenceInitFailed: 7487 OS << "reference initialization failed"; 7488 break; 7489 7490 case FK_ConversionFailed: 7491 OS << "conversion failed"; 7492 break; 7493 7494 case FK_ConversionFromPropertyFailed: 7495 OS << "conversion from property failed"; 7496 break; 7497 7498 case FK_TooManyInitsForScalar: 7499 OS << "too many initializers for scalar"; 7500 break; 7501 7502 case FK_ReferenceBindingToInitList: 7503 OS << "referencing binding to initializer list"; 7504 break; 7505 7506 case FK_InitListBadDestinationType: 7507 OS << "initializer list for non-aggregate, non-scalar type"; 7508 break; 7509 7510 case FK_UserConversionOverloadFailed: 7511 OS << "overloading failed for user-defined conversion"; 7512 break; 7513 7514 case FK_ConstructorOverloadFailed: 7515 OS << "constructor overloading failed"; 7516 break; 7517 7518 case FK_DefaultInitOfConst: 7519 OS << "default initialization of a const variable"; 7520 break; 7521 7522 case FK_Incomplete: 7523 OS << "initialization of incomplete type"; 7524 break; 7525 7526 case FK_ListInitializationFailed: 7527 OS << "list initialization checker failure"; 7528 break; 7529 7530 case FK_VariableLengthArrayHasInitializer: 7531 OS << "variable length array has an initializer"; 7532 break; 7533 7534 case FK_PlaceholderType: 7535 OS << "initializer expression isn't contextually valid"; 7536 break; 7537 7538 case FK_ListConstructorOverloadFailed: 7539 OS << "list constructor overloading failed"; 7540 break; 7541 7542 case FK_ExplicitConstructor: 7543 OS << "list copy initialization chose explicit constructor"; 7544 break; 7545 } 7546 OS << '\n'; 7547 return; 7548 } 7549 7550 case DependentSequence: 7551 OS << "Dependent sequence\n"; 7552 return; 7553 7554 case NormalSequence: 7555 OS << "Normal sequence: "; 7556 break; 7557 } 7558 7559 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 7560 if (S != step_begin()) { 7561 OS << " -> "; 7562 } 7563 7564 switch (S->Kind) { 7565 case SK_ResolveAddressOfOverloadedFunction: 7566 OS << "resolve address of overloaded function"; 7567 break; 7568 7569 case SK_CastDerivedToBaseRValue: 7570 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 7571 break; 7572 7573 case SK_CastDerivedToBaseXValue: 7574 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 7575 break; 7576 7577 case SK_CastDerivedToBaseLValue: 7578 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 7579 break; 7580 7581 case SK_BindReference: 7582 OS << "bind reference to lvalue"; 7583 break; 7584 7585 case SK_BindReferenceToTemporary: 7586 OS << "bind reference to a temporary"; 7587 break; 7588 7589 case SK_ExtraneousCopyToTemporary: 7590 OS << "extraneous C++03 copy to temporary"; 7591 break; 7592 7593 case SK_UserConversion: 7594 OS << "user-defined conversion via " << *S->Function.Function; 7595 break; 7596 7597 case SK_QualificationConversionRValue: 7598 OS << "qualification conversion (rvalue)"; 7599 break; 7600 7601 case SK_QualificationConversionXValue: 7602 OS << "qualification conversion (xvalue)"; 7603 break; 7604 7605 case SK_QualificationConversionLValue: 7606 OS << "qualification conversion (lvalue)"; 7607 break; 7608 7609 case SK_AtomicConversion: 7610 OS << "non-atomic-to-atomic conversion"; 7611 break; 7612 7613 case SK_LValueToRValue: 7614 OS << "load (lvalue to rvalue)"; 7615 break; 7616 7617 case SK_ConversionSequence: 7618 OS << "implicit conversion sequence ("; 7619 S->ICS->dump(); // FIXME: use OS 7620 OS << ")"; 7621 break; 7622 7623 case SK_ConversionSequenceNoNarrowing: 7624 OS << "implicit conversion sequence with narrowing prohibited ("; 7625 S->ICS->dump(); // FIXME: use OS 7626 OS << ")"; 7627 break; 7628 7629 case SK_ListInitialization: 7630 OS << "list aggregate initialization"; 7631 break; 7632 7633 case SK_UnwrapInitList: 7634 OS << "unwrap reference initializer list"; 7635 break; 7636 7637 case SK_RewrapInitList: 7638 OS << "rewrap reference initializer list"; 7639 break; 7640 7641 case SK_ConstructorInitialization: 7642 OS << "constructor initialization"; 7643 break; 7644 7645 case SK_ConstructorInitializationFromList: 7646 OS << "list initialization via constructor"; 7647 break; 7648 7649 case SK_ZeroInitialization: 7650 OS << "zero initialization"; 7651 break; 7652 7653 case SK_CAssignment: 7654 OS << "C assignment"; 7655 break; 7656 7657 case SK_StringInit: 7658 OS << "string initialization"; 7659 break; 7660 7661 case SK_ObjCObjectConversion: 7662 OS << "Objective-C object conversion"; 7663 break; 7664 7665 case SK_ArrayInit: 7666 OS << "array initialization"; 7667 break; 7668 7669 case SK_ParenthesizedArrayInit: 7670 OS << "parenthesized array initialization"; 7671 break; 7672 7673 case SK_PassByIndirectCopyRestore: 7674 OS << "pass by indirect copy and restore"; 7675 break; 7676 7677 case SK_PassByIndirectRestore: 7678 OS << "pass by indirect restore"; 7679 break; 7680 7681 case SK_ProduceObjCObject: 7682 OS << "Objective-C object retension"; 7683 break; 7684 7685 case SK_StdInitializerList: 7686 OS << "std::initializer_list from initializer list"; 7687 break; 7688 7689 case SK_StdInitializerListConstructorCall: 7690 OS << "list initialization from std::initializer_list"; 7691 break; 7692 7693 case SK_OCLSamplerInit: 7694 OS << "OpenCL sampler_t from integer constant"; 7695 break; 7696 7697 case SK_OCLZeroEvent: 7698 OS << "OpenCL event_t from zero"; 7699 break; 7700 } 7701 7702 OS << " [" << S->Type.getAsString() << ']'; 7703 } 7704 7705 OS << '\n'; 7706 } 7707 7708 void InitializationSequence::dump() const { 7709 dump(llvm::errs()); 7710 } 7711 7712 static void DiagnoseNarrowingInInitList(Sema &S, 7713 const ImplicitConversionSequence &ICS, 7714 QualType PreNarrowingType, 7715 QualType EntityType, 7716 const Expr *PostInit) { 7717 const StandardConversionSequence *SCS = nullptr; 7718 switch (ICS.getKind()) { 7719 case ImplicitConversionSequence::StandardConversion: 7720 SCS = &ICS.Standard; 7721 break; 7722 case ImplicitConversionSequence::UserDefinedConversion: 7723 SCS = &ICS.UserDefined.After; 7724 break; 7725 case ImplicitConversionSequence::AmbiguousConversion: 7726 case ImplicitConversionSequence::EllipsisConversion: 7727 case ImplicitConversionSequence::BadConversion: 7728 return; 7729 } 7730 7731 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. 7732 APValue ConstantValue; 7733 QualType ConstantType; 7734 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, 7735 ConstantType)) { 7736 case NK_Not_Narrowing: 7737 // No narrowing occurred. 7738 return; 7739 7740 case NK_Type_Narrowing: 7741 // This was a floating-to-integer conversion, which is always considered a 7742 // narrowing conversion even if the value is a constant and can be 7743 // represented exactly as an integer. 7744 S.Diag(PostInit->getLocStart(), 7745 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) 7746 ? diag::warn_init_list_type_narrowing 7747 : diag::ext_init_list_type_narrowing) 7748 << PostInit->getSourceRange() 7749 << PreNarrowingType.getLocalUnqualifiedType() 7750 << EntityType.getLocalUnqualifiedType(); 7751 break; 7752 7753 case NK_Constant_Narrowing: 7754 // A constant value was narrowed. 7755 S.Diag(PostInit->getLocStart(), 7756 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) 7757 ? diag::warn_init_list_constant_narrowing 7758 : diag::ext_init_list_constant_narrowing) 7759 << PostInit->getSourceRange() 7760 << ConstantValue.getAsString(S.getASTContext(), ConstantType) 7761 << EntityType.getLocalUnqualifiedType(); 7762 break; 7763 7764 case NK_Variable_Narrowing: 7765 // A variable's value may have been narrowed. 7766 S.Diag(PostInit->getLocStart(), 7767 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) 7768 ? diag::warn_init_list_variable_narrowing 7769 : diag::ext_init_list_variable_narrowing) 7770 << PostInit->getSourceRange() 7771 << PreNarrowingType.getLocalUnqualifiedType() 7772 << EntityType.getLocalUnqualifiedType(); 7773 break; 7774 } 7775 7776 SmallString<128> StaticCast; 7777 llvm::raw_svector_ostream OS(StaticCast); 7778 OS << "static_cast<"; 7779 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 7780 // It's important to use the typedef's name if there is one so that the 7781 // fixit doesn't break code using types like int64_t. 7782 // 7783 // FIXME: This will break if the typedef requires qualification. But 7784 // getQualifiedNameAsString() includes non-machine-parsable components. 7785 OS << *TT->getDecl(); 7786 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 7787 OS << BT->getName(S.getLangOpts()); 7788 else { 7789 // Oops, we didn't find the actual type of the variable. Don't emit a fixit 7790 // with a broken cast. 7791 return; 7792 } 7793 OS << ">("; 7794 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence) 7795 << PostInit->getSourceRange() 7796 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str()) 7797 << FixItHint::CreateInsertion( 7798 S.getLocForEndOfToken(PostInit->getLocEnd()), ")"); 7799 } 7800 7801 //===----------------------------------------------------------------------===// 7802 // Initialization helper functions 7803 //===----------------------------------------------------------------------===// 7804 bool 7805 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 7806 ExprResult Init) { 7807 if (Init.isInvalid()) 7808 return false; 7809 7810 Expr *InitE = Init.get(); 7811 assert(InitE && "No initialization expression"); 7812 7813 InitializationKind Kind 7814 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation()); 7815 InitializationSequence Seq(*this, Entity, Kind, InitE); 7816 return !Seq.Failed(); 7817 } 7818 7819 ExprResult 7820 Sema::PerformCopyInitialization(const InitializedEntity &Entity, 7821 SourceLocation EqualLoc, 7822 ExprResult Init, 7823 bool TopLevelOfInitList, 7824 bool AllowExplicit) { 7825 if (Init.isInvalid()) 7826 return ExprError(); 7827 7828 Expr *InitE = Init.get(); 7829 assert(InitE && "No initialization expression?"); 7830 7831 if (EqualLoc.isInvalid()) 7832 EqualLoc = InitE->getLocStart(); 7833 7834 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 7835 EqualLoc, 7836 AllowExplicit); 7837 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); 7838 7839 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); 7840 7841 return Result; 7842 } 7843