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