1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for initializers. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/AST/ExprObjC.h" 17 #include "clang/AST/ExprOpenMP.h" 18 #include "clang/AST/TypeLoc.h" 19 #include "clang/Basic/CharInfo.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Basic/TargetInfo.h" 22 #include "clang/Sema/Designator.h" 23 #include "clang/Sema/Initialization.h" 24 #include "clang/Sema/Lookup.h" 25 #include "clang/Sema/SemaInternal.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/SmallString.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Support/raw_ostream.h" 30 31 using namespace clang; 32 33 //===----------------------------------------------------------------------===// 34 // Sema Initialization Checking 35 //===----------------------------------------------------------------------===// 36 37 /// Check whether T is compatible with a wide character type (wchar_t, 38 /// char16_t or char32_t). 39 static bool IsWideCharCompatible(QualType T, ASTContext &Context) { 40 if (Context.typesAreCompatible(Context.getWideCharType(), T)) 41 return true; 42 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { 43 return Context.typesAreCompatible(Context.Char16Ty, T) || 44 Context.typesAreCompatible(Context.Char32Ty, T); 45 } 46 return false; 47 } 48 49 enum StringInitFailureKind { 50 SIF_None, 51 SIF_NarrowStringIntoWideChar, 52 SIF_WideStringIntoChar, 53 SIF_IncompatWideStringIntoWideChar, 54 SIF_UTF8StringIntoPlainChar, 55 SIF_PlainStringIntoUTF8Char, 56 SIF_Other 57 }; 58 59 /// Check whether the array of type AT can be initialized by the Init 60 /// expression by means of string initialization. Returns SIF_None if so, 61 /// otherwise returns a StringInitFailureKind that describes why the 62 /// initialization would not work. 63 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, 64 ASTContext &Context) { 65 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 66 return SIF_Other; 67 68 // See if this is a string literal or @encode. 69 Init = Init->IgnoreParens(); 70 71 // Handle @encode, which is a narrow string. 72 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 73 return SIF_None; 74 75 // Otherwise we can only handle string literals. 76 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 77 if (!SL) 78 return SIF_Other; 79 80 const QualType ElemTy = 81 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); 82 83 switch (SL->getKind()) { 84 case StringLiteral::UTF8: 85 // char8_t array can be initialized with a UTF-8 string. 86 if (ElemTy->isChar8Type()) 87 return SIF_None; 88 LLVM_FALLTHROUGH; 89 case StringLiteral::Ascii: 90 // char array can be initialized with a narrow string. 91 // Only allow char x[] = "foo"; not char x[] = L"foo"; 92 if (ElemTy->isCharType()) 93 return (SL->getKind() == StringLiteral::UTF8 && 94 Context.getLangOpts().Char8) 95 ? SIF_UTF8StringIntoPlainChar 96 : SIF_None; 97 if (ElemTy->isChar8Type()) 98 return SIF_PlainStringIntoUTF8Char; 99 if (IsWideCharCompatible(ElemTy, Context)) 100 return SIF_NarrowStringIntoWideChar; 101 return SIF_Other; 102 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: 103 // "An array with element type compatible with a qualified or unqualified 104 // version of wchar_t, char16_t, or char32_t may be initialized by a wide 105 // string literal with the corresponding encoding prefix (L, u, or U, 106 // respectively), optionally enclosed in braces. 107 case StringLiteral::UTF16: 108 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) 109 return SIF_None; 110 if (ElemTy->isCharType() || ElemTy->isChar8Type()) 111 return SIF_WideStringIntoChar; 112 if (IsWideCharCompatible(ElemTy, Context)) 113 return SIF_IncompatWideStringIntoWideChar; 114 return SIF_Other; 115 case StringLiteral::UTF32: 116 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) 117 return SIF_None; 118 if (ElemTy->isCharType() || ElemTy->isChar8Type()) 119 return SIF_WideStringIntoChar; 120 if (IsWideCharCompatible(ElemTy, Context)) 121 return SIF_IncompatWideStringIntoWideChar; 122 return SIF_Other; 123 case StringLiteral::Wide: 124 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) 125 return SIF_None; 126 if (ElemTy->isCharType() || ElemTy->isChar8Type()) 127 return SIF_WideStringIntoChar; 128 if (IsWideCharCompatible(ElemTy, Context)) 129 return SIF_IncompatWideStringIntoWideChar; 130 return SIF_Other; 131 } 132 133 llvm_unreachable("missed a StringLiteral kind?"); 134 } 135 136 static StringInitFailureKind IsStringInit(Expr *init, QualType declType, 137 ASTContext &Context) { 138 const ArrayType *arrayType = Context.getAsArrayType(declType); 139 if (!arrayType) 140 return SIF_Other; 141 return IsStringInit(init, arrayType, Context); 142 } 143 144 bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { 145 return ::IsStringInit(Init, AT, Context) == SIF_None; 146 } 147 148 /// Update the type of a string literal, including any surrounding parentheses, 149 /// to match the type of the object which it is initializing. 150 static void updateStringLiteralType(Expr *E, QualType Ty) { 151 while (true) { 152 E->setType(Ty); 153 E->setValueKind(VK_RValue); 154 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { 155 break; 156 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 157 E = PE->getSubExpr(); 158 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 159 assert(UO->getOpcode() == UO_Extension); 160 E = UO->getSubExpr(); 161 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { 162 E = GSE->getResultExpr(); 163 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { 164 E = CE->getChosenSubExpr(); 165 } else { 166 llvm_unreachable("unexpected expr in string literal init"); 167 } 168 } 169 } 170 171 /// Fix a compound literal initializing an array so it's correctly marked 172 /// as an rvalue. 173 static void updateGNUCompoundLiteralRValue(Expr *E) { 174 while (true) { 175 E->setValueKind(VK_RValue); 176 if (isa<CompoundLiteralExpr>(E)) { 177 break; 178 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 179 E = PE->getSubExpr(); 180 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 181 assert(UO->getOpcode() == UO_Extension); 182 E = UO->getSubExpr(); 183 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { 184 E = GSE->getResultExpr(); 185 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { 186 E = CE->getChosenSubExpr(); 187 } else { 188 llvm_unreachable("unexpected expr in array compound literal init"); 189 } 190 } 191 } 192 193 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 194 Sema &S) { 195 // Get the length of the string as parsed. 196 auto *ConstantArrayTy = 197 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); 198 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); 199 200 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 201 // C99 6.7.8p14. We have an array of character type with unknown size 202 // being initialized to a string literal. 203 llvm::APInt ConstVal(32, StrLength); 204 // Return a new array type (C99 6.7.8p22). 205 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 206 ConstVal, nullptr, 207 ArrayType::Normal, 0); 208 updateStringLiteralType(Str, DeclT); 209 return; 210 } 211 212 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 213 214 // We have an array of character type with known size. However, 215 // the size may be smaller or larger than the string we are initializing. 216 // FIXME: Avoid truncation for 64-bit length strings. 217 if (S.getLangOpts().CPlusPlus) { 218 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { 219 // For Pascal strings it's OK to strip off the terminating null character, 220 // so the example below is valid: 221 // 222 // unsigned char a[2] = "\pa"; 223 if (SL->isPascal()) 224 StrLength--; 225 } 226 227 // [dcl.init.string]p2 228 if (StrLength > CAT->getSize().getZExtValue()) 229 S.Diag(Str->getBeginLoc(), 230 diag::err_initializer_string_for_char_array_too_long) 231 << Str->getSourceRange(); 232 } else { 233 // C99 6.7.8p14. 234 if (StrLength-1 > CAT->getSize().getZExtValue()) 235 S.Diag(Str->getBeginLoc(), 236 diag::ext_initializer_string_for_char_array_too_long) 237 << Str->getSourceRange(); 238 } 239 240 // Set the type to the actual size that we are initializing. If we have 241 // something like: 242 // char x[1] = "foo"; 243 // then this will set the string literal's type to char[1]. 244 updateStringLiteralType(Str, DeclT); 245 } 246 247 //===----------------------------------------------------------------------===// 248 // Semantic checking for initializer lists. 249 //===----------------------------------------------------------------------===// 250 251 namespace { 252 253 /// Semantic checking for initializer lists. 254 /// 255 /// The InitListChecker class contains a set of routines that each 256 /// handle the initialization of a certain kind of entity, e.g., 257 /// arrays, vectors, struct/union types, scalars, etc. The 258 /// InitListChecker itself performs a recursive walk of the subobject 259 /// structure of the type to be initialized, while stepping through 260 /// the initializer list one element at a time. The IList and Index 261 /// parameters to each of the Check* routines contain the active 262 /// (syntactic) initializer list and the index into that initializer 263 /// list that represents the current initializer. Each routine is 264 /// responsible for moving that Index forward as it consumes elements. 265 /// 266 /// Each Check* routine also has a StructuredList/StructuredIndex 267 /// arguments, which contains the current "structured" (semantic) 268 /// initializer list and the index into that initializer list where we 269 /// are copying initializers as we map them over to the semantic 270 /// list. Once we have completed our recursive walk of the subobject 271 /// structure, we will have constructed a full semantic initializer 272 /// list. 273 /// 274 /// C99 designators cause changes in the initializer list traversal, 275 /// because they make the initialization "jump" into a specific 276 /// subobject and then continue the initialization from that 277 /// point. CheckDesignatedInitializer() recursively steps into the 278 /// designated subobject and manages backing out the recursion to 279 /// initialize the subobjects after the one designated. 280 /// 281 /// If an initializer list contains any designators, we build a placeholder 282 /// structured list even in 'verify only' mode, so that we can track which 283 /// elements need 'empty' initializtion. 284 class InitListChecker { 285 Sema &SemaRef; 286 bool hadError = false; 287 bool VerifyOnly; // No diagnostics. 288 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. 289 bool InOverloadResolution; 290 InitListExpr *FullyStructuredList = nullptr; 291 NoInitExpr *DummyExpr = nullptr; 292 293 NoInitExpr *getDummyInit() { 294 if (!DummyExpr) 295 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); 296 return DummyExpr; 297 } 298 299 void CheckImplicitInitList(const InitializedEntity &Entity, 300 InitListExpr *ParentIList, QualType T, 301 unsigned &Index, InitListExpr *StructuredList, 302 unsigned &StructuredIndex); 303 void CheckExplicitInitList(const InitializedEntity &Entity, 304 InitListExpr *IList, QualType &T, 305 InitListExpr *StructuredList, 306 bool TopLevelObject = false); 307 void CheckListElementTypes(const InitializedEntity &Entity, 308 InitListExpr *IList, QualType &DeclType, 309 bool SubobjectIsDesignatorContext, 310 unsigned &Index, 311 InitListExpr *StructuredList, 312 unsigned &StructuredIndex, 313 bool TopLevelObject = false); 314 void CheckSubElementType(const InitializedEntity &Entity, 315 InitListExpr *IList, QualType ElemType, 316 unsigned &Index, 317 InitListExpr *StructuredList, 318 unsigned &StructuredIndex); 319 void CheckComplexType(const InitializedEntity &Entity, 320 InitListExpr *IList, QualType DeclType, 321 unsigned &Index, 322 InitListExpr *StructuredList, 323 unsigned &StructuredIndex); 324 void CheckScalarType(const InitializedEntity &Entity, 325 InitListExpr *IList, QualType DeclType, 326 unsigned &Index, 327 InitListExpr *StructuredList, 328 unsigned &StructuredIndex); 329 void CheckReferenceType(const InitializedEntity &Entity, 330 InitListExpr *IList, QualType DeclType, 331 unsigned &Index, 332 InitListExpr *StructuredList, 333 unsigned &StructuredIndex); 334 void CheckVectorType(const InitializedEntity &Entity, 335 InitListExpr *IList, QualType DeclType, unsigned &Index, 336 InitListExpr *StructuredList, 337 unsigned &StructuredIndex); 338 void CheckStructUnionTypes(const InitializedEntity &Entity, 339 InitListExpr *IList, QualType DeclType, 340 CXXRecordDecl::base_class_range Bases, 341 RecordDecl::field_iterator Field, 342 bool SubobjectIsDesignatorContext, unsigned &Index, 343 InitListExpr *StructuredList, 344 unsigned &StructuredIndex, 345 bool TopLevelObject = false); 346 void CheckArrayType(const InitializedEntity &Entity, 347 InitListExpr *IList, QualType &DeclType, 348 llvm::APSInt elementIndex, 349 bool SubobjectIsDesignatorContext, unsigned &Index, 350 InitListExpr *StructuredList, 351 unsigned &StructuredIndex); 352 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 353 InitListExpr *IList, DesignatedInitExpr *DIE, 354 unsigned DesigIdx, 355 QualType &CurrentObjectType, 356 RecordDecl::field_iterator *NextField, 357 llvm::APSInt *NextElementIndex, 358 unsigned &Index, 359 InitListExpr *StructuredList, 360 unsigned &StructuredIndex, 361 bool FinishSubobjectInit, 362 bool TopLevelObject); 363 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 364 QualType CurrentObjectType, 365 InitListExpr *StructuredList, 366 unsigned StructuredIndex, 367 SourceRange InitRange, 368 bool IsFullyOverwritten = false); 369 void UpdateStructuredListElement(InitListExpr *StructuredList, 370 unsigned &StructuredIndex, 371 Expr *expr); 372 InitListExpr *createInitListExpr(QualType CurrentObjectType, 373 SourceRange InitRange, 374 unsigned ExpectedNumInits); 375 int numArrayElements(QualType DeclType); 376 int numStructUnionElements(QualType DeclType); 377 378 ExprResult PerformEmptyInit(SourceLocation Loc, 379 const InitializedEntity &Entity); 380 381 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. 382 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, 383 bool FullyOverwritten = true) { 384 // Overriding an initializer via a designator is valid with C99 designated 385 // initializers, but ill-formed with C++20 designated initializers. 386 unsigned DiagID = SemaRef.getLangOpts().CPlusPlus 387 ? diag::ext_initializer_overrides 388 : diag::warn_initializer_overrides; 389 390 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { 391 // In overload resolution, we have to strictly enforce the rules, and so 392 // don't allow any overriding of prior initializers. This matters for a 393 // case such as: 394 // 395 // union U { int a, b; }; 396 // struct S { int a, b; }; 397 // void f(U), f(S); 398 // 399 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For 400 // consistency, we disallow all overriding of prior initializers in 401 // overload resolution, not only overriding of union members. 402 hadError = true; 403 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { 404 // If we'll be keeping around the old initializer but overwriting part of 405 // the object it initialized, and that object is not trivially 406 // destructible, this can leak. Don't allow that, not even as an 407 // extension. 408 // 409 // FIXME: It might be reasonable to allow this in cases where the part of 410 // the initializer that we're overriding has trivial destruction. 411 DiagID = diag::err_initializer_overrides_destructed; 412 } else if (!OldInit->getSourceRange().isValid()) { 413 // We need to check on source range validity because the previous 414 // initializer does not have to be an explicit initializer. e.g., 415 // 416 // struct P { int a, b; }; 417 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; 418 // 419 // There is an overwrite taking place because the first braced initializer 420 // list "{ .a = 2 }" already provides value for .p.b (which is zero). 421 // 422 // Such overwrites are harmless, so we don't diagnose them. (Note that in 423 // C++, this cannot be reached unless we've already seen and diagnosed a 424 // different conformance issue, such as a mixture of designated and 425 // non-designated initializers or a multi-level designator.) 426 return; 427 } 428 429 if (!VerifyOnly) { 430 SemaRef.Diag(NewInitRange.getBegin(), DiagID) 431 << NewInitRange << FullyOverwritten << OldInit->getType(); 432 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) 433 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) 434 << OldInit->getSourceRange(); 435 } 436 } 437 438 // Explanation on the "FillWithNoInit" mode: 439 // 440 // Assume we have the following definitions (Case#1): 441 // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; 442 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; 443 // 444 // l.lp.x[1][0..1] should not be filled with implicit initializers because the 445 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". 446 // 447 // But if we have (Case#2): 448 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; 449 // 450 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the 451 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". 452 // 453 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" 454 // in the InitListExpr, the "holes" in Case#1 are filled not with empty 455 // initializers but with special "NoInitExpr" place holders, which tells the 456 // CodeGen not to generate any initializers for these parts. 457 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, 458 const InitializedEntity &ParentEntity, 459 InitListExpr *ILE, bool &RequiresSecondPass, 460 bool FillWithNoInit); 461 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 462 const InitializedEntity &ParentEntity, 463 InitListExpr *ILE, bool &RequiresSecondPass, 464 bool FillWithNoInit = false); 465 void FillInEmptyInitializations(const InitializedEntity &Entity, 466 InitListExpr *ILE, bool &RequiresSecondPass, 467 InitListExpr *OuterILE, unsigned OuterIndex, 468 bool FillWithNoInit = false); 469 bool CheckFlexibleArrayInit(const InitializedEntity &Entity, 470 Expr *InitExpr, FieldDecl *Field, 471 bool TopLevelObject); 472 void CheckEmptyInitializable(const InitializedEntity &Entity, 473 SourceLocation Loc); 474 475 public: 476 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, 477 QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, 478 bool InOverloadResolution = false); 479 bool HadError() { return hadError; } 480 481 // Retrieves the fully-structured initializer list used for 482 // semantic analysis and code generation. 483 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 484 }; 485 486 } // end anonymous namespace 487 488 ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, 489 const InitializedEntity &Entity) { 490 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 491 true); 492 MultiExprArg SubInit; 493 Expr *InitExpr; 494 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); 495 496 // C++ [dcl.init.aggr]p7: 497 // If there are fewer initializer-clauses in the list than there are 498 // members in the aggregate, then each member not explicitly initialized 499 // ... 500 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && 501 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); 502 if (EmptyInitList) { 503 // C++1y / DR1070: 504 // shall be initialized [...] from an empty initializer list. 505 // 506 // We apply the resolution of this DR to C++11 but not C++98, since C++98 507 // does not have useful semantics for initialization from an init list. 508 // We treat this as copy-initialization, because aggregate initialization 509 // always performs copy-initialization on its elements. 510 // 511 // Only do this if we're initializing a class type, to avoid filling in 512 // the initializer list where possible. 513 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) 514 InitListExpr(SemaRef.Context, Loc, None, Loc); 515 InitExpr->setType(SemaRef.Context.VoidTy); 516 SubInit = InitExpr; 517 Kind = InitializationKind::CreateCopy(Loc, Loc); 518 } else { 519 // C++03: 520 // shall be value-initialized. 521 } 522 523 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); 524 // libstdc++4.6 marks the vector default constructor as explicit in 525 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. 526 // stlport does so too. Look for std::__debug for libstdc++, and for 527 // std:: for stlport. This is effectively a compiler-side implementation of 528 // LWG2193. 529 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == 530 InitializationSequence::FK_ExplicitConstructor) { 531 OverloadCandidateSet::iterator Best; 532 OverloadingResult O = 533 InitSeq.getFailedCandidateSet() 534 .BestViableFunction(SemaRef, Kind.getLocation(), Best); 535 (void)O; 536 assert(O == OR_Success && "Inconsistent overload resolution"); 537 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 538 CXXRecordDecl *R = CtorDecl->getParent(); 539 540 if (CtorDecl->getMinRequiredArguments() == 0 && 541 CtorDecl->isExplicit() && R->getDeclName() && 542 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { 543 bool IsInStd = false; 544 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); 545 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { 546 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) 547 IsInStd = true; 548 } 549 550 if (IsInStd && llvm::StringSwitch<bool>(R->getName()) 551 .Cases("basic_string", "deque", "forward_list", true) 552 .Cases("list", "map", "multimap", "multiset", true) 553 .Cases("priority_queue", "queue", "set", "stack", true) 554 .Cases("unordered_map", "unordered_set", "vector", true) 555 .Default(false)) { 556 InitSeq.InitializeFrom( 557 SemaRef, Entity, 558 InitializationKind::CreateValue(Loc, Loc, Loc, true), 559 MultiExprArg(), /*TopLevelOfInitList=*/false, 560 TreatUnavailableAsInvalid); 561 // Emit a warning for this. System header warnings aren't shown 562 // by default, but people working on system headers should see it. 563 if (!VerifyOnly) { 564 SemaRef.Diag(CtorDecl->getLocation(), 565 diag::warn_invalid_initializer_from_system_header); 566 if (Entity.getKind() == InitializedEntity::EK_Member) 567 SemaRef.Diag(Entity.getDecl()->getLocation(), 568 diag::note_used_in_initialization_here); 569 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) 570 SemaRef.Diag(Loc, diag::note_used_in_initialization_here); 571 } 572 } 573 } 574 } 575 if (!InitSeq) { 576 if (!VerifyOnly) { 577 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); 578 if (Entity.getKind() == InitializedEntity::EK_Member) 579 SemaRef.Diag(Entity.getDecl()->getLocation(), 580 diag::note_in_omitted_aggregate_initializer) 581 << /*field*/1 << Entity.getDecl(); 582 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { 583 bool IsTrailingArrayNewMember = 584 Entity.getParent() && 585 Entity.getParent()->isVariableLengthArrayNew(); 586 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) 587 << (IsTrailingArrayNewMember ? 2 : /*array element*/0) 588 << Entity.getElementIndex(); 589 } 590 } 591 hadError = true; 592 return ExprError(); 593 } 594 595 return VerifyOnly ? ExprResult() 596 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); 597 } 598 599 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, 600 SourceLocation Loc) { 601 // If we're building a fully-structured list, we'll check this at the end 602 // once we know which elements are actually initialized. Otherwise, we know 603 // that there are no designators so we can just check now. 604 if (FullyStructuredList) 605 return; 606 PerformEmptyInit(Loc, Entity); 607 } 608 609 void InitListChecker::FillInEmptyInitForBase( 610 unsigned Init, const CXXBaseSpecifier &Base, 611 const InitializedEntity &ParentEntity, InitListExpr *ILE, 612 bool &RequiresSecondPass, bool FillWithNoInit) { 613 InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 614 SemaRef.Context, &Base, false, &ParentEntity); 615 616 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { 617 ExprResult BaseInit = FillWithNoInit 618 ? new (SemaRef.Context) NoInitExpr(Base.getType()) 619 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); 620 if (BaseInit.isInvalid()) { 621 hadError = true; 622 return; 623 } 624 625 if (!VerifyOnly) { 626 assert(Init < ILE->getNumInits() && "should have been expanded"); 627 ILE->setInit(Init, BaseInit.getAs<Expr>()); 628 } 629 } else if (InitListExpr *InnerILE = 630 dyn_cast<InitListExpr>(ILE->getInit(Init))) { 631 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, 632 ILE, Init, FillWithNoInit); 633 } else if (DesignatedInitUpdateExpr *InnerDIUE = 634 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 635 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), 636 RequiresSecondPass, ILE, Init, 637 /*FillWithNoInit =*/true); 638 } 639 } 640 641 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 642 const InitializedEntity &ParentEntity, 643 InitListExpr *ILE, 644 bool &RequiresSecondPass, 645 bool FillWithNoInit) { 646 SourceLocation Loc = ILE->getEndLoc(); 647 unsigned NumInits = ILE->getNumInits(); 648 InitializedEntity MemberEntity 649 = InitializedEntity::InitializeMember(Field, &ParentEntity); 650 651 if (Init >= NumInits || !ILE->getInit(Init)) { 652 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) 653 if (!RType->getDecl()->isUnion()) 654 assert((Init < NumInits || VerifyOnly) && 655 "This ILE should have been expanded"); 656 657 if (FillWithNoInit) { 658 assert(!VerifyOnly && "should not fill with no-init in verify-only mode"); 659 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); 660 if (Init < NumInits) 661 ILE->setInit(Init, Filler); 662 else 663 ILE->updateInit(SemaRef.Context, Init, Filler); 664 return; 665 } 666 // C++1y [dcl.init.aggr]p7: 667 // If there are fewer initializer-clauses in the list than there are 668 // members in the aggregate, then each member not explicitly initialized 669 // shall be initialized from its brace-or-equal-initializer [...] 670 if (Field->hasInClassInitializer()) { 671 if (VerifyOnly) 672 return; 673 674 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); 675 if (DIE.isInvalid()) { 676 hadError = true; 677 return; 678 } 679 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); 680 if (Init < NumInits) 681 ILE->setInit(Init, DIE.get()); 682 else { 683 ILE->updateInit(SemaRef.Context, Init, DIE.get()); 684 RequiresSecondPass = true; 685 } 686 return; 687 } 688 689 if (Field->getType()->isReferenceType()) { 690 if (!VerifyOnly) { 691 // C++ [dcl.init.aggr]p9: 692 // If an incomplete or empty initializer-list leaves a 693 // member of reference type uninitialized, the program is 694 // ill-formed. 695 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 696 << Field->getType() 697 << ILE->getSyntacticForm()->getSourceRange(); 698 SemaRef.Diag(Field->getLocation(), 699 diag::note_uninit_reference_member); 700 } 701 hadError = true; 702 return; 703 } 704 705 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); 706 if (MemberInit.isInvalid()) { 707 hadError = true; 708 return; 709 } 710 711 if (hadError || VerifyOnly) { 712 // Do nothing 713 } else if (Init < NumInits) { 714 ILE->setInit(Init, MemberInit.getAs<Expr>()); 715 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { 716 // Empty initialization requires a constructor call, so 717 // extend the initializer list to include the constructor 718 // call and make a note that we'll need to take another pass 719 // through the initializer list. 720 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); 721 RequiresSecondPass = true; 722 } 723 } else if (InitListExpr *InnerILE 724 = dyn_cast<InitListExpr>(ILE->getInit(Init))) { 725 FillInEmptyInitializations(MemberEntity, InnerILE, 726 RequiresSecondPass, ILE, Init, FillWithNoInit); 727 } else if (DesignatedInitUpdateExpr *InnerDIUE = 728 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 729 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), 730 RequiresSecondPass, ILE, Init, 731 /*FillWithNoInit =*/true); 732 } 733 } 734 735 /// Recursively replaces NULL values within the given initializer list 736 /// with expressions that perform value-initialization of the 737 /// appropriate type, and finish off the InitListExpr formation. 738 void 739 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, 740 InitListExpr *ILE, 741 bool &RequiresSecondPass, 742 InitListExpr *OuterILE, 743 unsigned OuterIndex, 744 bool FillWithNoInit) { 745 assert((ILE->getType() != SemaRef.Context.VoidTy) && 746 "Should not have void type"); 747 748 // We don't need to do any checks when just filling NoInitExprs; that can't 749 // fail. 750 if (FillWithNoInit && VerifyOnly) 751 return; 752 753 // If this is a nested initializer list, we might have changed its contents 754 // (and therefore some of its properties, such as instantiation-dependence) 755 // while filling it in. Inform the outer initializer list so that its state 756 // can be updated to match. 757 // FIXME: We should fully build the inner initializers before constructing 758 // the outer InitListExpr instead of mutating AST nodes after they have 759 // been used as subexpressions of other nodes. 760 struct UpdateOuterILEWithUpdatedInit { 761 InitListExpr *Outer; 762 unsigned OuterIndex; 763 ~UpdateOuterILEWithUpdatedInit() { 764 if (Outer) 765 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); 766 } 767 } UpdateOuterRAII = {OuterILE, OuterIndex}; 768 769 // A transparent ILE is not performing aggregate initialization and should 770 // not be filled in. 771 if (ILE->isTransparent()) 772 return; 773 774 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 775 const RecordDecl *RDecl = RType->getDecl(); 776 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) 777 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), 778 Entity, ILE, RequiresSecondPass, FillWithNoInit); 779 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && 780 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { 781 for (auto *Field : RDecl->fields()) { 782 if (Field->hasInClassInitializer()) { 783 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, 784 FillWithNoInit); 785 break; 786 } 787 } 788 } else { 789 // The fields beyond ILE->getNumInits() are default initialized, so in 790 // order to leave them uninitialized, the ILE is expanded and the extra 791 // fields are then filled with NoInitExpr. 792 unsigned NumElems = numStructUnionElements(ILE->getType()); 793 if (RDecl->hasFlexibleArrayMember()) 794 ++NumElems; 795 if (!VerifyOnly && ILE->getNumInits() < NumElems) 796 ILE->resizeInits(SemaRef.Context, NumElems); 797 798 unsigned Init = 0; 799 800 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { 801 for (auto &Base : CXXRD->bases()) { 802 if (hadError) 803 return; 804 805 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, 806 FillWithNoInit); 807 ++Init; 808 } 809 } 810 811 for (auto *Field : RDecl->fields()) { 812 if (Field->isUnnamedBitfield()) 813 continue; 814 815 if (hadError) 816 return; 817 818 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, 819 FillWithNoInit); 820 if (hadError) 821 return; 822 823 ++Init; 824 825 // Only look at the first initialization of a union. 826 if (RDecl->isUnion()) 827 break; 828 } 829 } 830 831 return; 832 } 833 834 QualType ElementType; 835 836 InitializedEntity ElementEntity = Entity; 837 unsigned NumInits = ILE->getNumInits(); 838 unsigned NumElements = NumInits; 839 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 840 ElementType = AType->getElementType(); 841 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) 842 NumElements = CAType->getSize().getZExtValue(); 843 // For an array new with an unknown bound, ask for one additional element 844 // in order to populate the array filler. 845 if (Entity.isVariableLengthArrayNew()) 846 ++NumElements; 847 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 848 0, Entity); 849 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 850 ElementType = VType->getElementType(); 851 NumElements = VType->getNumElements(); 852 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 853 0, Entity); 854 } else 855 ElementType = ILE->getType(); 856 857 bool SkipEmptyInitChecks = false; 858 for (unsigned Init = 0; Init != NumElements; ++Init) { 859 if (hadError) 860 return; 861 862 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 863 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 864 ElementEntity.setElementIndex(Init); 865 866 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) 867 return; 868 869 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); 870 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) 871 ILE->setInit(Init, ILE->getArrayFiller()); 872 else if (!InitExpr && !ILE->hasArrayFiller()) { 873 // In VerifyOnly mode, there's no point performing empty initialization 874 // more than once. 875 if (SkipEmptyInitChecks) 876 continue; 877 878 Expr *Filler = nullptr; 879 880 if (FillWithNoInit) 881 Filler = new (SemaRef.Context) NoInitExpr(ElementType); 882 else { 883 ExprResult ElementInit = 884 PerformEmptyInit(ILE->getEndLoc(), ElementEntity); 885 if (ElementInit.isInvalid()) { 886 hadError = true; 887 return; 888 } 889 890 Filler = ElementInit.getAs<Expr>(); 891 } 892 893 if (hadError) { 894 // Do nothing 895 } else if (VerifyOnly) { 896 SkipEmptyInitChecks = true; 897 } else if (Init < NumInits) { 898 // For arrays, just set the expression used for value-initialization 899 // of the "holes" in the array. 900 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 901 ILE->setArrayFiller(Filler); 902 else 903 ILE->setInit(Init, Filler); 904 } else { 905 // For arrays, just set the expression used for value-initialization 906 // of the rest of elements and exit. 907 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 908 ILE->setArrayFiller(Filler); 909 return; 910 } 911 912 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { 913 // Empty initialization requires a constructor call, so 914 // extend the initializer list to include the constructor 915 // call and make a note that we'll need to take another pass 916 // through the initializer list. 917 ILE->updateInit(SemaRef.Context, Init, Filler); 918 RequiresSecondPass = true; 919 } 920 } 921 } else if (InitListExpr *InnerILE 922 = dyn_cast_or_null<InitListExpr>(InitExpr)) { 923 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, 924 ILE, Init, FillWithNoInit); 925 } else if (DesignatedInitUpdateExpr *InnerDIUE = 926 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { 927 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), 928 RequiresSecondPass, ILE, Init, 929 /*FillWithNoInit =*/true); 930 } 931 } 932 } 933 934 static bool hasAnyDesignatedInits(const InitListExpr *IL) { 935 for (const Stmt *Init : *IL) 936 if (Init && isa<DesignatedInitExpr>(Init)) 937 return true; 938 return false; 939 } 940 941 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 942 InitListExpr *IL, QualType &T, bool VerifyOnly, 943 bool TreatUnavailableAsInvalid, 944 bool InOverloadResolution) 945 : SemaRef(S), VerifyOnly(VerifyOnly), 946 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), 947 InOverloadResolution(InOverloadResolution) { 948 if (!VerifyOnly || hasAnyDesignatedInits(IL)) { 949 FullyStructuredList = 950 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); 951 952 // FIXME: Check that IL isn't already the semantic form of some other 953 // InitListExpr. If it is, we'd create a broken AST. 954 if (!VerifyOnly) 955 FullyStructuredList->setSyntacticForm(IL); 956 } 957 958 CheckExplicitInitList(Entity, IL, T, FullyStructuredList, 959 /*TopLevelObject=*/true); 960 961 if (!hadError && FullyStructuredList) { 962 bool RequiresSecondPass = false; 963 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, 964 /*OuterILE=*/nullptr, /*OuterIndex=*/0); 965 if (RequiresSecondPass && !hadError) 966 FillInEmptyInitializations(Entity, FullyStructuredList, 967 RequiresSecondPass, nullptr, 0); 968 } 969 if (hadError && FullyStructuredList) 970 FullyStructuredList->markError(); 971 } 972 973 int InitListChecker::numArrayElements(QualType DeclType) { 974 // FIXME: use a proper constant 975 int maxElements = 0x7FFFFFFF; 976 if (const ConstantArrayType *CAT = 977 SemaRef.Context.getAsConstantArrayType(DeclType)) { 978 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 979 } 980 return maxElements; 981 } 982 983 int InitListChecker::numStructUnionElements(QualType DeclType) { 984 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); 985 int InitializableMembers = 0; 986 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) 987 InitializableMembers += CXXRD->getNumBases(); 988 for (const auto *Field : structDecl->fields()) 989 if (!Field->isUnnamedBitfield()) 990 ++InitializableMembers; 991 992 if (structDecl->isUnion()) 993 return std::min(InitializableMembers, 1); 994 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 995 } 996 997 /// Determine whether Entity is an entity for which it is idiomatic to elide 998 /// the braces in aggregate initialization. 999 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { 1000 // Recursive initialization of the one and only field within an aggregate 1001 // class is considered idiomatic. This case arises in particular for 1002 // initialization of std::array, where the C++ standard suggests the idiom of 1003 // 1004 // std::array<T, N> arr = {1, 2, 3}; 1005 // 1006 // (where std::array is an aggregate struct containing a single array field. 1007 1008 // FIXME: Should aggregate initialization of a struct with a single 1009 // base class and no members also suppress the warning? 1010 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent()) 1011 return false; 1012 1013 auto *ParentRD = 1014 Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); 1015 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) 1016 if (CXXRD->getNumBases()) 1017 return false; 1018 1019 auto FieldIt = ParentRD->field_begin(); 1020 assert(FieldIt != ParentRD->field_end() && 1021 "no fields but have initializer for member?"); 1022 return ++FieldIt == ParentRD->field_end(); 1023 } 1024 1025 /// Check whether the range of the initializer \p ParentIList from element 1026 /// \p Index onwards can be used to initialize an object of type \p T. Update 1027 /// \p Index to indicate how many elements of the list were consumed. 1028 /// 1029 /// This also fills in \p StructuredList, from element \p StructuredIndex 1030 /// onwards, with the fully-braced, desugared form of the initialization. 1031 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 1032 InitListExpr *ParentIList, 1033 QualType T, unsigned &Index, 1034 InitListExpr *StructuredList, 1035 unsigned &StructuredIndex) { 1036 int maxElements = 0; 1037 1038 if (T->isArrayType()) 1039 maxElements = numArrayElements(T); 1040 else if (T->isRecordType()) 1041 maxElements = numStructUnionElements(T); 1042 else if (T->isVectorType()) 1043 maxElements = T->castAs<VectorType>()->getNumElements(); 1044 else 1045 llvm_unreachable("CheckImplicitInitList(): Illegal type"); 1046 1047 if (maxElements == 0) { 1048 if (!VerifyOnly) 1049 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), 1050 diag::err_implicit_empty_initializer); 1051 ++Index; 1052 hadError = true; 1053 return; 1054 } 1055 1056 // Build a structured initializer list corresponding to this subobject. 1057 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( 1058 ParentIList, Index, T, StructuredList, StructuredIndex, 1059 SourceRange(ParentIList->getInit(Index)->getBeginLoc(), 1060 ParentIList->getSourceRange().getEnd())); 1061 unsigned StructuredSubobjectInitIndex = 0; 1062 1063 // Check the element types and build the structural subobject. 1064 unsigned StartIndex = Index; 1065 CheckListElementTypes(Entity, ParentIList, T, 1066 /*SubobjectIsDesignatorContext=*/false, Index, 1067 StructuredSubobjectInitList, 1068 StructuredSubobjectInitIndex); 1069 1070 if (StructuredSubobjectInitList) { 1071 StructuredSubobjectInitList->setType(T); 1072 1073 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 1074 // Update the structured sub-object initializer so that it's ending 1075 // range corresponds with the end of the last initializer it used. 1076 if (EndIndex < ParentIList->getNumInits() && 1077 ParentIList->getInit(EndIndex)) { 1078 SourceLocation EndLoc 1079 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 1080 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 1081 } 1082 1083 // Complain about missing braces. 1084 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && 1085 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && 1086 !isIdiomaticBraceElisionEntity(Entity)) { 1087 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), 1088 diag::warn_missing_braces) 1089 << StructuredSubobjectInitList->getSourceRange() 1090 << FixItHint::CreateInsertion( 1091 StructuredSubobjectInitList->getBeginLoc(), "{") 1092 << FixItHint::CreateInsertion( 1093 SemaRef.getLocForEndOfToken( 1094 StructuredSubobjectInitList->getEndLoc()), 1095 "}"); 1096 } 1097 1098 // Warn if this type won't be an aggregate in future versions of C++. 1099 auto *CXXRD = T->getAsCXXRecordDecl(); 1100 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { 1101 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), 1102 diag::warn_cxx20_compat_aggregate_init_with_ctors) 1103 << StructuredSubobjectInitList->getSourceRange() << T; 1104 } 1105 } 1106 } 1107 1108 /// Warn that \p Entity was of scalar type and was initialized by a 1109 /// single-element braced initializer list. 1110 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, 1111 SourceRange Braces) { 1112 // Don't warn during template instantiation. If the initialization was 1113 // non-dependent, we warned during the initial parse; otherwise, the 1114 // type might not be scalar in some uses of the template. 1115 if (S.inTemplateInstantiation()) 1116 return; 1117 1118 unsigned DiagID = 0; 1119 1120 switch (Entity.getKind()) { 1121 case InitializedEntity::EK_VectorElement: 1122 case InitializedEntity::EK_ComplexElement: 1123 case InitializedEntity::EK_ArrayElement: 1124 case InitializedEntity::EK_Parameter: 1125 case InitializedEntity::EK_Parameter_CF_Audited: 1126 case InitializedEntity::EK_Result: 1127 // Extra braces here are suspicious. 1128 DiagID = diag::warn_braces_around_init; 1129 break; 1130 1131 case InitializedEntity::EK_Member: 1132 // Warn on aggregate initialization but not on ctor init list or 1133 // default member initializer. 1134 if (Entity.getParent()) 1135 DiagID = diag::warn_braces_around_init; 1136 break; 1137 1138 case InitializedEntity::EK_Variable: 1139 case InitializedEntity::EK_LambdaCapture: 1140 // No warning, might be direct-list-initialization. 1141 // FIXME: Should we warn for copy-list-initialization in these cases? 1142 break; 1143 1144 case InitializedEntity::EK_New: 1145 case InitializedEntity::EK_Temporary: 1146 case InitializedEntity::EK_CompoundLiteralInit: 1147 // No warning, braces are part of the syntax of the underlying construct. 1148 break; 1149 1150 case InitializedEntity::EK_RelatedResult: 1151 // No warning, we already warned when initializing the result. 1152 break; 1153 1154 case InitializedEntity::EK_Exception: 1155 case InitializedEntity::EK_Base: 1156 case InitializedEntity::EK_Delegating: 1157 case InitializedEntity::EK_BlockElement: 1158 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 1159 case InitializedEntity::EK_Binding: 1160 case InitializedEntity::EK_StmtExprResult: 1161 llvm_unreachable("unexpected braced scalar init"); 1162 } 1163 1164 if (DiagID) { 1165 S.Diag(Braces.getBegin(), DiagID) 1166 << Entity.getType()->isSizelessBuiltinType() << Braces 1167 << FixItHint::CreateRemoval(Braces.getBegin()) 1168 << FixItHint::CreateRemoval(Braces.getEnd()); 1169 } 1170 } 1171 1172 /// Check whether the initializer \p IList (that was written with explicit 1173 /// braces) can be used to initialize an object of type \p T. 1174 /// 1175 /// This also fills in \p StructuredList with the fully-braced, desugared 1176 /// form of the initialization. 1177 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 1178 InitListExpr *IList, QualType &T, 1179 InitListExpr *StructuredList, 1180 bool TopLevelObject) { 1181 unsigned Index = 0, StructuredIndex = 0; 1182 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 1183 Index, StructuredList, StructuredIndex, TopLevelObject); 1184 if (StructuredList) { 1185 QualType ExprTy = T; 1186 if (!ExprTy->isArrayType()) 1187 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); 1188 if (!VerifyOnly) 1189 IList->setType(ExprTy); 1190 StructuredList->setType(ExprTy); 1191 } 1192 if (hadError) 1193 return; 1194 1195 // Don't complain for incomplete types, since we'll get an error elsewhere. 1196 if (Index < IList->getNumInits() && !T->isIncompleteType()) { 1197 // We have leftover initializers 1198 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || 1199 (SemaRef.getLangOpts().OpenCL && T->isVectorType()); 1200 hadError = ExtraInitsIsError; 1201 if (VerifyOnly) { 1202 return; 1203 } else if (StructuredIndex == 1 && 1204 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == 1205 SIF_None) { 1206 unsigned DK = 1207 ExtraInitsIsError 1208 ? diag::err_excess_initializers_in_char_array_initializer 1209 : diag::ext_excess_initializers_in_char_array_initializer; 1210 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1211 << IList->getInit(Index)->getSourceRange(); 1212 } else if (T->isSizelessBuiltinType()) { 1213 unsigned DK = ExtraInitsIsError 1214 ? diag::err_excess_initializers_for_sizeless_type 1215 : diag::ext_excess_initializers_for_sizeless_type; 1216 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1217 << T << IList->getInit(Index)->getSourceRange(); 1218 } else { 1219 int initKind = T->isArrayType() ? 0 : 1220 T->isVectorType() ? 1 : 1221 T->isScalarType() ? 2 : 1222 T->isUnionType() ? 3 : 1223 4; 1224 1225 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers 1226 : diag::ext_excess_initializers; 1227 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1228 << initKind << IList->getInit(Index)->getSourceRange(); 1229 } 1230 } 1231 1232 if (!VerifyOnly) { 1233 if (T->isScalarType() && IList->getNumInits() == 1 && 1234 !isa<InitListExpr>(IList->getInit(0))) 1235 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); 1236 1237 // Warn if this is a class type that won't be an aggregate in future 1238 // versions of C++. 1239 auto *CXXRD = T->getAsCXXRecordDecl(); 1240 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { 1241 // Don't warn if there's an equivalent default constructor that would be 1242 // used instead. 1243 bool HasEquivCtor = false; 1244 if (IList->getNumInits() == 0) { 1245 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); 1246 HasEquivCtor = CD && !CD->isDeleted(); 1247 } 1248 1249 if (!HasEquivCtor) { 1250 SemaRef.Diag(IList->getBeginLoc(), 1251 diag::warn_cxx20_compat_aggregate_init_with_ctors) 1252 << IList->getSourceRange() << T; 1253 } 1254 } 1255 } 1256 } 1257 1258 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 1259 InitListExpr *IList, 1260 QualType &DeclType, 1261 bool SubobjectIsDesignatorContext, 1262 unsigned &Index, 1263 InitListExpr *StructuredList, 1264 unsigned &StructuredIndex, 1265 bool TopLevelObject) { 1266 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { 1267 // Explicitly braced initializer for complex type can be real+imaginary 1268 // parts. 1269 CheckComplexType(Entity, IList, DeclType, Index, 1270 StructuredList, StructuredIndex); 1271 } else if (DeclType->isScalarType()) { 1272 CheckScalarType(Entity, IList, DeclType, Index, 1273 StructuredList, StructuredIndex); 1274 } else if (DeclType->isVectorType()) { 1275 CheckVectorType(Entity, IList, DeclType, Index, 1276 StructuredList, StructuredIndex); 1277 } else if (DeclType->isRecordType()) { 1278 assert(DeclType->isAggregateType() && 1279 "non-aggregate records should be handed in CheckSubElementType"); 1280 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 1281 auto Bases = 1282 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 1283 CXXRecordDecl::base_class_iterator()); 1284 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1285 Bases = CXXRD->bases(); 1286 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), 1287 SubobjectIsDesignatorContext, Index, StructuredList, 1288 StructuredIndex, TopLevelObject); 1289 } else if (DeclType->isArrayType()) { 1290 llvm::APSInt Zero( 1291 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 1292 false); 1293 CheckArrayType(Entity, IList, DeclType, Zero, 1294 SubobjectIsDesignatorContext, Index, 1295 StructuredList, StructuredIndex); 1296 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 1297 // This type is invalid, issue a diagnostic. 1298 ++Index; 1299 if (!VerifyOnly) 1300 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) 1301 << DeclType; 1302 hadError = true; 1303 } else if (DeclType->isReferenceType()) { 1304 CheckReferenceType(Entity, IList, DeclType, Index, 1305 StructuredList, StructuredIndex); 1306 } else if (DeclType->isObjCObjectType()) { 1307 if (!VerifyOnly) 1308 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; 1309 hadError = true; 1310 } else if (DeclType->isOCLIntelSubgroupAVCType() || 1311 DeclType->isSizelessBuiltinType()) { 1312 // Checks for scalar type are sufficient for these types too. 1313 CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1314 StructuredIndex); 1315 } else { 1316 if (!VerifyOnly) 1317 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) 1318 << DeclType; 1319 hadError = true; 1320 } 1321 } 1322 1323 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 1324 InitListExpr *IList, 1325 QualType ElemType, 1326 unsigned &Index, 1327 InitListExpr *StructuredList, 1328 unsigned &StructuredIndex) { 1329 Expr *expr = IList->getInit(Index); 1330 1331 if (ElemType->isReferenceType()) 1332 return CheckReferenceType(Entity, IList, ElemType, Index, 1333 StructuredList, StructuredIndex); 1334 1335 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 1336 if (SubInitList->getNumInits() == 1 && 1337 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == 1338 SIF_None) { 1339 // FIXME: It would be more faithful and no less correct to include an 1340 // InitListExpr in the semantic form of the initializer list in this case. 1341 expr = SubInitList->getInit(0); 1342 } 1343 // Nested aggregate initialization and C++ initialization are handled later. 1344 } else if (isa<ImplicitValueInitExpr>(expr)) { 1345 // This happens during template instantiation when we see an InitListExpr 1346 // that we've already checked once. 1347 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && 1348 "found implicit initialization for the wrong type"); 1349 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1350 ++Index; 1351 return; 1352 } 1353 1354 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { 1355 // C++ [dcl.init.aggr]p2: 1356 // Each member is copy-initialized from the corresponding 1357 // initializer-clause. 1358 1359 // FIXME: Better EqualLoc? 1360 InitializationKind Kind = 1361 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); 1362 1363 // Vector elements can be initialized from other vectors in which case 1364 // we need initialization entity with a type of a vector (and not a vector 1365 // element!) initializing multiple vector elements. 1366 auto TmpEntity = 1367 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) 1368 ? InitializedEntity::InitializeTemporary(ElemType) 1369 : Entity; 1370 1371 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, 1372 /*TopLevelOfInitList*/ true); 1373 1374 // C++14 [dcl.init.aggr]p13: 1375 // If the assignment-expression can initialize a member, the member is 1376 // initialized. Otherwise [...] brace elision is assumed 1377 // 1378 // Brace elision is never performed if the element is not an 1379 // assignment-expression. 1380 if (Seq || isa<InitListExpr>(expr)) { 1381 if (!VerifyOnly) { 1382 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); 1383 if (Result.isInvalid()) 1384 hadError = true; 1385 1386 UpdateStructuredListElement(StructuredList, StructuredIndex, 1387 Result.getAs<Expr>()); 1388 } else if (!Seq) { 1389 hadError = true; 1390 } else if (StructuredList) { 1391 UpdateStructuredListElement(StructuredList, StructuredIndex, 1392 getDummyInit()); 1393 } 1394 ++Index; 1395 return; 1396 } 1397 1398 // Fall through for subaggregate initialization 1399 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { 1400 // FIXME: Need to handle atomic aggregate types with implicit init lists. 1401 return CheckScalarType(Entity, IList, ElemType, Index, 1402 StructuredList, StructuredIndex); 1403 } else if (const ArrayType *arrayType = 1404 SemaRef.Context.getAsArrayType(ElemType)) { 1405 // arrayType can be incomplete if we're initializing a flexible 1406 // array member. There's nothing we can do with the completed 1407 // type here, though. 1408 1409 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { 1410 // FIXME: Should we do this checking in verify-only mode? 1411 if (!VerifyOnly) 1412 CheckStringInit(expr, ElemType, arrayType, SemaRef); 1413 if (StructuredList) 1414 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1415 ++Index; 1416 return; 1417 } 1418 1419 // Fall through for subaggregate initialization. 1420 1421 } else { 1422 assert((ElemType->isRecordType() || ElemType->isVectorType() || 1423 ElemType->isOpenCLSpecificType()) && "Unexpected type"); 1424 1425 // C99 6.7.8p13: 1426 // 1427 // The initializer for a structure or union object that has 1428 // automatic storage duration shall be either an initializer 1429 // list as described below, or a single expression that has 1430 // compatible structure or union type. In the latter case, the 1431 // initial value of the object, including unnamed members, is 1432 // that of the expression. 1433 ExprResult ExprRes = expr; 1434 if (SemaRef.CheckSingleAssignmentConstraints( 1435 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { 1436 if (ExprRes.isInvalid()) 1437 hadError = true; 1438 else { 1439 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); 1440 if (ExprRes.isInvalid()) 1441 hadError = true; 1442 } 1443 UpdateStructuredListElement(StructuredList, StructuredIndex, 1444 ExprRes.getAs<Expr>()); 1445 ++Index; 1446 return; 1447 } 1448 ExprRes.get(); 1449 // Fall through for subaggregate initialization 1450 } 1451 1452 // C++ [dcl.init.aggr]p12: 1453 // 1454 // [...] Otherwise, if the member is itself a non-empty 1455 // subaggregate, brace elision is assumed and the initializer is 1456 // considered for the initialization of the first member of 1457 // the subaggregate. 1458 // OpenCL vector initializer is handled elsewhere. 1459 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || 1460 ElemType->isAggregateType()) { 1461 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 1462 StructuredIndex); 1463 ++StructuredIndex; 1464 } else { 1465 if (!VerifyOnly) { 1466 // We cannot initialize this element, so let PerformCopyInitialization 1467 // produce the appropriate diagnostic. We already checked that this 1468 // initialization will fail. 1469 ExprResult Copy = 1470 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, 1471 /*TopLevelOfInitList=*/true); 1472 (void)Copy; 1473 assert(Copy.isInvalid() && 1474 "expected non-aggregate initialization to fail"); 1475 } 1476 hadError = true; 1477 ++Index; 1478 ++StructuredIndex; 1479 } 1480 } 1481 1482 void InitListChecker::CheckComplexType(const InitializedEntity &Entity, 1483 InitListExpr *IList, QualType DeclType, 1484 unsigned &Index, 1485 InitListExpr *StructuredList, 1486 unsigned &StructuredIndex) { 1487 assert(Index == 0 && "Index in explicit init list must be zero"); 1488 1489 // As an extension, clang supports complex initializers, which initialize 1490 // a complex number component-wise. When an explicit initializer list for 1491 // a complex number contains two two initializers, this extension kicks in: 1492 // it exepcts the initializer list to contain two elements convertible to 1493 // the element type of the complex type. The first element initializes 1494 // the real part, and the second element intitializes the imaginary part. 1495 1496 if (IList->getNumInits() != 2) 1497 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1498 StructuredIndex); 1499 1500 // This is an extension in C. (The builtin _Complex type does not exist 1501 // in the C++ standard.) 1502 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) 1503 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) 1504 << IList->getSourceRange(); 1505 1506 // Initialize the complex number. 1507 QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); 1508 InitializedEntity ElementEntity = 1509 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1510 1511 for (unsigned i = 0; i < 2; ++i) { 1512 ElementEntity.setElementIndex(Index); 1513 CheckSubElementType(ElementEntity, IList, elementType, Index, 1514 StructuredList, StructuredIndex); 1515 } 1516 } 1517 1518 void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 1519 InitListExpr *IList, QualType DeclType, 1520 unsigned &Index, 1521 InitListExpr *StructuredList, 1522 unsigned &StructuredIndex) { 1523 if (Index >= IList->getNumInits()) { 1524 if (!VerifyOnly) { 1525 if (DeclType->isSizelessBuiltinType()) 1526 SemaRef.Diag(IList->getBeginLoc(), 1527 SemaRef.getLangOpts().CPlusPlus11 1528 ? diag::warn_cxx98_compat_empty_sizeless_initializer 1529 : diag::err_empty_sizeless_initializer) 1530 << DeclType << IList->getSourceRange(); 1531 else 1532 SemaRef.Diag(IList->getBeginLoc(), 1533 SemaRef.getLangOpts().CPlusPlus11 1534 ? diag::warn_cxx98_compat_empty_scalar_initializer 1535 : diag::err_empty_scalar_initializer) 1536 << IList->getSourceRange(); 1537 } 1538 hadError = !SemaRef.getLangOpts().CPlusPlus11; 1539 ++Index; 1540 ++StructuredIndex; 1541 return; 1542 } 1543 1544 Expr *expr = IList->getInit(Index); 1545 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 1546 // FIXME: This is invalid, and accepting it causes overload resolution 1547 // to pick the wrong overload in some corner cases. 1548 if (!VerifyOnly) 1549 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init) 1550 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); 1551 1552 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 1553 StructuredIndex); 1554 return; 1555 } else if (isa<DesignatedInitExpr>(expr)) { 1556 if (!VerifyOnly) 1557 SemaRef.Diag(expr->getBeginLoc(), 1558 diag::err_designator_for_scalar_or_sizeless_init) 1559 << DeclType->isSizelessBuiltinType() << DeclType 1560 << expr->getSourceRange(); 1561 hadError = true; 1562 ++Index; 1563 ++StructuredIndex; 1564 return; 1565 } 1566 1567 ExprResult Result; 1568 if (VerifyOnly) { 1569 if (SemaRef.CanPerformCopyInitialization(Entity, expr)) 1570 Result = getDummyInit(); 1571 else 1572 Result = ExprError(); 1573 } else { 1574 Result = 1575 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, 1576 /*TopLevelOfInitList=*/true); 1577 } 1578 1579 Expr *ResultExpr = nullptr; 1580 1581 if (Result.isInvalid()) 1582 hadError = true; // types weren't compatible. 1583 else { 1584 ResultExpr = Result.getAs<Expr>(); 1585 1586 if (ResultExpr != expr && !VerifyOnly) { 1587 // The type was promoted, update initializer list. 1588 // FIXME: Why are we updating the syntactic init list? 1589 IList->setInit(Index, ResultExpr); 1590 } 1591 } 1592 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1593 ++Index; 1594 } 1595 1596 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 1597 InitListExpr *IList, QualType DeclType, 1598 unsigned &Index, 1599 InitListExpr *StructuredList, 1600 unsigned &StructuredIndex) { 1601 if (Index >= IList->getNumInits()) { 1602 // FIXME: It would be wonderful if we could point at the actual member. In 1603 // general, it would be useful to pass location information down the stack, 1604 // so that we know the location (or decl) of the "current object" being 1605 // initialized. 1606 if (!VerifyOnly) 1607 SemaRef.Diag(IList->getBeginLoc(), 1608 diag::err_init_reference_member_uninitialized) 1609 << DeclType << IList->getSourceRange(); 1610 hadError = true; 1611 ++Index; 1612 ++StructuredIndex; 1613 return; 1614 } 1615 1616 Expr *expr = IList->getInit(Index); 1617 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { 1618 if (!VerifyOnly) 1619 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) 1620 << DeclType << IList->getSourceRange(); 1621 hadError = true; 1622 ++Index; 1623 ++StructuredIndex; 1624 return; 1625 } 1626 1627 ExprResult Result; 1628 if (VerifyOnly) { 1629 if (SemaRef.CanPerformCopyInitialization(Entity,expr)) 1630 Result = getDummyInit(); 1631 else 1632 Result = ExprError(); 1633 } else { 1634 Result = 1635 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, 1636 /*TopLevelOfInitList=*/true); 1637 } 1638 1639 if (Result.isInvalid()) 1640 hadError = true; 1641 1642 expr = Result.getAs<Expr>(); 1643 // FIXME: Why are we updating the syntactic init list? 1644 if (!VerifyOnly && expr) 1645 IList->setInit(Index, expr); 1646 1647 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1648 ++Index; 1649 } 1650 1651 void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 1652 InitListExpr *IList, QualType DeclType, 1653 unsigned &Index, 1654 InitListExpr *StructuredList, 1655 unsigned &StructuredIndex) { 1656 const VectorType *VT = DeclType->castAs<VectorType>(); 1657 unsigned maxElements = VT->getNumElements(); 1658 unsigned numEltsInit = 0; 1659 QualType elementType = VT->getElementType(); 1660 1661 if (Index >= IList->getNumInits()) { 1662 // Make sure the element type can be value-initialized. 1663 CheckEmptyInitializable( 1664 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1665 IList->getEndLoc()); 1666 return; 1667 } 1668 1669 if (!SemaRef.getLangOpts().OpenCL) { 1670 // If the initializing element is a vector, try to copy-initialize 1671 // instead of breaking it apart (which is doomed to failure anyway). 1672 Expr *Init = IList->getInit(Index); 1673 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 1674 ExprResult Result; 1675 if (VerifyOnly) { 1676 if (SemaRef.CanPerformCopyInitialization(Entity, Init)) 1677 Result = getDummyInit(); 1678 else 1679 Result = ExprError(); 1680 } else { 1681 Result = 1682 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, 1683 /*TopLevelOfInitList=*/true); 1684 } 1685 1686 Expr *ResultExpr = nullptr; 1687 if (Result.isInvalid()) 1688 hadError = true; // types weren't compatible. 1689 else { 1690 ResultExpr = Result.getAs<Expr>(); 1691 1692 if (ResultExpr != Init && !VerifyOnly) { 1693 // The type was promoted, update initializer list. 1694 // FIXME: Why are we updating the syntactic init list? 1695 IList->setInit(Index, ResultExpr); 1696 } 1697 } 1698 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1699 ++Index; 1700 return; 1701 } 1702 1703 InitializedEntity ElementEntity = 1704 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1705 1706 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 1707 // Don't attempt to go past the end of the init list 1708 if (Index >= IList->getNumInits()) { 1709 CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); 1710 break; 1711 } 1712 1713 ElementEntity.setElementIndex(Index); 1714 CheckSubElementType(ElementEntity, IList, elementType, Index, 1715 StructuredList, StructuredIndex); 1716 } 1717 1718 if (VerifyOnly) 1719 return; 1720 1721 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); 1722 const VectorType *T = Entity.getType()->castAs<VectorType>(); 1723 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || 1724 T->getVectorKind() == VectorType::NeonPolyVector)) { 1725 // The ability to use vector initializer lists is a GNU vector extension 1726 // and is unrelated to the NEON intrinsics in arm_neon.h. On little 1727 // endian machines it works fine, however on big endian machines it 1728 // exhibits surprising behaviour: 1729 // 1730 // uint32x2_t x = {42, 64}; 1731 // return vget_lane_u32(x, 0); // Will return 64. 1732 // 1733 // Because of this, explicitly call out that it is non-portable. 1734 // 1735 SemaRef.Diag(IList->getBeginLoc(), 1736 diag::warn_neon_vector_initializer_non_portable); 1737 1738 const char *typeCode; 1739 unsigned typeSize = SemaRef.Context.getTypeSize(elementType); 1740 1741 if (elementType->isFloatingType()) 1742 typeCode = "f"; 1743 else if (elementType->isSignedIntegerType()) 1744 typeCode = "s"; 1745 else if (elementType->isUnsignedIntegerType()) 1746 typeCode = "u"; 1747 else 1748 llvm_unreachable("Invalid element type!"); 1749 1750 SemaRef.Diag(IList->getBeginLoc(), 1751 SemaRef.Context.getTypeSize(VT) > 64 1752 ? diag::note_neon_vector_initializer_non_portable_q 1753 : diag::note_neon_vector_initializer_non_portable) 1754 << typeCode << typeSize; 1755 } 1756 1757 return; 1758 } 1759 1760 InitializedEntity ElementEntity = 1761 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1762 1763 // OpenCL initializers allows vectors to be constructed from vectors. 1764 for (unsigned i = 0; i < maxElements; ++i) { 1765 // Don't attempt to go past the end of the init list 1766 if (Index >= IList->getNumInits()) 1767 break; 1768 1769 ElementEntity.setElementIndex(Index); 1770 1771 QualType IType = IList->getInit(Index)->getType(); 1772 if (!IType->isVectorType()) { 1773 CheckSubElementType(ElementEntity, IList, elementType, Index, 1774 StructuredList, StructuredIndex); 1775 ++numEltsInit; 1776 } else { 1777 QualType VecType; 1778 const VectorType *IVT = IType->castAs<VectorType>(); 1779 unsigned numIElts = IVT->getNumElements(); 1780 1781 if (IType->isExtVectorType()) 1782 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 1783 else 1784 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 1785 IVT->getVectorKind()); 1786 CheckSubElementType(ElementEntity, IList, VecType, Index, 1787 StructuredList, StructuredIndex); 1788 numEltsInit += numIElts; 1789 } 1790 } 1791 1792 // OpenCL requires all elements to be initialized. 1793 if (numEltsInit != maxElements) { 1794 if (!VerifyOnly) 1795 SemaRef.Diag(IList->getBeginLoc(), 1796 diag::err_vector_incorrect_num_initializers) 1797 << (numEltsInit < maxElements) << maxElements << numEltsInit; 1798 hadError = true; 1799 } 1800 } 1801 1802 /// Check if the type of a class element has an accessible destructor, and marks 1803 /// it referenced. Returns true if we shouldn't form a reference to the 1804 /// destructor. 1805 /// 1806 /// Aggregate initialization requires a class element's destructor be 1807 /// accessible per 11.6.1 [dcl.init.aggr]: 1808 /// 1809 /// The destructor for each element of class type is potentially invoked 1810 /// (15.4 [class.dtor]) from the context where the aggregate initialization 1811 /// occurs. 1812 static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, 1813 Sema &SemaRef) { 1814 auto *CXXRD = ElementType->getAsCXXRecordDecl(); 1815 if (!CXXRD) 1816 return false; 1817 1818 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); 1819 SemaRef.CheckDestructorAccess(Loc, Destructor, 1820 SemaRef.PDiag(diag::err_access_dtor_temp) 1821 << ElementType); 1822 SemaRef.MarkFunctionReferenced(Loc, Destructor); 1823 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); 1824 } 1825 1826 void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 1827 InitListExpr *IList, QualType &DeclType, 1828 llvm::APSInt elementIndex, 1829 bool SubobjectIsDesignatorContext, 1830 unsigned &Index, 1831 InitListExpr *StructuredList, 1832 unsigned &StructuredIndex) { 1833 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 1834 1835 if (!VerifyOnly) { 1836 if (checkDestructorReference(arrayType->getElementType(), 1837 IList->getEndLoc(), SemaRef)) { 1838 hadError = true; 1839 return; 1840 } 1841 } 1842 1843 // Check for the special-case of initializing an array with a string. 1844 if (Index < IList->getNumInits()) { 1845 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == 1846 SIF_None) { 1847 // We place the string literal directly into the resulting 1848 // initializer list. This is the only place where the structure 1849 // of the structured initializer list doesn't match exactly, 1850 // because doing so would involve allocating one character 1851 // constant for each string. 1852 // FIXME: Should we do these checks in verify-only mode too? 1853 if (!VerifyOnly) 1854 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); 1855 if (StructuredList) { 1856 UpdateStructuredListElement(StructuredList, StructuredIndex, 1857 IList->getInit(Index)); 1858 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1859 } 1860 ++Index; 1861 return; 1862 } 1863 } 1864 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1865 // Check for VLAs; in standard C it would be possible to check this 1866 // earlier, but I don't know where clang accepts VLAs (gcc accepts 1867 // them in all sorts of strange places). 1868 if (!VerifyOnly) 1869 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), 1870 diag::err_variable_object_no_init) 1871 << VAT->getSizeExpr()->getSourceRange(); 1872 hadError = true; 1873 ++Index; 1874 ++StructuredIndex; 1875 return; 1876 } 1877 1878 // We might know the maximum number of elements in advance. 1879 llvm::APSInt maxElements(elementIndex.getBitWidth(), 1880 elementIndex.isUnsigned()); 1881 bool maxElementsKnown = false; 1882 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1883 maxElements = CAT->getSize(); 1884 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1885 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1886 maxElementsKnown = true; 1887 } 1888 1889 QualType elementType = arrayType->getElementType(); 1890 while (Index < IList->getNumInits()) { 1891 Expr *Init = IList->getInit(Index); 1892 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1893 // If we're not the subobject that matches up with the '{' for 1894 // the designator, we shouldn't be handling the 1895 // designator. Return immediately. 1896 if (!SubobjectIsDesignatorContext) 1897 return; 1898 1899 // Handle this designated initializer. elementIndex will be 1900 // updated to be the next array element we'll initialize. 1901 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1902 DeclType, nullptr, &elementIndex, Index, 1903 StructuredList, StructuredIndex, true, 1904 false)) { 1905 hadError = true; 1906 continue; 1907 } 1908 1909 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1910 maxElements = maxElements.extend(elementIndex.getBitWidth()); 1911 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1912 elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1913 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1914 1915 // If the array is of incomplete type, keep track of the number of 1916 // elements in the initializer. 1917 if (!maxElementsKnown && elementIndex > maxElements) 1918 maxElements = elementIndex; 1919 1920 continue; 1921 } 1922 1923 // If we know the maximum number of elements, and we've already 1924 // hit it, stop consuming elements in the initializer list. 1925 if (maxElementsKnown && elementIndex == maxElements) 1926 break; 1927 1928 InitializedEntity ElementEntity = 1929 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1930 Entity); 1931 // Check this element. 1932 CheckSubElementType(ElementEntity, IList, elementType, Index, 1933 StructuredList, StructuredIndex); 1934 ++elementIndex; 1935 1936 // If the array is of incomplete type, keep track of the number of 1937 // elements in the initializer. 1938 if (!maxElementsKnown && elementIndex > maxElements) 1939 maxElements = elementIndex; 1940 } 1941 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { 1942 // If this is an incomplete array type, the actual type needs to 1943 // be calculated here. 1944 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1945 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { 1946 // Sizing an array implicitly to zero is not allowed by ISO C, 1947 // but is supported by GNU. 1948 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); 1949 } 1950 1951 DeclType = SemaRef.Context.getConstantArrayType( 1952 elementType, maxElements, nullptr, ArrayType::Normal, 0); 1953 } 1954 if (!hadError) { 1955 // If there are any members of the array that get value-initialized, check 1956 // that is possible. That happens if we know the bound and don't have 1957 // enough elements, or if we're performing an array new with an unknown 1958 // bound. 1959 if ((maxElementsKnown && elementIndex < maxElements) || 1960 Entity.isVariableLengthArrayNew()) 1961 CheckEmptyInitializable( 1962 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1963 IList->getEndLoc()); 1964 } 1965 } 1966 1967 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, 1968 Expr *InitExpr, 1969 FieldDecl *Field, 1970 bool TopLevelObject) { 1971 // Handle GNU flexible array initializers. 1972 unsigned FlexArrayDiag; 1973 if (isa<InitListExpr>(InitExpr) && 1974 cast<InitListExpr>(InitExpr)->getNumInits() == 0) { 1975 // Empty flexible array init always allowed as an extension 1976 FlexArrayDiag = diag::ext_flexible_array_init; 1977 } else if (SemaRef.getLangOpts().CPlusPlus) { 1978 // Disallow flexible array init in C++; it is not required for gcc 1979 // compatibility, and it needs work to IRGen correctly in general. 1980 FlexArrayDiag = diag::err_flexible_array_init; 1981 } else if (!TopLevelObject) { 1982 // Disallow flexible array init on non-top-level object 1983 FlexArrayDiag = diag::err_flexible_array_init; 1984 } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 1985 // Disallow flexible array init on anything which is not a variable. 1986 FlexArrayDiag = diag::err_flexible_array_init; 1987 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { 1988 // Disallow flexible array init on local variables. 1989 FlexArrayDiag = diag::err_flexible_array_init; 1990 } else { 1991 // Allow other cases. 1992 FlexArrayDiag = diag::ext_flexible_array_init; 1993 } 1994 1995 if (!VerifyOnly) { 1996 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) 1997 << InitExpr->getBeginLoc(); 1998 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1999 << Field; 2000 } 2001 2002 return FlexArrayDiag != diag::ext_flexible_array_init; 2003 } 2004 2005 void InitListChecker::CheckStructUnionTypes( 2006 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, 2007 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, 2008 bool SubobjectIsDesignatorContext, unsigned &Index, 2009 InitListExpr *StructuredList, unsigned &StructuredIndex, 2010 bool TopLevelObject) { 2011 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); 2012 2013 // If the record is invalid, some of it's members are invalid. To avoid 2014 // confusion, we forgo checking the intializer for the entire record. 2015 if (structDecl->isInvalidDecl()) { 2016 // Assume it was supposed to consume a single initializer. 2017 ++Index; 2018 hadError = true; 2019 return; 2020 } 2021 2022 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 2023 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 2024 2025 if (!VerifyOnly) 2026 for (FieldDecl *FD : RD->fields()) { 2027 QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); 2028 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { 2029 hadError = true; 2030 return; 2031 } 2032 } 2033 2034 // If there's a default initializer, use it. 2035 if (isa<CXXRecordDecl>(RD) && 2036 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { 2037 if (!StructuredList) 2038 return; 2039 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 2040 Field != FieldEnd; ++Field) { 2041 if (Field->hasInClassInitializer()) { 2042 StructuredList->setInitializedFieldInUnion(*Field); 2043 // FIXME: Actually build a CXXDefaultInitExpr? 2044 return; 2045 } 2046 } 2047 } 2048 2049 // Value-initialize the first member of the union that isn't an unnamed 2050 // bitfield. 2051 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 2052 Field != FieldEnd; ++Field) { 2053 if (!Field->isUnnamedBitfield()) { 2054 CheckEmptyInitializable( 2055 InitializedEntity::InitializeMember(*Field, &Entity), 2056 IList->getEndLoc()); 2057 if (StructuredList) 2058 StructuredList->setInitializedFieldInUnion(*Field); 2059 break; 2060 } 2061 } 2062 return; 2063 } 2064 2065 bool InitializedSomething = false; 2066 2067 // If we have any base classes, they are initialized prior to the fields. 2068 for (auto &Base : Bases) { 2069 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; 2070 2071 // Designated inits always initialize fields, so if we see one, all 2072 // remaining base classes have no explicit initializer. 2073 if (Init && isa<DesignatedInitExpr>(Init)) 2074 Init = nullptr; 2075 2076 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); 2077 InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 2078 SemaRef.Context, &Base, false, &Entity); 2079 if (Init) { 2080 CheckSubElementType(BaseEntity, IList, Base.getType(), Index, 2081 StructuredList, StructuredIndex); 2082 InitializedSomething = true; 2083 } else { 2084 CheckEmptyInitializable(BaseEntity, InitLoc); 2085 } 2086 2087 if (!VerifyOnly) 2088 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { 2089 hadError = true; 2090 return; 2091 } 2092 } 2093 2094 // If structDecl is a forward declaration, this loop won't do 2095 // anything except look at designated initializers; That's okay, 2096 // because an error should get printed out elsewhere. It might be 2097 // worthwhile to skip over the rest of the initializer, though. 2098 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 2099 RecordDecl::field_iterator FieldEnd = RD->field_end(); 2100 bool CheckForMissingFields = 2101 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); 2102 bool HasDesignatedInit = false; 2103 2104 while (Index < IList->getNumInits()) { 2105 Expr *Init = IList->getInit(Index); 2106 SourceLocation InitLoc = Init->getBeginLoc(); 2107 2108 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 2109 // If we're not the subobject that matches up with the '{' for 2110 // the designator, we shouldn't be handling the 2111 // designator. Return immediately. 2112 if (!SubobjectIsDesignatorContext) 2113 return; 2114 2115 HasDesignatedInit = true; 2116 2117 // Handle this designated initializer. Field will be updated to 2118 // the next field that we'll be initializing. 2119 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 2120 DeclType, &Field, nullptr, Index, 2121 StructuredList, StructuredIndex, 2122 true, TopLevelObject)) 2123 hadError = true; 2124 else if (!VerifyOnly) { 2125 // Find the field named by the designated initializer. 2126 RecordDecl::field_iterator F = RD->field_begin(); 2127 while (std::next(F) != Field) 2128 ++F; 2129 QualType ET = SemaRef.Context.getBaseElementType(F->getType()); 2130 if (checkDestructorReference(ET, InitLoc, SemaRef)) { 2131 hadError = true; 2132 return; 2133 } 2134 } 2135 2136 InitializedSomething = true; 2137 2138 // Disable check for missing fields when designators are used. 2139 // This matches gcc behaviour. 2140 CheckForMissingFields = false; 2141 continue; 2142 } 2143 2144 if (Field == FieldEnd) { 2145 // We've run out of fields. We're done. 2146 break; 2147 } 2148 2149 // We've already initialized a member of a union. We're done. 2150 if (InitializedSomething && DeclType->isUnionType()) 2151 break; 2152 2153 // If we've hit the flexible array member at the end, we're done. 2154 if (Field->getType()->isIncompleteArrayType()) 2155 break; 2156 2157 if (Field->isUnnamedBitfield()) { 2158 // Don't initialize unnamed bitfields, e.g. "int : 20;" 2159 ++Field; 2160 continue; 2161 } 2162 2163 // Make sure we can use this declaration. 2164 bool InvalidUse; 2165 if (VerifyOnly) 2166 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2167 else 2168 InvalidUse = SemaRef.DiagnoseUseOfDecl( 2169 *Field, IList->getInit(Index)->getBeginLoc()); 2170 if (InvalidUse) { 2171 ++Index; 2172 ++Field; 2173 hadError = true; 2174 continue; 2175 } 2176 2177 if (!VerifyOnly) { 2178 QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); 2179 if (checkDestructorReference(ET, InitLoc, SemaRef)) { 2180 hadError = true; 2181 return; 2182 } 2183 } 2184 2185 InitializedEntity MemberEntity = 2186 InitializedEntity::InitializeMember(*Field, &Entity); 2187 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2188 StructuredList, StructuredIndex); 2189 InitializedSomething = true; 2190 2191 if (DeclType->isUnionType() && StructuredList) { 2192 // Initialize the first field within the union. 2193 StructuredList->setInitializedFieldInUnion(*Field); 2194 } 2195 2196 ++Field; 2197 } 2198 2199 // Emit warnings for missing struct field initializers. 2200 if (!VerifyOnly && InitializedSomething && CheckForMissingFields && 2201 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && 2202 !DeclType->isUnionType()) { 2203 // It is possible we have one or more unnamed bitfields remaining. 2204 // Find first (if any) named field and emit warning. 2205 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 2206 it != end; ++it) { 2207 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { 2208 SemaRef.Diag(IList->getSourceRange().getEnd(), 2209 diag::warn_missing_field_initializers) << *it; 2210 break; 2211 } 2212 } 2213 } 2214 2215 // Check that any remaining fields can be value-initialized if we're not 2216 // building a structured list. (If we are, we'll check this later.) 2217 if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && 2218 !Field->getType()->isIncompleteArrayType()) { 2219 for (; Field != FieldEnd && !hadError; ++Field) { 2220 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) 2221 CheckEmptyInitializable( 2222 InitializedEntity::InitializeMember(*Field, &Entity), 2223 IList->getEndLoc()); 2224 } 2225 } 2226 2227 // Check that the types of the remaining fields have accessible destructors. 2228 if (!VerifyOnly) { 2229 // If the initializer expression has a designated initializer, check the 2230 // elements for which a designated initializer is not provided too. 2231 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() 2232 : Field; 2233 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { 2234 QualType ET = SemaRef.Context.getBaseElementType(I->getType()); 2235 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { 2236 hadError = true; 2237 return; 2238 } 2239 } 2240 } 2241 2242 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 2243 Index >= IList->getNumInits()) 2244 return; 2245 2246 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, 2247 TopLevelObject)) { 2248 hadError = true; 2249 ++Index; 2250 return; 2251 } 2252 2253 InitializedEntity MemberEntity = 2254 InitializedEntity::InitializeMember(*Field, &Entity); 2255 2256 if (isa<InitListExpr>(IList->getInit(Index))) 2257 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2258 StructuredList, StructuredIndex); 2259 else 2260 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 2261 StructuredList, StructuredIndex); 2262 } 2263 2264 /// Expand a field designator that refers to a member of an 2265 /// anonymous struct or union into a series of field designators that 2266 /// refers to the field within the appropriate subobject. 2267 /// 2268 static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 2269 DesignatedInitExpr *DIE, 2270 unsigned DesigIdx, 2271 IndirectFieldDecl *IndirectField) { 2272 typedef DesignatedInitExpr::Designator Designator; 2273 2274 // Build the replacement designators. 2275 SmallVector<Designator, 4> Replacements; 2276 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 2277 PE = IndirectField->chain_end(); PI != PE; ++PI) { 2278 if (PI + 1 == PE) 2279 Replacements.push_back(Designator((IdentifierInfo *)nullptr, 2280 DIE->getDesignator(DesigIdx)->getDotLoc(), 2281 DIE->getDesignator(DesigIdx)->getFieldLoc())); 2282 else 2283 Replacements.push_back(Designator((IdentifierInfo *)nullptr, 2284 SourceLocation(), SourceLocation())); 2285 assert(isa<FieldDecl>(*PI)); 2286 Replacements.back().setField(cast<FieldDecl>(*PI)); 2287 } 2288 2289 // Expand the current designator into the set of replacement 2290 // designators, so we have a full subobject path down to where the 2291 // member of the anonymous struct/union is actually stored. 2292 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 2293 &Replacements[0] + Replacements.size()); 2294 } 2295 2296 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, 2297 DesignatedInitExpr *DIE) { 2298 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; 2299 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); 2300 for (unsigned I = 0; I < NumIndexExprs; ++I) 2301 IndexExprs[I] = DIE->getSubExpr(I + 1); 2302 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), 2303 IndexExprs, 2304 DIE->getEqualOrColonLoc(), 2305 DIE->usesGNUSyntax(), DIE->getInit()); 2306 } 2307 2308 namespace { 2309 2310 // Callback to only accept typo corrections that are for field members of 2311 // the given struct or union. 2312 class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { 2313 public: 2314 explicit FieldInitializerValidatorCCC(RecordDecl *RD) 2315 : Record(RD) {} 2316 2317 bool ValidateCandidate(const TypoCorrection &candidate) override { 2318 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); 2319 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); 2320 } 2321 2322 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2323 return std::make_unique<FieldInitializerValidatorCCC>(*this); 2324 } 2325 2326 private: 2327 RecordDecl *Record; 2328 }; 2329 2330 } // end anonymous namespace 2331 2332 /// Check the well-formedness of a C99 designated initializer. 2333 /// 2334 /// Determines whether the designated initializer @p DIE, which 2335 /// resides at the given @p Index within the initializer list @p 2336 /// IList, is well-formed for a current object of type @p DeclType 2337 /// (C99 6.7.8). The actual subobject that this designator refers to 2338 /// within the current subobject is returned in either 2339 /// @p NextField or @p NextElementIndex (whichever is appropriate). 2340 /// 2341 /// @param IList The initializer list in which this designated 2342 /// initializer occurs. 2343 /// 2344 /// @param DIE The designated initializer expression. 2345 /// 2346 /// @param DesigIdx The index of the current designator. 2347 /// 2348 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), 2349 /// into which the designation in @p DIE should refer. 2350 /// 2351 /// @param NextField If non-NULL and the first designator in @p DIE is 2352 /// a field, this will be set to the field declaration corresponding 2353 /// to the field named by the designator. On input, this is expected to be 2354 /// the next field that would be initialized in the absence of designation, 2355 /// if the complete object being initialized is a struct. 2356 /// 2357 /// @param NextElementIndex If non-NULL and the first designator in @p 2358 /// DIE is an array designator or GNU array-range designator, this 2359 /// will be set to the last index initialized by this designator. 2360 /// 2361 /// @param Index Index into @p IList where the designated initializer 2362 /// @p DIE occurs. 2363 /// 2364 /// @param StructuredList The initializer list expression that 2365 /// describes all of the subobject initializers in the order they'll 2366 /// actually be initialized. 2367 /// 2368 /// @returns true if there was an error, false otherwise. 2369 bool 2370 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 2371 InitListExpr *IList, 2372 DesignatedInitExpr *DIE, 2373 unsigned DesigIdx, 2374 QualType &CurrentObjectType, 2375 RecordDecl::field_iterator *NextField, 2376 llvm::APSInt *NextElementIndex, 2377 unsigned &Index, 2378 InitListExpr *StructuredList, 2379 unsigned &StructuredIndex, 2380 bool FinishSubobjectInit, 2381 bool TopLevelObject) { 2382 if (DesigIdx == DIE->size()) { 2383 // C++20 designated initialization can result in direct-list-initialization 2384 // of the designated subobject. This is the only way that we can end up 2385 // performing direct initialization as part of aggregate initialization, so 2386 // it needs special handling. 2387 if (DIE->isDirectInit()) { 2388 Expr *Init = DIE->getInit(); 2389 assert(isa<InitListExpr>(Init) && 2390 "designator result in direct non-list initialization?"); 2391 InitializationKind Kind = InitializationKind::CreateDirectList( 2392 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); 2393 InitializationSequence Seq(SemaRef, Entity, Kind, Init, 2394 /*TopLevelOfInitList*/ true); 2395 if (StructuredList) { 2396 ExprResult Result = VerifyOnly 2397 ? getDummyInit() 2398 : Seq.Perform(SemaRef, Entity, Kind, Init); 2399 UpdateStructuredListElement(StructuredList, StructuredIndex, 2400 Result.get()); 2401 } 2402 ++Index; 2403 return !Seq; 2404 } 2405 2406 // Check the actual initialization for the designated object type. 2407 bool prevHadError = hadError; 2408 2409 // Temporarily remove the designator expression from the 2410 // initializer list that the child calls see, so that we don't try 2411 // to re-process the designator. 2412 unsigned OldIndex = Index; 2413 IList->setInit(OldIndex, DIE->getInit()); 2414 2415 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 2416 StructuredList, StructuredIndex); 2417 2418 // Restore the designated initializer expression in the syntactic 2419 // form of the initializer list. 2420 if (IList->getInit(OldIndex) != DIE->getInit()) 2421 DIE->setInit(IList->getInit(OldIndex)); 2422 IList->setInit(OldIndex, DIE); 2423 2424 return hadError && !prevHadError; 2425 } 2426 2427 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 2428 bool IsFirstDesignator = (DesigIdx == 0); 2429 if (IsFirstDesignator ? FullyStructuredList : StructuredList) { 2430 // Determine the structural initializer list that corresponds to the 2431 // current subobject. 2432 if (IsFirstDesignator) 2433 StructuredList = FullyStructuredList; 2434 else { 2435 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? 2436 StructuredList->getInit(StructuredIndex) : nullptr; 2437 if (!ExistingInit && StructuredList->hasArrayFiller()) 2438 ExistingInit = StructuredList->getArrayFiller(); 2439 2440 if (!ExistingInit) 2441 StructuredList = getStructuredSubobjectInit( 2442 IList, Index, CurrentObjectType, StructuredList, StructuredIndex, 2443 SourceRange(D->getBeginLoc(), DIE->getEndLoc())); 2444 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) 2445 StructuredList = Result; 2446 else { 2447 // We are creating an initializer list that initializes the 2448 // subobjects of the current object, but there was already an 2449 // initialization that completely initialized the current 2450 // subobject, e.g., by a compound literal: 2451 // 2452 // struct X { int a, b; }; 2453 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2454 // 2455 // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 2456 // designated initializer re-initializes only its current object 2457 // subobject [0].b. 2458 diagnoseInitOverride(ExistingInit, 2459 SourceRange(D->getBeginLoc(), DIE->getEndLoc()), 2460 /*FullyOverwritten=*/false); 2461 2462 if (!VerifyOnly) { 2463 if (DesignatedInitUpdateExpr *E = 2464 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) 2465 StructuredList = E->getUpdater(); 2466 else { 2467 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) 2468 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), 2469 ExistingInit, DIE->getEndLoc()); 2470 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); 2471 StructuredList = DIUE->getUpdater(); 2472 } 2473 } else { 2474 // We don't need to track the structured representation of a 2475 // designated init update of an already-fully-initialized object in 2476 // verify-only mode. The only reason we would need the structure is 2477 // to determine where the uninitialized "holes" are, and in this 2478 // case, we know there aren't any and we can't introduce any. 2479 StructuredList = nullptr; 2480 } 2481 } 2482 } 2483 } 2484 2485 if (D->isFieldDesignator()) { 2486 // C99 6.7.8p7: 2487 // 2488 // If a designator has the form 2489 // 2490 // . identifier 2491 // 2492 // then the current object (defined below) shall have 2493 // structure or union type and the identifier shall be the 2494 // name of a member of that type. 2495 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 2496 if (!RT) { 2497 SourceLocation Loc = D->getDotLoc(); 2498 if (Loc.isInvalid()) 2499 Loc = D->getFieldLoc(); 2500 if (!VerifyOnly) 2501 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 2502 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; 2503 ++Index; 2504 return true; 2505 } 2506 2507 FieldDecl *KnownField = D->getField(); 2508 if (!KnownField) { 2509 IdentifierInfo *FieldName = D->getFieldName(); 2510 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 2511 for (NamedDecl *ND : Lookup) { 2512 if (auto *FD = dyn_cast<FieldDecl>(ND)) { 2513 KnownField = FD; 2514 break; 2515 } 2516 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { 2517 // In verify mode, don't modify the original. 2518 if (VerifyOnly) 2519 DIE = CloneDesignatedInitExpr(SemaRef, DIE); 2520 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); 2521 D = DIE->getDesignator(DesigIdx); 2522 KnownField = cast<FieldDecl>(*IFD->chain_begin()); 2523 break; 2524 } 2525 } 2526 if (!KnownField) { 2527 if (VerifyOnly) { 2528 ++Index; 2529 return true; // No typo correction when just trying this out. 2530 } 2531 2532 // Name lookup found something, but it wasn't a field. 2533 if (!Lookup.empty()) { 2534 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 2535 << FieldName; 2536 SemaRef.Diag(Lookup.front()->getLocation(), 2537 diag::note_field_designator_found); 2538 ++Index; 2539 return true; 2540 } 2541 2542 // Name lookup didn't find anything. 2543 // Determine whether this was a typo for another field name. 2544 FieldInitializerValidatorCCC CCC(RT->getDecl()); 2545 if (TypoCorrection Corrected = SemaRef.CorrectTypo( 2546 DeclarationNameInfo(FieldName, D->getFieldLoc()), 2547 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, 2548 Sema::CTK_ErrorRecovery, RT->getDecl())) { 2549 SemaRef.diagnoseTypo( 2550 Corrected, 2551 SemaRef.PDiag(diag::err_field_designator_unknown_suggest) 2552 << FieldName << CurrentObjectType); 2553 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); 2554 hadError = true; 2555 } else { 2556 // Typo correction didn't find anything. 2557 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 2558 << FieldName << CurrentObjectType; 2559 ++Index; 2560 return true; 2561 } 2562 } 2563 } 2564 2565 unsigned NumBases = 0; 2566 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2567 NumBases = CXXRD->getNumBases(); 2568 2569 unsigned FieldIndex = NumBases; 2570 2571 for (auto *FI : RT->getDecl()->fields()) { 2572 if (FI->isUnnamedBitfield()) 2573 continue; 2574 if (declaresSameEntity(KnownField, FI)) { 2575 KnownField = FI; 2576 break; 2577 } 2578 ++FieldIndex; 2579 } 2580 2581 RecordDecl::field_iterator Field = 2582 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); 2583 2584 // All of the fields of a union are located at the same place in 2585 // the initializer list. 2586 if (RT->getDecl()->isUnion()) { 2587 FieldIndex = 0; 2588 if (StructuredList) { 2589 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); 2590 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { 2591 assert(StructuredList->getNumInits() == 1 2592 && "A union should never have more than one initializer!"); 2593 2594 Expr *ExistingInit = StructuredList->getInit(0); 2595 if (ExistingInit) { 2596 // We're about to throw away an initializer, emit warning. 2597 diagnoseInitOverride( 2598 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc())); 2599 } 2600 2601 // remove existing initializer 2602 StructuredList->resizeInits(SemaRef.Context, 0); 2603 StructuredList->setInitializedFieldInUnion(nullptr); 2604 } 2605 2606 StructuredList->setInitializedFieldInUnion(*Field); 2607 } 2608 } 2609 2610 // Make sure we can use this declaration. 2611 bool InvalidUse; 2612 if (VerifyOnly) 2613 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2614 else 2615 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); 2616 if (InvalidUse) { 2617 ++Index; 2618 return true; 2619 } 2620 2621 // C++20 [dcl.init.list]p3: 2622 // The ordered identifiers in the designators of the designated- 2623 // initializer-list shall form a subsequence of the ordered identifiers 2624 // in the direct non-static data members of T. 2625 // 2626 // Note that this is not a condition on forming the aggregate 2627 // initialization, only on actually performing initialization, 2628 // so it is not checked in VerifyOnly mode. 2629 // 2630 // FIXME: This is the only reordering diagnostic we produce, and it only 2631 // catches cases where we have a top-level field designator that jumps 2632 // backwards. This is the only such case that is reachable in an 2633 // otherwise-valid C++20 program, so is the only case that's required for 2634 // conformance, but for consistency, we should diagnose all the other 2635 // cases where a designator takes us backwards too. 2636 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && 2637 NextField && 2638 (*NextField == RT->getDecl()->field_end() || 2639 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { 2640 // Find the field that we just initialized. 2641 FieldDecl *PrevField = nullptr; 2642 for (auto FI = RT->getDecl()->field_begin(); 2643 FI != RT->getDecl()->field_end(); ++FI) { 2644 if (FI->isUnnamedBitfield()) 2645 continue; 2646 if (*NextField != RT->getDecl()->field_end() && 2647 declaresSameEntity(*FI, **NextField)) 2648 break; 2649 PrevField = *FI; 2650 } 2651 2652 if (PrevField && 2653 PrevField->getFieldIndex() > KnownField->getFieldIndex()) { 2654 SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) 2655 << KnownField << PrevField << DIE->getSourceRange(); 2656 2657 unsigned OldIndex = NumBases + PrevField->getFieldIndex(); 2658 if (StructuredList && OldIndex <= StructuredList->getNumInits()) { 2659 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { 2660 SemaRef.Diag(PrevInit->getBeginLoc(), 2661 diag::note_previous_field_init) 2662 << PrevField << PrevInit->getSourceRange(); 2663 } 2664 } 2665 } 2666 } 2667 2668 2669 // Update the designator with the field declaration. 2670 if (!VerifyOnly) 2671 D->setField(*Field); 2672 2673 // Make sure that our non-designated initializer list has space 2674 // for a subobject corresponding to this field. 2675 if (StructuredList && FieldIndex >= StructuredList->getNumInits()) 2676 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 2677 2678 // This designator names a flexible array member. 2679 if (Field->getType()->isIncompleteArrayType()) { 2680 bool Invalid = false; 2681 if ((DesigIdx + 1) != DIE->size()) { 2682 // We can't designate an object within the flexible array 2683 // member (because GCC doesn't allow it). 2684 if (!VerifyOnly) { 2685 DesignatedInitExpr::Designator *NextD 2686 = DIE->getDesignator(DesigIdx + 1); 2687 SemaRef.Diag(NextD->getBeginLoc(), 2688 diag::err_designator_into_flexible_array_member) 2689 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); 2690 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2691 << *Field; 2692 } 2693 Invalid = true; 2694 } 2695 2696 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 2697 !isa<StringLiteral>(DIE->getInit())) { 2698 // The initializer is not an initializer list. 2699 if (!VerifyOnly) { 2700 SemaRef.Diag(DIE->getInit()->getBeginLoc(), 2701 diag::err_flexible_array_init_needs_braces) 2702 << DIE->getInit()->getSourceRange(); 2703 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2704 << *Field; 2705 } 2706 Invalid = true; 2707 } 2708 2709 // Check GNU flexible array initializer. 2710 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, 2711 TopLevelObject)) 2712 Invalid = true; 2713 2714 if (Invalid) { 2715 ++Index; 2716 return true; 2717 } 2718 2719 // Initialize the array. 2720 bool prevHadError = hadError; 2721 unsigned newStructuredIndex = FieldIndex; 2722 unsigned OldIndex = Index; 2723 IList->setInit(Index, DIE->getInit()); 2724 2725 InitializedEntity MemberEntity = 2726 InitializedEntity::InitializeMember(*Field, &Entity); 2727 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2728 StructuredList, newStructuredIndex); 2729 2730 IList->setInit(OldIndex, DIE); 2731 if (hadError && !prevHadError) { 2732 ++Field; 2733 ++FieldIndex; 2734 if (NextField) 2735 *NextField = Field; 2736 StructuredIndex = FieldIndex; 2737 return true; 2738 } 2739 } else { 2740 // Recurse to check later designated subobjects. 2741 QualType FieldType = Field->getType(); 2742 unsigned newStructuredIndex = FieldIndex; 2743 2744 InitializedEntity MemberEntity = 2745 InitializedEntity::InitializeMember(*Field, &Entity); 2746 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 2747 FieldType, nullptr, nullptr, Index, 2748 StructuredList, newStructuredIndex, 2749 FinishSubobjectInit, false)) 2750 return true; 2751 } 2752 2753 // Find the position of the next field to be initialized in this 2754 // subobject. 2755 ++Field; 2756 ++FieldIndex; 2757 2758 // If this the first designator, our caller will continue checking 2759 // the rest of this struct/class/union subobject. 2760 if (IsFirstDesignator) { 2761 if (NextField) 2762 *NextField = Field; 2763 StructuredIndex = FieldIndex; 2764 return false; 2765 } 2766 2767 if (!FinishSubobjectInit) 2768 return false; 2769 2770 // We've already initialized something in the union; we're done. 2771 if (RT->getDecl()->isUnion()) 2772 return hadError; 2773 2774 // Check the remaining fields within this class/struct/union subobject. 2775 bool prevHadError = hadError; 2776 2777 auto NoBases = 2778 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 2779 CXXRecordDecl::base_class_iterator()); 2780 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, 2781 false, Index, StructuredList, FieldIndex); 2782 return hadError && !prevHadError; 2783 } 2784 2785 // C99 6.7.8p6: 2786 // 2787 // If a designator has the form 2788 // 2789 // [ constant-expression ] 2790 // 2791 // then the current object (defined below) shall have array 2792 // type and the expression shall be an integer constant 2793 // expression. If the array is of unknown size, any 2794 // nonnegative value is valid. 2795 // 2796 // Additionally, cope with the GNU extension that permits 2797 // designators of the form 2798 // 2799 // [ constant-expression ... constant-expression ] 2800 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 2801 if (!AT) { 2802 if (!VerifyOnly) 2803 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 2804 << CurrentObjectType; 2805 ++Index; 2806 return true; 2807 } 2808 2809 Expr *IndexExpr = nullptr; 2810 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 2811 if (D->isArrayDesignator()) { 2812 IndexExpr = DIE->getArrayIndex(*D); 2813 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); 2814 DesignatedEndIndex = DesignatedStartIndex; 2815 } else { 2816 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 2817 2818 DesignatedStartIndex = 2819 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); 2820 DesignatedEndIndex = 2821 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); 2822 IndexExpr = DIE->getArrayRangeEnd(*D); 2823 2824 // Codegen can't handle evaluating array range designators that have side 2825 // effects, because we replicate the AST value for each initialized element. 2826 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 2827 // elements with something that has a side effect, so codegen can emit an 2828 // "error unsupported" error instead of miscompiling the app. 2829 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 2830 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) 2831 FullyStructuredList->sawArrayRangeDesignator(); 2832 } 2833 2834 if (isa<ConstantArrayType>(AT)) { 2835 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 2836 DesignatedStartIndex 2837 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 2838 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 2839 DesignatedEndIndex 2840 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 2841 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 2842 if (DesignatedEndIndex >= MaxElements) { 2843 if (!VerifyOnly) 2844 SemaRef.Diag(IndexExpr->getBeginLoc(), 2845 diag::err_array_designator_too_large) 2846 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 2847 << IndexExpr->getSourceRange(); 2848 ++Index; 2849 return true; 2850 } 2851 } else { 2852 unsigned DesignatedIndexBitWidth = 2853 ConstantArrayType::getMaxSizeBits(SemaRef.Context); 2854 DesignatedStartIndex = 2855 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); 2856 DesignatedEndIndex = 2857 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); 2858 DesignatedStartIndex.setIsUnsigned(true); 2859 DesignatedEndIndex.setIsUnsigned(true); 2860 } 2861 2862 bool IsStringLiteralInitUpdate = 2863 StructuredList && StructuredList->isStringLiteralInit(); 2864 if (IsStringLiteralInitUpdate && VerifyOnly) { 2865 // We're just verifying an update to a string literal init. We don't need 2866 // to split the string up into individual characters to do that. 2867 StructuredList = nullptr; 2868 } else if (IsStringLiteralInitUpdate) { 2869 // We're modifying a string literal init; we have to decompose the string 2870 // so we can modify the individual characters. 2871 ASTContext &Context = SemaRef.Context; 2872 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); 2873 2874 // Compute the character type 2875 QualType CharTy = AT->getElementType(); 2876 2877 // Compute the type of the integer literals. 2878 QualType PromotedCharTy = CharTy; 2879 if (CharTy->isPromotableIntegerType()) 2880 PromotedCharTy = Context.getPromotedIntegerType(CharTy); 2881 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); 2882 2883 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { 2884 // Get the length of the string. 2885 uint64_t StrLen = SL->getLength(); 2886 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2887 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2888 StructuredList->resizeInits(Context, StrLen); 2889 2890 // Build a literal for each character in the string, and put them into 2891 // the init list. 2892 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2893 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); 2894 Expr *Init = new (Context) IntegerLiteral( 2895 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2896 if (CharTy != PromotedCharTy) 2897 Init = 2898 ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2899 nullptr, VK_RValue, FPOptionsOverride()); 2900 StructuredList->updateInit(Context, i, Init); 2901 } 2902 } else { 2903 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); 2904 std::string Str; 2905 Context.getObjCEncodingForType(E->getEncodedType(), Str); 2906 2907 // Get the length of the string. 2908 uint64_t StrLen = Str.size(); 2909 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2910 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2911 StructuredList->resizeInits(Context, StrLen); 2912 2913 // Build a literal for each character in the string, and put them into 2914 // the init list. 2915 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2916 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); 2917 Expr *Init = new (Context) IntegerLiteral( 2918 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2919 if (CharTy != PromotedCharTy) 2920 Init = 2921 ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2922 nullptr, VK_RValue, FPOptionsOverride()); 2923 StructuredList->updateInit(Context, i, Init); 2924 } 2925 } 2926 } 2927 2928 // Make sure that our non-designated initializer list has space 2929 // for a subobject corresponding to this array element. 2930 if (StructuredList && 2931 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 2932 StructuredList->resizeInits(SemaRef.Context, 2933 DesignatedEndIndex.getZExtValue() + 1); 2934 2935 // Repeatedly perform subobject initializations in the range 2936 // [DesignatedStartIndex, DesignatedEndIndex]. 2937 2938 // Move to the next designator 2939 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 2940 unsigned OldIndex = Index; 2941 2942 InitializedEntity ElementEntity = 2943 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 2944 2945 while (DesignatedStartIndex <= DesignatedEndIndex) { 2946 // Recurse to check later designated subobjects. 2947 QualType ElementType = AT->getElementType(); 2948 Index = OldIndex; 2949 2950 ElementEntity.setElementIndex(ElementIndex); 2951 if (CheckDesignatedInitializer( 2952 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, 2953 nullptr, Index, StructuredList, ElementIndex, 2954 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), 2955 false)) 2956 return true; 2957 2958 // Move to the next index in the array that we'll be initializing. 2959 ++DesignatedStartIndex; 2960 ElementIndex = DesignatedStartIndex.getZExtValue(); 2961 } 2962 2963 // If this the first designator, our caller will continue checking 2964 // the rest of this array subobject. 2965 if (IsFirstDesignator) { 2966 if (NextElementIndex) 2967 *NextElementIndex = DesignatedStartIndex; 2968 StructuredIndex = ElementIndex; 2969 return false; 2970 } 2971 2972 if (!FinishSubobjectInit) 2973 return false; 2974 2975 // Check the remaining elements within this array subobject. 2976 bool prevHadError = hadError; 2977 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 2978 /*SubobjectIsDesignatorContext=*/false, Index, 2979 StructuredList, ElementIndex); 2980 return hadError && !prevHadError; 2981 } 2982 2983 // Get the structured initializer list for a subobject of type 2984 // @p CurrentObjectType. 2985 InitListExpr * 2986 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 2987 QualType CurrentObjectType, 2988 InitListExpr *StructuredList, 2989 unsigned StructuredIndex, 2990 SourceRange InitRange, 2991 bool IsFullyOverwritten) { 2992 if (!StructuredList) 2993 return nullptr; 2994 2995 Expr *ExistingInit = nullptr; 2996 if (StructuredIndex < StructuredList->getNumInits()) 2997 ExistingInit = StructuredList->getInit(StructuredIndex); 2998 2999 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 3000 // There might have already been initializers for subobjects of the current 3001 // object, but a subsequent initializer list will overwrite the entirety 3002 // of the current object. (See DR 253 and C99 6.7.8p21). e.g., 3003 // 3004 // struct P { char x[6]; }; 3005 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; 3006 // 3007 // The first designated initializer is ignored, and l.x is just "f". 3008 if (!IsFullyOverwritten) 3009 return Result; 3010 3011 if (ExistingInit) { 3012 // We are creating an initializer list that initializes the 3013 // subobjects of the current object, but there was already an 3014 // initialization that completely initialized the current 3015 // subobject: 3016 // 3017 // struct X { int a, b; }; 3018 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; 3019 // 3020 // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 3021 // designated initializer overwrites the [0].b initializer 3022 // from the prior initialization. 3023 // 3024 // When the existing initializer is an expression rather than an 3025 // initializer list, we cannot decompose and update it in this way. 3026 // For example: 3027 // 3028 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 3029 // 3030 // This case is handled by CheckDesignatedInitializer. 3031 diagnoseInitOverride(ExistingInit, InitRange); 3032 } 3033 3034 unsigned ExpectedNumInits = 0; 3035 if (Index < IList->getNumInits()) { 3036 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) 3037 ExpectedNumInits = Init->getNumInits(); 3038 else 3039 ExpectedNumInits = IList->getNumInits() - Index; 3040 } 3041 3042 InitListExpr *Result = 3043 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); 3044 3045 // Link this new initializer list into the structured initializer 3046 // lists. 3047 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 3048 return Result; 3049 } 3050 3051 InitListExpr * 3052 InitListChecker::createInitListExpr(QualType CurrentObjectType, 3053 SourceRange InitRange, 3054 unsigned ExpectedNumInits) { 3055 InitListExpr *Result 3056 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 3057 InitRange.getBegin(), None, 3058 InitRange.getEnd()); 3059 3060 QualType ResultType = CurrentObjectType; 3061 if (!ResultType->isArrayType()) 3062 ResultType = ResultType.getNonLValueExprType(SemaRef.Context); 3063 Result->setType(ResultType); 3064 3065 // Pre-allocate storage for the structured initializer list. 3066 unsigned NumElements = 0; 3067 3068 if (const ArrayType *AType 3069 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 3070 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 3071 NumElements = CAType->getSize().getZExtValue(); 3072 // Simple heuristic so that we don't allocate a very large 3073 // initializer with many empty entries at the end. 3074 if (NumElements > ExpectedNumInits) 3075 NumElements = 0; 3076 } 3077 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { 3078 NumElements = VType->getNumElements(); 3079 } else if (CurrentObjectType->isRecordType()) { 3080 NumElements = numStructUnionElements(CurrentObjectType); 3081 } 3082 3083 Result->reserveInits(SemaRef.Context, NumElements); 3084 3085 return Result; 3086 } 3087 3088 /// Update the initializer at index @p StructuredIndex within the 3089 /// structured initializer list to the value @p expr. 3090 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 3091 unsigned &StructuredIndex, 3092 Expr *expr) { 3093 // No structured initializer list to update 3094 if (!StructuredList) 3095 return; 3096 3097 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 3098 StructuredIndex, expr)) { 3099 // This initializer overwrites a previous initializer. 3100 // No need to diagnose when `expr` is nullptr because a more relevant 3101 // diagnostic has already been issued and this diagnostic is potentially 3102 // noise. 3103 if (expr) 3104 diagnoseInitOverride(PrevInit, expr->getSourceRange()); 3105 } 3106 3107 ++StructuredIndex; 3108 } 3109 3110 /// Determine whether we can perform aggregate initialization for the purposes 3111 /// of overload resolution. 3112 bool Sema::CanPerformAggregateInitializationForOverloadResolution( 3113 const InitializedEntity &Entity, InitListExpr *From) { 3114 QualType Type = Entity.getType(); 3115 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, 3116 /*TreatUnavailableAsInvalid=*/false, 3117 /*InOverloadResolution=*/true); 3118 return !Check.HadError(); 3119 } 3120 3121 /// Check that the given Index expression is a valid array designator 3122 /// value. This is essentially just a wrapper around 3123 /// VerifyIntegerConstantExpression that also checks for negative values 3124 /// and produces a reasonable diagnostic if there is a 3125 /// failure. Returns the index expression, possibly with an implicit cast 3126 /// added, on success. If everything went okay, Value will receive the 3127 /// value of the constant expression. 3128 static ExprResult 3129 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 3130 SourceLocation Loc = Index->getBeginLoc(); 3131 3132 // Make sure this is an integer constant expression. 3133 ExprResult Result = 3134 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold); 3135 if (Result.isInvalid()) 3136 return Result; 3137 3138 if (Value.isSigned() && Value.isNegative()) 3139 return S.Diag(Loc, diag::err_array_designator_negative) 3140 << Value.toString(10) << Index->getSourceRange(); 3141 3142 Value.setIsUnsigned(true); 3143 return Result; 3144 } 3145 3146 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 3147 SourceLocation EqualOrColonLoc, 3148 bool GNUSyntax, 3149 ExprResult Init) { 3150 typedef DesignatedInitExpr::Designator ASTDesignator; 3151 3152 bool Invalid = false; 3153 SmallVector<ASTDesignator, 32> Designators; 3154 SmallVector<Expr *, 32> InitExpressions; 3155 3156 // Build designators and check array designator expressions. 3157 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 3158 const Designator &D = Desig.getDesignator(Idx); 3159 switch (D.getKind()) { 3160 case Designator::FieldDesignator: 3161 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 3162 D.getFieldLoc())); 3163 break; 3164 3165 case Designator::ArrayDesignator: { 3166 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 3167 llvm::APSInt IndexValue; 3168 if (!Index->isTypeDependent() && !Index->isValueDependent()) 3169 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); 3170 if (!Index) 3171 Invalid = true; 3172 else { 3173 Designators.push_back(ASTDesignator(InitExpressions.size(), 3174 D.getLBracketLoc(), 3175 D.getRBracketLoc())); 3176 InitExpressions.push_back(Index); 3177 } 3178 break; 3179 } 3180 3181 case Designator::ArrayRangeDesignator: { 3182 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 3183 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 3184 llvm::APSInt StartValue; 3185 llvm::APSInt EndValue; 3186 bool StartDependent = StartIndex->isTypeDependent() || 3187 StartIndex->isValueDependent(); 3188 bool EndDependent = EndIndex->isTypeDependent() || 3189 EndIndex->isValueDependent(); 3190 if (!StartDependent) 3191 StartIndex = 3192 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); 3193 if (!EndDependent) 3194 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); 3195 3196 if (!StartIndex || !EndIndex) 3197 Invalid = true; 3198 else { 3199 // Make sure we're comparing values with the same bit width. 3200 if (StartDependent || EndDependent) { 3201 // Nothing to compute. 3202 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 3203 EndValue = EndValue.extend(StartValue.getBitWidth()); 3204 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 3205 StartValue = StartValue.extend(EndValue.getBitWidth()); 3206 3207 if (!StartDependent && !EndDependent && EndValue < StartValue) { 3208 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 3209 << StartValue.toString(10) << EndValue.toString(10) 3210 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 3211 Invalid = true; 3212 } else { 3213 Designators.push_back(ASTDesignator(InitExpressions.size(), 3214 D.getLBracketLoc(), 3215 D.getEllipsisLoc(), 3216 D.getRBracketLoc())); 3217 InitExpressions.push_back(StartIndex); 3218 InitExpressions.push_back(EndIndex); 3219 } 3220 } 3221 break; 3222 } 3223 } 3224 } 3225 3226 if (Invalid || Init.isInvalid()) 3227 return ExprError(); 3228 3229 // Clear out the expressions within the designation. 3230 Desig.ClearExprs(*this); 3231 3232 return DesignatedInitExpr::Create(Context, Designators, InitExpressions, 3233 EqualOrColonLoc, GNUSyntax, 3234 Init.getAs<Expr>()); 3235 } 3236 3237 //===----------------------------------------------------------------------===// 3238 // Initialization entity 3239 //===----------------------------------------------------------------------===// 3240 3241 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 3242 const InitializedEntity &Parent) 3243 : Parent(&Parent), Index(Index) 3244 { 3245 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 3246 Kind = EK_ArrayElement; 3247 Type = AT->getElementType(); 3248 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 3249 Kind = EK_VectorElement; 3250 Type = VT->getElementType(); 3251 } else { 3252 const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 3253 assert(CT && "Unexpected type"); 3254 Kind = EK_ComplexElement; 3255 Type = CT->getElementType(); 3256 } 3257 } 3258 3259 InitializedEntity 3260 InitializedEntity::InitializeBase(ASTContext &Context, 3261 const CXXBaseSpecifier *Base, 3262 bool IsInheritedVirtualBase, 3263 const InitializedEntity *Parent) { 3264 InitializedEntity Result; 3265 Result.Kind = EK_Base; 3266 Result.Parent = Parent; 3267 Result.Base = reinterpret_cast<uintptr_t>(Base); 3268 if (IsInheritedVirtualBase) 3269 Result.Base |= 0x01; 3270 3271 Result.Type = Base->getType(); 3272 return Result; 3273 } 3274 3275 DeclarationName InitializedEntity::getName() const { 3276 switch (getKind()) { 3277 case EK_Parameter: 3278 case EK_Parameter_CF_Audited: { 3279 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 3280 return (D ? D->getDeclName() : DeclarationName()); 3281 } 3282 3283 case EK_Variable: 3284 case EK_Member: 3285 case EK_Binding: 3286 return Variable.VariableOrMember->getDeclName(); 3287 3288 case EK_LambdaCapture: 3289 return DeclarationName(Capture.VarID); 3290 3291 case EK_Result: 3292 case EK_StmtExprResult: 3293 case EK_Exception: 3294 case EK_New: 3295 case EK_Temporary: 3296 case EK_Base: 3297 case EK_Delegating: 3298 case EK_ArrayElement: 3299 case EK_VectorElement: 3300 case EK_ComplexElement: 3301 case EK_BlockElement: 3302 case EK_LambdaToBlockConversionBlockElement: 3303 case EK_CompoundLiteralInit: 3304 case EK_RelatedResult: 3305 return DeclarationName(); 3306 } 3307 3308 llvm_unreachable("Invalid EntityKind!"); 3309 } 3310 3311 ValueDecl *InitializedEntity::getDecl() const { 3312 switch (getKind()) { 3313 case EK_Variable: 3314 case EK_Member: 3315 case EK_Binding: 3316 return Variable.VariableOrMember; 3317 3318 case EK_Parameter: 3319 case EK_Parameter_CF_Audited: 3320 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 3321 3322 case EK_Result: 3323 case EK_StmtExprResult: 3324 case EK_Exception: 3325 case EK_New: 3326 case EK_Temporary: 3327 case EK_Base: 3328 case EK_Delegating: 3329 case EK_ArrayElement: 3330 case EK_VectorElement: 3331 case EK_ComplexElement: 3332 case EK_BlockElement: 3333 case EK_LambdaToBlockConversionBlockElement: 3334 case EK_LambdaCapture: 3335 case EK_CompoundLiteralInit: 3336 case EK_RelatedResult: 3337 return nullptr; 3338 } 3339 3340 llvm_unreachable("Invalid EntityKind!"); 3341 } 3342 3343 bool InitializedEntity::allowsNRVO() const { 3344 switch (getKind()) { 3345 case EK_Result: 3346 case EK_Exception: 3347 return LocAndNRVO.NRVO; 3348 3349 case EK_StmtExprResult: 3350 case EK_Variable: 3351 case EK_Parameter: 3352 case EK_Parameter_CF_Audited: 3353 case EK_Member: 3354 case EK_Binding: 3355 case EK_New: 3356 case EK_Temporary: 3357 case EK_CompoundLiteralInit: 3358 case EK_Base: 3359 case EK_Delegating: 3360 case EK_ArrayElement: 3361 case EK_VectorElement: 3362 case EK_ComplexElement: 3363 case EK_BlockElement: 3364 case EK_LambdaToBlockConversionBlockElement: 3365 case EK_LambdaCapture: 3366 case EK_RelatedResult: 3367 break; 3368 } 3369 3370 return false; 3371 } 3372 3373 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { 3374 assert(getParent() != this); 3375 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; 3376 for (unsigned I = 0; I != Depth; ++I) 3377 OS << "`-"; 3378 3379 switch (getKind()) { 3380 case EK_Variable: OS << "Variable"; break; 3381 case EK_Parameter: OS << "Parameter"; break; 3382 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; 3383 break; 3384 case EK_Result: OS << "Result"; break; 3385 case EK_StmtExprResult: OS << "StmtExprResult"; break; 3386 case EK_Exception: OS << "Exception"; break; 3387 case EK_Member: OS << "Member"; break; 3388 case EK_Binding: OS << "Binding"; break; 3389 case EK_New: OS << "New"; break; 3390 case EK_Temporary: OS << "Temporary"; break; 3391 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; 3392 case EK_RelatedResult: OS << "RelatedResult"; break; 3393 case EK_Base: OS << "Base"; break; 3394 case EK_Delegating: OS << "Delegating"; break; 3395 case EK_ArrayElement: OS << "ArrayElement " << Index; break; 3396 case EK_VectorElement: OS << "VectorElement " << Index; break; 3397 case EK_ComplexElement: OS << "ComplexElement " << Index; break; 3398 case EK_BlockElement: OS << "Block"; break; 3399 case EK_LambdaToBlockConversionBlockElement: 3400 OS << "Block (lambda)"; 3401 break; 3402 case EK_LambdaCapture: 3403 OS << "LambdaCapture "; 3404 OS << DeclarationName(Capture.VarID); 3405 break; 3406 } 3407 3408 if (auto *D = getDecl()) { 3409 OS << " "; 3410 D->printQualifiedName(OS); 3411 } 3412 3413 OS << " '" << getType().getAsString() << "'\n"; 3414 3415 return Depth + 1; 3416 } 3417 3418 LLVM_DUMP_METHOD void InitializedEntity::dump() const { 3419 dumpImpl(llvm::errs()); 3420 } 3421 3422 //===----------------------------------------------------------------------===// 3423 // Initialization sequence 3424 //===----------------------------------------------------------------------===// 3425 3426 void InitializationSequence::Step::Destroy() { 3427 switch (Kind) { 3428 case SK_ResolveAddressOfOverloadedFunction: 3429 case SK_CastDerivedToBaseRValue: 3430 case SK_CastDerivedToBaseXValue: 3431 case SK_CastDerivedToBaseLValue: 3432 case SK_BindReference: 3433 case SK_BindReferenceToTemporary: 3434 case SK_FinalCopy: 3435 case SK_ExtraneousCopyToTemporary: 3436 case SK_UserConversion: 3437 case SK_QualificationConversionRValue: 3438 case SK_QualificationConversionXValue: 3439 case SK_QualificationConversionLValue: 3440 case SK_AtomicConversion: 3441 case SK_ListInitialization: 3442 case SK_UnwrapInitList: 3443 case SK_RewrapInitList: 3444 case SK_ConstructorInitialization: 3445 case SK_ConstructorInitializationFromList: 3446 case SK_ZeroInitialization: 3447 case SK_CAssignment: 3448 case SK_StringInit: 3449 case SK_ObjCObjectConversion: 3450 case SK_ArrayLoopIndex: 3451 case SK_ArrayLoopInit: 3452 case SK_ArrayInit: 3453 case SK_GNUArrayInit: 3454 case SK_ParenthesizedArrayInit: 3455 case SK_PassByIndirectCopyRestore: 3456 case SK_PassByIndirectRestore: 3457 case SK_ProduceObjCObject: 3458 case SK_StdInitializerList: 3459 case SK_StdInitializerListConstructorCall: 3460 case SK_OCLSamplerInit: 3461 case SK_OCLZeroOpaqueType: 3462 break; 3463 3464 case SK_ConversionSequence: 3465 case SK_ConversionSequenceNoNarrowing: 3466 delete ICS; 3467 } 3468 } 3469 3470 bool InitializationSequence::isDirectReferenceBinding() const { 3471 // There can be some lvalue adjustments after the SK_BindReference step. 3472 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { 3473 if (I->Kind == SK_BindReference) 3474 return true; 3475 if (I->Kind == SK_BindReferenceToTemporary) 3476 return false; 3477 } 3478 return false; 3479 } 3480 3481 bool InitializationSequence::isAmbiguous() const { 3482 if (!Failed()) 3483 return false; 3484 3485 switch (getFailureKind()) { 3486 case FK_TooManyInitsForReference: 3487 case FK_ParenthesizedListInitForReference: 3488 case FK_ArrayNeedsInitList: 3489 case FK_ArrayNeedsInitListOrStringLiteral: 3490 case FK_ArrayNeedsInitListOrWideStringLiteral: 3491 case FK_NarrowStringIntoWideCharArray: 3492 case FK_WideStringIntoCharArray: 3493 case FK_IncompatWideStringIntoWideChar: 3494 case FK_PlainStringIntoUTF8Char: 3495 case FK_UTF8StringIntoPlainChar: 3496 case FK_AddressOfOverloadFailed: // FIXME: Could do better 3497 case FK_NonConstLValueReferenceBindingToTemporary: 3498 case FK_NonConstLValueReferenceBindingToBitfield: 3499 case FK_NonConstLValueReferenceBindingToVectorElement: 3500 case FK_NonConstLValueReferenceBindingToMatrixElement: 3501 case FK_NonConstLValueReferenceBindingToUnrelated: 3502 case FK_RValueReferenceBindingToLValue: 3503 case FK_ReferenceAddrspaceMismatchTemporary: 3504 case FK_ReferenceInitDropsQualifiers: 3505 case FK_ReferenceInitFailed: 3506 case FK_ConversionFailed: 3507 case FK_ConversionFromPropertyFailed: 3508 case FK_TooManyInitsForScalar: 3509 case FK_ParenthesizedListInitForScalar: 3510 case FK_ReferenceBindingToInitList: 3511 case FK_InitListBadDestinationType: 3512 case FK_DefaultInitOfConst: 3513 case FK_Incomplete: 3514 case FK_ArrayTypeMismatch: 3515 case FK_NonConstantArrayInit: 3516 case FK_ListInitializationFailed: 3517 case FK_VariableLengthArrayHasInitializer: 3518 case FK_PlaceholderType: 3519 case FK_ExplicitConstructor: 3520 case FK_AddressOfUnaddressableFunction: 3521 return false; 3522 3523 case FK_ReferenceInitOverloadFailed: 3524 case FK_UserConversionOverloadFailed: 3525 case FK_ConstructorOverloadFailed: 3526 case FK_ListConstructorOverloadFailed: 3527 return FailedOverloadResult == OR_Ambiguous; 3528 } 3529 3530 llvm_unreachable("Invalid EntityKind!"); 3531 } 3532 3533 bool InitializationSequence::isConstructorInitialization() const { 3534 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 3535 } 3536 3537 void 3538 InitializationSequence 3539 ::AddAddressOverloadResolutionStep(FunctionDecl *Function, 3540 DeclAccessPair Found, 3541 bool HadMultipleCandidates) { 3542 Step S; 3543 S.Kind = SK_ResolveAddressOfOverloadedFunction; 3544 S.Type = Function->getType(); 3545 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3546 S.Function.Function = Function; 3547 S.Function.FoundDecl = Found; 3548 Steps.push_back(S); 3549 } 3550 3551 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 3552 ExprValueKind VK) { 3553 Step S; 3554 switch (VK) { 3555 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 3556 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 3557 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 3558 } 3559 S.Type = BaseType; 3560 Steps.push_back(S); 3561 } 3562 3563 void InitializationSequence::AddReferenceBindingStep(QualType T, 3564 bool BindingTemporary) { 3565 Step S; 3566 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 3567 S.Type = T; 3568 Steps.push_back(S); 3569 } 3570 3571 void InitializationSequence::AddFinalCopy(QualType T) { 3572 Step S; 3573 S.Kind = SK_FinalCopy; 3574 S.Type = T; 3575 Steps.push_back(S); 3576 } 3577 3578 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 3579 Step S; 3580 S.Kind = SK_ExtraneousCopyToTemporary; 3581 S.Type = T; 3582 Steps.push_back(S); 3583 } 3584 3585 void 3586 InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 3587 DeclAccessPair FoundDecl, 3588 QualType T, 3589 bool HadMultipleCandidates) { 3590 Step S; 3591 S.Kind = SK_UserConversion; 3592 S.Type = T; 3593 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3594 S.Function.Function = Function; 3595 S.Function.FoundDecl = FoundDecl; 3596 Steps.push_back(S); 3597 } 3598 3599 void InitializationSequence::AddQualificationConversionStep(QualType Ty, 3600 ExprValueKind VK) { 3601 Step S; 3602 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 3603 switch (VK) { 3604 case VK_RValue: 3605 S.Kind = SK_QualificationConversionRValue; 3606 break; 3607 case VK_XValue: 3608 S.Kind = SK_QualificationConversionXValue; 3609 break; 3610 case VK_LValue: 3611 S.Kind = SK_QualificationConversionLValue; 3612 break; 3613 } 3614 S.Type = Ty; 3615 Steps.push_back(S); 3616 } 3617 3618 void InitializationSequence::AddAtomicConversionStep(QualType Ty) { 3619 Step S; 3620 S.Kind = SK_AtomicConversion; 3621 S.Type = Ty; 3622 Steps.push_back(S); 3623 } 3624 3625 void InitializationSequence::AddConversionSequenceStep( 3626 const ImplicitConversionSequence &ICS, QualType T, 3627 bool TopLevelOfInitList) { 3628 Step S; 3629 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing 3630 : SK_ConversionSequence; 3631 S.Type = T; 3632 S.ICS = new ImplicitConversionSequence(ICS); 3633 Steps.push_back(S); 3634 } 3635 3636 void InitializationSequence::AddListInitializationStep(QualType T) { 3637 Step S; 3638 S.Kind = SK_ListInitialization; 3639 S.Type = T; 3640 Steps.push_back(S); 3641 } 3642 3643 void InitializationSequence::AddConstructorInitializationStep( 3644 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, 3645 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { 3646 Step S; 3647 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall 3648 : SK_ConstructorInitializationFromList 3649 : SK_ConstructorInitialization; 3650 S.Type = T; 3651 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3652 S.Function.Function = Constructor; 3653 S.Function.FoundDecl = FoundDecl; 3654 Steps.push_back(S); 3655 } 3656 3657 void InitializationSequence::AddZeroInitializationStep(QualType T) { 3658 Step S; 3659 S.Kind = SK_ZeroInitialization; 3660 S.Type = T; 3661 Steps.push_back(S); 3662 } 3663 3664 void InitializationSequence::AddCAssignmentStep(QualType T) { 3665 Step S; 3666 S.Kind = SK_CAssignment; 3667 S.Type = T; 3668 Steps.push_back(S); 3669 } 3670 3671 void InitializationSequence::AddStringInitStep(QualType T) { 3672 Step S; 3673 S.Kind = SK_StringInit; 3674 S.Type = T; 3675 Steps.push_back(S); 3676 } 3677 3678 void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 3679 Step S; 3680 S.Kind = SK_ObjCObjectConversion; 3681 S.Type = T; 3682 Steps.push_back(S); 3683 } 3684 3685 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { 3686 Step S; 3687 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; 3688 S.Type = T; 3689 Steps.push_back(S); 3690 } 3691 3692 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { 3693 Step S; 3694 S.Kind = SK_ArrayLoopIndex; 3695 S.Type = EltT; 3696 Steps.insert(Steps.begin(), S); 3697 3698 S.Kind = SK_ArrayLoopInit; 3699 S.Type = T; 3700 Steps.push_back(S); 3701 } 3702 3703 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { 3704 Step S; 3705 S.Kind = SK_ParenthesizedArrayInit; 3706 S.Type = T; 3707 Steps.push_back(S); 3708 } 3709 3710 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 3711 bool shouldCopy) { 3712 Step s; 3713 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 3714 : SK_PassByIndirectRestore); 3715 s.Type = type; 3716 Steps.push_back(s); 3717 } 3718 3719 void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 3720 Step S; 3721 S.Kind = SK_ProduceObjCObject; 3722 S.Type = T; 3723 Steps.push_back(S); 3724 } 3725 3726 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { 3727 Step S; 3728 S.Kind = SK_StdInitializerList; 3729 S.Type = T; 3730 Steps.push_back(S); 3731 } 3732 3733 void InitializationSequence::AddOCLSamplerInitStep(QualType T) { 3734 Step S; 3735 S.Kind = SK_OCLSamplerInit; 3736 S.Type = T; 3737 Steps.push_back(S); 3738 } 3739 3740 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { 3741 Step S; 3742 S.Kind = SK_OCLZeroOpaqueType; 3743 S.Type = T; 3744 Steps.push_back(S); 3745 } 3746 3747 void InitializationSequence::RewrapReferenceInitList(QualType T, 3748 InitListExpr *Syntactic) { 3749 assert(Syntactic->getNumInits() == 1 && 3750 "Can only rewrap trivial init lists."); 3751 Step S; 3752 S.Kind = SK_UnwrapInitList; 3753 S.Type = Syntactic->getInit(0)->getType(); 3754 Steps.insert(Steps.begin(), S); 3755 3756 S.Kind = SK_RewrapInitList; 3757 S.Type = T; 3758 S.WrappingSyntacticList = Syntactic; 3759 Steps.push_back(S); 3760 } 3761 3762 void InitializationSequence::SetOverloadFailure(FailureKind Failure, 3763 OverloadingResult Result) { 3764 setSequenceKind(FailedSequence); 3765 this->Failure = Failure; 3766 this->FailedOverloadResult = Result; 3767 } 3768 3769 //===----------------------------------------------------------------------===// 3770 // Attempt initialization 3771 //===----------------------------------------------------------------------===// 3772 3773 /// Tries to add a zero initializer. Returns true if that worked. 3774 static bool 3775 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, 3776 const InitializedEntity &Entity) { 3777 if (Entity.getKind() != InitializedEntity::EK_Variable) 3778 return false; 3779 3780 VarDecl *VD = cast<VarDecl>(Entity.getDecl()); 3781 if (VD->getInit() || VD->getEndLoc().isMacroID()) 3782 return false; 3783 3784 QualType VariableTy = VD->getType().getCanonicalType(); 3785 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); 3786 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 3787 if (!Init.empty()) { 3788 Sequence.AddZeroInitializationStep(Entity.getType()); 3789 Sequence.SetZeroInitializationFixit(Init, Loc); 3790 return true; 3791 } 3792 return false; 3793 } 3794 3795 static void MaybeProduceObjCObject(Sema &S, 3796 InitializationSequence &Sequence, 3797 const InitializedEntity &Entity) { 3798 if (!S.getLangOpts().ObjCAutoRefCount) return; 3799 3800 /// When initializing a parameter, produce the value if it's marked 3801 /// __attribute__((ns_consumed)). 3802 if (Entity.isParameterKind()) { 3803 if (!Entity.isParameterConsumed()) 3804 return; 3805 3806 assert(Entity.getType()->isObjCRetainableType() && 3807 "consuming an object of unretainable type?"); 3808 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3809 3810 /// When initializing a return value, if the return type is a 3811 /// retainable type, then returns need to immediately retain the 3812 /// object. If an autorelease is required, it will be done at the 3813 /// last instant. 3814 } else if (Entity.getKind() == InitializedEntity::EK_Result || 3815 Entity.getKind() == InitializedEntity::EK_StmtExprResult) { 3816 if (!Entity.getType()->isObjCRetainableType()) 3817 return; 3818 3819 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3820 } 3821 } 3822 3823 static void TryListInitialization(Sema &S, 3824 const InitializedEntity &Entity, 3825 const InitializationKind &Kind, 3826 InitListExpr *InitList, 3827 InitializationSequence &Sequence, 3828 bool TreatUnavailableAsInvalid); 3829 3830 /// When initializing from init list via constructor, handle 3831 /// initialization of an object of type std::initializer_list<T>. 3832 /// 3833 /// \return true if we have handled initialization of an object of type 3834 /// std::initializer_list<T>, false otherwise. 3835 static bool TryInitializerListConstruction(Sema &S, 3836 InitListExpr *List, 3837 QualType DestType, 3838 InitializationSequence &Sequence, 3839 bool TreatUnavailableAsInvalid) { 3840 QualType E; 3841 if (!S.isStdInitializerList(DestType, &E)) 3842 return false; 3843 3844 if (!S.isCompleteType(List->getExprLoc(), E)) { 3845 Sequence.setIncompleteTypeFailure(E); 3846 return true; 3847 } 3848 3849 // Try initializing a temporary array from the init list. 3850 QualType ArrayType = S.Context.getConstantArrayType( 3851 E.withConst(), 3852 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 3853 List->getNumInits()), 3854 nullptr, clang::ArrayType::Normal, 0); 3855 InitializedEntity HiddenArray = 3856 InitializedEntity::InitializeTemporary(ArrayType); 3857 InitializationKind Kind = InitializationKind::CreateDirectList( 3858 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); 3859 TryListInitialization(S, HiddenArray, Kind, List, Sequence, 3860 TreatUnavailableAsInvalid); 3861 if (Sequence) 3862 Sequence.AddStdInitializerListConstructionStep(DestType); 3863 return true; 3864 } 3865 3866 /// Determine if the constructor has the signature of a copy or move 3867 /// constructor for the type T of the class in which it was found. That is, 3868 /// determine if its first parameter is of type T or reference to (possibly 3869 /// cv-qualified) T. 3870 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, 3871 const ConstructorInfo &Info) { 3872 if (Info.Constructor->getNumParams() == 0) 3873 return false; 3874 3875 QualType ParmT = 3876 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); 3877 QualType ClassT = 3878 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); 3879 3880 return Ctx.hasSameUnqualifiedType(ParmT, ClassT); 3881 } 3882 3883 static OverloadingResult 3884 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, 3885 MultiExprArg Args, 3886 OverloadCandidateSet &CandidateSet, 3887 QualType DestType, 3888 DeclContext::lookup_result Ctors, 3889 OverloadCandidateSet::iterator &Best, 3890 bool CopyInitializing, bool AllowExplicit, 3891 bool OnlyListConstructors, bool IsListInit, 3892 bool SecondStepOfCopyInit = false) { 3893 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); 3894 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 3895 3896 for (NamedDecl *D : Ctors) { 3897 auto Info = getConstructorInfo(D); 3898 if (!Info.Constructor || Info.Constructor->isInvalidDecl()) 3899 continue; 3900 3901 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) 3902 continue; 3903 3904 // C++11 [over.best.ics]p4: 3905 // ... and the constructor or user-defined conversion function is a 3906 // candidate by 3907 // - 13.3.1.3, when the argument is the temporary in the second step 3908 // of a class copy-initialization, or 3909 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] 3910 // - the second phase of 13.3.1.7 when the initializer list has exactly 3911 // one element that is itself an initializer list, and the target is 3912 // the first parameter of a constructor of class X, and the conversion 3913 // is to X or reference to (possibly cv-qualified X), 3914 // user-defined conversion sequences are not considered. 3915 bool SuppressUserConversions = 3916 SecondStepOfCopyInit || 3917 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && 3918 hasCopyOrMoveCtorParam(S.Context, Info)); 3919 3920 if (Info.ConstructorTmpl) 3921 S.AddTemplateOverloadCandidate( 3922 Info.ConstructorTmpl, Info.FoundDecl, 3923 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, 3924 /*PartialOverloading=*/false, AllowExplicit); 3925 else { 3926 // C++ [over.match.copy]p1: 3927 // - When initializing a temporary to be bound to the first parameter 3928 // of a constructor [for type T] that takes a reference to possibly 3929 // cv-qualified T as its first argument, called with a single 3930 // argument in the context of direct-initialization, explicit 3931 // conversion functions are also considered. 3932 // FIXME: What if a constructor template instantiates to such a signature? 3933 bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 3934 Args.size() == 1 && 3935 hasCopyOrMoveCtorParam(S.Context, Info); 3936 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, 3937 CandidateSet, SuppressUserConversions, 3938 /*PartialOverloading=*/false, AllowExplicit, 3939 AllowExplicitConv); 3940 } 3941 } 3942 3943 // FIXME: Work around a bug in C++17 guaranteed copy elision. 3944 // 3945 // When initializing an object of class type T by constructor 3946 // ([over.match.ctor]) or by list-initialization ([over.match.list]) 3947 // from a single expression of class type U, conversion functions of 3948 // U that convert to the non-reference type cv T are candidates. 3949 // Explicit conversion functions are only candidates during 3950 // direct-initialization. 3951 // 3952 // Note: SecondStepOfCopyInit is only ever true in this case when 3953 // evaluating whether to produce a C++98 compatibility warning. 3954 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && 3955 !SecondStepOfCopyInit) { 3956 Expr *Initializer = Args[0]; 3957 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); 3958 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { 3959 const auto &Conversions = SourceRD->getVisibleConversionFunctions(); 3960 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3961 NamedDecl *D = *I; 3962 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3963 D = D->getUnderlyingDecl(); 3964 3965 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3966 CXXConversionDecl *Conv; 3967 if (ConvTemplate) 3968 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3969 else 3970 Conv = cast<CXXConversionDecl>(D); 3971 3972 if (ConvTemplate) 3973 S.AddTemplateConversionCandidate( 3974 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 3975 CandidateSet, AllowExplicit, AllowExplicit, 3976 /*AllowResultConversion*/ false); 3977 else 3978 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 3979 DestType, CandidateSet, AllowExplicit, 3980 AllowExplicit, 3981 /*AllowResultConversion*/ false); 3982 } 3983 } 3984 } 3985 3986 // Perform overload resolution and return the result. 3987 return CandidateSet.BestViableFunction(S, DeclLoc, Best); 3988 } 3989 3990 /// Attempt initialization by constructor (C++ [dcl.init]), which 3991 /// enumerates the constructors of the initialized entity and performs overload 3992 /// resolution to select the best. 3993 /// \param DestType The destination class type. 3994 /// \param DestArrayType The destination type, which is either DestType or 3995 /// a (possibly multidimensional) array of DestType. 3996 /// \param IsListInit Is this list-initialization? 3997 /// \param IsInitListCopy Is this non-list-initialization resulting from a 3998 /// list-initialization from {x} where x is the same 3999 /// type as the entity? 4000 static void TryConstructorInitialization(Sema &S, 4001 const InitializedEntity &Entity, 4002 const InitializationKind &Kind, 4003 MultiExprArg Args, QualType DestType, 4004 QualType DestArrayType, 4005 InitializationSequence &Sequence, 4006 bool IsListInit = false, 4007 bool IsInitListCopy = false) { 4008 assert(((!IsListInit && !IsInitListCopy) || 4009 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 4010 "IsListInit/IsInitListCopy must come with a single initializer list " 4011 "argument."); 4012 InitListExpr *ILE = 4013 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; 4014 MultiExprArg UnwrappedArgs = 4015 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; 4016 4017 // The type we're constructing needs to be complete. 4018 if (!S.isCompleteType(Kind.getLocation(), DestType)) { 4019 Sequence.setIncompleteTypeFailure(DestType); 4020 return; 4021 } 4022 4023 // C++17 [dcl.init]p17: 4024 // - If the initializer expression is a prvalue and the cv-unqualified 4025 // version of the source type is the same class as the class of the 4026 // destination, the initializer expression is used to initialize the 4027 // destination object. 4028 // Per DR (no number yet), this does not apply when initializing a base 4029 // class or delegating to another constructor from a mem-initializer. 4030 // ObjC++: Lambda captured by the block in the lambda to block conversion 4031 // should avoid copy elision. 4032 if (S.getLangOpts().CPlusPlus17 && 4033 Entity.getKind() != InitializedEntity::EK_Base && 4034 Entity.getKind() != InitializedEntity::EK_Delegating && 4035 Entity.getKind() != 4036 InitializedEntity::EK_LambdaToBlockConversionBlockElement && 4037 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && 4038 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { 4039 // Convert qualifications if necessary. 4040 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4041 if (ILE) 4042 Sequence.RewrapReferenceInitList(DestType, ILE); 4043 return; 4044 } 4045 4046 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 4047 assert(DestRecordType && "Constructor initialization requires record type"); 4048 CXXRecordDecl *DestRecordDecl 4049 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 4050 4051 // Build the candidate set directly in the initialization sequence 4052 // structure, so that it will persist if we fail. 4053 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4054 4055 // Determine whether we are allowed to call explicit constructors or 4056 // explicit conversion operators. 4057 bool AllowExplicit = Kind.AllowExplicit() || IsListInit; 4058 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; 4059 4060 // - Otherwise, if T is a class type, constructors are considered. The 4061 // applicable constructors are enumerated, and the best one is chosen 4062 // through overload resolution. 4063 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); 4064 4065 OverloadingResult Result = OR_No_Viable_Function; 4066 OverloadCandidateSet::iterator Best; 4067 bool AsInitializerList = false; 4068 4069 // C++11 [over.match.list]p1, per DR1467: 4070 // When objects of non-aggregate type T are list-initialized, such that 4071 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed 4072 // according to the rules in this section, overload resolution selects 4073 // the constructor in two phases: 4074 // 4075 // - Initially, the candidate functions are the initializer-list 4076 // constructors of the class T and the argument list consists of the 4077 // initializer list as a single argument. 4078 if (IsListInit) { 4079 AsInitializerList = true; 4080 4081 // If the initializer list has no elements and T has a default constructor, 4082 // the first phase is omitted. 4083 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl))) 4084 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 4085 CandidateSet, DestType, Ctors, Best, 4086 CopyInitialization, AllowExplicit, 4087 /*OnlyListConstructors=*/true, 4088 IsListInit); 4089 } 4090 4091 // C++11 [over.match.list]p1: 4092 // - If no viable initializer-list constructor is found, overload resolution 4093 // is performed again, where the candidate functions are all the 4094 // constructors of the class T and the argument list consists of the 4095 // elements of the initializer list. 4096 if (Result == OR_No_Viable_Function) { 4097 AsInitializerList = false; 4098 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, 4099 CandidateSet, DestType, Ctors, Best, 4100 CopyInitialization, AllowExplicit, 4101 /*OnlyListConstructors=*/false, 4102 IsListInit); 4103 } 4104 if (Result) { 4105 Sequence.SetOverloadFailure(IsListInit ? 4106 InitializationSequence::FK_ListConstructorOverloadFailed : 4107 InitializationSequence::FK_ConstructorOverloadFailed, 4108 Result); 4109 return; 4110 } 4111 4112 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4113 4114 // In C++17, ResolveConstructorOverload can select a conversion function 4115 // instead of a constructor. 4116 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { 4117 // Add the user-defined conversion step that calls the conversion function. 4118 QualType ConvType = CD->getConversionType(); 4119 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && 4120 "should not have selected this conversion function"); 4121 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, 4122 HadMultipleCandidates); 4123 if (!S.Context.hasSameType(ConvType, DestType)) 4124 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4125 if (IsListInit) 4126 Sequence.RewrapReferenceInitList(Entity.getType(), ILE); 4127 return; 4128 } 4129 4130 // C++11 [dcl.init]p6: 4131 // If a program calls for the default initialization of an object 4132 // of a const-qualified type T, T shall be a class type with a 4133 // user-provided default constructor. 4134 // C++ core issue 253 proposal: 4135 // If the implicit default constructor initializes all subobjects, no 4136 // initializer should be required. 4137 // The 253 proposal is for example needed to process libstdc++ headers in 5.x. 4138 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 4139 if (Kind.getKind() == InitializationKind::IK_Default && 4140 Entity.getType().isConstQualified()) { 4141 if (!CtorDecl->getParent()->allowConstDefaultInit()) { 4142 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 4143 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 4144 return; 4145 } 4146 } 4147 4148 // C++11 [over.match.list]p1: 4149 // In copy-list-initialization, if an explicit constructor is chosen, the 4150 // initializer is ill-formed. 4151 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { 4152 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); 4153 return; 4154 } 4155 4156 // Add the constructor initialization step. Any cv-qualification conversion is 4157 // subsumed by the initialization. 4158 Sequence.AddConstructorInitializationStep( 4159 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, 4160 IsListInit | IsInitListCopy, AsInitializerList); 4161 } 4162 4163 static bool 4164 ResolveOverloadedFunctionForReferenceBinding(Sema &S, 4165 Expr *Initializer, 4166 QualType &SourceType, 4167 QualType &UnqualifiedSourceType, 4168 QualType UnqualifiedTargetType, 4169 InitializationSequence &Sequence) { 4170 if (S.Context.getCanonicalType(UnqualifiedSourceType) == 4171 S.Context.OverloadTy) { 4172 DeclAccessPair Found; 4173 bool HadMultipleCandidates = false; 4174 if (FunctionDecl *Fn 4175 = S.ResolveAddressOfOverloadedFunction(Initializer, 4176 UnqualifiedTargetType, 4177 false, Found, 4178 &HadMultipleCandidates)) { 4179 Sequence.AddAddressOverloadResolutionStep(Fn, Found, 4180 HadMultipleCandidates); 4181 SourceType = Fn->getType(); 4182 UnqualifiedSourceType = SourceType.getUnqualifiedType(); 4183 } else if (!UnqualifiedTargetType->isRecordType()) { 4184 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4185 return true; 4186 } 4187 } 4188 return false; 4189 } 4190 4191 static void TryReferenceInitializationCore(Sema &S, 4192 const InitializedEntity &Entity, 4193 const InitializationKind &Kind, 4194 Expr *Initializer, 4195 QualType cv1T1, QualType T1, 4196 Qualifiers T1Quals, 4197 QualType cv2T2, QualType T2, 4198 Qualifiers T2Quals, 4199 InitializationSequence &Sequence); 4200 4201 static void TryValueInitialization(Sema &S, 4202 const InitializedEntity &Entity, 4203 const InitializationKind &Kind, 4204 InitializationSequence &Sequence, 4205 InitListExpr *InitList = nullptr); 4206 4207 /// Attempt list initialization of a reference. 4208 static void TryReferenceListInitialization(Sema &S, 4209 const InitializedEntity &Entity, 4210 const InitializationKind &Kind, 4211 InitListExpr *InitList, 4212 InitializationSequence &Sequence, 4213 bool TreatUnavailableAsInvalid) { 4214 // First, catch C++03 where this isn't possible. 4215 if (!S.getLangOpts().CPlusPlus11) { 4216 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4217 return; 4218 } 4219 // Can't reference initialize a compound literal. 4220 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { 4221 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4222 return; 4223 } 4224 4225 QualType DestType = Entity.getType(); 4226 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4227 Qualifiers T1Quals; 4228 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4229 4230 // Reference initialization via an initializer list works thus: 4231 // If the initializer list consists of a single element that is 4232 // reference-related to the referenced type, bind directly to that element 4233 // (possibly creating temporaries). 4234 // Otherwise, initialize a temporary with the initializer list and 4235 // bind to that. 4236 if (InitList->getNumInits() == 1) { 4237 Expr *Initializer = InitList->getInit(0); 4238 QualType cv2T2 = Initializer->getType(); 4239 Qualifiers T2Quals; 4240 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4241 4242 // If this fails, creating a temporary wouldn't work either. 4243 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4244 T1, Sequence)) 4245 return; 4246 4247 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4248 Sema::ReferenceCompareResult RefRelationship 4249 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); 4250 if (RefRelationship >= Sema::Ref_Related) { 4251 // Try to bind the reference here. 4252 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4253 T1Quals, cv2T2, T2, T2Quals, Sequence); 4254 if (Sequence) 4255 Sequence.RewrapReferenceInitList(cv1T1, InitList); 4256 return; 4257 } 4258 4259 // Update the initializer if we've resolved an overloaded function. 4260 if (Sequence.step_begin() != Sequence.step_end()) 4261 Sequence.RewrapReferenceInitList(cv1T1, InitList); 4262 } 4263 4264 // Not reference-related. Create a temporary and bind to that. 4265 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 4266 4267 TryListInitialization(S, TempEntity, Kind, InitList, Sequence, 4268 TreatUnavailableAsInvalid); 4269 if (Sequence) { 4270 if (DestType->isRValueReferenceType() || 4271 (T1Quals.hasConst() && !T1Quals.hasVolatile())) 4272 Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true); 4273 else 4274 Sequence.SetFailed( 4275 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 4276 } 4277 } 4278 4279 /// Attempt list initialization (C++0x [dcl.init.list]) 4280 static void TryListInitialization(Sema &S, 4281 const InitializedEntity &Entity, 4282 const InitializationKind &Kind, 4283 InitListExpr *InitList, 4284 InitializationSequence &Sequence, 4285 bool TreatUnavailableAsInvalid) { 4286 QualType DestType = Entity.getType(); 4287 4288 // C++ doesn't allow scalar initialization with more than one argument. 4289 // But C99 complex numbers are scalars and it makes sense there. 4290 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && 4291 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 4292 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 4293 return; 4294 } 4295 if (DestType->isReferenceType()) { 4296 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, 4297 TreatUnavailableAsInvalid); 4298 return; 4299 } 4300 4301 if (DestType->isRecordType() && 4302 !S.isCompleteType(InitList->getBeginLoc(), DestType)) { 4303 Sequence.setIncompleteTypeFailure(DestType); 4304 return; 4305 } 4306 4307 // C++11 [dcl.init.list]p3, per DR1467: 4308 // - If T is a class type and the initializer list has a single element of 4309 // type cv U, where U is T or a class derived from T, the object is 4310 // initialized from that element (by copy-initialization for 4311 // copy-list-initialization, or by direct-initialization for 4312 // direct-list-initialization). 4313 // - Otherwise, if T is a character array and the initializer list has a 4314 // single element that is an appropriately-typed string literal 4315 // (8.5.2 [dcl.init.string]), initialization is performed as described 4316 // in that section. 4317 // - Otherwise, if T is an aggregate, [...] (continue below). 4318 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { 4319 if (DestType->isRecordType()) { 4320 QualType InitType = InitList->getInit(0)->getType(); 4321 if (S.Context.hasSameUnqualifiedType(InitType, DestType) || 4322 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { 4323 Expr *InitListAsExpr = InitList; 4324 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4325 DestType, Sequence, 4326 /*InitListSyntax*/false, 4327 /*IsInitListCopy*/true); 4328 return; 4329 } 4330 } 4331 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { 4332 Expr *SubInit[1] = {InitList->getInit(0)}; 4333 if (!isa<VariableArrayType>(DestAT) && 4334 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { 4335 InitializationKind SubKind = 4336 Kind.getKind() == InitializationKind::IK_DirectList 4337 ? InitializationKind::CreateDirect(Kind.getLocation(), 4338 InitList->getLBraceLoc(), 4339 InitList->getRBraceLoc()) 4340 : Kind; 4341 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4342 /*TopLevelOfInitList*/ true, 4343 TreatUnavailableAsInvalid); 4344 4345 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if 4346 // the element is not an appropriately-typed string literal, in which 4347 // case we should proceed as in C++11 (below). 4348 if (Sequence) { 4349 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4350 return; 4351 } 4352 } 4353 } 4354 } 4355 4356 // C++11 [dcl.init.list]p3: 4357 // - If T is an aggregate, aggregate initialization is performed. 4358 if ((DestType->isRecordType() && !DestType->isAggregateType()) || 4359 (S.getLangOpts().CPlusPlus11 && 4360 S.isStdInitializerList(DestType, nullptr))) { 4361 if (S.getLangOpts().CPlusPlus11) { 4362 // - Otherwise, if the initializer list has no elements and T is a 4363 // class type with a default constructor, the object is 4364 // value-initialized. 4365 if (InitList->getNumInits() == 0) { 4366 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); 4367 if (S.LookupDefaultConstructor(RD)) { 4368 TryValueInitialization(S, Entity, Kind, Sequence, InitList); 4369 return; 4370 } 4371 } 4372 4373 // - Otherwise, if T is a specialization of std::initializer_list<E>, 4374 // an initializer_list object constructed [...] 4375 if (TryInitializerListConstruction(S, InitList, DestType, Sequence, 4376 TreatUnavailableAsInvalid)) 4377 return; 4378 4379 // - Otherwise, if T is a class type, constructors are considered. 4380 Expr *InitListAsExpr = InitList; 4381 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4382 DestType, Sequence, /*InitListSyntax*/true); 4383 } else 4384 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 4385 return; 4386 } 4387 4388 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && 4389 InitList->getNumInits() == 1) { 4390 Expr *E = InitList->getInit(0); 4391 4392 // - Otherwise, if T is an enumeration with a fixed underlying type, 4393 // the initializer-list has a single element v, and the initialization 4394 // is direct-list-initialization, the object is initialized with the 4395 // value T(v); if a narrowing conversion is required to convert v to 4396 // the underlying type of T, the program is ill-formed. 4397 auto *ET = DestType->getAs<EnumType>(); 4398 if (S.getLangOpts().CPlusPlus17 && 4399 Kind.getKind() == InitializationKind::IK_DirectList && 4400 ET && ET->getDecl()->isFixed() && 4401 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && 4402 (E->getType()->isIntegralOrEnumerationType() || 4403 E->getType()->isFloatingType())) { 4404 // There are two ways that T(v) can work when T is an enumeration type. 4405 // If there is either an implicit conversion sequence from v to T or 4406 // a conversion function that can convert from v to T, then we use that. 4407 // Otherwise, if v is of integral, enumeration, or floating-point type, 4408 // it is converted to the enumeration type via its underlying type. 4409 // There is no overlap possible between these two cases (except when the 4410 // source value is already of the destination type), and the first 4411 // case is handled by the general case for single-element lists below. 4412 ImplicitConversionSequence ICS; 4413 ICS.setStandard(); 4414 ICS.Standard.setAsIdentityConversion(); 4415 if (!E->isRValue()) 4416 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 4417 // If E is of a floating-point type, then the conversion is ill-formed 4418 // due to narrowing, but go through the motions in order to produce the 4419 // right diagnostic. 4420 ICS.Standard.Second = E->getType()->isFloatingType() 4421 ? ICK_Floating_Integral 4422 : ICK_Integral_Conversion; 4423 ICS.Standard.setFromType(E->getType()); 4424 ICS.Standard.setToType(0, E->getType()); 4425 ICS.Standard.setToType(1, DestType); 4426 ICS.Standard.setToType(2, DestType); 4427 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), 4428 /*TopLevelOfInitList*/true); 4429 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4430 return; 4431 } 4432 4433 // - Otherwise, if the initializer list has a single element of type E 4434 // [...references are handled above...], the object or reference is 4435 // initialized from that element (by copy-initialization for 4436 // copy-list-initialization, or by direct-initialization for 4437 // direct-list-initialization); if a narrowing conversion is required 4438 // to convert the element to T, the program is ill-formed. 4439 // 4440 // Per core-24034, this is direct-initialization if we were performing 4441 // direct-list-initialization and copy-initialization otherwise. 4442 // We can't use InitListChecker for this, because it always performs 4443 // copy-initialization. This only matters if we might use an 'explicit' 4444 // conversion operator, or for the special case conversion of nullptr_t to 4445 // bool, so we only need to handle those cases. 4446 // 4447 // FIXME: Why not do this in all cases? 4448 Expr *Init = InitList->getInit(0); 4449 if (Init->getType()->isRecordType() || 4450 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { 4451 InitializationKind SubKind = 4452 Kind.getKind() == InitializationKind::IK_DirectList 4453 ? InitializationKind::CreateDirect(Kind.getLocation(), 4454 InitList->getLBraceLoc(), 4455 InitList->getRBraceLoc()) 4456 : Kind; 4457 Expr *SubInit[1] = { Init }; 4458 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4459 /*TopLevelOfInitList*/true, 4460 TreatUnavailableAsInvalid); 4461 if (Sequence) 4462 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4463 return; 4464 } 4465 } 4466 4467 InitListChecker CheckInitList(S, Entity, InitList, 4468 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); 4469 if (CheckInitList.HadError()) { 4470 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 4471 return; 4472 } 4473 4474 // Add the list initialization step with the built init list. 4475 Sequence.AddListInitializationStep(DestType); 4476 } 4477 4478 /// Try a reference initialization that involves calling a conversion 4479 /// function. 4480 static OverloadingResult TryRefInitWithConversionFunction( 4481 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, 4482 Expr *Initializer, bool AllowRValues, bool IsLValueRef, 4483 InitializationSequence &Sequence) { 4484 QualType DestType = Entity.getType(); 4485 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4486 QualType T1 = cv1T1.getUnqualifiedType(); 4487 QualType cv2T2 = Initializer->getType(); 4488 QualType T2 = cv2T2.getUnqualifiedType(); 4489 4490 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && 4491 "Must have incompatible references when binding via conversion"); 4492 4493 // Build the candidate set directly in the initialization sequence 4494 // structure, so that it will persist if we fail. 4495 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4496 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4497 4498 // Determine whether we are allowed to call explicit conversion operators. 4499 // Note that none of [over.match.copy], [over.match.conv], nor 4500 // [over.match.ref] permit an explicit constructor to be chosen when 4501 // initializing a reference, not even for direct-initialization. 4502 bool AllowExplicitCtors = false; 4503 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); 4504 4505 const RecordType *T1RecordType = nullptr; 4506 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 4507 S.isCompleteType(Kind.getLocation(), T1)) { 4508 // The type we're converting to is a class type. Enumerate its constructors 4509 // to see if there is a suitable conversion. 4510 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 4511 4512 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { 4513 auto Info = getConstructorInfo(D); 4514 if (!Info.Constructor) 4515 continue; 4516 4517 if (!Info.Constructor->isInvalidDecl() && 4518 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 4519 if (Info.ConstructorTmpl) 4520 S.AddTemplateOverloadCandidate( 4521 Info.ConstructorTmpl, Info.FoundDecl, 4522 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 4523 /*SuppressUserConversions=*/true, 4524 /*PartialOverloading*/ false, AllowExplicitCtors); 4525 else 4526 S.AddOverloadCandidate( 4527 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, 4528 /*SuppressUserConversions=*/true, 4529 /*PartialOverloading*/ false, AllowExplicitCtors); 4530 } 4531 } 4532 } 4533 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 4534 return OR_No_Viable_Function; 4535 4536 const RecordType *T2RecordType = nullptr; 4537 if ((T2RecordType = T2->getAs<RecordType>()) && 4538 S.isCompleteType(Kind.getLocation(), T2)) { 4539 // The type we're converting from is a class type, enumerate its conversion 4540 // functions. 4541 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 4542 4543 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4544 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4545 NamedDecl *D = *I; 4546 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4547 if (isa<UsingShadowDecl>(D)) 4548 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4549 4550 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4551 CXXConversionDecl *Conv; 4552 if (ConvTemplate) 4553 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4554 else 4555 Conv = cast<CXXConversionDecl>(D); 4556 4557 // If the conversion function doesn't return a reference type, 4558 // it can't be considered for this conversion unless we're allowed to 4559 // consider rvalues. 4560 // FIXME: Do we need to make sure that we only consider conversion 4561 // candidates with reference-compatible results? That might be needed to 4562 // break recursion. 4563 if ((AllowRValues || 4564 Conv->getConversionType()->isLValueReferenceType())) { 4565 if (ConvTemplate) 4566 S.AddTemplateConversionCandidate( 4567 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 4568 CandidateSet, 4569 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4570 else 4571 S.AddConversionCandidate( 4572 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, 4573 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4574 } 4575 } 4576 } 4577 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 4578 return OR_No_Viable_Function; 4579 4580 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4581 4582 // Perform overload resolution. If it fails, return the failed result. 4583 OverloadCandidateSet::iterator Best; 4584 if (OverloadingResult Result 4585 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) 4586 return Result; 4587 4588 FunctionDecl *Function = Best->Function; 4589 // This is the overload that will be used for this initialization step if we 4590 // use this initialization. Mark it as referenced. 4591 Function->setReferenced(); 4592 4593 // Compute the returned type and value kind of the conversion. 4594 QualType cv3T3; 4595 if (isa<CXXConversionDecl>(Function)) 4596 cv3T3 = Function->getReturnType(); 4597 else 4598 cv3T3 = T1; 4599 4600 ExprValueKind VK = VK_RValue; 4601 if (cv3T3->isLValueReferenceType()) 4602 VK = VK_LValue; 4603 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) 4604 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 4605 cv3T3 = cv3T3.getNonLValueExprType(S.Context); 4606 4607 // Add the user-defined conversion step. 4608 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4609 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, 4610 HadMultipleCandidates); 4611 4612 // Determine whether we'll need to perform derived-to-base adjustments or 4613 // other conversions. 4614 Sema::ReferenceConversions RefConv; 4615 Sema::ReferenceCompareResult NewRefRelationship = 4616 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); 4617 4618 // Add the final conversion sequence, if necessary. 4619 if (NewRefRelationship == Sema::Ref_Incompatible) { 4620 assert(!isa<CXXConstructorDecl>(Function) && 4621 "should not have conversion after constructor"); 4622 4623 ImplicitConversionSequence ICS; 4624 ICS.setStandard(); 4625 ICS.Standard = Best->FinalConversion; 4626 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); 4627 4628 // Every implicit conversion results in a prvalue, except for a glvalue 4629 // derived-to-base conversion, which we handle below. 4630 cv3T3 = ICS.Standard.getToType(2); 4631 VK = VK_RValue; 4632 } 4633 4634 // If the converted initializer is a prvalue, its type T4 is adjusted to 4635 // type "cv1 T4" and the temporary materialization conversion is applied. 4636 // 4637 // We adjust the cv-qualifications to match the reference regardless of 4638 // whether we have a prvalue so that the AST records the change. In this 4639 // case, T4 is "cv3 T3". 4640 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); 4641 if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) 4642 Sequence.AddQualificationConversionStep(cv1T4, VK); 4643 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); 4644 VK = IsLValueRef ? VK_LValue : VK_XValue; 4645 4646 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4647 Sequence.AddDerivedToBaseCastStep(cv1T1, VK); 4648 else if (RefConv & Sema::ReferenceConversions::ObjC) 4649 Sequence.AddObjCObjectConversionStep(cv1T1); 4650 else if (RefConv & Sema::ReferenceConversions::Function) 4651 Sequence.AddQualificationConversionStep(cv1T1, VK); 4652 else if (RefConv & Sema::ReferenceConversions::Qualification) { 4653 if (!S.Context.hasSameType(cv1T4, cv1T1)) 4654 Sequence.AddQualificationConversionStep(cv1T1, VK); 4655 } 4656 4657 return OR_Success; 4658 } 4659 4660 static void CheckCXX98CompatAccessibleCopy(Sema &S, 4661 const InitializedEntity &Entity, 4662 Expr *CurInitExpr); 4663 4664 /// Attempt reference initialization (C++0x [dcl.init.ref]) 4665 static void TryReferenceInitialization(Sema &S, 4666 const InitializedEntity &Entity, 4667 const InitializationKind &Kind, 4668 Expr *Initializer, 4669 InitializationSequence &Sequence) { 4670 QualType DestType = Entity.getType(); 4671 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4672 Qualifiers T1Quals; 4673 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4674 QualType cv2T2 = Initializer->getType(); 4675 Qualifiers T2Quals; 4676 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4677 4678 // If the initializer is the address of an overloaded function, try 4679 // to resolve the overloaded function. If all goes well, T2 is the 4680 // type of the resulting function. 4681 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4682 T1, Sequence)) 4683 return; 4684 4685 // Delegate everything else to a subfunction. 4686 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4687 T1Quals, cv2T2, T2, T2Quals, Sequence); 4688 } 4689 4690 /// Determine whether an expression is a non-referenceable glvalue (one to 4691 /// which a reference can never bind). Attempting to bind a reference to 4692 /// such a glvalue will always create a temporary. 4693 static bool isNonReferenceableGLValue(Expr *E) { 4694 return E->refersToBitField() || E->refersToVectorElement() || 4695 E->refersToMatrixElement(); 4696 } 4697 4698 /// Reference initialization without resolving overloaded functions. 4699 /// 4700 /// We also can get here in C if we call a builtin which is declared as 4701 /// a function with a parameter of reference type (such as __builtin_va_end()). 4702 static void TryReferenceInitializationCore(Sema &S, 4703 const InitializedEntity &Entity, 4704 const InitializationKind &Kind, 4705 Expr *Initializer, 4706 QualType cv1T1, QualType T1, 4707 Qualifiers T1Quals, 4708 QualType cv2T2, QualType T2, 4709 Qualifiers T2Quals, 4710 InitializationSequence &Sequence) { 4711 QualType DestType = Entity.getType(); 4712 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4713 4714 // Compute some basic properties of the types and the initializer. 4715 bool isLValueRef = DestType->isLValueReferenceType(); 4716 bool isRValueRef = !isLValueRef; 4717 Expr::Classification InitCategory = Initializer->Classify(S.Context); 4718 4719 Sema::ReferenceConversions RefConv; 4720 Sema::ReferenceCompareResult RefRelationship = 4721 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); 4722 4723 // C++0x [dcl.init.ref]p5: 4724 // A reference to type "cv1 T1" is initialized by an expression of type 4725 // "cv2 T2" as follows: 4726 // 4727 // - If the reference is an lvalue reference and the initializer 4728 // expression 4729 // Note the analogous bullet points for rvalue refs to functions. Because 4730 // there are no function rvalues in C++, rvalue refs to functions are treated 4731 // like lvalue refs. 4732 OverloadingResult ConvOvlResult = OR_Success; 4733 bool T1Function = T1->isFunctionType(); 4734 if (isLValueRef || T1Function) { 4735 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && 4736 (RefRelationship == Sema::Ref_Compatible || 4737 (Kind.isCStyleOrFunctionalCast() && 4738 RefRelationship == Sema::Ref_Related))) { 4739 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 4740 // reference-compatible with "cv2 T2," or 4741 if (RefConv & (Sema::ReferenceConversions::DerivedToBase | 4742 Sema::ReferenceConversions::ObjC)) { 4743 // If we're converting the pointee, add any qualifiers first; 4744 // these qualifiers must all be top-level, so just convert to "cv1 T2". 4745 if (RefConv & (Sema::ReferenceConversions::Qualification)) 4746 Sequence.AddQualificationConversionStep( 4747 S.Context.getQualifiedType(T2, T1Quals), 4748 Initializer->getValueKind()); 4749 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4750 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); 4751 else 4752 Sequence.AddObjCObjectConversionStep(cv1T1); 4753 } else if (RefConv & (Sema::ReferenceConversions::Qualification | 4754 Sema::ReferenceConversions::Function)) { 4755 // Perform a (possibly multi-level) qualification conversion. 4756 // FIXME: Should we use a different step kind for function conversions? 4757 Sequence.AddQualificationConversionStep(cv1T1, 4758 Initializer->getValueKind()); 4759 } 4760 4761 // We only create a temporary here when binding a reference to a 4762 // bit-field or vector element. Those cases are't supposed to be 4763 // handled by this bullet, but the outcome is the same either way. 4764 Sequence.AddReferenceBindingStep(cv1T1, false); 4765 return; 4766 } 4767 4768 // - has a class type (i.e., T2 is a class type), where T1 is not 4769 // reference-related to T2, and can be implicitly converted to an 4770 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 4771 // with "cv3 T3" (this conversion is selected by enumerating the 4772 // applicable conversion functions (13.3.1.6) and choosing the best 4773 // one through overload resolution (13.3)), 4774 // If we have an rvalue ref to function type here, the rhs must be 4775 // an rvalue. DR1287 removed the "implicitly" here. 4776 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 4777 (isLValueRef || InitCategory.isRValue())) { 4778 if (S.getLangOpts().CPlusPlus) { 4779 // Try conversion functions only for C++. 4780 ConvOvlResult = TryRefInitWithConversionFunction( 4781 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, 4782 /*IsLValueRef*/ isLValueRef, Sequence); 4783 if (ConvOvlResult == OR_Success) 4784 return; 4785 if (ConvOvlResult != OR_No_Viable_Function) 4786 Sequence.SetOverloadFailure( 4787 InitializationSequence::FK_ReferenceInitOverloadFailed, 4788 ConvOvlResult); 4789 } else { 4790 ConvOvlResult = OR_No_Viable_Function; 4791 } 4792 } 4793 } 4794 4795 // - Otherwise, the reference shall be an lvalue reference to a 4796 // non-volatile const type (i.e., cv1 shall be const), or the reference 4797 // shall be an rvalue reference. 4798 // For address spaces, we interpret this to mean that an addr space 4799 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". 4800 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && 4801 T1Quals.isAddressSpaceSupersetOf(T2Quals))) { 4802 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4803 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4804 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4805 Sequence.SetOverloadFailure( 4806 InitializationSequence::FK_ReferenceInitOverloadFailed, 4807 ConvOvlResult); 4808 else if (!InitCategory.isLValue()) 4809 Sequence.SetFailed( 4810 T1Quals.isAddressSpaceSupersetOf(T2Quals) 4811 ? InitializationSequence:: 4812 FK_NonConstLValueReferenceBindingToTemporary 4813 : InitializationSequence::FK_ReferenceInitDropsQualifiers); 4814 else { 4815 InitializationSequence::FailureKind FK; 4816 switch (RefRelationship) { 4817 case Sema::Ref_Compatible: 4818 if (Initializer->refersToBitField()) 4819 FK = InitializationSequence:: 4820 FK_NonConstLValueReferenceBindingToBitfield; 4821 else if (Initializer->refersToVectorElement()) 4822 FK = InitializationSequence:: 4823 FK_NonConstLValueReferenceBindingToVectorElement; 4824 else if (Initializer->refersToMatrixElement()) 4825 FK = InitializationSequence:: 4826 FK_NonConstLValueReferenceBindingToMatrixElement; 4827 else 4828 llvm_unreachable("unexpected kind of compatible initializer"); 4829 break; 4830 case Sema::Ref_Related: 4831 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; 4832 break; 4833 case Sema::Ref_Incompatible: 4834 FK = InitializationSequence:: 4835 FK_NonConstLValueReferenceBindingToUnrelated; 4836 break; 4837 } 4838 Sequence.SetFailed(FK); 4839 } 4840 return; 4841 } 4842 4843 // - If the initializer expression 4844 // - is an 4845 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or 4846 // [1z] rvalue (but not a bit-field) or 4847 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" 4848 // 4849 // Note: functions are handled above and below rather than here... 4850 if (!T1Function && 4851 (RefRelationship == Sema::Ref_Compatible || 4852 (Kind.isCStyleOrFunctionalCast() && 4853 RefRelationship == Sema::Ref_Related)) && 4854 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || 4855 (InitCategory.isPRValue() && 4856 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || 4857 T2->isArrayType())))) { 4858 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; 4859 if (InitCategory.isPRValue() && T2->isRecordType()) { 4860 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 4861 // compiler the freedom to perform a copy here or bind to the 4862 // object, while C++0x requires that we bind directly to the 4863 // object. Hence, we always bind to the object without making an 4864 // extra copy. However, in C++03 requires that we check for the 4865 // presence of a suitable copy constructor: 4866 // 4867 // The constructor that would be used to make the copy shall 4868 // be callable whether or not the copy is actually done. 4869 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) 4870 Sequence.AddExtraneousCopyToTemporary(cv2T2); 4871 else if (S.getLangOpts().CPlusPlus11) 4872 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 4873 } 4874 4875 // C++1z [dcl.init.ref]/5.2.1.2: 4876 // If the converted initializer is a prvalue, its type T4 is adjusted 4877 // to type "cv1 T4" and the temporary materialization conversion is 4878 // applied. 4879 // Postpone address space conversions to after the temporary materialization 4880 // conversion to allow creating temporaries in the alloca address space. 4881 auto T1QualsIgnoreAS = T1Quals; 4882 auto T2QualsIgnoreAS = T2Quals; 4883 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4884 T1QualsIgnoreAS.removeAddressSpace(); 4885 T2QualsIgnoreAS.removeAddressSpace(); 4886 } 4887 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); 4888 if (T1QualsIgnoreAS != T2QualsIgnoreAS) 4889 Sequence.AddQualificationConversionStep(cv1T4, ValueKind); 4890 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); 4891 ValueKind = isLValueRef ? VK_LValue : VK_XValue; 4892 // Add addr space conversion if required. 4893 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4894 auto T4Quals = cv1T4.getQualifiers(); 4895 T4Quals.addAddressSpace(T1Quals.getAddressSpace()); 4896 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); 4897 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); 4898 cv1T4 = cv1T4WithAS; 4899 } 4900 4901 // In any case, the reference is bound to the resulting glvalue (or to 4902 // an appropriate base class subobject). 4903 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4904 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); 4905 else if (RefConv & Sema::ReferenceConversions::ObjC) 4906 Sequence.AddObjCObjectConversionStep(cv1T1); 4907 else if (RefConv & Sema::ReferenceConversions::Qualification) { 4908 if (!S.Context.hasSameType(cv1T4, cv1T1)) 4909 Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 4910 } 4911 return; 4912 } 4913 4914 // - has a class type (i.e., T2 is a class type), where T1 is not 4915 // reference-related to T2, and can be implicitly converted to an 4916 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 4917 // where "cv1 T1" is reference-compatible with "cv3 T3", 4918 // 4919 // DR1287 removes the "implicitly" here. 4920 if (T2->isRecordType()) { 4921 if (RefRelationship == Sema::Ref_Incompatible) { 4922 ConvOvlResult = TryRefInitWithConversionFunction( 4923 S, Entity, Kind, Initializer, /*AllowRValues*/ true, 4924 /*IsLValueRef*/ isLValueRef, Sequence); 4925 if (ConvOvlResult) 4926 Sequence.SetOverloadFailure( 4927 InitializationSequence::FK_ReferenceInitOverloadFailed, 4928 ConvOvlResult); 4929 4930 return; 4931 } 4932 4933 if (RefRelationship == Sema::Ref_Compatible && 4934 isRValueRef && InitCategory.isLValue()) { 4935 Sequence.SetFailed( 4936 InitializationSequence::FK_RValueReferenceBindingToLValue); 4937 return; 4938 } 4939 4940 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 4941 return; 4942 } 4943 4944 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 4945 // from the initializer expression using the rules for a non-reference 4946 // copy-initialization (8.5). The reference is then bound to the 4947 // temporary. [...] 4948 4949 // Ignore address space of reference type at this point and perform address 4950 // space conversion after the reference binding step. 4951 QualType cv1T1IgnoreAS = 4952 T1Quals.hasAddressSpace() 4953 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) 4954 : cv1T1; 4955 4956 InitializedEntity TempEntity = 4957 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); 4958 4959 // FIXME: Why do we use an implicit conversion here rather than trying 4960 // copy-initialization? 4961 ImplicitConversionSequence ICS 4962 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 4963 /*SuppressUserConversions=*/false, 4964 Sema::AllowedExplicit::None, 4965 /*FIXME:InOverloadResolution=*/false, 4966 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 4967 /*AllowObjCWritebackConversion=*/false); 4968 4969 if (ICS.isBad()) { 4970 // FIXME: Use the conversion function set stored in ICS to turn 4971 // this into an overloading ambiguity diagnostic. However, we need 4972 // to keep that set as an OverloadCandidateSet rather than as some 4973 // other kind of set. 4974 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4975 Sequence.SetOverloadFailure( 4976 InitializationSequence::FK_ReferenceInitOverloadFailed, 4977 ConvOvlResult); 4978 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4979 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4980 else 4981 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 4982 return; 4983 } else { 4984 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 4985 } 4986 4987 // [...] If T1 is reference-related to T2, cv1 must be the 4988 // same cv-qualification as, or greater cv-qualification 4989 // than, cv2; otherwise, the program is ill-formed. 4990 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 4991 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 4992 if ((RefRelationship == Sema::Ref_Related && 4993 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) || 4994 !T1Quals.isAddressSpaceSupersetOf(T2Quals)) { 4995 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 4996 return; 4997 } 4998 4999 // [...] If T1 is reference-related to T2 and the reference is an rvalue 5000 // reference, the initializer expression shall not be an lvalue. 5001 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 5002 InitCategory.isLValue()) { 5003 Sequence.SetFailed( 5004 InitializationSequence::FK_RValueReferenceBindingToLValue); 5005 return; 5006 } 5007 5008 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); 5009 5010 if (T1Quals.hasAddressSpace()) { 5011 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), 5012 LangAS::Default)) { 5013 Sequence.SetFailed( 5014 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); 5015 return; 5016 } 5017 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue 5018 : VK_XValue); 5019 } 5020 } 5021 5022 /// Attempt character array initialization from a string literal 5023 /// (C++ [dcl.init.string], C99 6.7.8). 5024 static void TryStringLiteralInitialization(Sema &S, 5025 const InitializedEntity &Entity, 5026 const InitializationKind &Kind, 5027 Expr *Initializer, 5028 InitializationSequence &Sequence) { 5029 Sequence.AddStringInitStep(Entity.getType()); 5030 } 5031 5032 /// Attempt value initialization (C++ [dcl.init]p7). 5033 static void TryValueInitialization(Sema &S, 5034 const InitializedEntity &Entity, 5035 const InitializationKind &Kind, 5036 InitializationSequence &Sequence, 5037 InitListExpr *InitList) { 5038 assert((!InitList || InitList->getNumInits() == 0) && 5039 "Shouldn't use value-init for non-empty init lists"); 5040 5041 // C++98 [dcl.init]p5, C++11 [dcl.init]p7: 5042 // 5043 // To value-initialize an object of type T means: 5044 QualType T = Entity.getType(); 5045 5046 // -- if T is an array type, then each element is value-initialized; 5047 T = S.Context.getBaseElementType(T); 5048 5049 if (const RecordType *RT = T->getAs<RecordType>()) { 5050 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 5051 bool NeedZeroInitialization = true; 5052 // C++98: 5053 // -- if T is a class type (clause 9) with a user-declared constructor 5054 // (12.1), then the default constructor for T is called (and the 5055 // initialization is ill-formed if T has no accessible default 5056 // constructor); 5057 // C++11: 5058 // -- if T is a class type (clause 9) with either no default constructor 5059 // (12.1 [class.ctor]) or a default constructor that is user-provided 5060 // or deleted, then the object is default-initialized; 5061 // 5062 // Note that the C++11 rule is the same as the C++98 rule if there are no 5063 // defaulted or deleted constructors, so we just use it unconditionally. 5064 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); 5065 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) 5066 NeedZeroInitialization = false; 5067 5068 // -- if T is a (possibly cv-qualified) non-union class type without a 5069 // user-provided or deleted default constructor, then the object is 5070 // zero-initialized and, if T has a non-trivial default constructor, 5071 // default-initialized; 5072 // The 'non-union' here was removed by DR1502. The 'non-trivial default 5073 // constructor' part was removed by DR1507. 5074 if (NeedZeroInitialization) 5075 Sequence.AddZeroInitializationStep(Entity.getType()); 5076 5077 // C++03: 5078 // -- if T is a non-union class type without a user-declared constructor, 5079 // then every non-static data member and base class component of T is 5080 // value-initialized; 5081 // [...] A program that calls for [...] value-initialization of an 5082 // entity of reference type is ill-formed. 5083 // 5084 // C++11 doesn't need this handling, because value-initialization does not 5085 // occur recursively there, and the implicit default constructor is 5086 // defined as deleted in the problematic cases. 5087 if (!S.getLangOpts().CPlusPlus11 && 5088 ClassDecl->hasUninitializedReferenceMember()) { 5089 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); 5090 return; 5091 } 5092 5093 // If this is list-value-initialization, pass the empty init list on when 5094 // building the constructor call. This affects the semantics of a few 5095 // things (such as whether an explicit default constructor can be called). 5096 Expr *InitListAsExpr = InitList; 5097 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); 5098 bool InitListSyntax = InitList; 5099 5100 // FIXME: Instead of creating a CXXConstructExpr of array type here, 5101 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. 5102 return TryConstructorInitialization( 5103 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); 5104 } 5105 } 5106 5107 Sequence.AddZeroInitializationStep(Entity.getType()); 5108 } 5109 5110 /// Attempt default initialization (C++ [dcl.init]p6). 5111 static void TryDefaultInitialization(Sema &S, 5112 const InitializedEntity &Entity, 5113 const InitializationKind &Kind, 5114 InitializationSequence &Sequence) { 5115 assert(Kind.getKind() == InitializationKind::IK_Default); 5116 5117 // C++ [dcl.init]p6: 5118 // To default-initialize an object of type T means: 5119 // - if T is an array type, each element is default-initialized; 5120 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 5121 5122 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 5123 // constructor for T is called (and the initialization is ill-formed if 5124 // T has no accessible default constructor); 5125 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { 5126 TryConstructorInitialization(S, Entity, Kind, None, DestType, 5127 Entity.getType(), Sequence); 5128 return; 5129 } 5130 5131 // - otherwise, no initialization is performed. 5132 5133 // If a program calls for the default initialization of an object of 5134 // a const-qualified type T, T shall be a class type with a user-provided 5135 // default constructor. 5136 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { 5137 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 5138 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 5139 return; 5140 } 5141 5142 // If the destination type has a lifetime property, zero-initialize it. 5143 if (DestType.getQualifiers().hasObjCLifetime()) { 5144 Sequence.AddZeroInitializationStep(Entity.getType()); 5145 return; 5146 } 5147 } 5148 5149 /// Attempt a user-defined conversion between two types (C++ [dcl.init]), 5150 /// which enumerates all conversion functions and performs overload resolution 5151 /// to select the best. 5152 static void TryUserDefinedConversion(Sema &S, 5153 QualType DestType, 5154 const InitializationKind &Kind, 5155 Expr *Initializer, 5156 InitializationSequence &Sequence, 5157 bool TopLevelOfInitList) { 5158 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 5159 QualType SourceType = Initializer->getType(); 5160 assert((DestType->isRecordType() || SourceType->isRecordType()) && 5161 "Must have a class type to perform a user-defined conversion"); 5162 5163 // Build the candidate set directly in the initialization sequence 5164 // structure, so that it will persist if we fail. 5165 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 5166 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 5167 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 5168 5169 // Determine whether we are allowed to call explicit constructors or 5170 // explicit conversion operators. 5171 bool AllowExplicit = Kind.AllowExplicit(); 5172 5173 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 5174 // The type we're converting to is a class type. Enumerate its constructors 5175 // to see if there is a suitable conversion. 5176 CXXRecordDecl *DestRecordDecl 5177 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 5178 5179 // Try to complete the type we're converting to. 5180 if (S.isCompleteType(Kind.getLocation(), DestType)) { 5181 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { 5182 auto Info = getConstructorInfo(D); 5183 if (!Info.Constructor) 5184 continue; 5185 5186 if (!Info.Constructor->isInvalidDecl() && 5187 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 5188 if (Info.ConstructorTmpl) 5189 S.AddTemplateOverloadCandidate( 5190 Info.ConstructorTmpl, Info.FoundDecl, 5191 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 5192 /*SuppressUserConversions=*/true, 5193 /*PartialOverloading*/ false, AllowExplicit); 5194 else 5195 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 5196 Initializer, CandidateSet, 5197 /*SuppressUserConversions=*/true, 5198 /*PartialOverloading*/ false, AllowExplicit); 5199 } 5200 } 5201 } 5202 } 5203 5204 SourceLocation DeclLoc = Initializer->getBeginLoc(); 5205 5206 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 5207 // The type we're converting from is a class type, enumerate its conversion 5208 // functions. 5209 5210 // We can only enumerate the conversion functions for a complete type; if 5211 // the type isn't complete, simply skip this step. 5212 if (S.isCompleteType(DeclLoc, SourceType)) { 5213 CXXRecordDecl *SourceRecordDecl 5214 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 5215 5216 const auto &Conversions = 5217 SourceRecordDecl->getVisibleConversionFunctions(); 5218 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5219 NamedDecl *D = *I; 5220 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 5221 if (isa<UsingShadowDecl>(D)) 5222 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5223 5224 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5225 CXXConversionDecl *Conv; 5226 if (ConvTemplate) 5227 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5228 else 5229 Conv = cast<CXXConversionDecl>(D); 5230 5231 if (ConvTemplate) 5232 S.AddTemplateConversionCandidate( 5233 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 5234 CandidateSet, AllowExplicit, AllowExplicit); 5235 else 5236 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 5237 DestType, CandidateSet, AllowExplicit, 5238 AllowExplicit); 5239 } 5240 } 5241 } 5242 5243 // Perform overload resolution. If it fails, return the failed result. 5244 OverloadCandidateSet::iterator Best; 5245 if (OverloadingResult Result 5246 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 5247 Sequence.SetOverloadFailure( 5248 InitializationSequence::FK_UserConversionOverloadFailed, 5249 Result); 5250 return; 5251 } 5252 5253 FunctionDecl *Function = Best->Function; 5254 Function->setReferenced(); 5255 bool HadMultipleCandidates = (CandidateSet.size() > 1); 5256 5257 if (isa<CXXConstructorDecl>(Function)) { 5258 // Add the user-defined conversion step. Any cv-qualification conversion is 5259 // subsumed by the initialization. Per DR5, the created temporary is of the 5260 // cv-unqualified type of the destination. 5261 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 5262 DestType.getUnqualifiedType(), 5263 HadMultipleCandidates); 5264 5265 // C++14 and before: 5266 // - if the function is a constructor, the call initializes a temporary 5267 // of the cv-unqualified version of the destination type. The [...] 5268 // temporary [...] is then used to direct-initialize, according to the 5269 // rules above, the object that is the destination of the 5270 // copy-initialization. 5271 // Note that this just performs a simple object copy from the temporary. 5272 // 5273 // C++17: 5274 // - if the function is a constructor, the call is a prvalue of the 5275 // cv-unqualified version of the destination type whose return object 5276 // is initialized by the constructor. The call is used to 5277 // direct-initialize, according to the rules above, the object that 5278 // is the destination of the copy-initialization. 5279 // Therefore we need to do nothing further. 5280 // 5281 // FIXME: Mark this copy as extraneous. 5282 if (!S.getLangOpts().CPlusPlus17) 5283 Sequence.AddFinalCopy(DestType); 5284 else if (DestType.hasQualifiers()) 5285 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5286 return; 5287 } 5288 5289 // Add the user-defined conversion step that calls the conversion function. 5290 QualType ConvType = Function->getCallResultType(); 5291 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 5292 HadMultipleCandidates); 5293 5294 if (ConvType->getAs<RecordType>()) { 5295 // The call is used to direct-initialize [...] the object that is the 5296 // destination of the copy-initialization. 5297 // 5298 // In C++17, this does not call a constructor if we enter /17.6.1: 5299 // - If the initializer expression is a prvalue and the cv-unqualified 5300 // version of the source type is the same as the class of the 5301 // destination [... do not make an extra copy] 5302 // 5303 // FIXME: Mark this copy as extraneous. 5304 if (!S.getLangOpts().CPlusPlus17 || 5305 Function->getReturnType()->isReferenceType() || 5306 !S.Context.hasSameUnqualifiedType(ConvType, DestType)) 5307 Sequence.AddFinalCopy(DestType); 5308 else if (!S.Context.hasSameType(ConvType, DestType)) 5309 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5310 return; 5311 } 5312 5313 // If the conversion following the call to the conversion function 5314 // is interesting, add it as a separate step. 5315 if (Best->FinalConversion.First || Best->FinalConversion.Second || 5316 Best->FinalConversion.Third) { 5317 ImplicitConversionSequence ICS; 5318 ICS.setStandard(); 5319 ICS.Standard = Best->FinalConversion; 5320 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5321 } 5322 } 5323 5324 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, 5325 /// a function with a pointer return type contains a 'return false;' statement. 5326 /// In C++11, 'false' is not a null pointer, so this breaks the build of any 5327 /// code using that header. 5328 /// 5329 /// Work around this by treating 'return false;' as zero-initializing the result 5330 /// if it's used in a pointer-returning function in a system header. 5331 static bool isLibstdcxxPointerReturnFalseHack(Sema &S, 5332 const InitializedEntity &Entity, 5333 const Expr *Init) { 5334 return S.getLangOpts().CPlusPlus11 && 5335 Entity.getKind() == InitializedEntity::EK_Result && 5336 Entity.getType()->isPointerType() && 5337 isa<CXXBoolLiteralExpr>(Init) && 5338 !cast<CXXBoolLiteralExpr>(Init)->getValue() && 5339 S.getSourceManager().isInSystemHeader(Init->getExprLoc()); 5340 } 5341 5342 /// The non-zero enum values here are indexes into diagnostic alternatives. 5343 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 5344 5345 /// Determines whether this expression is an acceptable ICR source. 5346 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 5347 bool isAddressOf, bool &isWeakAccess) { 5348 // Skip parens. 5349 e = e->IgnoreParens(); 5350 5351 // Skip address-of nodes. 5352 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 5353 if (op->getOpcode() == UO_AddrOf) 5354 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, 5355 isWeakAccess); 5356 5357 // Skip certain casts. 5358 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 5359 switch (ce->getCastKind()) { 5360 case CK_Dependent: 5361 case CK_BitCast: 5362 case CK_LValueBitCast: 5363 case CK_NoOp: 5364 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); 5365 5366 case CK_ArrayToPointerDecay: 5367 return IIK_nonscalar; 5368 5369 case CK_NullToPointer: 5370 return IIK_okay; 5371 5372 default: 5373 break; 5374 } 5375 5376 // If we have a declaration reference, it had better be a local variable. 5377 } else if (isa<DeclRefExpr>(e)) { 5378 // set isWeakAccess to true, to mean that there will be an implicit 5379 // load which requires a cleanup. 5380 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 5381 isWeakAccess = true; 5382 5383 if (!isAddressOf) return IIK_nonlocal; 5384 5385 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 5386 if (!var) return IIK_nonlocal; 5387 5388 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 5389 5390 // If we have a conditional operator, check both sides. 5391 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 5392 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, 5393 isWeakAccess)) 5394 return iik; 5395 5396 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); 5397 5398 // These are never scalar. 5399 } else if (isa<ArraySubscriptExpr>(e)) { 5400 return IIK_nonscalar; 5401 5402 // Otherwise, it needs to be a null pointer constant. 5403 } else { 5404 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 5405 ? IIK_okay : IIK_nonlocal); 5406 } 5407 5408 return IIK_nonlocal; 5409 } 5410 5411 /// Check whether the given expression is a valid operand for an 5412 /// indirect copy/restore. 5413 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 5414 assert(src->isRValue()); 5415 bool isWeakAccess = false; 5416 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); 5417 // If isWeakAccess to true, there will be an implicit 5418 // load which requires a cleanup. 5419 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) 5420 S.Cleanup.setExprNeedsCleanups(true); 5421 5422 if (iik == IIK_okay) return; 5423 5424 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 5425 << ((unsigned) iik - 1) // shift index into diagnostic explanations 5426 << src->getSourceRange(); 5427 } 5428 5429 /// Determine whether we have compatible array types for the 5430 /// purposes of GNU by-copy array initialization. 5431 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, 5432 const ArrayType *Source) { 5433 // If the source and destination array types are equivalent, we're 5434 // done. 5435 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 5436 return true; 5437 5438 // Make sure that the element types are the same. 5439 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 5440 return false; 5441 5442 // The only mismatch we allow is when the destination is an 5443 // incomplete array type and the source is a constant array type. 5444 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 5445 } 5446 5447 static bool tryObjCWritebackConversion(Sema &S, 5448 InitializationSequence &Sequence, 5449 const InitializedEntity &Entity, 5450 Expr *Initializer) { 5451 bool ArrayDecay = false; 5452 QualType ArgType = Initializer->getType(); 5453 QualType ArgPointee; 5454 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 5455 ArrayDecay = true; 5456 ArgPointee = ArgArrayType->getElementType(); 5457 ArgType = S.Context.getPointerType(ArgPointee); 5458 } 5459 5460 // Handle write-back conversion. 5461 QualType ConvertedArgType; 5462 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 5463 ConvertedArgType)) 5464 return false; 5465 5466 // We should copy unless we're passing to an argument explicitly 5467 // marked 'out'. 5468 bool ShouldCopy = true; 5469 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5470 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5471 5472 // Do we need an lvalue conversion? 5473 if (ArrayDecay || Initializer->isGLValue()) { 5474 ImplicitConversionSequence ICS; 5475 ICS.setStandard(); 5476 ICS.Standard.setAsIdentityConversion(); 5477 5478 QualType ResultType; 5479 if (ArrayDecay) { 5480 ICS.Standard.First = ICK_Array_To_Pointer; 5481 ResultType = S.Context.getPointerType(ArgPointee); 5482 } else { 5483 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 5484 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 5485 } 5486 5487 Sequence.AddConversionSequenceStep(ICS, ResultType); 5488 } 5489 5490 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 5491 return true; 5492 } 5493 5494 static bool TryOCLSamplerInitialization(Sema &S, 5495 InitializationSequence &Sequence, 5496 QualType DestType, 5497 Expr *Initializer) { 5498 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || 5499 (!Initializer->isIntegerConstantExpr(S.Context) && 5500 !Initializer->getType()->isSamplerT())) 5501 return false; 5502 5503 Sequence.AddOCLSamplerInitStep(DestType); 5504 return true; 5505 } 5506 5507 static bool IsZeroInitializer(Expr *Initializer, Sema &S) { 5508 return Initializer->isIntegerConstantExpr(S.getASTContext()) && 5509 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); 5510 } 5511 5512 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, 5513 InitializationSequence &Sequence, 5514 QualType DestType, 5515 Expr *Initializer) { 5516 if (!S.getLangOpts().OpenCL) 5517 return false; 5518 5519 // 5520 // OpenCL 1.2 spec, s6.12.10 5521 // 5522 // The event argument can also be used to associate the 5523 // async_work_group_copy with a previous async copy allowing 5524 // an event to be shared by multiple async copies; otherwise 5525 // event should be zero. 5526 // 5527 if (DestType->isEventT() || DestType->isQueueT()) { 5528 if (!IsZeroInitializer(Initializer, S)) 5529 return false; 5530 5531 Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5532 return true; 5533 } 5534 5535 // We should allow zero initialization for all types defined in the 5536 // cl_intel_device_side_avc_motion_estimation extension, except 5537 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. 5538 if (S.getOpenCLOptions().isEnabled( 5539 "cl_intel_device_side_avc_motion_estimation") && 5540 DestType->isOCLIntelSubgroupAVCType()) { 5541 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || 5542 DestType->isOCLIntelSubgroupAVCMceResultType()) 5543 return false; 5544 if (!IsZeroInitializer(Initializer, S)) 5545 return false; 5546 5547 Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5548 return true; 5549 } 5550 5551 return false; 5552 } 5553 5554 InitializationSequence::InitializationSequence(Sema &S, 5555 const InitializedEntity &Entity, 5556 const InitializationKind &Kind, 5557 MultiExprArg Args, 5558 bool TopLevelOfInitList, 5559 bool TreatUnavailableAsInvalid) 5560 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { 5561 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, 5562 TreatUnavailableAsInvalid); 5563 } 5564 5565 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the 5566 /// address of that function, this returns true. Otherwise, it returns false. 5567 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { 5568 auto *DRE = dyn_cast<DeclRefExpr>(E); 5569 if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) 5570 return false; 5571 5572 return !S.checkAddressOfFunctionIsAvailable( 5573 cast<FunctionDecl>(DRE->getDecl())); 5574 } 5575 5576 /// Determine whether we can perform an elementwise array copy for this kind 5577 /// of entity. 5578 static bool canPerformArrayCopy(const InitializedEntity &Entity) { 5579 switch (Entity.getKind()) { 5580 case InitializedEntity::EK_LambdaCapture: 5581 // C++ [expr.prim.lambda]p24: 5582 // For array members, the array elements are direct-initialized in 5583 // increasing subscript order. 5584 return true; 5585 5586 case InitializedEntity::EK_Variable: 5587 // C++ [dcl.decomp]p1: 5588 // [...] each element is copy-initialized or direct-initialized from the 5589 // corresponding element of the assignment-expression [...] 5590 return isa<DecompositionDecl>(Entity.getDecl()); 5591 5592 case InitializedEntity::EK_Member: 5593 // C++ [class.copy.ctor]p14: 5594 // - if the member is an array, each element is direct-initialized with 5595 // the corresponding subobject of x 5596 return Entity.isImplicitMemberInitializer(); 5597 5598 case InitializedEntity::EK_ArrayElement: 5599 // All the above cases are intended to apply recursively, even though none 5600 // of them actually say that. 5601 if (auto *E = Entity.getParent()) 5602 return canPerformArrayCopy(*E); 5603 break; 5604 5605 default: 5606 break; 5607 } 5608 5609 return false; 5610 } 5611 5612 void InitializationSequence::InitializeFrom(Sema &S, 5613 const InitializedEntity &Entity, 5614 const InitializationKind &Kind, 5615 MultiExprArg Args, 5616 bool TopLevelOfInitList, 5617 bool TreatUnavailableAsInvalid) { 5618 ASTContext &Context = S.Context; 5619 5620 // Eliminate non-overload placeholder types in the arguments. We 5621 // need to do this before checking whether types are dependent 5622 // because lowering a pseudo-object expression might well give us 5623 // something of dependent type. 5624 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5625 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 5626 // FIXME: should we be doing this here? 5627 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 5628 if (result.isInvalid()) { 5629 SetFailed(FK_PlaceholderType); 5630 return; 5631 } 5632 Args[I] = result.get(); 5633 } 5634 5635 // C++0x [dcl.init]p16: 5636 // The semantics of initializers are as follows. The destination type is 5637 // the type of the object or reference being initialized and the source 5638 // type is the type of the initializer expression. The source type is not 5639 // defined when the initializer is a braced-init-list or when it is a 5640 // parenthesized list of expressions. 5641 QualType DestType = Entity.getType(); 5642 5643 if (DestType->isDependentType() || 5644 Expr::hasAnyTypeDependentArguments(Args)) { 5645 SequenceKind = DependentSequence; 5646 return; 5647 } 5648 5649 // Almost everything is a normal sequence. 5650 setSequenceKind(NormalSequence); 5651 5652 QualType SourceType; 5653 Expr *Initializer = nullptr; 5654 if (Args.size() == 1) { 5655 Initializer = Args[0]; 5656 if (S.getLangOpts().ObjC) { 5657 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), 5658 DestType, Initializer->getType(), 5659 Initializer) || 5660 S.CheckConversionToObjCLiteral(DestType, Initializer)) 5661 Args[0] = Initializer; 5662 } 5663 if (!isa<InitListExpr>(Initializer)) 5664 SourceType = Initializer->getType(); 5665 } 5666 5667 // - If the initializer is a (non-parenthesized) braced-init-list, the 5668 // object is list-initialized (8.5.4). 5669 if (Kind.getKind() != InitializationKind::IK_Direct) { 5670 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 5671 TryListInitialization(S, Entity, Kind, InitList, *this, 5672 TreatUnavailableAsInvalid); 5673 return; 5674 } 5675 } 5676 5677 // - If the destination type is a reference type, see 8.5.3. 5678 if (DestType->isReferenceType()) { 5679 // C++0x [dcl.init.ref]p1: 5680 // A variable declared to be a T& or T&&, that is, "reference to type T" 5681 // (8.3.2), shall be initialized by an object, or function, of type T or 5682 // by an object that can be converted into a T. 5683 // (Therefore, multiple arguments are not permitted.) 5684 if (Args.size() != 1) 5685 SetFailed(FK_TooManyInitsForReference); 5686 // C++17 [dcl.init.ref]p5: 5687 // A reference [...] is initialized by an expression [...] as follows: 5688 // If the initializer is not an expression, presumably we should reject, 5689 // but the standard fails to actually say so. 5690 else if (isa<InitListExpr>(Args[0])) 5691 SetFailed(FK_ParenthesizedListInitForReference); 5692 else 5693 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 5694 return; 5695 } 5696 5697 // - If the initializer is (), the object is value-initialized. 5698 if (Kind.getKind() == InitializationKind::IK_Value || 5699 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 5700 TryValueInitialization(S, Entity, Kind, *this); 5701 return; 5702 } 5703 5704 // Handle default initialization. 5705 if (Kind.getKind() == InitializationKind::IK_Default) { 5706 TryDefaultInitialization(S, Entity, Kind, *this); 5707 return; 5708 } 5709 5710 // - If the destination type is an array of characters, an array of 5711 // char16_t, an array of char32_t, or an array of wchar_t, and the 5712 // initializer is a string literal, see 8.5.2. 5713 // - Otherwise, if the destination type is an array, the program is 5714 // ill-formed. 5715 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 5716 if (Initializer && isa<VariableArrayType>(DestAT)) { 5717 SetFailed(FK_VariableLengthArrayHasInitializer); 5718 return; 5719 } 5720 5721 if (Initializer) { 5722 switch (IsStringInit(Initializer, DestAT, Context)) { 5723 case SIF_None: 5724 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 5725 return; 5726 case SIF_NarrowStringIntoWideChar: 5727 SetFailed(FK_NarrowStringIntoWideCharArray); 5728 return; 5729 case SIF_WideStringIntoChar: 5730 SetFailed(FK_WideStringIntoCharArray); 5731 return; 5732 case SIF_IncompatWideStringIntoWideChar: 5733 SetFailed(FK_IncompatWideStringIntoWideChar); 5734 return; 5735 case SIF_PlainStringIntoUTF8Char: 5736 SetFailed(FK_PlainStringIntoUTF8Char); 5737 return; 5738 case SIF_UTF8StringIntoPlainChar: 5739 SetFailed(FK_UTF8StringIntoPlainChar); 5740 return; 5741 case SIF_Other: 5742 break; 5743 } 5744 } 5745 5746 // Some kinds of initialization permit an array to be initialized from 5747 // another array of the same type, and perform elementwise initialization. 5748 if (Initializer && isa<ConstantArrayType>(DestAT) && 5749 S.Context.hasSameUnqualifiedType(Initializer->getType(), 5750 Entity.getType()) && 5751 canPerformArrayCopy(Entity)) { 5752 // If source is a prvalue, use it directly. 5753 if (Initializer->getValueKind() == VK_RValue) { 5754 AddArrayInitStep(DestType, /*IsGNUExtension*/false); 5755 return; 5756 } 5757 5758 // Emit element-at-a-time copy loop. 5759 InitializedEntity Element = 5760 InitializedEntity::InitializeElement(S.Context, 0, Entity); 5761 QualType InitEltT = 5762 Context.getAsArrayType(Initializer->getType())->getElementType(); 5763 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, 5764 Initializer->getValueKind(), 5765 Initializer->getObjectKind()); 5766 Expr *OVEAsExpr = &OVE; 5767 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, 5768 TreatUnavailableAsInvalid); 5769 if (!Failed()) 5770 AddArrayInitLoopStep(Entity.getType(), InitEltT); 5771 return; 5772 } 5773 5774 // Note: as an GNU C extension, we allow initialization of an 5775 // array from a compound literal that creates an array of the same 5776 // type, so long as the initializer has no side effects. 5777 if (!S.getLangOpts().CPlusPlus && Initializer && 5778 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 5779 Initializer->getType()->isArrayType()) { 5780 const ArrayType *SourceAT 5781 = Context.getAsArrayType(Initializer->getType()); 5782 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 5783 SetFailed(FK_ArrayTypeMismatch); 5784 else if (Initializer->HasSideEffects(S.Context)) 5785 SetFailed(FK_NonConstantArrayInit); 5786 else { 5787 AddArrayInitStep(DestType, /*IsGNUExtension*/true); 5788 } 5789 } 5790 // Note: as a GNU C++ extension, we allow list-initialization of a 5791 // class member of array type from a parenthesized initializer list. 5792 else if (S.getLangOpts().CPlusPlus && 5793 Entity.getKind() == InitializedEntity::EK_Member && 5794 Initializer && isa<InitListExpr>(Initializer)) { 5795 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 5796 *this, TreatUnavailableAsInvalid); 5797 AddParenthesizedArrayInitStep(DestType); 5798 } else if (DestAT->getElementType()->isCharType()) 5799 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 5800 else if (IsWideCharCompatible(DestAT->getElementType(), Context)) 5801 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); 5802 else 5803 SetFailed(FK_ArrayNeedsInitList); 5804 5805 return; 5806 } 5807 5808 // Determine whether we should consider writeback conversions for 5809 // Objective-C ARC. 5810 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 5811 Entity.isParameterKind(); 5812 5813 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 5814 return; 5815 5816 // We're at the end of the line for C: it's either a write-back conversion 5817 // or it's a C assignment. There's no need to check anything else. 5818 if (!S.getLangOpts().CPlusPlus) { 5819 // If allowed, check whether this is an Objective-C writeback conversion. 5820 if (allowObjCWritebackConversion && 5821 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 5822 return; 5823 } 5824 5825 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) 5826 return; 5827 5828 // Handle initialization in C 5829 AddCAssignmentStep(DestType); 5830 MaybeProduceObjCObject(S, *this, Entity); 5831 return; 5832 } 5833 5834 assert(S.getLangOpts().CPlusPlus); 5835 5836 // - If the destination type is a (possibly cv-qualified) class type: 5837 if (DestType->isRecordType()) { 5838 // - If the initialization is direct-initialization, or if it is 5839 // copy-initialization where the cv-unqualified version of the 5840 // source type is the same class as, or a derived class of, the 5841 // class of the destination, constructors are considered. [...] 5842 if (Kind.getKind() == InitializationKind::IK_Direct || 5843 (Kind.getKind() == InitializationKind::IK_Copy && 5844 (Context.hasSameUnqualifiedType(SourceType, DestType) || 5845 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) 5846 TryConstructorInitialization(S, Entity, Kind, Args, 5847 DestType, DestType, *this); 5848 // - Otherwise (i.e., for the remaining copy-initialization cases), 5849 // user-defined conversion sequences that can convert from the source 5850 // type to the destination type or (when a conversion function is 5851 // used) to a derived class thereof are enumerated as described in 5852 // 13.3.1.4, and the best one is chosen through overload resolution 5853 // (13.3). 5854 else 5855 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5856 TopLevelOfInitList); 5857 return; 5858 } 5859 5860 assert(Args.size() >= 1 && "Zero-argument case handled above"); 5861 5862 // The remaining cases all need a source type. 5863 if (Args.size() > 1) { 5864 SetFailed(FK_TooManyInitsForScalar); 5865 return; 5866 } else if (isa<InitListExpr>(Args[0])) { 5867 SetFailed(FK_ParenthesizedListInitForScalar); 5868 return; 5869 } 5870 5871 // - Otherwise, if the source type is a (possibly cv-qualified) class 5872 // type, conversion functions are considered. 5873 if (!SourceType.isNull() && SourceType->isRecordType()) { 5874 // For a conversion to _Atomic(T) from either T or a class type derived 5875 // from T, initialize the T object then convert to _Atomic type. 5876 bool NeedAtomicConversion = false; 5877 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { 5878 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || 5879 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, 5880 Atomic->getValueType())) { 5881 DestType = Atomic->getValueType(); 5882 NeedAtomicConversion = true; 5883 } 5884 } 5885 5886 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5887 TopLevelOfInitList); 5888 MaybeProduceObjCObject(S, *this, Entity); 5889 if (!Failed() && NeedAtomicConversion) 5890 AddAtomicConversionStep(Entity.getType()); 5891 return; 5892 } 5893 5894 // - Otherwise, if the initialization is direct-initialization, the source 5895 // type is std::nullptr_t, and the destination type is bool, the initial 5896 // value of the object being initialized is false. 5897 if (!SourceType.isNull() && SourceType->isNullPtrType() && 5898 DestType->isBooleanType() && 5899 Kind.getKind() == InitializationKind::IK_Direct) { 5900 AddConversionSequenceStep( 5901 ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, 5902 Initializer->isGLValue()), 5903 DestType); 5904 return; 5905 } 5906 5907 // - Otherwise, the initial value of the object being initialized is the 5908 // (possibly converted) value of the initializer expression. Standard 5909 // conversions (Clause 4) will be used, if necessary, to convert the 5910 // initializer expression to the cv-unqualified version of the 5911 // destination type; no user-defined conversions are considered. 5912 5913 ImplicitConversionSequence ICS 5914 = S.TryImplicitConversion(Initializer, DestType, 5915 /*SuppressUserConversions*/true, 5916 Sema::AllowedExplicit::None, 5917 /*InOverloadResolution*/ false, 5918 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5919 allowObjCWritebackConversion); 5920 5921 if (ICS.isStandard() && 5922 ICS.Standard.Second == ICK_Writeback_Conversion) { 5923 // Objective-C ARC writeback conversion. 5924 5925 // We should copy unless we're passing to an argument explicitly 5926 // marked 'out'. 5927 bool ShouldCopy = true; 5928 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5929 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5930 5931 // If there was an lvalue adjustment, add it as a separate conversion. 5932 if (ICS.Standard.First == ICK_Array_To_Pointer || 5933 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5934 ImplicitConversionSequence LvalueICS; 5935 LvalueICS.setStandard(); 5936 LvalueICS.Standard.setAsIdentityConversion(); 5937 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 5938 LvalueICS.Standard.First = ICS.Standard.First; 5939 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 5940 } 5941 5942 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); 5943 } else if (ICS.isBad()) { 5944 DeclAccessPair dap; 5945 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { 5946 AddZeroInitializationStep(Entity.getType()); 5947 } else if (Initializer->getType() == Context.OverloadTy && 5948 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, 5949 false, dap)) 5950 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 5951 else if (Initializer->getType()->isFunctionType() && 5952 isExprAnUnaddressableFunction(S, Initializer)) 5953 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); 5954 else 5955 SetFailed(InitializationSequence::FK_ConversionFailed); 5956 } else { 5957 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5958 5959 MaybeProduceObjCObject(S, *this, Entity); 5960 } 5961 } 5962 5963 InitializationSequence::~InitializationSequence() { 5964 for (auto &S : Steps) 5965 S.Destroy(); 5966 } 5967 5968 //===----------------------------------------------------------------------===// 5969 // Perform initialization 5970 //===----------------------------------------------------------------------===// 5971 static Sema::AssignmentAction 5972 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { 5973 switch(Entity.getKind()) { 5974 case InitializedEntity::EK_Variable: 5975 case InitializedEntity::EK_New: 5976 case InitializedEntity::EK_Exception: 5977 case InitializedEntity::EK_Base: 5978 case InitializedEntity::EK_Delegating: 5979 return Sema::AA_Initializing; 5980 5981 case InitializedEntity::EK_Parameter: 5982 if (Entity.getDecl() && 5983 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5984 return Sema::AA_Sending; 5985 5986 return Sema::AA_Passing; 5987 5988 case InitializedEntity::EK_Parameter_CF_Audited: 5989 if (Entity.getDecl() && 5990 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5991 return Sema::AA_Sending; 5992 5993 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; 5994 5995 case InitializedEntity::EK_Result: 5996 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. 5997 return Sema::AA_Returning; 5998 5999 case InitializedEntity::EK_Temporary: 6000 case InitializedEntity::EK_RelatedResult: 6001 // FIXME: Can we tell apart casting vs. converting? 6002 return Sema::AA_Casting; 6003 6004 case InitializedEntity::EK_Member: 6005 case InitializedEntity::EK_Binding: 6006 case InitializedEntity::EK_ArrayElement: 6007 case InitializedEntity::EK_VectorElement: 6008 case InitializedEntity::EK_ComplexElement: 6009 case InitializedEntity::EK_BlockElement: 6010 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6011 case InitializedEntity::EK_LambdaCapture: 6012 case InitializedEntity::EK_CompoundLiteralInit: 6013 return Sema::AA_Initializing; 6014 } 6015 6016 llvm_unreachable("Invalid EntityKind!"); 6017 } 6018 6019 /// Whether we should bind a created object as a temporary when 6020 /// initializing the given entity. 6021 static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 6022 switch (Entity.getKind()) { 6023 case InitializedEntity::EK_ArrayElement: 6024 case InitializedEntity::EK_Member: 6025 case InitializedEntity::EK_Result: 6026 case InitializedEntity::EK_StmtExprResult: 6027 case InitializedEntity::EK_New: 6028 case InitializedEntity::EK_Variable: 6029 case InitializedEntity::EK_Base: 6030 case InitializedEntity::EK_Delegating: 6031 case InitializedEntity::EK_VectorElement: 6032 case InitializedEntity::EK_ComplexElement: 6033 case InitializedEntity::EK_Exception: 6034 case InitializedEntity::EK_BlockElement: 6035 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6036 case InitializedEntity::EK_LambdaCapture: 6037 case InitializedEntity::EK_CompoundLiteralInit: 6038 return false; 6039 6040 case InitializedEntity::EK_Parameter: 6041 case InitializedEntity::EK_Parameter_CF_Audited: 6042 case InitializedEntity::EK_Temporary: 6043 case InitializedEntity::EK_RelatedResult: 6044 case InitializedEntity::EK_Binding: 6045 return true; 6046 } 6047 6048 llvm_unreachable("missed an InitializedEntity kind?"); 6049 } 6050 6051 /// Whether the given entity, when initialized with an object 6052 /// created for that initialization, requires destruction. 6053 static bool shouldDestroyEntity(const InitializedEntity &Entity) { 6054 switch (Entity.getKind()) { 6055 case InitializedEntity::EK_Result: 6056 case InitializedEntity::EK_StmtExprResult: 6057 case InitializedEntity::EK_New: 6058 case InitializedEntity::EK_Base: 6059 case InitializedEntity::EK_Delegating: 6060 case InitializedEntity::EK_VectorElement: 6061 case InitializedEntity::EK_ComplexElement: 6062 case InitializedEntity::EK_BlockElement: 6063 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6064 case InitializedEntity::EK_LambdaCapture: 6065 return false; 6066 6067 case InitializedEntity::EK_Member: 6068 case InitializedEntity::EK_Binding: 6069 case InitializedEntity::EK_Variable: 6070 case InitializedEntity::EK_Parameter: 6071 case InitializedEntity::EK_Parameter_CF_Audited: 6072 case InitializedEntity::EK_Temporary: 6073 case InitializedEntity::EK_ArrayElement: 6074 case InitializedEntity::EK_Exception: 6075 case InitializedEntity::EK_CompoundLiteralInit: 6076 case InitializedEntity::EK_RelatedResult: 6077 return true; 6078 } 6079 6080 llvm_unreachable("missed an InitializedEntity kind?"); 6081 } 6082 6083 /// Get the location at which initialization diagnostics should appear. 6084 static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 6085 Expr *Initializer) { 6086 switch (Entity.getKind()) { 6087 case InitializedEntity::EK_Result: 6088 case InitializedEntity::EK_StmtExprResult: 6089 return Entity.getReturnLoc(); 6090 6091 case InitializedEntity::EK_Exception: 6092 return Entity.getThrowLoc(); 6093 6094 case InitializedEntity::EK_Variable: 6095 case InitializedEntity::EK_Binding: 6096 return Entity.getDecl()->getLocation(); 6097 6098 case InitializedEntity::EK_LambdaCapture: 6099 return Entity.getCaptureLoc(); 6100 6101 case InitializedEntity::EK_ArrayElement: 6102 case InitializedEntity::EK_Member: 6103 case InitializedEntity::EK_Parameter: 6104 case InitializedEntity::EK_Parameter_CF_Audited: 6105 case InitializedEntity::EK_Temporary: 6106 case InitializedEntity::EK_New: 6107 case InitializedEntity::EK_Base: 6108 case InitializedEntity::EK_Delegating: 6109 case InitializedEntity::EK_VectorElement: 6110 case InitializedEntity::EK_ComplexElement: 6111 case InitializedEntity::EK_BlockElement: 6112 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6113 case InitializedEntity::EK_CompoundLiteralInit: 6114 case InitializedEntity::EK_RelatedResult: 6115 return Initializer->getBeginLoc(); 6116 } 6117 llvm_unreachable("missed an InitializedEntity kind?"); 6118 } 6119 6120 /// Make a (potentially elidable) temporary copy of the object 6121 /// provided by the given initializer by calling the appropriate copy 6122 /// constructor. 6123 /// 6124 /// \param S The Sema object used for type-checking. 6125 /// 6126 /// \param T The type of the temporary object, which must either be 6127 /// the type of the initializer expression or a superclass thereof. 6128 /// 6129 /// \param Entity The entity being initialized. 6130 /// 6131 /// \param CurInit The initializer expression. 6132 /// 6133 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that 6134 /// is permitted in C++03 (but not C++0x) when binding a reference to 6135 /// an rvalue. 6136 /// 6137 /// \returns An expression that copies the initializer expression into 6138 /// a temporary object, or an error expression if a copy could not be 6139 /// created. 6140 static ExprResult CopyObject(Sema &S, 6141 QualType T, 6142 const InitializedEntity &Entity, 6143 ExprResult CurInit, 6144 bool IsExtraneousCopy) { 6145 if (CurInit.isInvalid()) 6146 return CurInit; 6147 // Determine which class type we're copying to. 6148 Expr *CurInitExpr = (Expr *)CurInit.get(); 6149 CXXRecordDecl *Class = nullptr; 6150 if (const RecordType *Record = T->getAs<RecordType>()) 6151 Class = cast<CXXRecordDecl>(Record->getDecl()); 6152 if (!Class) 6153 return CurInit; 6154 6155 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 6156 6157 // Make sure that the type we are copying is complete. 6158 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 6159 return CurInit; 6160 6161 // Perform overload resolution using the class's constructors. Per 6162 // C++11 [dcl.init]p16, second bullet for class types, this initialization 6163 // is direct-initialization. 6164 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6165 DeclContext::lookup_result Ctors = S.LookupConstructors(Class); 6166 6167 OverloadCandidateSet::iterator Best; 6168 switch (ResolveConstructorOverload( 6169 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, 6170 /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6171 /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6172 /*SecondStepOfCopyInit=*/true)) { 6173 case OR_Success: 6174 break; 6175 6176 case OR_No_Viable_Function: 6177 CandidateSet.NoteCandidates( 6178 PartialDiagnosticAt( 6179 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() 6180 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 6181 : diag::err_temp_copy_no_viable) 6182 << (int)Entity.getKind() << CurInitExpr->getType() 6183 << CurInitExpr->getSourceRange()), 6184 S, OCD_AllCandidates, CurInitExpr); 6185 if (!IsExtraneousCopy || S.isSFINAEContext()) 6186 return ExprError(); 6187 return CurInit; 6188 6189 case OR_Ambiguous: 6190 CandidateSet.NoteCandidates( 6191 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) 6192 << (int)Entity.getKind() 6193 << CurInitExpr->getType() 6194 << CurInitExpr->getSourceRange()), 6195 S, OCD_AmbiguousCandidates, CurInitExpr); 6196 return ExprError(); 6197 6198 case OR_Deleted: 6199 S.Diag(Loc, diag::err_temp_copy_deleted) 6200 << (int)Entity.getKind() << CurInitExpr->getType() 6201 << CurInitExpr->getSourceRange(); 6202 S.NoteDeletedFunction(Best->Function); 6203 return ExprError(); 6204 } 6205 6206 bool HadMultipleCandidates = CandidateSet.size() > 1; 6207 6208 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 6209 SmallVector<Expr*, 8> ConstructorArgs; 6210 CurInit.get(); // Ownership transferred into MultiExprArg, below. 6211 6212 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, 6213 IsExtraneousCopy); 6214 6215 if (IsExtraneousCopy) { 6216 // If this is a totally extraneous copy for C++03 reference 6217 // binding purposes, just return the original initialization 6218 // expression. We don't generate an (elided) copy operation here 6219 // because doing so would require us to pass down a flag to avoid 6220 // infinite recursion, where each step adds another extraneous, 6221 // elidable copy. 6222 6223 // Instantiate the default arguments of any extra parameters in 6224 // the selected copy constructor, as if we were going to create a 6225 // proper call to the copy constructor. 6226 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 6227 ParmVarDecl *Parm = Constructor->getParamDecl(I); 6228 if (S.RequireCompleteType(Loc, Parm->getType(), 6229 diag::err_call_incomplete_argument)) 6230 break; 6231 6232 // Build the default argument expression; we don't actually care 6233 // if this succeeds or not, because this routine will complain 6234 // if there was a problem. 6235 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 6236 } 6237 6238 return CurInitExpr; 6239 } 6240 6241 // Determine the arguments required to actually perform the 6242 // constructor call (we might have derived-to-base conversions, or 6243 // the copy constructor may have default arguments). 6244 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) 6245 return ExprError(); 6246 6247 // C++0x [class.copy]p32: 6248 // When certain criteria are met, an implementation is allowed to 6249 // omit the copy/move construction of a class object, even if the 6250 // copy/move constructor and/or destructor for the object have 6251 // side effects. [...] 6252 // - when a temporary class object that has not been bound to a 6253 // reference (12.2) would be copied/moved to a class object 6254 // with the same cv-unqualified type, the copy/move operation 6255 // can be omitted by constructing the temporary object 6256 // directly into the target of the omitted copy/move 6257 // 6258 // Note that the other three bullets are handled elsewhere. Copy 6259 // elision for return statements and throw expressions are handled as part 6260 // of constructor initialization, while copy elision for exception handlers 6261 // is handled by the run-time. 6262 // 6263 // FIXME: If the function parameter is not the same type as the temporary, we 6264 // should still be able to elide the copy, but we don't have a way to 6265 // represent in the AST how much should be elided in this case. 6266 bool Elidable = 6267 CurInitExpr->isTemporaryObject(S.Context, Class) && 6268 S.Context.hasSameUnqualifiedType( 6269 Best->Function->getParamDecl(0)->getType().getNonReferenceType(), 6270 CurInitExpr->getType()); 6271 6272 // Actually perform the constructor call. 6273 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, 6274 Elidable, 6275 ConstructorArgs, 6276 HadMultipleCandidates, 6277 /*ListInit*/ false, 6278 /*StdInitListInit*/ false, 6279 /*ZeroInit*/ false, 6280 CXXConstructExpr::CK_Complete, 6281 SourceRange()); 6282 6283 // If we're supposed to bind temporaries, do so. 6284 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 6285 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 6286 return CurInit; 6287 } 6288 6289 /// Check whether elidable copy construction for binding a reference to 6290 /// a temporary would have succeeded if we were building in C++98 mode, for 6291 /// -Wc++98-compat. 6292 static void CheckCXX98CompatAccessibleCopy(Sema &S, 6293 const InitializedEntity &Entity, 6294 Expr *CurInitExpr) { 6295 assert(S.getLangOpts().CPlusPlus11); 6296 6297 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 6298 if (!Record) 6299 return; 6300 6301 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 6302 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) 6303 return; 6304 6305 // Find constructors which would have been considered. 6306 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6307 DeclContext::lookup_result Ctors = 6308 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); 6309 6310 // Perform overload resolution. 6311 OverloadCandidateSet::iterator Best; 6312 OverloadingResult OR = ResolveConstructorOverload( 6313 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, 6314 /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6315 /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6316 /*SecondStepOfCopyInit=*/true); 6317 6318 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 6319 << OR << (int)Entity.getKind() << CurInitExpr->getType() 6320 << CurInitExpr->getSourceRange(); 6321 6322 switch (OR) { 6323 case OR_Success: 6324 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 6325 Best->FoundDecl, Entity, Diag); 6326 // FIXME: Check default arguments as far as that's possible. 6327 break; 6328 6329 case OR_No_Viable_Function: 6330 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6331 OCD_AllCandidates, CurInitExpr); 6332 break; 6333 6334 case OR_Ambiguous: 6335 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6336 OCD_AmbiguousCandidates, CurInitExpr); 6337 break; 6338 6339 case OR_Deleted: 6340 S.Diag(Loc, Diag); 6341 S.NoteDeletedFunction(Best->Function); 6342 break; 6343 } 6344 } 6345 6346 void InitializationSequence::PrintInitLocationNote(Sema &S, 6347 const InitializedEntity &Entity) { 6348 if (Entity.isParameterKind() && Entity.getDecl()) { 6349 if (Entity.getDecl()->getLocation().isInvalid()) 6350 return; 6351 6352 if (Entity.getDecl()->getDeclName()) 6353 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 6354 << Entity.getDecl()->getDeclName(); 6355 else 6356 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 6357 } 6358 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && 6359 Entity.getMethodDecl()) 6360 S.Diag(Entity.getMethodDecl()->getLocation(), 6361 diag::note_method_return_type_change) 6362 << Entity.getMethodDecl()->getDeclName(); 6363 } 6364 6365 /// Returns true if the parameters describe a constructor initialization of 6366 /// an explicit temporary object, e.g. "Point(x, y)". 6367 static bool isExplicitTemporary(const InitializedEntity &Entity, 6368 const InitializationKind &Kind, 6369 unsigned NumArgs) { 6370 switch (Entity.getKind()) { 6371 case InitializedEntity::EK_Temporary: 6372 case InitializedEntity::EK_CompoundLiteralInit: 6373 case InitializedEntity::EK_RelatedResult: 6374 break; 6375 default: 6376 return false; 6377 } 6378 6379 switch (Kind.getKind()) { 6380 case InitializationKind::IK_DirectList: 6381 return true; 6382 // FIXME: Hack to work around cast weirdness. 6383 case InitializationKind::IK_Direct: 6384 case InitializationKind::IK_Value: 6385 return NumArgs != 1; 6386 default: 6387 return false; 6388 } 6389 } 6390 6391 static ExprResult 6392 PerformConstructorInitialization(Sema &S, 6393 const InitializedEntity &Entity, 6394 const InitializationKind &Kind, 6395 MultiExprArg Args, 6396 const InitializationSequence::Step& Step, 6397 bool &ConstructorInitRequiresZeroInit, 6398 bool IsListInitialization, 6399 bool IsStdInitListInitialization, 6400 SourceLocation LBraceLoc, 6401 SourceLocation RBraceLoc) { 6402 unsigned NumArgs = Args.size(); 6403 CXXConstructorDecl *Constructor 6404 = cast<CXXConstructorDecl>(Step.Function.Function); 6405 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 6406 6407 // Build a call to the selected constructor. 6408 SmallVector<Expr*, 8> ConstructorArgs; 6409 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 6410 ? Kind.getEqualLoc() 6411 : Kind.getLocation(); 6412 6413 if (Kind.getKind() == InitializationKind::IK_Default) { 6414 // Force even a trivial, implicit default constructor to be 6415 // semantically checked. We do this explicitly because we don't build 6416 // the definition for completely trivial constructors. 6417 assert(Constructor->getParent() && "No parent class for constructor."); 6418 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6419 Constructor->isTrivial() && !Constructor->isUsed(false)) { 6420 S.runWithSufficientStackSpace(Loc, [&] { 6421 S.DefineImplicitDefaultConstructor(Loc, Constructor); 6422 }); 6423 } 6424 } 6425 6426 ExprResult CurInit((Expr *)nullptr); 6427 6428 // C++ [over.match.copy]p1: 6429 // - When initializing a temporary to be bound to the first parameter 6430 // of a constructor that takes a reference to possibly cv-qualified 6431 // T as its first argument, called with a single argument in the 6432 // context of direct-initialization, explicit conversion functions 6433 // are also considered. 6434 bool AllowExplicitConv = 6435 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && 6436 hasCopyOrMoveCtorParam(S.Context, 6437 getConstructorInfo(Step.Function.FoundDecl)); 6438 6439 // Determine the arguments required to actually perform the constructor 6440 // call. 6441 if (S.CompleteConstructorCall(Constructor, Args, 6442 Loc, ConstructorArgs, 6443 AllowExplicitConv, 6444 IsListInitialization)) 6445 return ExprError(); 6446 6447 6448 if (isExplicitTemporary(Entity, Kind, NumArgs)) { 6449 // An explicitly-constructed temporary, e.g., X(1, 2). 6450 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 6451 return ExprError(); 6452 6453 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 6454 if (!TSInfo) 6455 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 6456 SourceRange ParenOrBraceRange = 6457 (Kind.getKind() == InitializationKind::IK_DirectList) 6458 ? SourceRange(LBraceLoc, RBraceLoc) 6459 : Kind.getParenOrBraceRange(); 6460 6461 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( 6462 Step.Function.FoundDecl.getDecl())) { 6463 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow); 6464 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 6465 return ExprError(); 6466 } 6467 S.MarkFunctionReferenced(Loc, Constructor); 6468 6469 CurInit = S.CheckForImmediateInvocation( 6470 CXXTemporaryObjectExpr::Create( 6471 S.Context, Constructor, 6472 Entity.getType().getNonLValueExprType(S.Context), TSInfo, 6473 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, 6474 IsListInitialization, IsStdInitListInitialization, 6475 ConstructorInitRequiresZeroInit), 6476 Constructor); 6477 } else { 6478 CXXConstructExpr::ConstructionKind ConstructKind = 6479 CXXConstructExpr::CK_Complete; 6480 6481 if (Entity.getKind() == InitializedEntity::EK_Base) { 6482 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 6483 CXXConstructExpr::CK_VirtualBase : 6484 CXXConstructExpr::CK_NonVirtualBase; 6485 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 6486 ConstructKind = CXXConstructExpr::CK_Delegating; 6487 } 6488 6489 // Only get the parenthesis or brace range if it is a list initialization or 6490 // direct construction. 6491 SourceRange ParenOrBraceRange; 6492 if (IsListInitialization) 6493 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); 6494 else if (Kind.getKind() == InitializationKind::IK_Direct) 6495 ParenOrBraceRange = Kind.getParenOrBraceRange(); 6496 6497 // If the entity allows NRVO, mark the construction as elidable 6498 // unconditionally. 6499 if (Entity.allowsNRVO()) 6500 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6501 Step.Function.FoundDecl, 6502 Constructor, /*Elidable=*/true, 6503 ConstructorArgs, 6504 HadMultipleCandidates, 6505 IsListInitialization, 6506 IsStdInitListInitialization, 6507 ConstructorInitRequiresZeroInit, 6508 ConstructKind, 6509 ParenOrBraceRange); 6510 else 6511 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6512 Step.Function.FoundDecl, 6513 Constructor, 6514 ConstructorArgs, 6515 HadMultipleCandidates, 6516 IsListInitialization, 6517 IsStdInitListInitialization, 6518 ConstructorInitRequiresZeroInit, 6519 ConstructKind, 6520 ParenOrBraceRange); 6521 } 6522 if (CurInit.isInvalid()) 6523 return ExprError(); 6524 6525 // Only check access if all of that succeeded. 6526 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); 6527 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 6528 return ExprError(); 6529 6530 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) 6531 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) 6532 return ExprError(); 6533 6534 if (shouldBindAsTemporary(Entity)) 6535 CurInit = S.MaybeBindToTemporary(CurInit.get()); 6536 6537 return CurInit; 6538 } 6539 6540 namespace { 6541 enum LifetimeKind { 6542 /// The lifetime of a temporary bound to this entity ends at the end of the 6543 /// full-expression, and that's (probably) fine. 6544 LK_FullExpression, 6545 6546 /// The lifetime of a temporary bound to this entity is extended to the 6547 /// lifeitme of the entity itself. 6548 LK_Extended, 6549 6550 /// The lifetime of a temporary bound to this entity probably ends too soon, 6551 /// because the entity is allocated in a new-expression. 6552 LK_New, 6553 6554 /// The lifetime of a temporary bound to this entity ends too soon, because 6555 /// the entity is a return object. 6556 LK_Return, 6557 6558 /// The lifetime of a temporary bound to this entity ends too soon, because 6559 /// the entity is the result of a statement expression. 6560 LK_StmtExprResult, 6561 6562 /// This is a mem-initializer: if it would extend a temporary (other than via 6563 /// a default member initializer), the program is ill-formed. 6564 LK_MemInitializer, 6565 }; 6566 using LifetimeResult = 6567 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; 6568 } 6569 6570 /// Determine the declaration which an initialized entity ultimately refers to, 6571 /// for the purpose of lifetime-extending a temporary bound to a reference in 6572 /// the initialization of \p Entity. 6573 static LifetimeResult getEntityLifetime( 6574 const InitializedEntity *Entity, 6575 const InitializedEntity *InitField = nullptr) { 6576 // C++11 [class.temporary]p5: 6577 switch (Entity->getKind()) { 6578 case InitializedEntity::EK_Variable: 6579 // The temporary [...] persists for the lifetime of the reference 6580 return {Entity, LK_Extended}; 6581 6582 case InitializedEntity::EK_Member: 6583 // For subobjects, we look at the complete object. 6584 if (Entity->getParent()) 6585 return getEntityLifetime(Entity->getParent(), Entity); 6586 6587 // except: 6588 // C++17 [class.base.init]p8: 6589 // A temporary expression bound to a reference member in a 6590 // mem-initializer is ill-formed. 6591 // C++17 [class.base.init]p11: 6592 // A temporary expression bound to a reference member from a 6593 // default member initializer is ill-formed. 6594 // 6595 // The context of p11 and its example suggest that it's only the use of a 6596 // default member initializer from a constructor that makes the program 6597 // ill-formed, not its mere existence, and that it can even be used by 6598 // aggregate initialization. 6599 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended 6600 : LK_MemInitializer}; 6601 6602 case InitializedEntity::EK_Binding: 6603 // Per [dcl.decomp]p3, the binding is treated as a variable of reference 6604 // type. 6605 return {Entity, LK_Extended}; 6606 6607 case InitializedEntity::EK_Parameter: 6608 case InitializedEntity::EK_Parameter_CF_Audited: 6609 // -- A temporary bound to a reference parameter in a function call 6610 // persists until the completion of the full-expression containing 6611 // the call. 6612 return {nullptr, LK_FullExpression}; 6613 6614 case InitializedEntity::EK_Result: 6615 // -- The lifetime of a temporary bound to the returned value in a 6616 // function return statement is not extended; the temporary is 6617 // destroyed at the end of the full-expression in the return statement. 6618 return {nullptr, LK_Return}; 6619 6620 case InitializedEntity::EK_StmtExprResult: 6621 // FIXME: Should we lifetime-extend through the result of a statement 6622 // expression? 6623 return {nullptr, LK_StmtExprResult}; 6624 6625 case InitializedEntity::EK_New: 6626 // -- A temporary bound to a reference in a new-initializer persists 6627 // until the completion of the full-expression containing the 6628 // new-initializer. 6629 return {nullptr, LK_New}; 6630 6631 case InitializedEntity::EK_Temporary: 6632 case InitializedEntity::EK_CompoundLiteralInit: 6633 case InitializedEntity::EK_RelatedResult: 6634 // We don't yet know the storage duration of the surrounding temporary. 6635 // Assume it's got full-expression duration for now, it will patch up our 6636 // storage duration if that's not correct. 6637 return {nullptr, LK_FullExpression}; 6638 6639 case InitializedEntity::EK_ArrayElement: 6640 // For subobjects, we look at the complete object. 6641 return getEntityLifetime(Entity->getParent(), InitField); 6642 6643 case InitializedEntity::EK_Base: 6644 // For subobjects, we look at the complete object. 6645 if (Entity->getParent()) 6646 return getEntityLifetime(Entity->getParent(), InitField); 6647 return {InitField, LK_MemInitializer}; 6648 6649 case InitializedEntity::EK_Delegating: 6650 // We can reach this case for aggregate initialization in a constructor: 6651 // struct A { int &&r; }; 6652 // struct B : A { B() : A{0} {} }; 6653 // In this case, use the outermost field decl as the context. 6654 return {InitField, LK_MemInitializer}; 6655 6656 case InitializedEntity::EK_BlockElement: 6657 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6658 case InitializedEntity::EK_LambdaCapture: 6659 case InitializedEntity::EK_VectorElement: 6660 case InitializedEntity::EK_ComplexElement: 6661 return {nullptr, LK_FullExpression}; 6662 6663 case InitializedEntity::EK_Exception: 6664 // FIXME: Can we diagnose lifetime problems with exceptions? 6665 return {nullptr, LK_FullExpression}; 6666 } 6667 llvm_unreachable("unknown entity kind"); 6668 } 6669 6670 namespace { 6671 enum ReferenceKind { 6672 /// Lifetime would be extended by a reference binding to a temporary. 6673 RK_ReferenceBinding, 6674 /// Lifetime would be extended by a std::initializer_list object binding to 6675 /// its backing array. 6676 RK_StdInitializerList, 6677 }; 6678 6679 /// A temporary or local variable. This will be one of: 6680 /// * A MaterializeTemporaryExpr. 6681 /// * A DeclRefExpr whose declaration is a local. 6682 /// * An AddrLabelExpr. 6683 /// * A BlockExpr for a block with captures. 6684 using Local = Expr*; 6685 6686 /// Expressions we stepped over when looking for the local state. Any steps 6687 /// that would inhibit lifetime extension or take us out of subexpressions of 6688 /// the initializer are included. 6689 struct IndirectLocalPathEntry { 6690 enum EntryKind { 6691 DefaultInit, 6692 AddressOf, 6693 VarInit, 6694 LValToRVal, 6695 LifetimeBoundCall, 6696 GslReferenceInit, 6697 GslPointerInit 6698 } Kind; 6699 Expr *E; 6700 const Decl *D = nullptr; 6701 IndirectLocalPathEntry() {} 6702 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} 6703 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) 6704 : Kind(K), E(E), D(D) {} 6705 }; 6706 6707 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; 6708 6709 struct RevertToOldSizeRAII { 6710 IndirectLocalPath &Path; 6711 unsigned OldSize = Path.size(); 6712 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} 6713 ~RevertToOldSizeRAII() { Path.resize(OldSize); } 6714 }; 6715 6716 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, 6717 ReferenceKind RK)>; 6718 } 6719 6720 static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { 6721 for (auto E : Path) 6722 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) 6723 return true; 6724 return false; 6725 } 6726 6727 static bool pathContainsInit(IndirectLocalPath &Path) { 6728 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { 6729 return E.Kind == IndirectLocalPathEntry::DefaultInit || 6730 E.Kind == IndirectLocalPathEntry::VarInit; 6731 }); 6732 } 6733 6734 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 6735 Expr *Init, LocalVisitor Visit, 6736 bool RevisitSubinits, 6737 bool EnableLifetimeWarnings); 6738 6739 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 6740 Expr *Init, ReferenceKind RK, 6741 LocalVisitor Visit, 6742 bool EnableLifetimeWarnings); 6743 6744 template <typename T> static bool isRecordWithAttr(QualType Type) { 6745 if (auto *RD = Type->getAsCXXRecordDecl()) 6746 return RD->hasAttr<T>(); 6747 return false; 6748 } 6749 6750 // Decl::isInStdNamespace will return false for iterators in some STL 6751 // implementations due to them being defined in a namespace outside of the std 6752 // namespace. 6753 static bool isInStlNamespace(const Decl *D) { 6754 const DeclContext *DC = D->getDeclContext(); 6755 if (!DC) 6756 return false; 6757 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) 6758 if (const IdentifierInfo *II = ND->getIdentifier()) { 6759 StringRef Name = II->getName(); 6760 if (Name.size() >= 2 && Name.front() == '_' && 6761 (Name[1] == '_' || isUppercase(Name[1]))) 6762 return true; 6763 } 6764 6765 return DC->isStdNamespace(); 6766 } 6767 6768 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { 6769 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) 6770 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) 6771 return true; 6772 if (!isInStlNamespace(Callee->getParent())) 6773 return false; 6774 if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && 6775 !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) 6776 return false; 6777 if (Callee->getReturnType()->isPointerType() || 6778 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { 6779 if (!Callee->getIdentifier()) 6780 return false; 6781 return llvm::StringSwitch<bool>(Callee->getName()) 6782 .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6783 .Cases("end", "rend", "cend", "crend", true) 6784 .Cases("c_str", "data", "get", true) 6785 // Map and set types. 6786 .Cases("find", "equal_range", "lower_bound", "upper_bound", true) 6787 .Default(false); 6788 } else if (Callee->getReturnType()->isReferenceType()) { 6789 if (!Callee->getIdentifier()) { 6790 auto OO = Callee->getOverloadedOperator(); 6791 return OO == OverloadedOperatorKind::OO_Subscript || 6792 OO == OverloadedOperatorKind::OO_Star; 6793 } 6794 return llvm::StringSwitch<bool>(Callee->getName()) 6795 .Cases("front", "back", "at", "top", "value", true) 6796 .Default(false); 6797 } 6798 return false; 6799 } 6800 6801 static bool shouldTrackFirstArgument(const FunctionDecl *FD) { 6802 if (!FD->getIdentifier() || FD->getNumParams() != 1) 6803 return false; 6804 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); 6805 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) 6806 return false; 6807 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && 6808 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) 6809 return false; 6810 if (FD->getReturnType()->isPointerType() || 6811 isRecordWithAttr<PointerAttr>(FD->getReturnType())) { 6812 return llvm::StringSwitch<bool>(FD->getName()) 6813 .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6814 .Cases("end", "rend", "cend", "crend", true) 6815 .Case("data", true) 6816 .Default(false); 6817 } else if (FD->getReturnType()->isReferenceType()) { 6818 return llvm::StringSwitch<bool>(FD->getName()) 6819 .Cases("get", "any_cast", true) 6820 .Default(false); 6821 } 6822 return false; 6823 } 6824 6825 static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, 6826 LocalVisitor Visit) { 6827 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { 6828 // We are not interested in the temporary base objects of gsl Pointers: 6829 // Temp().ptr; // Here ptr might not dangle. 6830 if (isa<MemberExpr>(Arg->IgnoreImpCasts())) 6831 return; 6832 // Once we initialized a value with a reference, it can no longer dangle. 6833 if (!Value) { 6834 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 6835 if (It->Kind == IndirectLocalPathEntry::GslReferenceInit) 6836 continue; 6837 if (It->Kind == IndirectLocalPathEntry::GslPointerInit) 6838 return; 6839 break; 6840 } 6841 } 6842 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit 6843 : IndirectLocalPathEntry::GslReferenceInit, 6844 Arg, D}); 6845 if (Arg->isGLValue()) 6846 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 6847 Visit, 6848 /*EnableLifetimeWarnings=*/true); 6849 else 6850 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 6851 /*EnableLifetimeWarnings=*/true); 6852 Path.pop_back(); 6853 }; 6854 6855 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 6856 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); 6857 if (MD && shouldTrackImplicitObjectArg(MD)) 6858 VisitPointerArg(MD, MCE->getImplicitObjectArgument(), 6859 !MD->getReturnType()->isReferenceType()); 6860 return; 6861 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { 6862 FunctionDecl *Callee = OCE->getDirectCallee(); 6863 if (Callee && Callee->isCXXInstanceMember() && 6864 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) 6865 VisitPointerArg(Callee, OCE->getArg(0), 6866 !Callee->getReturnType()->isReferenceType()); 6867 return; 6868 } else if (auto *CE = dyn_cast<CallExpr>(Call)) { 6869 FunctionDecl *Callee = CE->getDirectCallee(); 6870 if (Callee && shouldTrackFirstArgument(Callee)) 6871 VisitPointerArg(Callee, CE->getArg(0), 6872 !Callee->getReturnType()->isReferenceType()); 6873 return; 6874 } 6875 6876 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { 6877 const auto *Ctor = CCE->getConstructor(); 6878 const CXXRecordDecl *RD = Ctor->getParent(); 6879 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) 6880 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); 6881 } 6882 } 6883 6884 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { 6885 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6886 if (!TSI) 6887 return false; 6888 // Don't declare this variable in the second operand of the for-statement; 6889 // GCC miscompiles that by ending its lifetime before evaluating the 6890 // third operand. See gcc.gnu.org/PR86769. 6891 AttributedTypeLoc ATL; 6892 for (TypeLoc TL = TSI->getTypeLoc(); 6893 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6894 TL = ATL.getModifiedLoc()) { 6895 if (ATL.getAttrAs<LifetimeBoundAttr>()) 6896 return true; 6897 } 6898 return false; 6899 } 6900 6901 static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, 6902 LocalVisitor Visit) { 6903 const FunctionDecl *Callee; 6904 ArrayRef<Expr*> Args; 6905 6906 if (auto *CE = dyn_cast<CallExpr>(Call)) { 6907 Callee = CE->getDirectCallee(); 6908 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); 6909 } else { 6910 auto *CCE = cast<CXXConstructExpr>(Call); 6911 Callee = CCE->getConstructor(); 6912 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); 6913 } 6914 if (!Callee) 6915 return; 6916 6917 Expr *ObjectArg = nullptr; 6918 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { 6919 ObjectArg = Args[0]; 6920 Args = Args.slice(1); 6921 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 6922 ObjectArg = MCE->getImplicitObjectArgument(); 6923 } 6924 6925 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { 6926 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); 6927 if (Arg->isGLValue()) 6928 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 6929 Visit, 6930 /*EnableLifetimeWarnings=*/false); 6931 else 6932 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 6933 /*EnableLifetimeWarnings=*/false); 6934 Path.pop_back(); 6935 }; 6936 6937 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) 6938 VisitLifetimeBoundArg(Callee, ObjectArg); 6939 6940 for (unsigned I = 0, 6941 N = std::min<unsigned>(Callee->getNumParams(), Args.size()); 6942 I != N; ++I) { 6943 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) 6944 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); 6945 } 6946 } 6947 6948 /// Visit the locals that would be reachable through a reference bound to the 6949 /// glvalue expression \c Init. 6950 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 6951 Expr *Init, ReferenceKind RK, 6952 LocalVisitor Visit, 6953 bool EnableLifetimeWarnings) { 6954 RevertToOldSizeRAII RAII(Path); 6955 6956 // Walk past any constructs which we can lifetime-extend across. 6957 Expr *Old; 6958 do { 6959 Old = Init; 6960 6961 if (auto *FE = dyn_cast<FullExpr>(Init)) 6962 Init = FE->getSubExpr(); 6963 6964 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 6965 // If this is just redundant braces around an initializer, step over it. 6966 if (ILE->isTransparent()) 6967 Init = ILE->getInit(0); 6968 } 6969 6970 // Step over any subobject adjustments; we may have a materialized 6971 // temporary inside them. 6972 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 6973 6974 // Per current approach for DR1376, look through casts to reference type 6975 // when performing lifetime extension. 6976 if (CastExpr *CE = dyn_cast<CastExpr>(Init)) 6977 if (CE->getSubExpr()->isGLValue()) 6978 Init = CE->getSubExpr(); 6979 6980 // Per the current approach for DR1299, look through array element access 6981 // on array glvalues when performing lifetime extension. 6982 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { 6983 Init = ASE->getBase(); 6984 auto *ICE = dyn_cast<ImplicitCastExpr>(Init); 6985 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) 6986 Init = ICE->getSubExpr(); 6987 else 6988 // We can't lifetime extend through this but we might still find some 6989 // retained temporaries. 6990 return visitLocalsRetainedByInitializer(Path, Init, Visit, true, 6991 EnableLifetimeWarnings); 6992 } 6993 6994 // Step into CXXDefaultInitExprs so we can diagnose cases where a 6995 // constructor inherits one as an implicit mem-initializer. 6996 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 6997 Path.push_back( 6998 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 6999 Init = DIE->getExpr(); 7000 } 7001 } while (Init != Old); 7002 7003 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { 7004 if (Visit(Path, Local(MTE), RK)) 7005 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, 7006 EnableLifetimeWarnings); 7007 } 7008 7009 if (isa<CallExpr>(Init)) { 7010 if (EnableLifetimeWarnings) 7011 handleGslAnnotatedTypes(Path, Init, Visit); 7012 return visitLifetimeBoundArguments(Path, Init, Visit); 7013 } 7014 7015 switch (Init->getStmtClass()) { 7016 case Stmt::DeclRefExprClass: { 7017 // If we find the name of a local non-reference parameter, we could have a 7018 // lifetime problem. 7019 auto *DRE = cast<DeclRefExpr>(Init); 7020 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7021 if (VD && VD->hasLocalStorage() && 7022 !DRE->refersToEnclosingVariableOrCapture()) { 7023 if (!VD->getType()->isReferenceType()) { 7024 Visit(Path, Local(DRE), RK); 7025 } else if (isa<ParmVarDecl>(DRE->getDecl())) { 7026 // The lifetime of a reference parameter is unknown; assume it's OK 7027 // for now. 7028 break; 7029 } else if (VD->getInit() && !isVarOnPath(Path, VD)) { 7030 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7031 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), 7032 RK_ReferenceBinding, Visit, 7033 EnableLifetimeWarnings); 7034 } 7035 } 7036 break; 7037 } 7038 7039 case Stmt::UnaryOperatorClass: { 7040 // The only unary operator that make sense to handle here 7041 // is Deref. All others don't resolve to a "name." This includes 7042 // handling all sorts of rvalues passed to a unary operator. 7043 const UnaryOperator *U = cast<UnaryOperator>(Init); 7044 if (U->getOpcode() == UO_Deref) 7045 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, 7046 EnableLifetimeWarnings); 7047 break; 7048 } 7049 7050 case Stmt::OMPArraySectionExprClass: { 7051 visitLocalsRetainedByInitializer(Path, 7052 cast<OMPArraySectionExpr>(Init)->getBase(), 7053 Visit, true, EnableLifetimeWarnings); 7054 break; 7055 } 7056 7057 case Stmt::ConditionalOperatorClass: 7058 case Stmt::BinaryConditionalOperatorClass: { 7059 auto *C = cast<AbstractConditionalOperator>(Init); 7060 if (!C->getTrueExpr()->getType()->isVoidType()) 7061 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, 7062 EnableLifetimeWarnings); 7063 if (!C->getFalseExpr()->getType()->isVoidType()) 7064 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, 7065 EnableLifetimeWarnings); 7066 break; 7067 } 7068 7069 // FIXME: Visit the left-hand side of an -> or ->*. 7070 7071 default: 7072 break; 7073 } 7074 } 7075 7076 /// Visit the locals that would be reachable through an object initialized by 7077 /// the prvalue expression \c Init. 7078 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 7079 Expr *Init, LocalVisitor Visit, 7080 bool RevisitSubinits, 7081 bool EnableLifetimeWarnings) { 7082 RevertToOldSizeRAII RAII(Path); 7083 7084 Expr *Old; 7085 do { 7086 Old = Init; 7087 7088 // Step into CXXDefaultInitExprs so we can diagnose cases where a 7089 // constructor inherits one as an implicit mem-initializer. 7090 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 7091 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 7092 Init = DIE->getExpr(); 7093 } 7094 7095 if (auto *FE = dyn_cast<FullExpr>(Init)) 7096 Init = FE->getSubExpr(); 7097 7098 // Dig out the expression which constructs the extended temporary. 7099 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 7100 7101 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) 7102 Init = BTE->getSubExpr(); 7103 7104 Init = Init->IgnoreParens(); 7105 7106 // Step over value-preserving rvalue casts. 7107 if (auto *CE = dyn_cast<CastExpr>(Init)) { 7108 switch (CE->getCastKind()) { 7109 case CK_LValueToRValue: 7110 // If we can match the lvalue to a const object, we can look at its 7111 // initializer. 7112 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); 7113 return visitLocalsRetainedByReferenceBinding( 7114 Path, Init, RK_ReferenceBinding, 7115 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { 7116 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7117 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7118 if (VD && VD->getType().isConstQualified() && VD->getInit() && 7119 !isVarOnPath(Path, VD)) { 7120 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7121 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, 7122 EnableLifetimeWarnings); 7123 } 7124 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { 7125 if (MTE->getType().isConstQualified()) 7126 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, 7127 true, EnableLifetimeWarnings); 7128 } 7129 return false; 7130 }, EnableLifetimeWarnings); 7131 7132 // We assume that objects can be retained by pointers cast to integers, 7133 // but not if the integer is cast to floating-point type or to _Complex. 7134 // We assume that casts to 'bool' do not preserve enough information to 7135 // retain a local object. 7136 case CK_NoOp: 7137 case CK_BitCast: 7138 case CK_BaseToDerived: 7139 case CK_DerivedToBase: 7140 case CK_UncheckedDerivedToBase: 7141 case CK_Dynamic: 7142 case CK_ToUnion: 7143 case CK_UserDefinedConversion: 7144 case CK_ConstructorConversion: 7145 case CK_IntegralToPointer: 7146 case CK_PointerToIntegral: 7147 case CK_VectorSplat: 7148 case CK_IntegralCast: 7149 case CK_CPointerToObjCPointerCast: 7150 case CK_BlockPointerToObjCPointerCast: 7151 case CK_AnyPointerToBlockPointerCast: 7152 case CK_AddressSpaceConversion: 7153 break; 7154 7155 case CK_ArrayToPointerDecay: 7156 // Model array-to-pointer decay as taking the address of the array 7157 // lvalue. 7158 Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); 7159 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), 7160 RK_ReferenceBinding, Visit, 7161 EnableLifetimeWarnings); 7162 7163 default: 7164 return; 7165 } 7166 7167 Init = CE->getSubExpr(); 7168 } 7169 } while (Old != Init); 7170 7171 // C++17 [dcl.init.list]p6: 7172 // initializing an initializer_list object from the array extends the 7173 // lifetime of the array exactly like binding a reference to a temporary. 7174 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) 7175 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), 7176 RK_StdInitializerList, Visit, 7177 EnableLifetimeWarnings); 7178 7179 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 7180 // We already visited the elements of this initializer list while 7181 // performing the initialization. Don't visit them again unless we've 7182 // changed the lifetime of the initialized entity. 7183 if (!RevisitSubinits) 7184 return; 7185 7186 if (ILE->isTransparent()) 7187 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, 7188 RevisitSubinits, 7189 EnableLifetimeWarnings); 7190 7191 if (ILE->getType()->isArrayType()) { 7192 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) 7193 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, 7194 RevisitSubinits, 7195 EnableLifetimeWarnings); 7196 return; 7197 } 7198 7199 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { 7200 assert(RD->isAggregate() && "aggregate init on non-aggregate"); 7201 7202 // If we lifetime-extend a braced initializer which is initializing an 7203 // aggregate, and that aggregate contains reference members which are 7204 // bound to temporaries, those temporaries are also lifetime-extended. 7205 if (RD->isUnion() && ILE->getInitializedFieldInUnion() && 7206 ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) 7207 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), 7208 RK_ReferenceBinding, Visit, 7209 EnableLifetimeWarnings); 7210 else { 7211 unsigned Index = 0; 7212 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) 7213 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, 7214 RevisitSubinits, 7215 EnableLifetimeWarnings); 7216 for (const auto *I : RD->fields()) { 7217 if (Index >= ILE->getNumInits()) 7218 break; 7219 if (I->isUnnamedBitfield()) 7220 continue; 7221 Expr *SubInit = ILE->getInit(Index); 7222 if (I->getType()->isReferenceType()) 7223 visitLocalsRetainedByReferenceBinding(Path, SubInit, 7224 RK_ReferenceBinding, Visit, 7225 EnableLifetimeWarnings); 7226 else 7227 // This might be either aggregate-initialization of a member or 7228 // initialization of a std::initializer_list object. Regardless, 7229 // we should recursively lifetime-extend that initializer. 7230 visitLocalsRetainedByInitializer(Path, SubInit, Visit, 7231 RevisitSubinits, 7232 EnableLifetimeWarnings); 7233 ++Index; 7234 } 7235 } 7236 } 7237 return; 7238 } 7239 7240 // The lifetime of an init-capture is that of the closure object constructed 7241 // by a lambda-expression. 7242 if (auto *LE = dyn_cast<LambdaExpr>(Init)) { 7243 for (Expr *E : LE->capture_inits()) { 7244 if (!E) 7245 continue; 7246 if (E->isGLValue()) 7247 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, 7248 Visit, EnableLifetimeWarnings); 7249 else 7250 visitLocalsRetainedByInitializer(Path, E, Visit, true, 7251 EnableLifetimeWarnings); 7252 } 7253 } 7254 7255 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { 7256 if (EnableLifetimeWarnings) 7257 handleGslAnnotatedTypes(Path, Init, Visit); 7258 return visitLifetimeBoundArguments(Path, Init, Visit); 7259 } 7260 7261 switch (Init->getStmtClass()) { 7262 case Stmt::UnaryOperatorClass: { 7263 auto *UO = cast<UnaryOperator>(Init); 7264 // If the initializer is the address of a local, we could have a lifetime 7265 // problem. 7266 if (UO->getOpcode() == UO_AddrOf) { 7267 // If this is &rvalue, then it's ill-formed and we have already diagnosed 7268 // it. Don't produce a redundant warning about the lifetime of the 7269 // temporary. 7270 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) 7271 return; 7272 7273 Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); 7274 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), 7275 RK_ReferenceBinding, Visit, 7276 EnableLifetimeWarnings); 7277 } 7278 break; 7279 } 7280 7281 case Stmt::BinaryOperatorClass: { 7282 // Handle pointer arithmetic. 7283 auto *BO = cast<BinaryOperator>(Init); 7284 BinaryOperatorKind BOK = BO->getOpcode(); 7285 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) 7286 break; 7287 7288 if (BO->getLHS()->getType()->isPointerType()) 7289 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, 7290 EnableLifetimeWarnings); 7291 else if (BO->getRHS()->getType()->isPointerType()) 7292 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, 7293 EnableLifetimeWarnings); 7294 break; 7295 } 7296 7297 case Stmt::ConditionalOperatorClass: 7298 case Stmt::BinaryConditionalOperatorClass: { 7299 auto *C = cast<AbstractConditionalOperator>(Init); 7300 // In C++, we can have a throw-expression operand, which has 'void' type 7301 // and isn't interesting from a lifetime perspective. 7302 if (!C->getTrueExpr()->getType()->isVoidType()) 7303 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, 7304 EnableLifetimeWarnings); 7305 if (!C->getFalseExpr()->getType()->isVoidType()) 7306 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, 7307 EnableLifetimeWarnings); 7308 break; 7309 } 7310 7311 case Stmt::BlockExprClass: 7312 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { 7313 // This is a local block, whose lifetime is that of the function. 7314 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); 7315 } 7316 break; 7317 7318 case Stmt::AddrLabelExprClass: 7319 // We want to warn if the address of a label would escape the function. 7320 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); 7321 break; 7322 7323 default: 7324 break; 7325 } 7326 } 7327 7328 /// Determine whether this is an indirect path to a temporary that we are 7329 /// supposed to lifetime-extend along (but don't). 7330 static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { 7331 for (auto Elem : Path) { 7332 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit) 7333 return false; 7334 } 7335 return true; 7336 } 7337 7338 /// Find the range for the first interesting entry in the path at or after I. 7339 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, 7340 Expr *E) { 7341 for (unsigned N = Path.size(); I != N; ++I) { 7342 switch (Path[I].Kind) { 7343 case IndirectLocalPathEntry::AddressOf: 7344 case IndirectLocalPathEntry::LValToRVal: 7345 case IndirectLocalPathEntry::LifetimeBoundCall: 7346 case IndirectLocalPathEntry::GslReferenceInit: 7347 case IndirectLocalPathEntry::GslPointerInit: 7348 // These exist primarily to mark the path as not permitting or 7349 // supporting lifetime extension. 7350 break; 7351 7352 case IndirectLocalPathEntry::VarInit: 7353 if (cast<VarDecl>(Path[I].D)->isImplicit()) 7354 return SourceRange(); 7355 LLVM_FALLTHROUGH; 7356 case IndirectLocalPathEntry::DefaultInit: 7357 return Path[I].E->getSourceRange(); 7358 } 7359 } 7360 return E->getSourceRange(); 7361 } 7362 7363 static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { 7364 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 7365 if (It->Kind == IndirectLocalPathEntry::VarInit) 7366 continue; 7367 if (It->Kind == IndirectLocalPathEntry::AddressOf) 7368 continue; 7369 return It->Kind == IndirectLocalPathEntry::GslPointerInit || 7370 It->Kind == IndirectLocalPathEntry::GslReferenceInit; 7371 } 7372 return false; 7373 } 7374 7375 void Sema::checkInitializerLifetime(const InitializedEntity &Entity, 7376 Expr *Init) { 7377 LifetimeResult LR = getEntityLifetime(&Entity); 7378 LifetimeKind LK = LR.getInt(); 7379 const InitializedEntity *ExtendingEntity = LR.getPointer(); 7380 7381 // If this entity doesn't have an interesting lifetime, don't bother looking 7382 // for temporaries within its initializer. 7383 if (LK == LK_FullExpression) 7384 return; 7385 7386 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, 7387 ReferenceKind RK) -> bool { 7388 SourceRange DiagRange = nextPathEntryRange(Path, 0, L); 7389 SourceLocation DiagLoc = DiagRange.getBegin(); 7390 7391 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); 7392 7393 bool IsGslPtrInitWithGslTempOwner = false; 7394 bool IsLocalGslOwner = false; 7395 if (pathOnlyInitializesGslPointer(Path)) { 7396 if (isa<DeclRefExpr>(L)) { 7397 // We do not want to follow the references when returning a pointer originating 7398 // from a local owner to avoid the following false positive: 7399 // int &p = *localUniquePtr; 7400 // someContainer.add(std::move(localUniquePtr)); 7401 // return p; 7402 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); 7403 if (pathContainsInit(Path) || !IsLocalGslOwner) 7404 return false; 7405 } else { 7406 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && 7407 isRecordWithAttr<OwnerAttr>(MTE->getType()); 7408 // Skipping a chain of initializing gsl::Pointer annotated objects. 7409 // We are looking only for the final source to find out if it was 7410 // a local or temporary owner or the address of a local variable/param. 7411 if (!IsGslPtrInitWithGslTempOwner) 7412 return true; 7413 } 7414 } 7415 7416 switch (LK) { 7417 case LK_FullExpression: 7418 llvm_unreachable("already handled this"); 7419 7420 case LK_Extended: { 7421 if (!MTE) { 7422 // The initialized entity has lifetime beyond the full-expression, 7423 // and the local entity does too, so don't warn. 7424 // 7425 // FIXME: We should consider warning if a static / thread storage 7426 // duration variable retains an automatic storage duration local. 7427 return false; 7428 } 7429 7430 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { 7431 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; 7432 return false; 7433 } 7434 7435 // Lifetime-extend the temporary. 7436 if (Path.empty()) { 7437 // Update the storage duration of the materialized temporary. 7438 // FIXME: Rebuild the expression instead of mutating it. 7439 MTE->setExtendingDecl(ExtendingEntity->getDecl(), 7440 ExtendingEntity->allocateManglingNumber()); 7441 // Also visit the temporaries lifetime-extended by this initializer. 7442 return true; 7443 } 7444 7445 if (shouldLifetimeExtendThroughPath(Path)) { 7446 // We're supposed to lifetime-extend the temporary along this path (per 7447 // the resolution of DR1815), but we don't support that yet. 7448 // 7449 // FIXME: Properly handle this situation. Perhaps the easiest approach 7450 // would be to clone the initializer expression on each use that would 7451 // lifetime extend its temporaries. 7452 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) 7453 << RK << DiagRange; 7454 } else { 7455 // If the path goes through the initialization of a variable or field, 7456 // it can't possibly reach a temporary created in this full-expression. 7457 // We will have already diagnosed any problems with the initializer. 7458 if (pathContainsInit(Path)) 7459 return false; 7460 7461 Diag(DiagLoc, diag::warn_dangling_variable) 7462 << RK << !Entity.getParent() 7463 << ExtendingEntity->getDecl()->isImplicit() 7464 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; 7465 } 7466 break; 7467 } 7468 7469 case LK_MemInitializer: { 7470 if (isa<MaterializeTemporaryExpr>(L)) { 7471 // Under C++ DR1696, if a mem-initializer (or a default member 7472 // initializer used by the absence of one) would lifetime-extend a 7473 // temporary, the program is ill-formed. 7474 if (auto *ExtendingDecl = 7475 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { 7476 if (IsGslPtrInitWithGslTempOwner) { 7477 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) 7478 << ExtendingDecl << DiagRange; 7479 Diag(ExtendingDecl->getLocation(), 7480 diag::note_ref_or_ptr_member_declared_here) 7481 << true; 7482 return false; 7483 } 7484 bool IsSubobjectMember = ExtendingEntity != &Entity; 7485 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) 7486 ? diag::err_dangling_member 7487 : diag::warn_dangling_member) 7488 << ExtendingDecl << IsSubobjectMember << RK << DiagRange; 7489 // Don't bother adding a note pointing to the field if we're inside 7490 // its default member initializer; our primary diagnostic points to 7491 // the same place in that case. 7492 if (Path.empty() || 7493 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { 7494 Diag(ExtendingDecl->getLocation(), 7495 diag::note_lifetime_extending_member_declared_here) 7496 << RK << IsSubobjectMember; 7497 } 7498 } else { 7499 // We have a mem-initializer but no particular field within it; this 7500 // is either a base class or a delegating initializer directly 7501 // initializing the base-class from something that doesn't live long 7502 // enough. 7503 // 7504 // FIXME: Warn on this. 7505 return false; 7506 } 7507 } else { 7508 // Paths via a default initializer can only occur during error recovery 7509 // (there's no other way that a default initializer can refer to a 7510 // local). Don't produce a bogus warning on those cases. 7511 if (pathContainsInit(Path)) 7512 return false; 7513 7514 // Suppress false positives for code like the one below: 7515 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} 7516 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) 7517 return false; 7518 7519 auto *DRE = dyn_cast<DeclRefExpr>(L); 7520 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; 7521 if (!VD) { 7522 // A member was initialized to a local block. 7523 // FIXME: Warn on this. 7524 return false; 7525 } 7526 7527 if (auto *Member = 7528 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { 7529 bool IsPointer = !Member->getType()->isReferenceType(); 7530 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 7531 : diag::warn_bind_ref_member_to_parameter) 7532 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; 7533 Diag(Member->getLocation(), 7534 diag::note_ref_or_ptr_member_declared_here) 7535 << (unsigned)IsPointer; 7536 } 7537 } 7538 break; 7539 } 7540 7541 case LK_New: 7542 if (isa<MaterializeTemporaryExpr>(L)) { 7543 if (IsGslPtrInitWithGslTempOwner) 7544 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; 7545 else 7546 Diag(DiagLoc, RK == RK_ReferenceBinding 7547 ? diag::warn_new_dangling_reference 7548 : diag::warn_new_dangling_initializer_list) 7549 << !Entity.getParent() << DiagRange; 7550 } else { 7551 // We can't determine if the allocation outlives the local declaration. 7552 return false; 7553 } 7554 break; 7555 7556 case LK_Return: 7557 case LK_StmtExprResult: 7558 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7559 // We can't determine if the local variable outlives the statement 7560 // expression. 7561 if (LK == LK_StmtExprResult) 7562 return false; 7563 Diag(DiagLoc, diag::warn_ret_stack_addr_ref) 7564 << Entity.getType()->isReferenceType() << DRE->getDecl() 7565 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; 7566 } else if (isa<BlockExpr>(L)) { 7567 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; 7568 } else if (isa<AddrLabelExpr>(L)) { 7569 // Don't warn when returning a label from a statement expression. 7570 // Leaving the scope doesn't end its lifetime. 7571 if (LK == LK_StmtExprResult) 7572 return false; 7573 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; 7574 } else { 7575 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) 7576 << Entity.getType()->isReferenceType() << DiagRange; 7577 } 7578 break; 7579 } 7580 7581 for (unsigned I = 0; I != Path.size(); ++I) { 7582 auto Elem = Path[I]; 7583 7584 switch (Elem.Kind) { 7585 case IndirectLocalPathEntry::AddressOf: 7586 case IndirectLocalPathEntry::LValToRVal: 7587 // These exist primarily to mark the path as not permitting or 7588 // supporting lifetime extension. 7589 break; 7590 7591 case IndirectLocalPathEntry::LifetimeBoundCall: 7592 case IndirectLocalPathEntry::GslPointerInit: 7593 case IndirectLocalPathEntry::GslReferenceInit: 7594 // FIXME: Consider adding a note for these. 7595 break; 7596 7597 case IndirectLocalPathEntry::DefaultInit: { 7598 auto *FD = cast<FieldDecl>(Elem.D); 7599 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) 7600 << FD << nextPathEntryRange(Path, I + 1, L); 7601 break; 7602 } 7603 7604 case IndirectLocalPathEntry::VarInit: 7605 const VarDecl *VD = cast<VarDecl>(Elem.D); 7606 Diag(VD->getLocation(), diag::note_local_var_initializer) 7607 << VD->getType()->isReferenceType() 7608 << VD->isImplicit() << VD->getDeclName() 7609 << nextPathEntryRange(Path, I + 1, L); 7610 break; 7611 } 7612 } 7613 7614 // We didn't lifetime-extend, so don't go any further; we don't need more 7615 // warnings or errors on inner temporaries within this one's initializer. 7616 return false; 7617 }; 7618 7619 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( 7620 diag::warn_dangling_lifetime_pointer, SourceLocation()); 7621 llvm::SmallVector<IndirectLocalPathEntry, 8> Path; 7622 if (Init->isGLValue()) 7623 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, 7624 TemporaryVisitor, 7625 EnableLifetimeWarnings); 7626 else 7627 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, 7628 EnableLifetimeWarnings); 7629 } 7630 7631 static void DiagnoseNarrowingInInitList(Sema &S, 7632 const ImplicitConversionSequence &ICS, 7633 QualType PreNarrowingType, 7634 QualType EntityType, 7635 const Expr *PostInit); 7636 7637 /// Provide warnings when std::move is used on construction. 7638 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, 7639 bool IsReturnStmt) { 7640 if (!InitExpr) 7641 return; 7642 7643 if (S.inTemplateInstantiation()) 7644 return; 7645 7646 QualType DestType = InitExpr->getType(); 7647 if (!DestType->isRecordType()) 7648 return; 7649 7650 unsigned DiagID = 0; 7651 if (IsReturnStmt) { 7652 const CXXConstructExpr *CCE = 7653 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); 7654 if (!CCE || CCE->getNumArgs() != 1) 7655 return; 7656 7657 if (!CCE->getConstructor()->isCopyOrMoveConstructor()) 7658 return; 7659 7660 InitExpr = CCE->getArg(0)->IgnoreImpCasts(); 7661 } 7662 7663 // Find the std::move call and get the argument. 7664 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); 7665 if (!CE || !CE->isCallToStdMove()) 7666 return; 7667 7668 const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); 7669 7670 if (IsReturnStmt) { 7671 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); 7672 if (!DRE || DRE->refersToEnclosingVariableOrCapture()) 7673 return; 7674 7675 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7676 if (!VD || !VD->hasLocalStorage()) 7677 return; 7678 7679 // __block variables are not moved implicitly. 7680 if (VD->hasAttr<BlocksAttr>()) 7681 return; 7682 7683 QualType SourceType = VD->getType(); 7684 if (!SourceType->isRecordType()) 7685 return; 7686 7687 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { 7688 return; 7689 } 7690 7691 // If we're returning a function parameter, copy elision 7692 // is not possible. 7693 if (isa<ParmVarDecl>(VD)) 7694 DiagID = diag::warn_redundant_move_on_return; 7695 else 7696 DiagID = diag::warn_pessimizing_move_on_return; 7697 } else { 7698 DiagID = diag::warn_pessimizing_move_on_initialization; 7699 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); 7700 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) 7701 return; 7702 } 7703 7704 S.Diag(CE->getBeginLoc(), DiagID); 7705 7706 // Get all the locations for a fix-it. Don't emit the fix-it if any location 7707 // is within a macro. 7708 SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); 7709 if (CallBegin.isMacroID()) 7710 return; 7711 SourceLocation RParen = CE->getRParenLoc(); 7712 if (RParen.isMacroID()) 7713 return; 7714 SourceLocation LParen; 7715 SourceLocation ArgLoc = Arg->getBeginLoc(); 7716 7717 // Special testing for the argument location. Since the fix-it needs the 7718 // location right before the argument, the argument location can be in a 7719 // macro only if it is at the beginning of the macro. 7720 while (ArgLoc.isMacroID() && 7721 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { 7722 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); 7723 } 7724 7725 if (LParen.isMacroID()) 7726 return; 7727 7728 LParen = ArgLoc.getLocWithOffset(-1); 7729 7730 S.Diag(CE->getBeginLoc(), diag::note_remove_move) 7731 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) 7732 << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); 7733 } 7734 7735 static void CheckForNullPointerDereference(Sema &S, const Expr *E) { 7736 // Check to see if we are dereferencing a null pointer. If so, this is 7737 // undefined behavior, so warn about it. This only handles the pattern 7738 // "*null", which is a very syntactic check. 7739 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 7740 if (UO->getOpcode() == UO_Deref && 7741 UO->getSubExpr()->IgnoreParenCasts()-> 7742 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { 7743 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 7744 S.PDiag(diag::warn_binding_null_to_reference) 7745 << UO->getSubExpr()->getSourceRange()); 7746 } 7747 } 7748 7749 MaterializeTemporaryExpr * 7750 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 7751 bool BoundToLvalueReference) { 7752 auto MTE = new (Context) 7753 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); 7754 7755 // Order an ExprWithCleanups for lifetime marks. 7756 // 7757 // TODO: It'll be good to have a single place to check the access of the 7758 // destructor and generate ExprWithCleanups for various uses. Currently these 7759 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, 7760 // but there may be a chance to merge them. 7761 Cleanup.setExprNeedsCleanups(false); 7762 return MTE; 7763 } 7764 7765 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { 7766 // In C++98, we don't want to implicitly create an xvalue. 7767 // FIXME: This means that AST consumers need to deal with "prvalues" that 7768 // denote materialized temporaries. Maybe we should add another ValueKind 7769 // for "xvalue pretending to be a prvalue" for C++98 support. 7770 if (!E->isRValue() || !getLangOpts().CPlusPlus11) 7771 return E; 7772 7773 // C++1z [conv.rval]/1: T shall be a complete type. 7774 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? 7775 // If so, we should check for a non-abstract class type here too. 7776 QualType T = E->getType(); 7777 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) 7778 return ExprError(); 7779 7780 return CreateMaterializeTemporaryExpr(E->getType(), E, false); 7781 } 7782 7783 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, 7784 ExprValueKind VK, 7785 CheckedConversionKind CCK) { 7786 7787 CastKind CK = CK_NoOp; 7788 7789 if (VK == VK_RValue) { 7790 auto PointeeTy = Ty->getPointeeType(); 7791 auto ExprPointeeTy = E->getType()->getPointeeType(); 7792 if (!PointeeTy.isNull() && 7793 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) 7794 CK = CK_AddressSpaceConversion; 7795 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { 7796 CK = CK_AddressSpaceConversion; 7797 } 7798 7799 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); 7800 } 7801 7802 ExprResult InitializationSequence::Perform(Sema &S, 7803 const InitializedEntity &Entity, 7804 const InitializationKind &Kind, 7805 MultiExprArg Args, 7806 QualType *ResultType) { 7807 if (Failed()) { 7808 Diagnose(S, Entity, Kind, Args); 7809 return ExprError(); 7810 } 7811 if (!ZeroInitializationFixit.empty()) { 7812 unsigned DiagID = diag::err_default_init_const; 7813 if (Decl *D = Entity.getDecl()) 7814 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) 7815 DiagID = diag::ext_default_init_const; 7816 7817 // The initialization would have succeeded with this fixit. Since the fixit 7818 // is on the error, we need to build a valid AST in this case, so this isn't 7819 // handled in the Failed() branch above. 7820 QualType DestType = Entity.getType(); 7821 S.Diag(Kind.getLocation(), DiagID) 7822 << DestType << (bool)DestType->getAs<RecordType>() 7823 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, 7824 ZeroInitializationFixit); 7825 } 7826 7827 if (getKind() == DependentSequence) { 7828 // If the declaration is a non-dependent, incomplete array type 7829 // that has an initializer, then its type will be completed once 7830 // the initializer is instantiated. 7831 if (ResultType && !Entity.getType()->isDependentType() && 7832 Args.size() == 1) { 7833 QualType DeclType = Entity.getType(); 7834 if (const IncompleteArrayType *ArrayT 7835 = S.Context.getAsIncompleteArrayType(DeclType)) { 7836 // FIXME: We don't currently have the ability to accurately 7837 // compute the length of an initializer list without 7838 // performing full type-checking of the initializer list 7839 // (since we have to determine where braces are implicitly 7840 // introduced and such). So, we fall back to making the array 7841 // type a dependently-sized array type with no specified 7842 // bound. 7843 if (isa<InitListExpr>((Expr *)Args[0])) { 7844 SourceRange Brackets; 7845 7846 // Scavange the location of the brackets from the entity, if we can. 7847 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { 7848 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 7849 TypeLoc TL = TInfo->getTypeLoc(); 7850 if (IncompleteArrayTypeLoc ArrayLoc = 7851 TL.getAs<IncompleteArrayTypeLoc>()) 7852 Brackets = ArrayLoc.getBracketsRange(); 7853 } 7854 } 7855 7856 *ResultType 7857 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 7858 /*NumElts=*/nullptr, 7859 ArrayT->getSizeModifier(), 7860 ArrayT->getIndexTypeCVRQualifiers(), 7861 Brackets); 7862 } 7863 7864 } 7865 } 7866 if (Kind.getKind() == InitializationKind::IK_Direct && 7867 !Kind.isExplicitCast()) { 7868 // Rebuild the ParenListExpr. 7869 SourceRange ParenRange = Kind.getParenOrBraceRange(); 7870 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), 7871 Args); 7872 } 7873 assert(Kind.getKind() == InitializationKind::IK_Copy || 7874 Kind.isExplicitCast() || 7875 Kind.getKind() == InitializationKind::IK_DirectList); 7876 return ExprResult(Args[0]); 7877 } 7878 7879 // No steps means no initialization. 7880 if (Steps.empty()) 7881 return ExprResult((Expr *)nullptr); 7882 7883 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && 7884 Args.size() == 1 && isa<InitListExpr>(Args[0]) && 7885 !Entity.isParameterKind()) { 7886 // Produce a C++98 compatibility warning if we are initializing a reference 7887 // from an initializer list. For parameters, we produce a better warning 7888 // elsewhere. 7889 Expr *Init = Args[0]; 7890 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) 7891 << Init->getSourceRange(); 7892 } 7893 7894 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope 7895 QualType ETy = Entity.getType(); 7896 bool HasGlobalAS = ETy.hasAddressSpace() && 7897 ETy.getAddressSpace() == LangAS::opencl_global; 7898 7899 if (S.getLangOpts().OpenCLVersion >= 200 && 7900 ETy->isAtomicType() && !HasGlobalAS && 7901 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { 7902 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) 7903 << 1 7904 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); 7905 return ExprError(); 7906 } 7907 7908 QualType DestType = Entity.getType().getNonReferenceType(); 7909 // FIXME: Ugly hack around the fact that Entity.getType() is not 7910 // the same as Entity.getDecl()->getType() in cases involving type merging, 7911 // and we want latter when it makes sense. 7912 if (ResultType) 7913 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 7914 Entity.getType(); 7915 7916 ExprResult CurInit((Expr *)nullptr); 7917 SmallVector<Expr*, 4> ArrayLoopCommonExprs; 7918 7919 // For initialization steps that start with a single initializer, 7920 // grab the only argument out the Args and place it into the "current" 7921 // initializer. 7922 switch (Steps.front().Kind) { 7923 case SK_ResolveAddressOfOverloadedFunction: 7924 case SK_CastDerivedToBaseRValue: 7925 case SK_CastDerivedToBaseXValue: 7926 case SK_CastDerivedToBaseLValue: 7927 case SK_BindReference: 7928 case SK_BindReferenceToTemporary: 7929 case SK_FinalCopy: 7930 case SK_ExtraneousCopyToTemporary: 7931 case SK_UserConversion: 7932 case SK_QualificationConversionLValue: 7933 case SK_QualificationConversionXValue: 7934 case SK_QualificationConversionRValue: 7935 case SK_AtomicConversion: 7936 case SK_ConversionSequence: 7937 case SK_ConversionSequenceNoNarrowing: 7938 case SK_ListInitialization: 7939 case SK_UnwrapInitList: 7940 case SK_RewrapInitList: 7941 case SK_CAssignment: 7942 case SK_StringInit: 7943 case SK_ObjCObjectConversion: 7944 case SK_ArrayLoopIndex: 7945 case SK_ArrayLoopInit: 7946 case SK_ArrayInit: 7947 case SK_GNUArrayInit: 7948 case SK_ParenthesizedArrayInit: 7949 case SK_PassByIndirectCopyRestore: 7950 case SK_PassByIndirectRestore: 7951 case SK_ProduceObjCObject: 7952 case SK_StdInitializerList: 7953 case SK_OCLSamplerInit: 7954 case SK_OCLZeroOpaqueType: { 7955 assert(Args.size() == 1); 7956 CurInit = Args[0]; 7957 if (!CurInit.get()) return ExprError(); 7958 break; 7959 } 7960 7961 case SK_ConstructorInitialization: 7962 case SK_ConstructorInitializationFromList: 7963 case SK_StdInitializerListConstructorCall: 7964 case SK_ZeroInitialization: 7965 break; 7966 } 7967 7968 // Promote from an unevaluated context to an unevaluated list context in 7969 // C++11 list-initialization; we need to instantiate entities usable in 7970 // constant expressions here in order to perform narrowing checks =( 7971 EnterExpressionEvaluationContext Evaluated( 7972 S, EnterExpressionEvaluationContext::InitList, 7973 CurInit.get() && isa<InitListExpr>(CurInit.get())); 7974 7975 // C++ [class.abstract]p2: 7976 // no objects of an abstract class can be created except as subobjects 7977 // of a class derived from it 7978 auto checkAbstractType = [&](QualType T) -> bool { 7979 if (Entity.getKind() == InitializedEntity::EK_Base || 7980 Entity.getKind() == InitializedEntity::EK_Delegating) 7981 return false; 7982 return S.RequireNonAbstractType(Kind.getLocation(), T, 7983 diag::err_allocation_of_abstract_type); 7984 }; 7985 7986 // Walk through the computed steps for the initialization sequence, 7987 // performing the specified conversions along the way. 7988 bool ConstructorInitRequiresZeroInit = false; 7989 for (step_iterator Step = step_begin(), StepEnd = step_end(); 7990 Step != StepEnd; ++Step) { 7991 if (CurInit.isInvalid()) 7992 return ExprError(); 7993 7994 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 7995 7996 switch (Step->Kind) { 7997 case SK_ResolveAddressOfOverloadedFunction: 7998 // Overload resolution determined which function invoke; update the 7999 // initializer to reflect that choice. 8000 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 8001 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) 8002 return ExprError(); 8003 CurInit = S.FixOverloadedFunctionReference(CurInit, 8004 Step->Function.FoundDecl, 8005 Step->Function.Function); 8006 break; 8007 8008 case SK_CastDerivedToBaseRValue: 8009 case SK_CastDerivedToBaseXValue: 8010 case SK_CastDerivedToBaseLValue: { 8011 // We have a derived-to-base cast that produces either an rvalue or an 8012 // lvalue. Perform that cast. 8013 8014 CXXCastPath BasePath; 8015 8016 // Casts to inaccessible base classes are allowed with C-style casts. 8017 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 8018 if (S.CheckDerivedToBaseConversion( 8019 SourceType, Step->Type, CurInit.get()->getBeginLoc(), 8020 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) 8021 return ExprError(); 8022 8023 ExprValueKind VK = 8024 Step->Kind == SK_CastDerivedToBaseLValue ? 8025 VK_LValue : 8026 (Step->Kind == SK_CastDerivedToBaseXValue ? 8027 VK_XValue : 8028 VK_RValue); 8029 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, 8030 CK_DerivedToBase, CurInit.get(), 8031 &BasePath, VK, FPOptionsOverride()); 8032 break; 8033 } 8034 8035 case SK_BindReference: 8036 // Reference binding does not have any corresponding ASTs. 8037 8038 // Check exception specifications 8039 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 8040 return ExprError(); 8041 8042 // We don't check for e.g. function pointers here, since address 8043 // availability checks should only occur when the function first decays 8044 // into a pointer or reference. 8045 if (CurInit.get()->getType()->isFunctionProtoType()) { 8046 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { 8047 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 8048 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 8049 DRE->getBeginLoc())) 8050 return ExprError(); 8051 } 8052 } 8053 } 8054 8055 CheckForNullPointerDereference(S, CurInit.get()); 8056 break; 8057 8058 case SK_BindReferenceToTemporary: { 8059 // Make sure the "temporary" is actually an rvalue. 8060 assert(CurInit.get()->isRValue() && "not a temporary"); 8061 8062 // Check exception specifications 8063 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 8064 return ExprError(); 8065 8066 // Materialize the temporary into memory. 8067 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 8068 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType()); 8069 CurInit = MTE; 8070 8071 // If we're extending this temporary to automatic storage duration -- we 8072 // need to register its cleanup during the full-expression's cleanups. 8073 if (MTE->getStorageDuration() == SD_Automatic && 8074 MTE->getType().isDestructedType()) 8075 S.Cleanup.setExprNeedsCleanups(true); 8076 break; 8077 } 8078 8079 case SK_FinalCopy: 8080 if (checkAbstractType(Step->Type)) 8081 return ExprError(); 8082 8083 // If the overall initialization is initializing a temporary, we already 8084 // bound our argument if it was necessary to do so. If not (if we're 8085 // ultimately initializing a non-temporary), our argument needs to be 8086 // bound since it's initializing a function parameter. 8087 // FIXME: This is a mess. Rationalize temporary destruction. 8088 if (!shouldBindAsTemporary(Entity)) 8089 CurInit = S.MaybeBindToTemporary(CurInit.get()); 8090 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 8091 /*IsExtraneousCopy=*/false); 8092 break; 8093 8094 case SK_ExtraneousCopyToTemporary: 8095 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 8096 /*IsExtraneousCopy=*/true); 8097 break; 8098 8099 case SK_UserConversion: { 8100 // We have a user-defined conversion that invokes either a constructor 8101 // or a conversion function. 8102 CastKind CastKind; 8103 FunctionDecl *Fn = Step->Function.Function; 8104 DeclAccessPair FoundFn = Step->Function.FoundDecl; 8105 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 8106 bool CreatedObject = false; 8107 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 8108 // Build a call to the selected constructor. 8109 SmallVector<Expr*, 8> ConstructorArgs; 8110 SourceLocation Loc = CurInit.get()->getBeginLoc(); 8111 8112 // Determine the arguments required to actually perform the constructor 8113 // call. 8114 Expr *Arg = CurInit.get(); 8115 if (S.CompleteConstructorCall(Constructor, 8116 MultiExprArg(&Arg, 1), 8117 Loc, ConstructorArgs)) 8118 return ExprError(); 8119 8120 // Build an expression that constructs a temporary. 8121 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, 8122 FoundFn, Constructor, 8123 ConstructorArgs, 8124 HadMultipleCandidates, 8125 /*ListInit*/ false, 8126 /*StdInitListInit*/ false, 8127 /*ZeroInit*/ false, 8128 CXXConstructExpr::CK_Complete, 8129 SourceRange()); 8130 if (CurInit.isInvalid()) 8131 return ExprError(); 8132 8133 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, 8134 Entity); 8135 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 8136 return ExprError(); 8137 8138 CastKind = CK_ConstructorConversion; 8139 CreatedObject = true; 8140 } else { 8141 // Build a call to the conversion function. 8142 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 8143 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, 8144 FoundFn); 8145 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 8146 return ExprError(); 8147 8148 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 8149 HadMultipleCandidates); 8150 if (CurInit.isInvalid()) 8151 return ExprError(); 8152 8153 CastKind = CK_UserDefinedConversion; 8154 CreatedObject = Conversion->getReturnType()->isRecordType(); 8155 } 8156 8157 if (CreatedObject && checkAbstractType(CurInit.get()->getType())) 8158 return ExprError(); 8159 8160 CurInit = ImplicitCastExpr::Create( 8161 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr, 8162 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides()); 8163 8164 if (shouldBindAsTemporary(Entity)) 8165 // The overall entity is temporary, so this expression should be 8166 // destroyed at the end of its full-expression. 8167 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 8168 else if (CreatedObject && shouldDestroyEntity(Entity)) { 8169 // The object outlasts the full-expression, but we need to prepare for 8170 // a destructor being run on it. 8171 // FIXME: It makes no sense to do this here. This should happen 8172 // regardless of how we initialized the entity. 8173 QualType T = CurInit.get()->getType(); 8174 if (const RecordType *Record = T->getAs<RecordType>()) { 8175 CXXDestructorDecl *Destructor 8176 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 8177 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, 8178 S.PDiag(diag::err_access_dtor_temp) << T); 8179 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); 8180 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) 8181 return ExprError(); 8182 } 8183 } 8184 break; 8185 } 8186 8187 case SK_QualificationConversionLValue: 8188 case SK_QualificationConversionXValue: 8189 case SK_QualificationConversionRValue: { 8190 // Perform a qualification conversion; these can never go wrong. 8191 ExprValueKind VK = 8192 Step->Kind == SK_QualificationConversionLValue 8193 ? VK_LValue 8194 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue 8195 : VK_RValue); 8196 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); 8197 break; 8198 } 8199 8200 case SK_AtomicConversion: { 8201 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic"); 8202 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8203 CK_NonAtomicToAtomic, VK_RValue); 8204 break; 8205 } 8206 8207 case SK_ConversionSequence: 8208 case SK_ConversionSequenceNoNarrowing: { 8209 if (const auto *FromPtrType = 8210 CurInit.get()->getType()->getAs<PointerType>()) { 8211 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { 8212 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8213 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8214 // Do not check static casts here because they are checked earlier 8215 // in Sema::ActOnCXXNamedCast() 8216 if (!Kind.isStaticCast()) { 8217 S.Diag(CurInit.get()->getExprLoc(), 8218 diag::warn_noderef_to_dereferenceable_pointer) 8219 << CurInit.get()->getSourceRange(); 8220 } 8221 } 8222 } 8223 } 8224 8225 Sema::CheckedConversionKind CCK 8226 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 8227 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 8228 : Kind.isExplicitCast()? Sema::CCK_OtherCast 8229 : Sema::CCK_ImplicitConversion; 8230 ExprResult CurInitExprRes = 8231 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 8232 getAssignmentAction(Entity), CCK); 8233 if (CurInitExprRes.isInvalid()) 8234 return ExprError(); 8235 8236 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); 8237 8238 CurInit = CurInitExprRes; 8239 8240 if (Step->Kind == SK_ConversionSequenceNoNarrowing && 8241 S.getLangOpts().CPlusPlus) 8242 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), 8243 CurInit.get()); 8244 8245 break; 8246 } 8247 8248 case SK_ListInitialization: { 8249 if (checkAbstractType(Step->Type)) 8250 return ExprError(); 8251 8252 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 8253 // If we're not initializing the top-level entity, we need to create an 8254 // InitializeTemporary entity for our target type. 8255 QualType Ty = Step->Type; 8256 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); 8257 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 8258 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; 8259 InitListChecker PerformInitList(S, InitEntity, 8260 InitList, Ty, /*VerifyOnly=*/false, 8261 /*TreatUnavailableAsInvalid=*/false); 8262 if (PerformInitList.HadError()) 8263 return ExprError(); 8264 8265 // Hack: We must update *ResultType if available in order to set the 8266 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 8267 // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 8268 if (ResultType && 8269 ResultType->getNonReferenceType()->isIncompleteArrayType()) { 8270 if ((*ResultType)->isRValueReferenceType()) 8271 Ty = S.Context.getRValueReferenceType(Ty); 8272 else if ((*ResultType)->isLValueReferenceType()) 8273 Ty = S.Context.getLValueReferenceType(Ty, 8274 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); 8275 *ResultType = Ty; 8276 } 8277 8278 InitListExpr *StructuredInitList = 8279 PerformInitList.getFullyStructuredList(); 8280 CurInit.get(); 8281 CurInit = shouldBindAsTemporary(InitEntity) 8282 ? S.MaybeBindToTemporary(StructuredInitList) 8283 : StructuredInitList; 8284 break; 8285 } 8286 8287 case SK_ConstructorInitializationFromList: { 8288 if (checkAbstractType(Step->Type)) 8289 return ExprError(); 8290 8291 // When an initializer list is passed for a parameter of type "reference 8292 // to object", we don't get an EK_Temporary entity, but instead an 8293 // EK_Parameter entity with reference type. 8294 // FIXME: This is a hack. What we really should do is create a user 8295 // conversion step for this case, but this makes it considerably more 8296 // complicated. For now, this will do. 8297 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 8298 Entity.getType().getNonReferenceType()); 8299 bool UseTemporary = Entity.getType()->isReferenceType(); 8300 assert(Args.size() == 1 && "expected a single argument for list init"); 8301 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 8302 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) 8303 << InitList->getSourceRange(); 8304 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 8305 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : 8306 Entity, 8307 Kind, Arg, *Step, 8308 ConstructorInitRequiresZeroInit, 8309 /*IsListInitialization*/true, 8310 /*IsStdInitListInit*/false, 8311 InitList->getLBraceLoc(), 8312 InitList->getRBraceLoc()); 8313 break; 8314 } 8315 8316 case SK_UnwrapInitList: 8317 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); 8318 break; 8319 8320 case SK_RewrapInitList: { 8321 Expr *E = CurInit.get(); 8322 InitListExpr *Syntactic = Step->WrappingSyntacticList; 8323 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 8324 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); 8325 ILE->setSyntacticForm(Syntactic); 8326 ILE->setType(E->getType()); 8327 ILE->setValueKind(E->getValueKind()); 8328 CurInit = ILE; 8329 break; 8330 } 8331 8332 case SK_ConstructorInitialization: 8333 case SK_StdInitializerListConstructorCall: { 8334 if (checkAbstractType(Step->Type)) 8335 return ExprError(); 8336 8337 // When an initializer list is passed for a parameter of type "reference 8338 // to object", we don't get an EK_Temporary entity, but instead an 8339 // EK_Parameter entity with reference type. 8340 // FIXME: This is a hack. What we really should do is create a user 8341 // conversion step for this case, but this makes it considerably more 8342 // complicated. For now, this will do. 8343 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 8344 Entity.getType().getNonReferenceType()); 8345 bool UseTemporary = Entity.getType()->isReferenceType(); 8346 bool IsStdInitListInit = 8347 Step->Kind == SK_StdInitializerListConstructorCall; 8348 Expr *Source = CurInit.get(); 8349 SourceRange Range = Kind.hasParenOrBraceRange() 8350 ? Kind.getParenOrBraceRange() 8351 : SourceRange(); 8352 CurInit = PerformConstructorInitialization( 8353 S, UseTemporary ? TempEntity : Entity, Kind, 8354 Source ? MultiExprArg(Source) : Args, *Step, 8355 ConstructorInitRequiresZeroInit, 8356 /*IsListInitialization*/ IsStdInitListInit, 8357 /*IsStdInitListInitialization*/ IsStdInitListInit, 8358 /*LBraceLoc*/ Range.getBegin(), 8359 /*RBraceLoc*/ Range.getEnd()); 8360 break; 8361 } 8362 8363 case SK_ZeroInitialization: { 8364 step_iterator NextStep = Step; 8365 ++NextStep; 8366 if (NextStep != StepEnd && 8367 (NextStep->Kind == SK_ConstructorInitialization || 8368 NextStep->Kind == SK_ConstructorInitializationFromList)) { 8369 // The need for zero-initialization is recorded directly into 8370 // the call to the object's constructor within the next step. 8371 ConstructorInitRequiresZeroInit = true; 8372 } else if (Kind.getKind() == InitializationKind::IK_Value && 8373 S.getLangOpts().CPlusPlus && 8374 !Kind.isImplicitValueInit()) { 8375 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 8376 if (!TSInfo) 8377 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 8378 Kind.getRange().getBegin()); 8379 8380 CurInit = new (S.Context) CXXScalarValueInitExpr( 8381 Entity.getType().getNonLValueExprType(S.Context), TSInfo, 8382 Kind.getRange().getEnd()); 8383 } else { 8384 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); 8385 } 8386 break; 8387 } 8388 8389 case SK_CAssignment: { 8390 QualType SourceType = CurInit.get()->getType(); 8391 8392 // Save off the initial CurInit in case we need to emit a diagnostic 8393 ExprResult InitialCurInit = CurInit; 8394 ExprResult Result = CurInit; 8395 Sema::AssignConvertType ConvTy = 8396 S.CheckSingleAssignmentConstraints(Step->Type, Result, true, 8397 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); 8398 if (Result.isInvalid()) 8399 return ExprError(); 8400 CurInit = Result; 8401 8402 // If this is a call, allow conversion to a transparent union. 8403 ExprResult CurInitExprRes = CurInit; 8404 if (ConvTy != Sema::Compatible && 8405 Entity.isParameterKind() && 8406 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 8407 == Sema::Compatible) 8408 ConvTy = Sema::Compatible; 8409 if (CurInitExprRes.isInvalid()) 8410 return ExprError(); 8411 CurInit = CurInitExprRes; 8412 8413 bool Complained; 8414 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 8415 Step->Type, SourceType, 8416 InitialCurInit.get(), 8417 getAssignmentAction(Entity, true), 8418 &Complained)) { 8419 PrintInitLocationNote(S, Entity); 8420 return ExprError(); 8421 } else if (Complained) 8422 PrintInitLocationNote(S, Entity); 8423 break; 8424 } 8425 8426 case SK_StringInit: { 8427 QualType Ty = Step->Type; 8428 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); 8429 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty, 8430 S.Context.getAsArrayType(Ty), S); 8431 break; 8432 } 8433 8434 case SK_ObjCObjectConversion: 8435 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8436 CK_ObjCObjectLValueCast, 8437 CurInit.get()->getValueKind()); 8438 break; 8439 8440 case SK_ArrayLoopIndex: { 8441 Expr *Cur = CurInit.get(); 8442 Expr *BaseExpr = new (S.Context) 8443 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), 8444 Cur->getValueKind(), Cur->getObjectKind(), Cur); 8445 Expr *IndexExpr = 8446 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); 8447 CurInit = S.CreateBuiltinArraySubscriptExpr( 8448 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); 8449 ArrayLoopCommonExprs.push_back(BaseExpr); 8450 break; 8451 } 8452 8453 case SK_ArrayLoopInit: { 8454 assert(!ArrayLoopCommonExprs.empty() && 8455 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit"); 8456 Expr *Common = ArrayLoopCommonExprs.pop_back_val(); 8457 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, 8458 CurInit.get()); 8459 break; 8460 } 8461 8462 case SK_GNUArrayInit: 8463 // Okay: we checked everything before creating this step. Note that 8464 // this is a GNU extension. 8465 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 8466 << Step->Type << CurInit.get()->getType() 8467 << CurInit.get()->getSourceRange(); 8468 updateGNUCompoundLiteralRValue(CurInit.get()); 8469 LLVM_FALLTHROUGH; 8470 case SK_ArrayInit: 8471 // If the destination type is an incomplete array type, update the 8472 // type accordingly. 8473 if (ResultType) { 8474 if (const IncompleteArrayType *IncompleteDest 8475 = S.Context.getAsIncompleteArrayType(Step->Type)) { 8476 if (const ConstantArrayType *ConstantSource 8477 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 8478 *ResultType = S.Context.getConstantArrayType( 8479 IncompleteDest->getElementType(), 8480 ConstantSource->getSize(), 8481 ConstantSource->getSizeExpr(), 8482 ArrayType::Normal, 0); 8483 } 8484 } 8485 } 8486 break; 8487 8488 case SK_ParenthesizedArrayInit: 8489 // Okay: we checked everything before creating this step. Note that 8490 // this is a GNU extension. 8491 S.Diag(Kind.getLocation(), diag::ext_array_init_parens) 8492 << CurInit.get()->getSourceRange(); 8493 break; 8494 8495 case SK_PassByIndirectCopyRestore: 8496 case SK_PassByIndirectRestore: 8497 checkIndirectCopyRestoreSource(S, CurInit.get()); 8498 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( 8499 CurInit.get(), Step->Type, 8500 Step->Kind == SK_PassByIndirectCopyRestore); 8501 break; 8502 8503 case SK_ProduceObjCObject: 8504 CurInit = ImplicitCastExpr::Create( 8505 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr, 8506 VK_RValue, FPOptionsOverride()); 8507 break; 8508 8509 case SK_StdInitializerList: { 8510 S.Diag(CurInit.get()->getExprLoc(), 8511 diag::warn_cxx98_compat_initializer_list_init) 8512 << CurInit.get()->getSourceRange(); 8513 8514 // Materialize the temporary into memory. 8515 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 8516 CurInit.get()->getType(), CurInit.get(), 8517 /*BoundToLvalueReference=*/false); 8518 8519 // Wrap it in a construction of a std::initializer_list<T>. 8520 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); 8521 8522 // Bind the result, in case the library has given initializer_list a 8523 // non-trivial destructor. 8524 if (shouldBindAsTemporary(Entity)) 8525 CurInit = S.MaybeBindToTemporary(CurInit.get()); 8526 break; 8527 } 8528 8529 case SK_OCLSamplerInit: { 8530 // Sampler initialization have 5 cases: 8531 // 1. function argument passing 8532 // 1a. argument is a file-scope variable 8533 // 1b. argument is a function-scope variable 8534 // 1c. argument is one of caller function's parameters 8535 // 2. variable initialization 8536 // 2a. initializing a file-scope variable 8537 // 2b. initializing a function-scope variable 8538 // 8539 // For file-scope variables, since they cannot be initialized by function 8540 // call of __translate_sampler_initializer in LLVM IR, their references 8541 // need to be replaced by a cast from their literal initializers to 8542 // sampler type. Since sampler variables can only be used in function 8543 // calls as arguments, we only need to replace them when handling the 8544 // argument passing. 8545 assert(Step->Type->isSamplerT() && 8546 "Sampler initialization on non-sampler type."); 8547 Expr *Init = CurInit.get()->IgnoreParens(); 8548 QualType SourceType = Init->getType(); 8549 // Case 1 8550 if (Entity.isParameterKind()) { 8551 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { 8552 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) 8553 << SourceType; 8554 break; 8555 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { 8556 auto Var = cast<VarDecl>(DRE->getDecl()); 8557 // Case 1b and 1c 8558 // No cast from integer to sampler is needed. 8559 if (!Var->hasGlobalStorage()) { 8560 CurInit = ImplicitCastExpr::Create( 8561 S.Context, Step->Type, CK_LValueToRValue, Init, 8562 /*BasePath=*/nullptr, VK_RValue, FPOptionsOverride()); 8563 break; 8564 } 8565 // Case 1a 8566 // For function call with a file-scope sampler variable as argument, 8567 // get the integer literal. 8568 // Do not diagnose if the file-scope variable does not have initializer 8569 // since this has already been diagnosed when parsing the variable 8570 // declaration. 8571 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) 8572 break; 8573 Init = cast<ImplicitCastExpr>(const_cast<Expr*>( 8574 Var->getInit()))->getSubExpr(); 8575 SourceType = Init->getType(); 8576 } 8577 } else { 8578 // Case 2 8579 // Check initializer is 32 bit integer constant. 8580 // If the initializer is taken from global variable, do not diagnose since 8581 // this has already been done when parsing the variable declaration. 8582 if (!Init->isConstantInitializer(S.Context, false)) 8583 break; 8584 8585 if (!SourceType->isIntegerType() || 8586 32 != S.Context.getIntWidth(SourceType)) { 8587 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) 8588 << SourceType; 8589 break; 8590 } 8591 8592 Expr::EvalResult EVResult; 8593 Init->EvaluateAsInt(EVResult, S.Context); 8594 llvm::APSInt Result = EVResult.Val.getInt(); 8595 const uint64_t SamplerValue = Result.getLimitedValue(); 8596 // 32-bit value of sampler's initializer is interpreted as 8597 // bit-field with the following structure: 8598 // |unspecified|Filter|Addressing Mode| Normalized Coords| 8599 // |31 6|5 4|3 1| 0| 8600 // This structure corresponds to enum values of sampler properties 8601 // defined in SPIR spec v1.2 and also opencl-c.h 8602 unsigned AddressingMode = (0x0E & SamplerValue) >> 1; 8603 unsigned FilterMode = (0x30 & SamplerValue) >> 4; 8604 if (FilterMode != 1 && FilterMode != 2 && 8605 !S.getOpenCLOptions().isEnabled( 8606 "cl_intel_device_side_avc_motion_estimation")) 8607 S.Diag(Kind.getLocation(), 8608 diag::warn_sampler_initializer_invalid_bits) 8609 << "Filter Mode"; 8610 if (AddressingMode > 4) 8611 S.Diag(Kind.getLocation(), 8612 diag::warn_sampler_initializer_invalid_bits) 8613 << "Addressing Mode"; 8614 } 8615 8616 // Cases 1a, 2a and 2b 8617 // Insert cast from integer to sampler. 8618 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, 8619 CK_IntToOCLSampler); 8620 break; 8621 } 8622 case SK_OCLZeroOpaqueType: { 8623 assert((Step->Type->isEventT() || Step->Type->isQueueT() || 8624 Step->Type->isOCLIntelSubgroupAVCType()) && 8625 "Wrong type for initialization of OpenCL opaque type."); 8626 8627 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8628 CK_ZeroToOCLOpaqueType, 8629 CurInit.get()->getValueKind()); 8630 break; 8631 } 8632 } 8633 } 8634 8635 // Check whether the initializer has a shorter lifetime than the initialized 8636 // entity, and if not, either lifetime-extend or warn as appropriate. 8637 if (auto *Init = CurInit.get()) 8638 S.checkInitializerLifetime(Entity, Init); 8639 8640 // Diagnose non-fatal problems with the completed initialization. 8641 if (Entity.getKind() == InitializedEntity::EK_Member && 8642 cast<FieldDecl>(Entity.getDecl())->isBitField()) 8643 S.CheckBitFieldInitialization(Kind.getLocation(), 8644 cast<FieldDecl>(Entity.getDecl()), 8645 CurInit.get()); 8646 8647 // Check for std::move on construction. 8648 if (const Expr *E = CurInit.get()) { 8649 CheckMoveOnConstruction(S, E, 8650 Entity.getKind() == InitializedEntity::EK_Result); 8651 } 8652 8653 return CurInit; 8654 } 8655 8656 /// Somewhere within T there is an uninitialized reference subobject. 8657 /// Dig it out and diagnose it. 8658 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, 8659 QualType T) { 8660 if (T->isReferenceType()) { 8661 S.Diag(Loc, diag::err_reference_without_init) 8662 << T.getNonReferenceType(); 8663 return true; 8664 } 8665 8666 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 8667 if (!RD || !RD->hasUninitializedReferenceMember()) 8668 return false; 8669 8670 for (const auto *FI : RD->fields()) { 8671 if (FI->isUnnamedBitfield()) 8672 continue; 8673 8674 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { 8675 S.Diag(Loc, diag::note_value_initialization_here) << RD; 8676 return true; 8677 } 8678 } 8679 8680 for (const auto &BI : RD->bases()) { 8681 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { 8682 S.Diag(Loc, diag::note_value_initialization_here) << RD; 8683 return true; 8684 } 8685 } 8686 8687 return false; 8688 } 8689 8690 8691 //===----------------------------------------------------------------------===// 8692 // Diagnose initialization failures 8693 //===----------------------------------------------------------------------===// 8694 8695 /// Emit notes associated with an initialization that failed due to a 8696 /// "simple" conversion failure. 8697 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, 8698 Expr *op) { 8699 QualType destType = entity.getType(); 8700 if (destType.getNonReferenceType()->isObjCObjectPointerType() && 8701 op->getType()->isObjCObjectPointerType()) { 8702 8703 // Emit a possible note about the conversion failing because the 8704 // operand is a message send with a related result type. 8705 S.EmitRelatedResultTypeNote(op); 8706 8707 // Emit a possible note about a return failing because we're 8708 // expecting a related result type. 8709 if (entity.getKind() == InitializedEntity::EK_Result) 8710 S.EmitRelatedResultTypeNoteForReturn(destType); 8711 } 8712 QualType fromType = op->getType(); 8713 auto *fromDecl = fromType.getTypePtr()->getPointeeCXXRecordDecl(); 8714 auto *destDecl = destType.getTypePtr()->getPointeeCXXRecordDecl(); 8715 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && 8716 destDecl->getDeclKind() == Decl::CXXRecord && 8717 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && 8718 !fromDecl->hasDefinition()) 8719 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion) 8720 << S.getASTContext().getTagDeclType(fromDecl) 8721 << S.getASTContext().getTagDeclType(destDecl); 8722 } 8723 8724 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, 8725 InitListExpr *InitList) { 8726 QualType DestType = Entity.getType(); 8727 8728 QualType E; 8729 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { 8730 QualType ArrayType = S.Context.getConstantArrayType( 8731 E.withConst(), 8732 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 8733 InitList->getNumInits()), 8734 nullptr, clang::ArrayType::Normal, 0); 8735 InitializedEntity HiddenArray = 8736 InitializedEntity::InitializeTemporary(ArrayType); 8737 return diagnoseListInit(S, HiddenArray, InitList); 8738 } 8739 8740 if (DestType->isReferenceType()) { 8741 // A list-initialization failure for a reference means that we tried to 8742 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the 8743 // inner initialization failed. 8744 QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); 8745 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); 8746 SourceLocation Loc = InitList->getBeginLoc(); 8747 if (auto *D = Entity.getDecl()) 8748 Loc = D->getLocation(); 8749 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; 8750 return; 8751 } 8752 8753 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, 8754 /*VerifyOnly=*/false, 8755 /*TreatUnavailableAsInvalid=*/false); 8756 assert(DiagnoseInitList.HadError() && 8757 "Inconsistent init list check result."); 8758 } 8759 8760 bool InitializationSequence::Diagnose(Sema &S, 8761 const InitializedEntity &Entity, 8762 const InitializationKind &Kind, 8763 ArrayRef<Expr *> Args) { 8764 if (!Failed()) 8765 return false; 8766 8767 // When we want to diagnose only one element of a braced-init-list, 8768 // we need to factor it out. 8769 Expr *OnlyArg; 8770 if (Args.size() == 1) { 8771 auto *List = dyn_cast<InitListExpr>(Args[0]); 8772 if (List && List->getNumInits() == 1) 8773 OnlyArg = List->getInit(0); 8774 else 8775 OnlyArg = Args[0]; 8776 } 8777 else 8778 OnlyArg = nullptr; 8779 8780 QualType DestType = Entity.getType(); 8781 switch (Failure) { 8782 case FK_TooManyInitsForReference: 8783 // FIXME: Customize for the initialized entity? 8784 if (Args.empty()) { 8785 // Dig out the reference subobject which is uninitialized and diagnose it. 8786 // If this is value-initialization, this could be nested some way within 8787 // the target type. 8788 assert(Kind.getKind() == InitializationKind::IK_Value || 8789 DestType->isReferenceType()); 8790 bool Diagnosed = 8791 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); 8792 assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); 8793 (void)Diagnosed; 8794 } else // FIXME: diagnostic below could be better! 8795 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 8796 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); 8797 break; 8798 case FK_ParenthesizedListInitForReference: 8799 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) 8800 << 1 << Entity.getType() << Args[0]->getSourceRange(); 8801 break; 8802 8803 case FK_ArrayNeedsInitList: 8804 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; 8805 break; 8806 case FK_ArrayNeedsInitListOrStringLiteral: 8807 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; 8808 break; 8809 case FK_ArrayNeedsInitListOrWideStringLiteral: 8810 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; 8811 break; 8812 case FK_NarrowStringIntoWideCharArray: 8813 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); 8814 break; 8815 case FK_WideStringIntoCharArray: 8816 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); 8817 break; 8818 case FK_IncompatWideStringIntoWideChar: 8819 S.Diag(Kind.getLocation(), 8820 diag::err_array_init_incompat_wide_string_into_wchar); 8821 break; 8822 case FK_PlainStringIntoUTF8Char: 8823 S.Diag(Kind.getLocation(), 8824 diag::err_array_init_plain_string_into_char8_t); 8825 S.Diag(Args.front()->getBeginLoc(), 8826 diag::note_array_init_plain_string_into_char8_t) 8827 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); 8828 break; 8829 case FK_UTF8StringIntoPlainChar: 8830 S.Diag(Kind.getLocation(), 8831 diag::err_array_init_utf8_string_into_char) 8832 << S.getLangOpts().CPlusPlus20; 8833 break; 8834 case FK_ArrayTypeMismatch: 8835 case FK_NonConstantArrayInit: 8836 S.Diag(Kind.getLocation(), 8837 (Failure == FK_ArrayTypeMismatch 8838 ? diag::err_array_init_different_type 8839 : diag::err_array_init_non_constant_array)) 8840 << DestType.getNonReferenceType() 8841 << OnlyArg->getType() 8842 << Args[0]->getSourceRange(); 8843 break; 8844 8845 case FK_VariableLengthArrayHasInitializer: 8846 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 8847 << Args[0]->getSourceRange(); 8848 break; 8849 8850 case FK_AddressOfOverloadFailed: { 8851 DeclAccessPair Found; 8852 S.ResolveAddressOfOverloadedFunction(OnlyArg, 8853 DestType.getNonReferenceType(), 8854 true, 8855 Found); 8856 break; 8857 } 8858 8859 case FK_AddressOfUnaddressableFunction: { 8860 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); 8861 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 8862 OnlyArg->getBeginLoc()); 8863 break; 8864 } 8865 8866 case FK_ReferenceInitOverloadFailed: 8867 case FK_UserConversionOverloadFailed: 8868 switch (FailedOverloadResult) { 8869 case OR_Ambiguous: 8870 8871 FailedCandidateSet.NoteCandidates( 8872 PartialDiagnosticAt( 8873 Kind.getLocation(), 8874 Failure == FK_UserConversionOverloadFailed 8875 ? (S.PDiag(diag::err_typecheck_ambiguous_condition) 8876 << OnlyArg->getType() << DestType 8877 << Args[0]->getSourceRange()) 8878 : (S.PDiag(diag::err_ref_init_ambiguous) 8879 << DestType << OnlyArg->getType() 8880 << Args[0]->getSourceRange())), 8881 S, OCD_AmbiguousCandidates, Args); 8882 break; 8883 8884 case OR_No_Viable_Function: { 8885 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); 8886 if (!S.RequireCompleteType(Kind.getLocation(), 8887 DestType.getNonReferenceType(), 8888 diag::err_typecheck_nonviable_condition_incomplete, 8889 OnlyArg->getType(), Args[0]->getSourceRange())) 8890 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 8891 << (Entity.getKind() == InitializedEntity::EK_Result) 8892 << OnlyArg->getType() << Args[0]->getSourceRange() 8893 << DestType.getNonReferenceType(); 8894 8895 FailedCandidateSet.NoteCandidates(S, Args, Cands); 8896 break; 8897 } 8898 case OR_Deleted: { 8899 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 8900 << OnlyArg->getType() << DestType.getNonReferenceType() 8901 << Args[0]->getSourceRange(); 8902 OverloadCandidateSet::iterator Best; 8903 OverloadingResult Ovl 8904 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 8905 if (Ovl == OR_Deleted) { 8906 S.NoteDeletedFunction(Best->Function); 8907 } else { 8908 llvm_unreachable("Inconsistent overload resolution?"); 8909 } 8910 break; 8911 } 8912 8913 case OR_Success: 8914 llvm_unreachable("Conversion did not fail!"); 8915 } 8916 break; 8917 8918 case FK_NonConstLValueReferenceBindingToTemporary: 8919 if (isa<InitListExpr>(Args[0])) { 8920 S.Diag(Kind.getLocation(), 8921 diag::err_lvalue_reference_bind_to_initlist) 8922 << DestType.getNonReferenceType().isVolatileQualified() 8923 << DestType.getNonReferenceType() 8924 << Args[0]->getSourceRange(); 8925 break; 8926 } 8927 LLVM_FALLTHROUGH; 8928 8929 case FK_NonConstLValueReferenceBindingToUnrelated: 8930 S.Diag(Kind.getLocation(), 8931 Failure == FK_NonConstLValueReferenceBindingToTemporary 8932 ? diag::err_lvalue_reference_bind_to_temporary 8933 : diag::err_lvalue_reference_bind_to_unrelated) 8934 << DestType.getNonReferenceType().isVolatileQualified() 8935 << DestType.getNonReferenceType() 8936 << OnlyArg->getType() 8937 << Args[0]->getSourceRange(); 8938 break; 8939 8940 case FK_NonConstLValueReferenceBindingToBitfield: { 8941 // We don't necessarily have an unambiguous source bit-field. 8942 FieldDecl *BitField = Args[0]->getSourceBitField(); 8943 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 8944 << DestType.isVolatileQualified() 8945 << (BitField ? BitField->getDeclName() : DeclarationName()) 8946 << (BitField != nullptr) 8947 << Args[0]->getSourceRange(); 8948 if (BitField) 8949 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 8950 break; 8951 } 8952 8953 case FK_NonConstLValueReferenceBindingToVectorElement: 8954 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 8955 << DestType.isVolatileQualified() 8956 << Args[0]->getSourceRange(); 8957 break; 8958 8959 case FK_NonConstLValueReferenceBindingToMatrixElement: 8960 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element) 8961 << DestType.isVolatileQualified() << Args[0]->getSourceRange(); 8962 break; 8963 8964 case FK_RValueReferenceBindingToLValue: 8965 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 8966 << DestType.getNonReferenceType() << OnlyArg->getType() 8967 << Args[0]->getSourceRange(); 8968 break; 8969 8970 case FK_ReferenceAddrspaceMismatchTemporary: 8971 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) 8972 << DestType << Args[0]->getSourceRange(); 8973 break; 8974 8975 case FK_ReferenceInitDropsQualifiers: { 8976 QualType SourceType = OnlyArg->getType(); 8977 QualType NonRefType = DestType.getNonReferenceType(); 8978 Qualifiers DroppedQualifiers = 8979 SourceType.getQualifiers() - NonRefType.getQualifiers(); 8980 8981 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( 8982 SourceType.getQualifiers())) 8983 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 8984 << NonRefType << SourceType << 1 /*addr space*/ 8985 << Args[0]->getSourceRange(); 8986 else if (DroppedQualifiers.hasQualifiers()) 8987 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 8988 << NonRefType << SourceType << 0 /*cv quals*/ 8989 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) 8990 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); 8991 else 8992 // FIXME: Consider decomposing the type and explaining which qualifiers 8993 // were dropped where, or on which level a 'const' is missing, etc. 8994 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 8995 << NonRefType << SourceType << 2 /*incompatible quals*/ 8996 << Args[0]->getSourceRange(); 8997 break; 8998 } 8999 9000 case FK_ReferenceInitFailed: 9001 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 9002 << DestType.getNonReferenceType() 9003 << DestType.getNonReferenceType()->isIncompleteType() 9004 << OnlyArg->isLValue() 9005 << OnlyArg->getType() 9006 << Args[0]->getSourceRange(); 9007 emitBadConversionNotes(S, Entity, Args[0]); 9008 break; 9009 9010 case FK_ConversionFailed: { 9011 QualType FromType = OnlyArg->getType(); 9012 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 9013 << (int)Entity.getKind() 9014 << DestType 9015 << OnlyArg->isLValue() 9016 << FromType 9017 << Args[0]->getSourceRange(); 9018 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 9019 S.Diag(Kind.getLocation(), PDiag); 9020 emitBadConversionNotes(S, Entity, Args[0]); 9021 break; 9022 } 9023 9024 case FK_ConversionFromPropertyFailed: 9025 // No-op. This error has already been reported. 9026 break; 9027 9028 case FK_TooManyInitsForScalar: { 9029 SourceRange R; 9030 9031 auto *InitList = dyn_cast<InitListExpr>(Args[0]); 9032 if (InitList && InitList->getNumInits() >= 1) { 9033 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); 9034 } else { 9035 assert(Args.size() > 1 && "Expected multiple initializers!"); 9036 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); 9037 } 9038 9039 R.setBegin(S.getLocForEndOfToken(R.getBegin())); 9040 if (Kind.isCStyleOrFunctionalCast()) 9041 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 9042 << R; 9043 else 9044 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 9045 << /*scalar=*/2 << R; 9046 break; 9047 } 9048 9049 case FK_ParenthesizedListInitForScalar: 9050 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) 9051 << 0 << Entity.getType() << Args[0]->getSourceRange(); 9052 break; 9053 9054 case FK_ReferenceBindingToInitList: 9055 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 9056 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 9057 break; 9058 9059 case FK_InitListBadDestinationType: 9060 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 9061 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 9062 break; 9063 9064 case FK_ListConstructorOverloadFailed: 9065 case FK_ConstructorOverloadFailed: { 9066 SourceRange ArgsRange; 9067 if (Args.size()) 9068 ArgsRange = 9069 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); 9070 9071 if (Failure == FK_ListConstructorOverloadFailed) { 9072 assert(Args.size() == 1 && 9073 "List construction from other than 1 argument."); 9074 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 9075 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 9076 } 9077 9078 // FIXME: Using "DestType" for the entity we're printing is probably 9079 // bad. 9080 switch (FailedOverloadResult) { 9081 case OR_Ambiguous: 9082 FailedCandidateSet.NoteCandidates( 9083 PartialDiagnosticAt(Kind.getLocation(), 9084 S.PDiag(diag::err_ovl_ambiguous_init) 9085 << DestType << ArgsRange), 9086 S, OCD_AmbiguousCandidates, Args); 9087 break; 9088 9089 case OR_No_Viable_Function: 9090 if (Kind.getKind() == InitializationKind::IK_Default && 9091 (Entity.getKind() == InitializedEntity::EK_Base || 9092 Entity.getKind() == InitializedEntity::EK_Member) && 9093 isa<CXXConstructorDecl>(S.CurContext)) { 9094 // This is implicit default initialization of a member or 9095 // base within a constructor. If no viable function was 9096 // found, notify the user that they need to explicitly 9097 // initialize this base/member. 9098 CXXConstructorDecl *Constructor 9099 = cast<CXXConstructorDecl>(S.CurContext); 9100 const CXXRecordDecl *InheritedFrom = nullptr; 9101 if (auto Inherited = Constructor->getInheritedConstructor()) 9102 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); 9103 if (Entity.getKind() == InitializedEntity::EK_Base) { 9104 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 9105 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 9106 << S.Context.getTypeDeclType(Constructor->getParent()) 9107 << /*base=*/0 9108 << Entity.getType() 9109 << InheritedFrom; 9110 9111 RecordDecl *BaseDecl 9112 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() 9113 ->getDecl(); 9114 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 9115 << S.Context.getTagDeclType(BaseDecl); 9116 } else { 9117 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 9118 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 9119 << S.Context.getTypeDeclType(Constructor->getParent()) 9120 << /*member=*/1 9121 << Entity.getName() 9122 << InheritedFrom; 9123 S.Diag(Entity.getDecl()->getLocation(), 9124 diag::note_member_declared_at); 9125 9126 if (const RecordType *Record 9127 = Entity.getType()->getAs<RecordType>()) 9128 S.Diag(Record->getDecl()->getLocation(), 9129 diag::note_previous_decl) 9130 << S.Context.getTagDeclType(Record->getDecl()); 9131 } 9132 break; 9133 } 9134 9135 FailedCandidateSet.NoteCandidates( 9136 PartialDiagnosticAt( 9137 Kind.getLocation(), 9138 S.PDiag(diag::err_ovl_no_viable_function_in_init) 9139 << DestType << ArgsRange), 9140 S, OCD_AllCandidates, Args); 9141 break; 9142 9143 case OR_Deleted: { 9144 OverloadCandidateSet::iterator Best; 9145 OverloadingResult Ovl 9146 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9147 if (Ovl != OR_Deleted) { 9148 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 9149 << DestType << ArgsRange; 9150 llvm_unreachable("Inconsistent overload resolution?"); 9151 break; 9152 } 9153 9154 // If this is a defaulted or implicitly-declared function, then 9155 // it was implicitly deleted. Make it clear that the deletion was 9156 // implicit. 9157 if (S.isImplicitlyDeleted(Best->Function)) 9158 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) 9159 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) 9160 << DestType << ArgsRange; 9161 else 9162 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 9163 << DestType << ArgsRange; 9164 9165 S.NoteDeletedFunction(Best->Function); 9166 break; 9167 } 9168 9169 case OR_Success: 9170 llvm_unreachable("Conversion did not fail!"); 9171 } 9172 } 9173 break; 9174 9175 case FK_DefaultInitOfConst: 9176 if (Entity.getKind() == InitializedEntity::EK_Member && 9177 isa<CXXConstructorDecl>(S.CurContext)) { 9178 // This is implicit default-initialization of a const member in 9179 // a constructor. Complain that it needs to be explicitly 9180 // initialized. 9181 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 9182 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 9183 << (Constructor->getInheritedConstructor() ? 2 : 9184 Constructor->isImplicit() ? 1 : 0) 9185 << S.Context.getTypeDeclType(Constructor->getParent()) 9186 << /*const=*/1 9187 << Entity.getName(); 9188 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 9189 << Entity.getName(); 9190 } else { 9191 S.Diag(Kind.getLocation(), diag::err_default_init_const) 9192 << DestType << (bool)DestType->getAs<RecordType>(); 9193 } 9194 break; 9195 9196 case FK_Incomplete: 9197 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, 9198 diag::err_init_incomplete_type); 9199 break; 9200 9201 case FK_ListInitializationFailed: { 9202 // Run the init list checker again to emit diagnostics. 9203 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 9204 diagnoseListInit(S, Entity, InitList); 9205 break; 9206 } 9207 9208 case FK_PlaceholderType: { 9209 // FIXME: Already diagnosed! 9210 break; 9211 } 9212 9213 case FK_ExplicitConstructor: { 9214 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) 9215 << Args[0]->getSourceRange(); 9216 OverloadCandidateSet::iterator Best; 9217 OverloadingResult Ovl 9218 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9219 (void)Ovl; 9220 assert(Ovl == OR_Success && "Inconsistent overload resolution"); 9221 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 9222 S.Diag(CtorDecl->getLocation(), 9223 diag::note_explicit_ctor_deduction_guide_here) << false; 9224 break; 9225 } 9226 } 9227 9228 PrintInitLocationNote(S, Entity); 9229 return true; 9230 } 9231 9232 void InitializationSequence::dump(raw_ostream &OS) const { 9233 switch (SequenceKind) { 9234 case FailedSequence: { 9235 OS << "Failed sequence: "; 9236 switch (Failure) { 9237 case FK_TooManyInitsForReference: 9238 OS << "too many initializers for reference"; 9239 break; 9240 9241 case FK_ParenthesizedListInitForReference: 9242 OS << "parenthesized list init for reference"; 9243 break; 9244 9245 case FK_ArrayNeedsInitList: 9246 OS << "array requires initializer list"; 9247 break; 9248 9249 case FK_AddressOfUnaddressableFunction: 9250 OS << "address of unaddressable function was taken"; 9251 break; 9252 9253 case FK_ArrayNeedsInitListOrStringLiteral: 9254 OS << "array requires initializer list or string literal"; 9255 break; 9256 9257 case FK_ArrayNeedsInitListOrWideStringLiteral: 9258 OS << "array requires initializer list or wide string literal"; 9259 break; 9260 9261 case FK_NarrowStringIntoWideCharArray: 9262 OS << "narrow string into wide char array"; 9263 break; 9264 9265 case FK_WideStringIntoCharArray: 9266 OS << "wide string into char array"; 9267 break; 9268 9269 case FK_IncompatWideStringIntoWideChar: 9270 OS << "incompatible wide string into wide char array"; 9271 break; 9272 9273 case FK_PlainStringIntoUTF8Char: 9274 OS << "plain string literal into char8_t array"; 9275 break; 9276 9277 case FK_UTF8StringIntoPlainChar: 9278 OS << "u8 string literal into char array"; 9279 break; 9280 9281 case FK_ArrayTypeMismatch: 9282 OS << "array type mismatch"; 9283 break; 9284 9285 case FK_NonConstantArrayInit: 9286 OS << "non-constant array initializer"; 9287 break; 9288 9289 case FK_AddressOfOverloadFailed: 9290 OS << "address of overloaded function failed"; 9291 break; 9292 9293 case FK_ReferenceInitOverloadFailed: 9294 OS << "overload resolution for reference initialization failed"; 9295 break; 9296 9297 case FK_NonConstLValueReferenceBindingToTemporary: 9298 OS << "non-const lvalue reference bound to temporary"; 9299 break; 9300 9301 case FK_NonConstLValueReferenceBindingToBitfield: 9302 OS << "non-const lvalue reference bound to bit-field"; 9303 break; 9304 9305 case FK_NonConstLValueReferenceBindingToVectorElement: 9306 OS << "non-const lvalue reference bound to vector element"; 9307 break; 9308 9309 case FK_NonConstLValueReferenceBindingToMatrixElement: 9310 OS << "non-const lvalue reference bound to matrix element"; 9311 break; 9312 9313 case FK_NonConstLValueReferenceBindingToUnrelated: 9314 OS << "non-const lvalue reference bound to unrelated type"; 9315 break; 9316 9317 case FK_RValueReferenceBindingToLValue: 9318 OS << "rvalue reference bound to an lvalue"; 9319 break; 9320 9321 case FK_ReferenceInitDropsQualifiers: 9322 OS << "reference initialization drops qualifiers"; 9323 break; 9324 9325 case FK_ReferenceAddrspaceMismatchTemporary: 9326 OS << "reference with mismatching address space bound to temporary"; 9327 break; 9328 9329 case FK_ReferenceInitFailed: 9330 OS << "reference initialization failed"; 9331 break; 9332 9333 case FK_ConversionFailed: 9334 OS << "conversion failed"; 9335 break; 9336 9337 case FK_ConversionFromPropertyFailed: 9338 OS << "conversion from property failed"; 9339 break; 9340 9341 case FK_TooManyInitsForScalar: 9342 OS << "too many initializers for scalar"; 9343 break; 9344 9345 case FK_ParenthesizedListInitForScalar: 9346 OS << "parenthesized list init for reference"; 9347 break; 9348 9349 case FK_ReferenceBindingToInitList: 9350 OS << "referencing binding to initializer list"; 9351 break; 9352 9353 case FK_InitListBadDestinationType: 9354 OS << "initializer list for non-aggregate, non-scalar type"; 9355 break; 9356 9357 case FK_UserConversionOverloadFailed: 9358 OS << "overloading failed for user-defined conversion"; 9359 break; 9360 9361 case FK_ConstructorOverloadFailed: 9362 OS << "constructor overloading failed"; 9363 break; 9364 9365 case FK_DefaultInitOfConst: 9366 OS << "default initialization of a const variable"; 9367 break; 9368 9369 case FK_Incomplete: 9370 OS << "initialization of incomplete type"; 9371 break; 9372 9373 case FK_ListInitializationFailed: 9374 OS << "list initialization checker failure"; 9375 break; 9376 9377 case FK_VariableLengthArrayHasInitializer: 9378 OS << "variable length array has an initializer"; 9379 break; 9380 9381 case FK_PlaceholderType: 9382 OS << "initializer expression isn't contextually valid"; 9383 break; 9384 9385 case FK_ListConstructorOverloadFailed: 9386 OS << "list constructor overloading failed"; 9387 break; 9388 9389 case FK_ExplicitConstructor: 9390 OS << "list copy initialization chose explicit constructor"; 9391 break; 9392 } 9393 OS << '\n'; 9394 return; 9395 } 9396 9397 case DependentSequence: 9398 OS << "Dependent sequence\n"; 9399 return; 9400 9401 case NormalSequence: 9402 OS << "Normal sequence: "; 9403 break; 9404 } 9405 9406 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 9407 if (S != step_begin()) { 9408 OS << " -> "; 9409 } 9410 9411 switch (S->Kind) { 9412 case SK_ResolveAddressOfOverloadedFunction: 9413 OS << "resolve address of overloaded function"; 9414 break; 9415 9416 case SK_CastDerivedToBaseRValue: 9417 OS << "derived-to-base (rvalue)"; 9418 break; 9419 9420 case SK_CastDerivedToBaseXValue: 9421 OS << "derived-to-base (xvalue)"; 9422 break; 9423 9424 case SK_CastDerivedToBaseLValue: 9425 OS << "derived-to-base (lvalue)"; 9426 break; 9427 9428 case SK_BindReference: 9429 OS << "bind reference to lvalue"; 9430 break; 9431 9432 case SK_BindReferenceToTemporary: 9433 OS << "bind reference to a temporary"; 9434 break; 9435 9436 case SK_FinalCopy: 9437 OS << "final copy in class direct-initialization"; 9438 break; 9439 9440 case SK_ExtraneousCopyToTemporary: 9441 OS << "extraneous C++03 copy to temporary"; 9442 break; 9443 9444 case SK_UserConversion: 9445 OS << "user-defined conversion via " << *S->Function.Function; 9446 break; 9447 9448 case SK_QualificationConversionRValue: 9449 OS << "qualification conversion (rvalue)"; 9450 break; 9451 9452 case SK_QualificationConversionXValue: 9453 OS << "qualification conversion (xvalue)"; 9454 break; 9455 9456 case SK_QualificationConversionLValue: 9457 OS << "qualification conversion (lvalue)"; 9458 break; 9459 9460 case SK_AtomicConversion: 9461 OS << "non-atomic-to-atomic conversion"; 9462 break; 9463 9464 case SK_ConversionSequence: 9465 OS << "implicit conversion sequence ("; 9466 S->ICS->dump(); // FIXME: use OS 9467 OS << ")"; 9468 break; 9469 9470 case SK_ConversionSequenceNoNarrowing: 9471 OS << "implicit conversion sequence with narrowing prohibited ("; 9472 S->ICS->dump(); // FIXME: use OS 9473 OS << ")"; 9474 break; 9475 9476 case SK_ListInitialization: 9477 OS << "list aggregate initialization"; 9478 break; 9479 9480 case SK_UnwrapInitList: 9481 OS << "unwrap reference initializer list"; 9482 break; 9483 9484 case SK_RewrapInitList: 9485 OS << "rewrap reference initializer list"; 9486 break; 9487 9488 case SK_ConstructorInitialization: 9489 OS << "constructor initialization"; 9490 break; 9491 9492 case SK_ConstructorInitializationFromList: 9493 OS << "list initialization via constructor"; 9494 break; 9495 9496 case SK_ZeroInitialization: 9497 OS << "zero initialization"; 9498 break; 9499 9500 case SK_CAssignment: 9501 OS << "C assignment"; 9502 break; 9503 9504 case SK_StringInit: 9505 OS << "string initialization"; 9506 break; 9507 9508 case SK_ObjCObjectConversion: 9509 OS << "Objective-C object conversion"; 9510 break; 9511 9512 case SK_ArrayLoopIndex: 9513 OS << "indexing for array initialization loop"; 9514 break; 9515 9516 case SK_ArrayLoopInit: 9517 OS << "array initialization loop"; 9518 break; 9519 9520 case SK_ArrayInit: 9521 OS << "array initialization"; 9522 break; 9523 9524 case SK_GNUArrayInit: 9525 OS << "array initialization (GNU extension)"; 9526 break; 9527 9528 case SK_ParenthesizedArrayInit: 9529 OS << "parenthesized array initialization"; 9530 break; 9531 9532 case SK_PassByIndirectCopyRestore: 9533 OS << "pass by indirect copy and restore"; 9534 break; 9535 9536 case SK_PassByIndirectRestore: 9537 OS << "pass by indirect restore"; 9538 break; 9539 9540 case SK_ProduceObjCObject: 9541 OS << "Objective-C object retension"; 9542 break; 9543 9544 case SK_StdInitializerList: 9545 OS << "std::initializer_list from initializer list"; 9546 break; 9547 9548 case SK_StdInitializerListConstructorCall: 9549 OS << "list initialization from std::initializer_list"; 9550 break; 9551 9552 case SK_OCLSamplerInit: 9553 OS << "OpenCL sampler_t from integer constant"; 9554 break; 9555 9556 case SK_OCLZeroOpaqueType: 9557 OS << "OpenCL opaque type from zero"; 9558 break; 9559 } 9560 9561 OS << " [" << S->Type.getAsString() << ']'; 9562 } 9563 9564 OS << '\n'; 9565 } 9566 9567 void InitializationSequence::dump() const { 9568 dump(llvm::errs()); 9569 } 9570 9571 static bool NarrowingErrs(const LangOptions &L) { 9572 return L.CPlusPlus11 && 9573 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); 9574 } 9575 9576 static void DiagnoseNarrowingInInitList(Sema &S, 9577 const ImplicitConversionSequence &ICS, 9578 QualType PreNarrowingType, 9579 QualType EntityType, 9580 const Expr *PostInit) { 9581 const StandardConversionSequence *SCS = nullptr; 9582 switch (ICS.getKind()) { 9583 case ImplicitConversionSequence::StandardConversion: 9584 SCS = &ICS.Standard; 9585 break; 9586 case ImplicitConversionSequence::UserDefinedConversion: 9587 SCS = &ICS.UserDefined.After; 9588 break; 9589 case ImplicitConversionSequence::AmbiguousConversion: 9590 case ImplicitConversionSequence::EllipsisConversion: 9591 case ImplicitConversionSequence::BadConversion: 9592 return; 9593 } 9594 9595 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. 9596 APValue ConstantValue; 9597 QualType ConstantType; 9598 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, 9599 ConstantType)) { 9600 case NK_Not_Narrowing: 9601 case NK_Dependent_Narrowing: 9602 // No narrowing occurred. 9603 return; 9604 9605 case NK_Type_Narrowing: 9606 // This was a floating-to-integer conversion, which is always considered a 9607 // narrowing conversion even if the value is a constant and can be 9608 // represented exactly as an integer. 9609 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) 9610 ? diag::ext_init_list_type_narrowing 9611 : diag::warn_init_list_type_narrowing) 9612 << PostInit->getSourceRange() 9613 << PreNarrowingType.getLocalUnqualifiedType() 9614 << EntityType.getLocalUnqualifiedType(); 9615 break; 9616 9617 case NK_Constant_Narrowing: 9618 // A constant value was narrowed. 9619 S.Diag(PostInit->getBeginLoc(), 9620 NarrowingErrs(S.getLangOpts()) 9621 ? diag::ext_init_list_constant_narrowing 9622 : diag::warn_init_list_constant_narrowing) 9623 << PostInit->getSourceRange() 9624 << ConstantValue.getAsString(S.getASTContext(), ConstantType) 9625 << EntityType.getLocalUnqualifiedType(); 9626 break; 9627 9628 case NK_Variable_Narrowing: 9629 // A variable's value may have been narrowed. 9630 S.Diag(PostInit->getBeginLoc(), 9631 NarrowingErrs(S.getLangOpts()) 9632 ? diag::ext_init_list_variable_narrowing 9633 : diag::warn_init_list_variable_narrowing) 9634 << PostInit->getSourceRange() 9635 << PreNarrowingType.getLocalUnqualifiedType() 9636 << EntityType.getLocalUnqualifiedType(); 9637 break; 9638 } 9639 9640 SmallString<128> StaticCast; 9641 llvm::raw_svector_ostream OS(StaticCast); 9642 OS << "static_cast<"; 9643 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 9644 // It's important to use the typedef's name if there is one so that the 9645 // fixit doesn't break code using types like int64_t. 9646 // 9647 // FIXME: This will break if the typedef requires qualification. But 9648 // getQualifiedNameAsString() includes non-machine-parsable components. 9649 OS << *TT->getDecl(); 9650 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 9651 OS << BT->getName(S.getLangOpts()); 9652 else { 9653 // Oops, we didn't find the actual type of the variable. Don't emit a fixit 9654 // with a broken cast. 9655 return; 9656 } 9657 OS << ">("; 9658 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) 9659 << PostInit->getSourceRange() 9660 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) 9661 << FixItHint::CreateInsertion( 9662 S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); 9663 } 9664 9665 //===----------------------------------------------------------------------===// 9666 // Initialization helper functions 9667 //===----------------------------------------------------------------------===// 9668 bool 9669 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 9670 ExprResult Init) { 9671 if (Init.isInvalid()) 9672 return false; 9673 9674 Expr *InitE = Init.get(); 9675 assert(InitE && "No initialization expression"); 9676 9677 InitializationKind Kind = 9678 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); 9679 InitializationSequence Seq(*this, Entity, Kind, InitE); 9680 return !Seq.Failed(); 9681 } 9682 9683 ExprResult 9684 Sema::PerformCopyInitialization(const InitializedEntity &Entity, 9685 SourceLocation EqualLoc, 9686 ExprResult Init, 9687 bool TopLevelOfInitList, 9688 bool AllowExplicit) { 9689 if (Init.isInvalid()) 9690 return ExprError(); 9691 9692 Expr *InitE = Init.get(); 9693 assert(InitE && "No initialization expression?"); 9694 9695 if (EqualLoc.isInvalid()) 9696 EqualLoc = InitE->getBeginLoc(); 9697 9698 InitializationKind Kind = InitializationKind::CreateCopy( 9699 InitE->getBeginLoc(), EqualLoc, AllowExplicit); 9700 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); 9701 9702 // Prevent infinite recursion when performing parameter copy-initialization. 9703 const bool ShouldTrackCopy = 9704 Entity.isParameterKind() && Seq.isConstructorInitialization(); 9705 if (ShouldTrackCopy) { 9706 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != 9707 CurrentParameterCopyTypes.end()) { 9708 Seq.SetOverloadFailure( 9709 InitializationSequence::FK_ConstructorOverloadFailed, 9710 OR_No_Viable_Function); 9711 9712 // Try to give a meaningful diagnostic note for the problematic 9713 // constructor. 9714 const auto LastStep = Seq.step_end() - 1; 9715 assert(LastStep->Kind == 9716 InitializationSequence::SK_ConstructorInitialization); 9717 const FunctionDecl *Function = LastStep->Function.Function; 9718 auto Candidate = 9719 llvm::find_if(Seq.getFailedCandidateSet(), 9720 [Function](const OverloadCandidate &Candidate) -> bool { 9721 return Candidate.Viable && 9722 Candidate.Function == Function && 9723 Candidate.Conversions.size() > 0; 9724 }); 9725 if (Candidate != Seq.getFailedCandidateSet().end() && 9726 Function->getNumParams() > 0) { 9727 Candidate->Viable = false; 9728 Candidate->FailureKind = ovl_fail_bad_conversion; 9729 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, 9730 InitE, 9731 Function->getParamDecl(0)->getType()); 9732 } 9733 } 9734 CurrentParameterCopyTypes.push_back(Entity.getType()); 9735 } 9736 9737 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); 9738 9739 if (ShouldTrackCopy) 9740 CurrentParameterCopyTypes.pop_back(); 9741 9742 return Result; 9743 } 9744 9745 /// Determine whether RD is, or is derived from, a specialization of CTD. 9746 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, 9747 ClassTemplateDecl *CTD) { 9748 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { 9749 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); 9750 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); 9751 }; 9752 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); 9753 } 9754 9755 QualType Sema::DeduceTemplateSpecializationFromInitializer( 9756 TypeSourceInfo *TSInfo, const InitializedEntity &Entity, 9757 const InitializationKind &Kind, MultiExprArg Inits) { 9758 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( 9759 TSInfo->getType()->getContainedDeducedType()); 9760 assert(DeducedTST && "not a deduced template specialization type"); 9761 9762 auto TemplateName = DeducedTST->getTemplateName(); 9763 if (TemplateName.isDependent()) 9764 return SubstAutoType(TSInfo->getType(), Context.DependentTy); 9765 9766 // We can only perform deduction for class templates. 9767 auto *Template = 9768 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); 9769 if (!Template) { 9770 Diag(Kind.getLocation(), 9771 diag::err_deduced_non_class_template_specialization_type) 9772 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; 9773 if (auto *TD = TemplateName.getAsTemplateDecl()) 9774 Diag(TD->getLocation(), diag::note_template_decl_here); 9775 return QualType(); 9776 } 9777 9778 // Can't deduce from dependent arguments. 9779 if (Expr::hasAnyTypeDependentArguments(Inits)) { 9780 Diag(TSInfo->getTypeLoc().getBeginLoc(), 9781 diag::warn_cxx14_compat_class_template_argument_deduction) 9782 << TSInfo->getTypeLoc().getSourceRange() << 0; 9783 return SubstAutoType(TSInfo->getType(), Context.DependentTy); 9784 } 9785 9786 // FIXME: Perform "exact type" matching first, per CWG discussion? 9787 // Or implement this via an implied 'T(T) -> T' deduction guide? 9788 9789 // FIXME: Do we need/want a std::initializer_list<T> special case? 9790 9791 // Look up deduction guides, including those synthesized from constructors. 9792 // 9793 // C++1z [over.match.class.deduct]p1: 9794 // A set of functions and function templates is formed comprising: 9795 // - For each constructor of the class template designated by the 9796 // template-name, a function template [...] 9797 // - For each deduction-guide, a function or function template [...] 9798 DeclarationNameInfo NameInfo( 9799 Context.DeclarationNames.getCXXDeductionGuideName(Template), 9800 TSInfo->getTypeLoc().getEndLoc()); 9801 LookupResult Guides(*this, NameInfo, LookupOrdinaryName); 9802 LookupQualifiedName(Guides, Template->getDeclContext()); 9803 9804 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't 9805 // clear on this, but they're not found by name so access does not apply. 9806 Guides.suppressDiagnostics(); 9807 9808 // Figure out if this is list-initialization. 9809 InitListExpr *ListInit = 9810 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) 9811 ? dyn_cast<InitListExpr>(Inits[0]) 9812 : nullptr; 9813 9814 // C++1z [over.match.class.deduct]p1: 9815 // Initialization and overload resolution are performed as described in 9816 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] 9817 // (as appropriate for the type of initialization performed) for an object 9818 // of a hypothetical class type, where the selected functions and function 9819 // templates are considered to be the constructors of that class type 9820 // 9821 // Since we know we're initializing a class type of a type unrelated to that 9822 // of the initializer, this reduces to something fairly reasonable. 9823 OverloadCandidateSet Candidates(Kind.getLocation(), 9824 OverloadCandidateSet::CSK_Normal); 9825 OverloadCandidateSet::iterator Best; 9826 9827 bool HasAnyDeductionGuide = false; 9828 bool AllowExplicit = !Kind.isCopyInit() || ListInit; 9829 9830 auto tryToResolveOverload = 9831 [&](bool OnlyListConstructors) -> OverloadingResult { 9832 Candidates.clear(OverloadCandidateSet::CSK_Normal); 9833 HasAnyDeductionGuide = false; 9834 9835 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { 9836 NamedDecl *D = (*I)->getUnderlyingDecl(); 9837 if (D->isInvalidDecl()) 9838 continue; 9839 9840 auto *TD = dyn_cast<FunctionTemplateDecl>(D); 9841 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( 9842 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); 9843 if (!GD) 9844 continue; 9845 9846 if (!GD->isImplicit()) 9847 HasAnyDeductionGuide = true; 9848 9849 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) 9850 // For copy-initialization, the candidate functions are all the 9851 // converting constructors (12.3.1) of that class. 9852 // C++ [over.match.copy]p1: (non-list copy-initialization from class) 9853 // The converting constructors of T are candidate functions. 9854 if (!AllowExplicit) { 9855 // Overload resolution checks whether the deduction guide is declared 9856 // explicit for us. 9857 9858 // When looking for a converting constructor, deduction guides that 9859 // could never be called with one argument are not interesting to 9860 // check or note. 9861 if (GD->getMinRequiredArguments() > 1 || 9862 (GD->getNumParams() == 0 && !GD->isVariadic())) 9863 continue; 9864 } 9865 9866 // C++ [over.match.list]p1.1: (first phase list initialization) 9867 // Initially, the candidate functions are the initializer-list 9868 // constructors of the class T 9869 if (OnlyListConstructors && !isInitListConstructor(GD)) 9870 continue; 9871 9872 // C++ [over.match.list]p1.2: (second phase list initialization) 9873 // the candidate functions are all the constructors of the class T 9874 // C++ [over.match.ctor]p1: (all other cases) 9875 // the candidate functions are all the constructors of the class of 9876 // the object being initialized 9877 9878 // C++ [over.best.ics]p4: 9879 // When [...] the constructor [...] is a candidate by 9880 // - [over.match.copy] (in all cases) 9881 // FIXME: The "second phase of [over.match.list] case can also 9882 // theoretically happen here, but it's not clear whether we can 9883 // ever have a parameter of the right type. 9884 bool SuppressUserConversions = Kind.isCopyInit(); 9885 9886 if (TD) 9887 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, 9888 Inits, Candidates, SuppressUserConversions, 9889 /*PartialOverloading*/ false, 9890 AllowExplicit); 9891 else 9892 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, 9893 SuppressUserConversions, 9894 /*PartialOverloading*/ false, AllowExplicit); 9895 } 9896 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); 9897 }; 9898 9899 OverloadingResult Result = OR_No_Viable_Function; 9900 9901 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first 9902 // try initializer-list constructors. 9903 if (ListInit) { 9904 bool TryListConstructors = true; 9905 9906 // Try list constructors unless the list is empty and the class has one or 9907 // more default constructors, in which case those constructors win. 9908 if (!ListInit->getNumInits()) { 9909 for (NamedDecl *D : Guides) { 9910 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); 9911 if (FD && FD->getMinRequiredArguments() == 0) { 9912 TryListConstructors = false; 9913 break; 9914 } 9915 } 9916 } else if (ListInit->getNumInits() == 1) { 9917 // C++ [over.match.class.deduct]: 9918 // As an exception, the first phase in [over.match.list] (considering 9919 // initializer-list constructors) is omitted if the initializer list 9920 // consists of a single expression of type cv U, where U is a 9921 // specialization of C or a class derived from a specialization of C. 9922 Expr *E = ListInit->getInit(0); 9923 auto *RD = E->getType()->getAsCXXRecordDecl(); 9924 if (!isa<InitListExpr>(E) && RD && 9925 isCompleteType(Kind.getLocation(), E->getType()) && 9926 isOrIsDerivedFromSpecializationOf(RD, Template)) 9927 TryListConstructors = false; 9928 } 9929 9930 if (TryListConstructors) 9931 Result = tryToResolveOverload(/*OnlyListConstructor*/true); 9932 // Then unwrap the initializer list and try again considering all 9933 // constructors. 9934 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); 9935 } 9936 9937 // If list-initialization fails, or if we're doing any other kind of 9938 // initialization, we (eventually) consider constructors. 9939 if (Result == OR_No_Viable_Function) 9940 Result = tryToResolveOverload(/*OnlyListConstructor*/false); 9941 9942 switch (Result) { 9943 case OR_Ambiguous: 9944 // FIXME: For list-initialization candidates, it'd usually be better to 9945 // list why they were not viable when given the initializer list itself as 9946 // an argument. 9947 Candidates.NoteCandidates( 9948 PartialDiagnosticAt( 9949 Kind.getLocation(), 9950 PDiag(diag::err_deduced_class_template_ctor_ambiguous) 9951 << TemplateName), 9952 *this, OCD_AmbiguousCandidates, Inits); 9953 return QualType(); 9954 9955 case OR_No_Viable_Function: { 9956 CXXRecordDecl *Primary = 9957 cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); 9958 bool Complete = 9959 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); 9960 Candidates.NoteCandidates( 9961 PartialDiagnosticAt( 9962 Kind.getLocation(), 9963 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable 9964 : diag::err_deduced_class_template_incomplete) 9965 << TemplateName << !Guides.empty()), 9966 *this, OCD_AllCandidates, Inits); 9967 return QualType(); 9968 } 9969 9970 case OR_Deleted: { 9971 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) 9972 << TemplateName; 9973 NoteDeletedFunction(Best->Function); 9974 return QualType(); 9975 } 9976 9977 case OR_Success: 9978 // C++ [over.match.list]p1: 9979 // In copy-list-initialization, if an explicit constructor is chosen, the 9980 // initialization is ill-formed. 9981 if (Kind.isCopyInit() && ListInit && 9982 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { 9983 bool IsDeductionGuide = !Best->Function->isImplicit(); 9984 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) 9985 << TemplateName << IsDeductionGuide; 9986 Diag(Best->Function->getLocation(), 9987 diag::note_explicit_ctor_deduction_guide_here) 9988 << IsDeductionGuide; 9989 return QualType(); 9990 } 9991 9992 // Make sure we didn't select an unusable deduction guide, and mark it 9993 // as referenced. 9994 DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); 9995 MarkFunctionReferenced(Kind.getLocation(), Best->Function); 9996 break; 9997 } 9998 9999 // C++ [dcl.type.class.deduct]p1: 10000 // The placeholder is replaced by the return type of the function selected 10001 // by overload resolution for class template deduction. 10002 QualType DeducedType = 10003 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); 10004 Diag(TSInfo->getTypeLoc().getBeginLoc(), 10005 diag::warn_cxx14_compat_class_template_argument_deduction) 10006 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; 10007 10008 // Warn if CTAD was used on a type that does not have any user-defined 10009 // deduction guides. 10010 if (!HasAnyDeductionGuide) { 10011 Diag(TSInfo->getTypeLoc().getBeginLoc(), 10012 diag::warn_ctad_maybe_unsupported) 10013 << TemplateName; 10014 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); 10015 } 10016 10017 return DeducedType; 10018 } 10019