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