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