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