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 = 2894 ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2895 nullptr, VK_RValue, FPOptionsOverride()); 2896 StructuredList->updateInit(Context, i, Init); 2897 } 2898 } else { 2899 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); 2900 std::string Str; 2901 Context.getObjCEncodingForType(E->getEncodedType(), Str); 2902 2903 // Get the length of the string. 2904 uint64_t StrLen = Str.size(); 2905 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2906 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2907 StructuredList->resizeInits(Context, StrLen); 2908 2909 // Build a literal for each character in the string, and put them into 2910 // the init list. 2911 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2912 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); 2913 Expr *Init = new (Context) IntegerLiteral( 2914 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2915 if (CharTy != PromotedCharTy) 2916 Init = 2917 ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2918 nullptr, VK_RValue, FPOptionsOverride()); 2919 StructuredList->updateInit(Context, i, Init); 2920 } 2921 } 2922 } 2923 2924 // Make sure that our non-designated initializer list has space 2925 // for a subobject corresponding to this array element. 2926 if (StructuredList && 2927 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 2928 StructuredList->resizeInits(SemaRef.Context, 2929 DesignatedEndIndex.getZExtValue() + 1); 2930 2931 // Repeatedly perform subobject initializations in the range 2932 // [DesignatedStartIndex, DesignatedEndIndex]. 2933 2934 // Move to the next designator 2935 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 2936 unsigned OldIndex = Index; 2937 2938 InitializedEntity ElementEntity = 2939 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 2940 2941 while (DesignatedStartIndex <= DesignatedEndIndex) { 2942 // Recurse to check later designated subobjects. 2943 QualType ElementType = AT->getElementType(); 2944 Index = OldIndex; 2945 2946 ElementEntity.setElementIndex(ElementIndex); 2947 if (CheckDesignatedInitializer( 2948 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, 2949 nullptr, Index, StructuredList, ElementIndex, 2950 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), 2951 false)) 2952 return true; 2953 2954 // Move to the next index in the array that we'll be initializing. 2955 ++DesignatedStartIndex; 2956 ElementIndex = DesignatedStartIndex.getZExtValue(); 2957 } 2958 2959 // If this the first designator, our caller will continue checking 2960 // the rest of this array subobject. 2961 if (IsFirstDesignator) { 2962 if (NextElementIndex) 2963 *NextElementIndex = DesignatedStartIndex; 2964 StructuredIndex = ElementIndex; 2965 return false; 2966 } 2967 2968 if (!FinishSubobjectInit) 2969 return false; 2970 2971 // Check the remaining elements within this array subobject. 2972 bool prevHadError = hadError; 2973 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 2974 /*SubobjectIsDesignatorContext=*/false, Index, 2975 StructuredList, ElementIndex); 2976 return hadError && !prevHadError; 2977 } 2978 2979 // Get the structured initializer list for a subobject of type 2980 // @p CurrentObjectType. 2981 InitListExpr * 2982 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 2983 QualType CurrentObjectType, 2984 InitListExpr *StructuredList, 2985 unsigned StructuredIndex, 2986 SourceRange InitRange, 2987 bool IsFullyOverwritten) { 2988 if (!StructuredList) 2989 return nullptr; 2990 2991 Expr *ExistingInit = nullptr; 2992 if (StructuredIndex < StructuredList->getNumInits()) 2993 ExistingInit = StructuredList->getInit(StructuredIndex); 2994 2995 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 2996 // There might have already been initializers for subobjects of the current 2997 // object, but a subsequent initializer list will overwrite the entirety 2998 // of the current object. (See DR 253 and C99 6.7.8p21). e.g., 2999 // 3000 // struct P { char x[6]; }; 3001 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; 3002 // 3003 // The first designated initializer is ignored, and l.x is just "f". 3004 if (!IsFullyOverwritten) 3005 return Result; 3006 3007 if (ExistingInit) { 3008 // We are creating an initializer list that initializes the 3009 // subobjects of the current object, but there was already an 3010 // initialization that completely initialized the current 3011 // subobject: 3012 // 3013 // struct X { int a, b; }; 3014 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; 3015 // 3016 // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 3017 // designated initializer overwrites the [0].b initializer 3018 // from the prior initialization. 3019 // 3020 // When the existing initializer is an expression rather than an 3021 // initializer list, we cannot decompose and update it in this way. 3022 // For example: 3023 // 3024 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 3025 // 3026 // This case is handled by CheckDesignatedInitializer. 3027 diagnoseInitOverride(ExistingInit, InitRange); 3028 } 3029 3030 unsigned ExpectedNumInits = 0; 3031 if (Index < IList->getNumInits()) { 3032 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) 3033 ExpectedNumInits = Init->getNumInits(); 3034 else 3035 ExpectedNumInits = IList->getNumInits() - Index; 3036 } 3037 3038 InitListExpr *Result = 3039 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); 3040 3041 // Link this new initializer list into the structured initializer 3042 // lists. 3043 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 3044 return Result; 3045 } 3046 3047 InitListExpr * 3048 InitListChecker::createInitListExpr(QualType CurrentObjectType, 3049 SourceRange InitRange, 3050 unsigned ExpectedNumInits) { 3051 InitListExpr *Result 3052 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 3053 InitRange.getBegin(), None, 3054 InitRange.getEnd()); 3055 3056 QualType ResultType = CurrentObjectType; 3057 if (!ResultType->isArrayType()) 3058 ResultType = ResultType.getNonLValueExprType(SemaRef.Context); 3059 Result->setType(ResultType); 3060 3061 // Pre-allocate storage for the structured initializer list. 3062 unsigned NumElements = 0; 3063 3064 if (const ArrayType *AType 3065 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 3066 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 3067 NumElements = CAType->getSize().getZExtValue(); 3068 // Simple heuristic so that we don't allocate a very large 3069 // initializer with many empty entries at the end. 3070 if (NumElements > ExpectedNumInits) 3071 NumElements = 0; 3072 } 3073 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { 3074 NumElements = VType->getNumElements(); 3075 } else if (CurrentObjectType->isRecordType()) { 3076 NumElements = numStructUnionElements(CurrentObjectType); 3077 } 3078 3079 Result->reserveInits(SemaRef.Context, NumElements); 3080 3081 return Result; 3082 } 3083 3084 /// Update the initializer at index @p StructuredIndex within the 3085 /// structured initializer list to the value @p expr. 3086 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 3087 unsigned &StructuredIndex, 3088 Expr *expr) { 3089 // No structured initializer list to update 3090 if (!StructuredList) 3091 return; 3092 3093 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 3094 StructuredIndex, expr)) { 3095 // This initializer overwrites a previous initializer. 3096 // No need to diagnose when `expr` is nullptr because a more relevant 3097 // diagnostic has already been issued and this diagnostic is potentially 3098 // noise. 3099 if (expr) 3100 diagnoseInitOverride(PrevInit, expr->getSourceRange()); 3101 } 3102 3103 ++StructuredIndex; 3104 } 3105 3106 /// Determine whether we can perform aggregate initialization for the purposes 3107 /// of overload resolution. 3108 bool Sema::CanPerformAggregateInitializationForOverloadResolution( 3109 const InitializedEntity &Entity, InitListExpr *From) { 3110 QualType Type = Entity.getType(); 3111 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, 3112 /*TreatUnavailableAsInvalid=*/false, 3113 /*InOverloadResolution=*/true); 3114 return !Check.HadError(); 3115 } 3116 3117 /// Check that the given Index expression is a valid array designator 3118 /// value. This is essentially just a wrapper around 3119 /// VerifyIntegerConstantExpression that also checks for negative values 3120 /// and produces a reasonable diagnostic if there is a 3121 /// failure. Returns the index expression, possibly with an implicit cast 3122 /// added, on success. If everything went okay, Value will receive the 3123 /// value of the constant expression. 3124 static ExprResult 3125 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 3126 SourceLocation Loc = Index->getBeginLoc(); 3127 3128 // Make sure this is an integer constant expression. 3129 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value); 3130 if (Result.isInvalid()) 3131 return Result; 3132 3133 if (Value.isSigned() && Value.isNegative()) 3134 return S.Diag(Loc, diag::err_array_designator_negative) 3135 << Value.toString(10) << Index->getSourceRange(); 3136 3137 Value.setIsUnsigned(true); 3138 return Result; 3139 } 3140 3141 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 3142 SourceLocation EqualOrColonLoc, 3143 bool GNUSyntax, 3144 ExprResult Init) { 3145 typedef DesignatedInitExpr::Designator ASTDesignator; 3146 3147 bool Invalid = false; 3148 SmallVector<ASTDesignator, 32> Designators; 3149 SmallVector<Expr *, 32> InitExpressions; 3150 3151 // Build designators and check array designator expressions. 3152 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 3153 const Designator &D = Desig.getDesignator(Idx); 3154 switch (D.getKind()) { 3155 case Designator::FieldDesignator: 3156 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 3157 D.getFieldLoc())); 3158 break; 3159 3160 case Designator::ArrayDesignator: { 3161 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 3162 llvm::APSInt IndexValue; 3163 if (!Index->isTypeDependent() && !Index->isValueDependent()) 3164 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); 3165 if (!Index) 3166 Invalid = true; 3167 else { 3168 Designators.push_back(ASTDesignator(InitExpressions.size(), 3169 D.getLBracketLoc(), 3170 D.getRBracketLoc())); 3171 InitExpressions.push_back(Index); 3172 } 3173 break; 3174 } 3175 3176 case Designator::ArrayRangeDesignator: { 3177 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 3178 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 3179 llvm::APSInt StartValue; 3180 llvm::APSInt EndValue; 3181 bool StartDependent = StartIndex->isTypeDependent() || 3182 StartIndex->isValueDependent(); 3183 bool EndDependent = EndIndex->isTypeDependent() || 3184 EndIndex->isValueDependent(); 3185 if (!StartDependent) 3186 StartIndex = 3187 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); 3188 if (!EndDependent) 3189 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); 3190 3191 if (!StartIndex || !EndIndex) 3192 Invalid = true; 3193 else { 3194 // Make sure we're comparing values with the same bit width. 3195 if (StartDependent || EndDependent) { 3196 // Nothing to compute. 3197 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 3198 EndValue = EndValue.extend(StartValue.getBitWidth()); 3199 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 3200 StartValue = StartValue.extend(EndValue.getBitWidth()); 3201 3202 if (!StartDependent && !EndDependent && EndValue < StartValue) { 3203 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 3204 << StartValue.toString(10) << EndValue.toString(10) 3205 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 3206 Invalid = true; 3207 } else { 3208 Designators.push_back(ASTDesignator(InitExpressions.size(), 3209 D.getLBracketLoc(), 3210 D.getEllipsisLoc(), 3211 D.getRBracketLoc())); 3212 InitExpressions.push_back(StartIndex); 3213 InitExpressions.push_back(EndIndex); 3214 } 3215 } 3216 break; 3217 } 3218 } 3219 } 3220 3221 if (Invalid || Init.isInvalid()) 3222 return ExprError(); 3223 3224 // Clear out the expressions within the designation. 3225 Desig.ClearExprs(*this); 3226 3227 return DesignatedInitExpr::Create(Context, Designators, InitExpressions, 3228 EqualOrColonLoc, GNUSyntax, 3229 Init.getAs<Expr>()); 3230 } 3231 3232 //===----------------------------------------------------------------------===// 3233 // Initialization entity 3234 //===----------------------------------------------------------------------===// 3235 3236 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 3237 const InitializedEntity &Parent) 3238 : Parent(&Parent), Index(Index) 3239 { 3240 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 3241 Kind = EK_ArrayElement; 3242 Type = AT->getElementType(); 3243 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 3244 Kind = EK_VectorElement; 3245 Type = VT->getElementType(); 3246 } else { 3247 const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 3248 assert(CT && "Unexpected type"); 3249 Kind = EK_ComplexElement; 3250 Type = CT->getElementType(); 3251 } 3252 } 3253 3254 InitializedEntity 3255 InitializedEntity::InitializeBase(ASTContext &Context, 3256 const CXXBaseSpecifier *Base, 3257 bool IsInheritedVirtualBase, 3258 const InitializedEntity *Parent) { 3259 InitializedEntity Result; 3260 Result.Kind = EK_Base; 3261 Result.Parent = Parent; 3262 Result.Base = reinterpret_cast<uintptr_t>(Base); 3263 if (IsInheritedVirtualBase) 3264 Result.Base |= 0x01; 3265 3266 Result.Type = Base->getType(); 3267 return Result; 3268 } 3269 3270 DeclarationName InitializedEntity::getName() const { 3271 switch (getKind()) { 3272 case EK_Parameter: 3273 case EK_Parameter_CF_Audited: { 3274 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 3275 return (D ? D->getDeclName() : DeclarationName()); 3276 } 3277 3278 case EK_Variable: 3279 case EK_Member: 3280 case EK_Binding: 3281 return Variable.VariableOrMember->getDeclName(); 3282 3283 case EK_LambdaCapture: 3284 return DeclarationName(Capture.VarID); 3285 3286 case EK_Result: 3287 case EK_StmtExprResult: 3288 case EK_Exception: 3289 case EK_New: 3290 case EK_Temporary: 3291 case EK_Base: 3292 case EK_Delegating: 3293 case EK_ArrayElement: 3294 case EK_VectorElement: 3295 case EK_ComplexElement: 3296 case EK_BlockElement: 3297 case EK_LambdaToBlockConversionBlockElement: 3298 case EK_CompoundLiteralInit: 3299 case EK_RelatedResult: 3300 return DeclarationName(); 3301 } 3302 3303 llvm_unreachable("Invalid EntityKind!"); 3304 } 3305 3306 ValueDecl *InitializedEntity::getDecl() const { 3307 switch (getKind()) { 3308 case EK_Variable: 3309 case EK_Member: 3310 case EK_Binding: 3311 return Variable.VariableOrMember; 3312 3313 case EK_Parameter: 3314 case EK_Parameter_CF_Audited: 3315 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 3316 3317 case EK_Result: 3318 case EK_StmtExprResult: 3319 case EK_Exception: 3320 case EK_New: 3321 case EK_Temporary: 3322 case EK_Base: 3323 case EK_Delegating: 3324 case EK_ArrayElement: 3325 case EK_VectorElement: 3326 case EK_ComplexElement: 3327 case EK_BlockElement: 3328 case EK_LambdaToBlockConversionBlockElement: 3329 case EK_LambdaCapture: 3330 case EK_CompoundLiteralInit: 3331 case EK_RelatedResult: 3332 return nullptr; 3333 } 3334 3335 llvm_unreachable("Invalid EntityKind!"); 3336 } 3337 3338 bool InitializedEntity::allowsNRVO() const { 3339 switch (getKind()) { 3340 case EK_Result: 3341 case EK_Exception: 3342 return LocAndNRVO.NRVO; 3343 3344 case EK_StmtExprResult: 3345 case EK_Variable: 3346 case EK_Parameter: 3347 case EK_Parameter_CF_Audited: 3348 case EK_Member: 3349 case EK_Binding: 3350 case EK_New: 3351 case EK_Temporary: 3352 case EK_CompoundLiteralInit: 3353 case EK_Base: 3354 case EK_Delegating: 3355 case EK_ArrayElement: 3356 case EK_VectorElement: 3357 case EK_ComplexElement: 3358 case EK_BlockElement: 3359 case EK_LambdaToBlockConversionBlockElement: 3360 case EK_LambdaCapture: 3361 case EK_RelatedResult: 3362 break; 3363 } 3364 3365 return false; 3366 } 3367 3368 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { 3369 assert(getParent() != this); 3370 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; 3371 for (unsigned I = 0; I != Depth; ++I) 3372 OS << "`-"; 3373 3374 switch (getKind()) { 3375 case EK_Variable: OS << "Variable"; break; 3376 case EK_Parameter: OS << "Parameter"; break; 3377 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; 3378 break; 3379 case EK_Result: OS << "Result"; break; 3380 case EK_StmtExprResult: OS << "StmtExprResult"; break; 3381 case EK_Exception: OS << "Exception"; break; 3382 case EK_Member: OS << "Member"; break; 3383 case EK_Binding: OS << "Binding"; break; 3384 case EK_New: OS << "New"; break; 3385 case EK_Temporary: OS << "Temporary"; break; 3386 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; 3387 case EK_RelatedResult: OS << "RelatedResult"; break; 3388 case EK_Base: OS << "Base"; break; 3389 case EK_Delegating: OS << "Delegating"; break; 3390 case EK_ArrayElement: OS << "ArrayElement " << Index; break; 3391 case EK_VectorElement: OS << "VectorElement " << Index; break; 3392 case EK_ComplexElement: OS << "ComplexElement " << Index; break; 3393 case EK_BlockElement: OS << "Block"; break; 3394 case EK_LambdaToBlockConversionBlockElement: 3395 OS << "Block (lambda)"; 3396 break; 3397 case EK_LambdaCapture: 3398 OS << "LambdaCapture "; 3399 OS << DeclarationName(Capture.VarID); 3400 break; 3401 } 3402 3403 if (auto *D = getDecl()) { 3404 OS << " "; 3405 D->printQualifiedName(OS); 3406 } 3407 3408 OS << " '" << getType().getAsString() << "'\n"; 3409 3410 return Depth + 1; 3411 } 3412 3413 LLVM_DUMP_METHOD void InitializedEntity::dump() const { 3414 dumpImpl(llvm::errs()); 3415 } 3416 3417 //===----------------------------------------------------------------------===// 3418 // Initialization sequence 3419 //===----------------------------------------------------------------------===// 3420 3421 void InitializationSequence::Step::Destroy() { 3422 switch (Kind) { 3423 case SK_ResolveAddressOfOverloadedFunction: 3424 case SK_CastDerivedToBaseRValue: 3425 case SK_CastDerivedToBaseXValue: 3426 case SK_CastDerivedToBaseLValue: 3427 case SK_BindReference: 3428 case SK_BindReferenceToTemporary: 3429 case SK_FinalCopy: 3430 case SK_ExtraneousCopyToTemporary: 3431 case SK_UserConversion: 3432 case SK_QualificationConversionRValue: 3433 case SK_QualificationConversionXValue: 3434 case SK_QualificationConversionLValue: 3435 case SK_AtomicConversion: 3436 case SK_ListInitialization: 3437 case SK_UnwrapInitList: 3438 case SK_RewrapInitList: 3439 case SK_ConstructorInitialization: 3440 case SK_ConstructorInitializationFromList: 3441 case SK_ZeroInitialization: 3442 case SK_CAssignment: 3443 case SK_StringInit: 3444 case SK_ObjCObjectConversion: 3445 case SK_ArrayLoopIndex: 3446 case SK_ArrayLoopInit: 3447 case SK_ArrayInit: 3448 case SK_GNUArrayInit: 3449 case SK_ParenthesizedArrayInit: 3450 case SK_PassByIndirectCopyRestore: 3451 case SK_PassByIndirectRestore: 3452 case SK_ProduceObjCObject: 3453 case SK_StdInitializerList: 3454 case SK_StdInitializerListConstructorCall: 3455 case SK_OCLSamplerInit: 3456 case SK_OCLZeroOpaqueType: 3457 break; 3458 3459 case SK_ConversionSequence: 3460 case SK_ConversionSequenceNoNarrowing: 3461 delete ICS; 3462 } 3463 } 3464 3465 bool InitializationSequence::isDirectReferenceBinding() const { 3466 // There can be some lvalue adjustments after the SK_BindReference step. 3467 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { 3468 if (I->Kind == SK_BindReference) 3469 return true; 3470 if (I->Kind == SK_BindReferenceToTemporary) 3471 return false; 3472 } 3473 return false; 3474 } 3475 3476 bool InitializationSequence::isAmbiguous() const { 3477 if (!Failed()) 3478 return false; 3479 3480 switch (getFailureKind()) { 3481 case FK_TooManyInitsForReference: 3482 case FK_ParenthesizedListInitForReference: 3483 case FK_ArrayNeedsInitList: 3484 case FK_ArrayNeedsInitListOrStringLiteral: 3485 case FK_ArrayNeedsInitListOrWideStringLiteral: 3486 case FK_NarrowStringIntoWideCharArray: 3487 case FK_WideStringIntoCharArray: 3488 case FK_IncompatWideStringIntoWideChar: 3489 case FK_PlainStringIntoUTF8Char: 3490 case FK_UTF8StringIntoPlainChar: 3491 case FK_AddressOfOverloadFailed: // FIXME: Could do better 3492 case FK_NonConstLValueReferenceBindingToTemporary: 3493 case FK_NonConstLValueReferenceBindingToBitfield: 3494 case FK_NonConstLValueReferenceBindingToVectorElement: 3495 case FK_NonConstLValueReferenceBindingToMatrixElement: 3496 case FK_NonConstLValueReferenceBindingToUnrelated: 3497 case FK_RValueReferenceBindingToLValue: 3498 case FK_ReferenceAddrspaceMismatchTemporary: 3499 case FK_ReferenceInitDropsQualifiers: 3500 case FK_ReferenceInitFailed: 3501 case FK_ConversionFailed: 3502 case FK_ConversionFromPropertyFailed: 3503 case FK_TooManyInitsForScalar: 3504 case FK_ParenthesizedListInitForScalar: 3505 case FK_ReferenceBindingToInitList: 3506 case FK_InitListBadDestinationType: 3507 case FK_DefaultInitOfConst: 3508 case FK_Incomplete: 3509 case FK_ArrayTypeMismatch: 3510 case FK_NonConstantArrayInit: 3511 case FK_ListInitializationFailed: 3512 case FK_VariableLengthArrayHasInitializer: 3513 case FK_PlaceholderType: 3514 case FK_ExplicitConstructor: 3515 case FK_AddressOfUnaddressableFunction: 3516 return false; 3517 3518 case FK_ReferenceInitOverloadFailed: 3519 case FK_UserConversionOverloadFailed: 3520 case FK_ConstructorOverloadFailed: 3521 case FK_ListConstructorOverloadFailed: 3522 return FailedOverloadResult == OR_Ambiguous; 3523 } 3524 3525 llvm_unreachable("Invalid EntityKind!"); 3526 } 3527 3528 bool InitializationSequence::isConstructorInitialization() const { 3529 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 3530 } 3531 3532 void 3533 InitializationSequence 3534 ::AddAddressOverloadResolutionStep(FunctionDecl *Function, 3535 DeclAccessPair Found, 3536 bool HadMultipleCandidates) { 3537 Step S; 3538 S.Kind = SK_ResolveAddressOfOverloadedFunction; 3539 S.Type = Function->getType(); 3540 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3541 S.Function.Function = Function; 3542 S.Function.FoundDecl = Found; 3543 Steps.push_back(S); 3544 } 3545 3546 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 3547 ExprValueKind VK) { 3548 Step S; 3549 switch (VK) { 3550 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 3551 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 3552 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 3553 } 3554 S.Type = BaseType; 3555 Steps.push_back(S); 3556 } 3557 3558 void InitializationSequence::AddReferenceBindingStep(QualType T, 3559 bool BindingTemporary) { 3560 Step S; 3561 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 3562 S.Type = T; 3563 Steps.push_back(S); 3564 } 3565 3566 void InitializationSequence::AddFinalCopy(QualType T) { 3567 Step S; 3568 S.Kind = SK_FinalCopy; 3569 S.Type = T; 3570 Steps.push_back(S); 3571 } 3572 3573 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 3574 Step S; 3575 S.Kind = SK_ExtraneousCopyToTemporary; 3576 S.Type = T; 3577 Steps.push_back(S); 3578 } 3579 3580 void 3581 InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 3582 DeclAccessPair FoundDecl, 3583 QualType T, 3584 bool HadMultipleCandidates) { 3585 Step S; 3586 S.Kind = SK_UserConversion; 3587 S.Type = T; 3588 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3589 S.Function.Function = Function; 3590 S.Function.FoundDecl = FoundDecl; 3591 Steps.push_back(S); 3592 } 3593 3594 void InitializationSequence::AddQualificationConversionStep(QualType Ty, 3595 ExprValueKind VK) { 3596 Step S; 3597 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 3598 switch (VK) { 3599 case VK_RValue: 3600 S.Kind = SK_QualificationConversionRValue; 3601 break; 3602 case VK_XValue: 3603 S.Kind = SK_QualificationConversionXValue; 3604 break; 3605 case VK_LValue: 3606 S.Kind = SK_QualificationConversionLValue; 3607 break; 3608 } 3609 S.Type = Ty; 3610 Steps.push_back(S); 3611 } 3612 3613 void InitializationSequence::AddAtomicConversionStep(QualType Ty) { 3614 Step S; 3615 S.Kind = SK_AtomicConversion; 3616 S.Type = Ty; 3617 Steps.push_back(S); 3618 } 3619 3620 void InitializationSequence::AddConversionSequenceStep( 3621 const ImplicitConversionSequence &ICS, QualType T, 3622 bool TopLevelOfInitList) { 3623 Step S; 3624 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing 3625 : SK_ConversionSequence; 3626 S.Type = T; 3627 S.ICS = new ImplicitConversionSequence(ICS); 3628 Steps.push_back(S); 3629 } 3630 3631 void InitializationSequence::AddListInitializationStep(QualType T) { 3632 Step S; 3633 S.Kind = SK_ListInitialization; 3634 S.Type = T; 3635 Steps.push_back(S); 3636 } 3637 3638 void InitializationSequence::AddConstructorInitializationStep( 3639 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, 3640 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { 3641 Step S; 3642 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall 3643 : SK_ConstructorInitializationFromList 3644 : SK_ConstructorInitialization; 3645 S.Type = T; 3646 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3647 S.Function.Function = Constructor; 3648 S.Function.FoundDecl = FoundDecl; 3649 Steps.push_back(S); 3650 } 3651 3652 void InitializationSequence::AddZeroInitializationStep(QualType T) { 3653 Step S; 3654 S.Kind = SK_ZeroInitialization; 3655 S.Type = T; 3656 Steps.push_back(S); 3657 } 3658 3659 void InitializationSequence::AddCAssignmentStep(QualType T) { 3660 Step S; 3661 S.Kind = SK_CAssignment; 3662 S.Type = T; 3663 Steps.push_back(S); 3664 } 3665 3666 void InitializationSequence::AddStringInitStep(QualType T) { 3667 Step S; 3668 S.Kind = SK_StringInit; 3669 S.Type = T; 3670 Steps.push_back(S); 3671 } 3672 3673 void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 3674 Step S; 3675 S.Kind = SK_ObjCObjectConversion; 3676 S.Type = T; 3677 Steps.push_back(S); 3678 } 3679 3680 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { 3681 Step S; 3682 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; 3683 S.Type = T; 3684 Steps.push_back(S); 3685 } 3686 3687 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { 3688 Step S; 3689 S.Kind = SK_ArrayLoopIndex; 3690 S.Type = EltT; 3691 Steps.insert(Steps.begin(), S); 3692 3693 S.Kind = SK_ArrayLoopInit; 3694 S.Type = T; 3695 Steps.push_back(S); 3696 } 3697 3698 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { 3699 Step S; 3700 S.Kind = SK_ParenthesizedArrayInit; 3701 S.Type = T; 3702 Steps.push_back(S); 3703 } 3704 3705 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 3706 bool shouldCopy) { 3707 Step s; 3708 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 3709 : SK_PassByIndirectRestore); 3710 s.Type = type; 3711 Steps.push_back(s); 3712 } 3713 3714 void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 3715 Step S; 3716 S.Kind = SK_ProduceObjCObject; 3717 S.Type = T; 3718 Steps.push_back(S); 3719 } 3720 3721 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { 3722 Step S; 3723 S.Kind = SK_StdInitializerList; 3724 S.Type = T; 3725 Steps.push_back(S); 3726 } 3727 3728 void InitializationSequence::AddOCLSamplerInitStep(QualType T) { 3729 Step S; 3730 S.Kind = SK_OCLSamplerInit; 3731 S.Type = T; 3732 Steps.push_back(S); 3733 } 3734 3735 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { 3736 Step S; 3737 S.Kind = SK_OCLZeroOpaqueType; 3738 S.Type = T; 3739 Steps.push_back(S); 3740 } 3741 3742 void InitializationSequence::RewrapReferenceInitList(QualType T, 3743 InitListExpr *Syntactic) { 3744 assert(Syntactic->getNumInits() == 1 && 3745 "Can only rewrap trivial init lists."); 3746 Step S; 3747 S.Kind = SK_UnwrapInitList; 3748 S.Type = Syntactic->getInit(0)->getType(); 3749 Steps.insert(Steps.begin(), S); 3750 3751 S.Kind = SK_RewrapInitList; 3752 S.Type = T; 3753 S.WrappingSyntacticList = Syntactic; 3754 Steps.push_back(S); 3755 } 3756 3757 void InitializationSequence::SetOverloadFailure(FailureKind Failure, 3758 OverloadingResult Result) { 3759 setSequenceKind(FailedSequence); 3760 this->Failure = Failure; 3761 this->FailedOverloadResult = Result; 3762 } 3763 3764 //===----------------------------------------------------------------------===// 3765 // Attempt initialization 3766 //===----------------------------------------------------------------------===// 3767 3768 /// Tries to add a zero initializer. Returns true if that worked. 3769 static bool 3770 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, 3771 const InitializedEntity &Entity) { 3772 if (Entity.getKind() != InitializedEntity::EK_Variable) 3773 return false; 3774 3775 VarDecl *VD = cast<VarDecl>(Entity.getDecl()); 3776 if (VD->getInit() || VD->getEndLoc().isMacroID()) 3777 return false; 3778 3779 QualType VariableTy = VD->getType().getCanonicalType(); 3780 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); 3781 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 3782 if (!Init.empty()) { 3783 Sequence.AddZeroInitializationStep(Entity.getType()); 3784 Sequence.SetZeroInitializationFixit(Init, Loc); 3785 return true; 3786 } 3787 return false; 3788 } 3789 3790 static void MaybeProduceObjCObject(Sema &S, 3791 InitializationSequence &Sequence, 3792 const InitializedEntity &Entity) { 3793 if (!S.getLangOpts().ObjCAutoRefCount) return; 3794 3795 /// When initializing a parameter, produce the value if it's marked 3796 /// __attribute__((ns_consumed)). 3797 if (Entity.isParameterKind()) { 3798 if (!Entity.isParameterConsumed()) 3799 return; 3800 3801 assert(Entity.getType()->isObjCRetainableType() && 3802 "consuming an object of unretainable type?"); 3803 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3804 3805 /// When initializing a return value, if the return type is a 3806 /// retainable type, then returns need to immediately retain the 3807 /// object. If an autorelease is required, it will be done at the 3808 /// last instant. 3809 } else if (Entity.getKind() == InitializedEntity::EK_Result || 3810 Entity.getKind() == InitializedEntity::EK_StmtExprResult) { 3811 if (!Entity.getType()->isObjCRetainableType()) 3812 return; 3813 3814 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3815 } 3816 } 3817 3818 static void TryListInitialization(Sema &S, 3819 const InitializedEntity &Entity, 3820 const InitializationKind &Kind, 3821 InitListExpr *InitList, 3822 InitializationSequence &Sequence, 3823 bool TreatUnavailableAsInvalid); 3824 3825 /// When initializing from init list via constructor, handle 3826 /// initialization of an object of type std::initializer_list<T>. 3827 /// 3828 /// \return true if we have handled initialization of an object of type 3829 /// std::initializer_list<T>, false otherwise. 3830 static bool TryInitializerListConstruction(Sema &S, 3831 InitListExpr *List, 3832 QualType DestType, 3833 InitializationSequence &Sequence, 3834 bool TreatUnavailableAsInvalid) { 3835 QualType E; 3836 if (!S.isStdInitializerList(DestType, &E)) 3837 return false; 3838 3839 if (!S.isCompleteType(List->getExprLoc(), E)) { 3840 Sequence.setIncompleteTypeFailure(E); 3841 return true; 3842 } 3843 3844 // Try initializing a temporary array from the init list. 3845 QualType ArrayType = S.Context.getConstantArrayType( 3846 E.withConst(), 3847 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 3848 List->getNumInits()), 3849 nullptr, clang::ArrayType::Normal, 0); 3850 InitializedEntity HiddenArray = 3851 InitializedEntity::InitializeTemporary(ArrayType); 3852 InitializationKind Kind = InitializationKind::CreateDirectList( 3853 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); 3854 TryListInitialization(S, HiddenArray, Kind, List, Sequence, 3855 TreatUnavailableAsInvalid); 3856 if (Sequence) 3857 Sequence.AddStdInitializerListConstructionStep(DestType); 3858 return true; 3859 } 3860 3861 /// Determine if the constructor has the signature of a copy or move 3862 /// constructor for the type T of the class in which it was found. That is, 3863 /// determine if its first parameter is of type T or reference to (possibly 3864 /// cv-qualified) T. 3865 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, 3866 const ConstructorInfo &Info) { 3867 if (Info.Constructor->getNumParams() == 0) 3868 return false; 3869 3870 QualType ParmT = 3871 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); 3872 QualType ClassT = 3873 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); 3874 3875 return Ctx.hasSameUnqualifiedType(ParmT, ClassT); 3876 } 3877 3878 static OverloadingResult 3879 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, 3880 MultiExprArg Args, 3881 OverloadCandidateSet &CandidateSet, 3882 QualType DestType, 3883 DeclContext::lookup_result Ctors, 3884 OverloadCandidateSet::iterator &Best, 3885 bool CopyInitializing, bool AllowExplicit, 3886 bool OnlyListConstructors, bool IsListInit, 3887 bool SecondStepOfCopyInit = false) { 3888 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); 3889 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 3890 3891 for (NamedDecl *D : Ctors) { 3892 auto Info = getConstructorInfo(D); 3893 if (!Info.Constructor || Info.Constructor->isInvalidDecl()) 3894 continue; 3895 3896 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) 3897 continue; 3898 3899 // C++11 [over.best.ics]p4: 3900 // ... and the constructor or user-defined conversion function is a 3901 // candidate by 3902 // - 13.3.1.3, when the argument is the temporary in the second step 3903 // of a class copy-initialization, or 3904 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] 3905 // - the second phase of 13.3.1.7 when the initializer list has exactly 3906 // one element that is itself an initializer list, and the target is 3907 // the first parameter of a constructor of class X, and the conversion 3908 // is to X or reference to (possibly cv-qualified X), 3909 // user-defined conversion sequences are not considered. 3910 bool SuppressUserConversions = 3911 SecondStepOfCopyInit || 3912 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && 3913 hasCopyOrMoveCtorParam(S.Context, Info)); 3914 3915 if (Info.ConstructorTmpl) 3916 S.AddTemplateOverloadCandidate( 3917 Info.ConstructorTmpl, Info.FoundDecl, 3918 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, 3919 /*PartialOverloading=*/false, AllowExplicit); 3920 else { 3921 // C++ [over.match.copy]p1: 3922 // - When initializing a temporary to be bound to the first parameter 3923 // of a constructor [for type T] that takes a reference to possibly 3924 // cv-qualified T as its first argument, called with a single 3925 // argument in the context of direct-initialization, explicit 3926 // conversion functions are also considered. 3927 // FIXME: What if a constructor template instantiates to such a signature? 3928 bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 3929 Args.size() == 1 && 3930 hasCopyOrMoveCtorParam(S.Context, Info); 3931 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, 3932 CandidateSet, SuppressUserConversions, 3933 /*PartialOverloading=*/false, AllowExplicit, 3934 AllowExplicitConv); 3935 } 3936 } 3937 3938 // FIXME: Work around a bug in C++17 guaranteed copy elision. 3939 // 3940 // When initializing an object of class type T by constructor 3941 // ([over.match.ctor]) or by list-initialization ([over.match.list]) 3942 // from a single expression of class type U, conversion functions of 3943 // U that convert to the non-reference type cv T are candidates. 3944 // Explicit conversion functions are only candidates during 3945 // direct-initialization. 3946 // 3947 // Note: SecondStepOfCopyInit is only ever true in this case when 3948 // evaluating whether to produce a C++98 compatibility warning. 3949 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && 3950 !SecondStepOfCopyInit) { 3951 Expr *Initializer = Args[0]; 3952 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); 3953 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { 3954 const auto &Conversions = SourceRD->getVisibleConversionFunctions(); 3955 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3956 NamedDecl *D = *I; 3957 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3958 D = D->getUnderlyingDecl(); 3959 3960 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3961 CXXConversionDecl *Conv; 3962 if (ConvTemplate) 3963 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3964 else 3965 Conv = cast<CXXConversionDecl>(D); 3966 3967 if (ConvTemplate) 3968 S.AddTemplateConversionCandidate( 3969 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 3970 CandidateSet, AllowExplicit, AllowExplicit, 3971 /*AllowResultConversion*/ false); 3972 else 3973 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 3974 DestType, CandidateSet, AllowExplicit, 3975 AllowExplicit, 3976 /*AllowResultConversion*/ false); 3977 } 3978 } 3979 } 3980 3981 // Perform overload resolution and return the result. 3982 return CandidateSet.BestViableFunction(S, DeclLoc, Best); 3983 } 3984 3985 /// Attempt initialization by constructor (C++ [dcl.init]), which 3986 /// enumerates the constructors of the initialized entity and performs overload 3987 /// resolution to select the best. 3988 /// \param DestType The destination class type. 3989 /// \param DestArrayType The destination type, which is either DestType or 3990 /// a (possibly multidimensional) array of DestType. 3991 /// \param IsListInit Is this list-initialization? 3992 /// \param IsInitListCopy Is this non-list-initialization resulting from a 3993 /// list-initialization from {x} where x is the same 3994 /// type as the entity? 3995 static void TryConstructorInitialization(Sema &S, 3996 const InitializedEntity &Entity, 3997 const InitializationKind &Kind, 3998 MultiExprArg Args, QualType DestType, 3999 QualType DestArrayType, 4000 InitializationSequence &Sequence, 4001 bool IsListInit = false, 4002 bool IsInitListCopy = false) { 4003 assert(((!IsListInit && !IsInitListCopy) || 4004 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 4005 "IsListInit/IsInitListCopy must come with a single initializer list " 4006 "argument."); 4007 InitListExpr *ILE = 4008 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; 4009 MultiExprArg UnwrappedArgs = 4010 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; 4011 4012 // The type we're constructing needs to be complete. 4013 if (!S.isCompleteType(Kind.getLocation(), DestType)) { 4014 Sequence.setIncompleteTypeFailure(DestType); 4015 return; 4016 } 4017 4018 // C++17 [dcl.init]p17: 4019 // - If the initializer expression is a prvalue and the cv-unqualified 4020 // version of the source type is the same class as the class of the 4021 // destination, the initializer expression is used to initialize the 4022 // destination object. 4023 // Per DR (no number yet), this does not apply when initializing a base 4024 // class or delegating to another constructor from a mem-initializer. 4025 // ObjC++: Lambda captured by the block in the lambda to block conversion 4026 // should avoid copy elision. 4027 if (S.getLangOpts().CPlusPlus17 && 4028 Entity.getKind() != InitializedEntity::EK_Base && 4029 Entity.getKind() != InitializedEntity::EK_Delegating && 4030 Entity.getKind() != 4031 InitializedEntity::EK_LambdaToBlockConversionBlockElement && 4032 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && 4033 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { 4034 // Convert qualifications if necessary. 4035 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4036 if (ILE) 4037 Sequence.RewrapReferenceInitList(DestType, ILE); 4038 return; 4039 } 4040 4041 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 4042 assert(DestRecordType && "Constructor initialization requires record type"); 4043 CXXRecordDecl *DestRecordDecl 4044 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 4045 4046 // Build the candidate set directly in the initialization sequence 4047 // structure, so that it will persist if we fail. 4048 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4049 4050 // Determine whether we are allowed to call explicit constructors or 4051 // explicit conversion operators. 4052 bool AllowExplicit = Kind.AllowExplicit() || IsListInit; 4053 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; 4054 4055 // - Otherwise, if T is a class type, constructors are considered. The 4056 // applicable constructors are enumerated, and the best one is chosen 4057 // through overload resolution. 4058 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); 4059 4060 OverloadingResult Result = OR_No_Viable_Function; 4061 OverloadCandidateSet::iterator Best; 4062 bool AsInitializerList = false; 4063 4064 // C++11 [over.match.list]p1, per DR1467: 4065 // When objects of non-aggregate type T are list-initialized, such that 4066 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed 4067 // according to the rules in this section, overload resolution selects 4068 // the constructor in two phases: 4069 // 4070 // - Initially, the candidate functions are the initializer-list 4071 // constructors of the class T and the argument list consists of the 4072 // initializer list as a single argument. 4073 if (IsListInit) { 4074 AsInitializerList = true; 4075 4076 // If the initializer list has no elements and T has a default constructor, 4077 // the first phase is omitted. 4078 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl))) 4079 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 4080 CandidateSet, DestType, Ctors, Best, 4081 CopyInitialization, AllowExplicit, 4082 /*OnlyListConstructors=*/true, 4083 IsListInit); 4084 } 4085 4086 // C++11 [over.match.list]p1: 4087 // - If no viable initializer-list constructor is found, overload resolution 4088 // is performed again, where the candidate functions are all the 4089 // constructors of the class T and the argument list consists of the 4090 // elements of the initializer list. 4091 if (Result == OR_No_Viable_Function) { 4092 AsInitializerList = false; 4093 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, 4094 CandidateSet, DestType, Ctors, Best, 4095 CopyInitialization, AllowExplicit, 4096 /*OnlyListConstructors=*/false, 4097 IsListInit); 4098 } 4099 if (Result) { 4100 Sequence.SetOverloadFailure(IsListInit ? 4101 InitializationSequence::FK_ListConstructorOverloadFailed : 4102 InitializationSequence::FK_ConstructorOverloadFailed, 4103 Result); 4104 return; 4105 } 4106 4107 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4108 4109 // In C++17, ResolveConstructorOverload can select a conversion function 4110 // instead of a constructor. 4111 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { 4112 // Add the user-defined conversion step that calls the conversion function. 4113 QualType ConvType = CD->getConversionType(); 4114 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && 4115 "should not have selected this conversion function"); 4116 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, 4117 HadMultipleCandidates); 4118 if (!S.Context.hasSameType(ConvType, DestType)) 4119 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4120 if (IsListInit) 4121 Sequence.RewrapReferenceInitList(Entity.getType(), ILE); 4122 return; 4123 } 4124 4125 // C++11 [dcl.init]p6: 4126 // If a program calls for the default initialization of an object 4127 // of a const-qualified type T, T shall be a class type with a 4128 // user-provided default constructor. 4129 // C++ core issue 253 proposal: 4130 // If the implicit default constructor initializes all subobjects, no 4131 // initializer should be required. 4132 // The 253 proposal is for example needed to process libstdc++ headers in 5.x. 4133 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 4134 if (Kind.getKind() == InitializationKind::IK_Default && 4135 Entity.getType().isConstQualified()) { 4136 if (!CtorDecl->getParent()->allowConstDefaultInit()) { 4137 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 4138 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 4139 return; 4140 } 4141 } 4142 4143 // C++11 [over.match.list]p1: 4144 // In copy-list-initialization, if an explicit constructor is chosen, the 4145 // initializer is ill-formed. 4146 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { 4147 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); 4148 return; 4149 } 4150 4151 // Add the constructor initialization step. Any cv-qualification conversion is 4152 // subsumed by the initialization. 4153 Sequence.AddConstructorInitializationStep( 4154 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, 4155 IsListInit | IsInitListCopy, AsInitializerList); 4156 } 4157 4158 static bool 4159 ResolveOverloadedFunctionForReferenceBinding(Sema &S, 4160 Expr *Initializer, 4161 QualType &SourceType, 4162 QualType &UnqualifiedSourceType, 4163 QualType UnqualifiedTargetType, 4164 InitializationSequence &Sequence) { 4165 if (S.Context.getCanonicalType(UnqualifiedSourceType) == 4166 S.Context.OverloadTy) { 4167 DeclAccessPair Found; 4168 bool HadMultipleCandidates = false; 4169 if (FunctionDecl *Fn 4170 = S.ResolveAddressOfOverloadedFunction(Initializer, 4171 UnqualifiedTargetType, 4172 false, Found, 4173 &HadMultipleCandidates)) { 4174 Sequence.AddAddressOverloadResolutionStep(Fn, Found, 4175 HadMultipleCandidates); 4176 SourceType = Fn->getType(); 4177 UnqualifiedSourceType = SourceType.getUnqualifiedType(); 4178 } else if (!UnqualifiedTargetType->isRecordType()) { 4179 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4180 return true; 4181 } 4182 } 4183 return false; 4184 } 4185 4186 static void TryReferenceInitializationCore(Sema &S, 4187 const InitializedEntity &Entity, 4188 const InitializationKind &Kind, 4189 Expr *Initializer, 4190 QualType cv1T1, QualType T1, 4191 Qualifiers T1Quals, 4192 QualType cv2T2, QualType T2, 4193 Qualifiers T2Quals, 4194 InitializationSequence &Sequence); 4195 4196 static void TryValueInitialization(Sema &S, 4197 const InitializedEntity &Entity, 4198 const InitializationKind &Kind, 4199 InitializationSequence &Sequence, 4200 InitListExpr *InitList = nullptr); 4201 4202 /// Attempt list initialization of a reference. 4203 static void TryReferenceListInitialization(Sema &S, 4204 const InitializedEntity &Entity, 4205 const InitializationKind &Kind, 4206 InitListExpr *InitList, 4207 InitializationSequence &Sequence, 4208 bool TreatUnavailableAsInvalid) { 4209 // First, catch C++03 where this isn't possible. 4210 if (!S.getLangOpts().CPlusPlus11) { 4211 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4212 return; 4213 } 4214 // Can't reference initialize a compound literal. 4215 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { 4216 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4217 return; 4218 } 4219 4220 QualType DestType = Entity.getType(); 4221 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4222 Qualifiers T1Quals; 4223 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4224 4225 // Reference initialization via an initializer list works thus: 4226 // If the initializer list consists of a single element that is 4227 // reference-related to the referenced type, bind directly to that element 4228 // (possibly creating temporaries). 4229 // Otherwise, initialize a temporary with the initializer list and 4230 // bind to that. 4231 if (InitList->getNumInits() == 1) { 4232 Expr *Initializer = InitList->getInit(0); 4233 QualType cv2T2 = Initializer->getType(); 4234 Qualifiers T2Quals; 4235 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4236 4237 // If this fails, creating a temporary wouldn't work either. 4238 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4239 T1, Sequence)) 4240 return; 4241 4242 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4243 Sema::ReferenceCompareResult RefRelationship 4244 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); 4245 if (RefRelationship >= Sema::Ref_Related) { 4246 // Try to bind the reference here. 4247 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4248 T1Quals, cv2T2, T2, T2Quals, Sequence); 4249 if (Sequence) 4250 Sequence.RewrapReferenceInitList(cv1T1, InitList); 4251 return; 4252 } 4253 4254 // Update the initializer if we've resolved an overloaded function. 4255 if (Sequence.step_begin() != Sequence.step_end()) 4256 Sequence.RewrapReferenceInitList(cv1T1, InitList); 4257 } 4258 4259 // Not reference-related. Create a temporary and bind to that. 4260 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 4261 4262 TryListInitialization(S, TempEntity, Kind, InitList, Sequence, 4263 TreatUnavailableAsInvalid); 4264 if (Sequence) { 4265 if (DestType->isRValueReferenceType() || 4266 (T1Quals.hasConst() && !T1Quals.hasVolatile())) 4267 Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true); 4268 else 4269 Sequence.SetFailed( 4270 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 4271 } 4272 } 4273 4274 /// Attempt list initialization (C++0x [dcl.init.list]) 4275 static void TryListInitialization(Sema &S, 4276 const InitializedEntity &Entity, 4277 const InitializationKind &Kind, 4278 InitListExpr *InitList, 4279 InitializationSequence &Sequence, 4280 bool TreatUnavailableAsInvalid) { 4281 QualType DestType = Entity.getType(); 4282 4283 // C++ doesn't allow scalar initialization with more than one argument. 4284 // But C99 complex numbers are scalars and it makes sense there. 4285 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && 4286 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 4287 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 4288 return; 4289 } 4290 if (DestType->isReferenceType()) { 4291 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, 4292 TreatUnavailableAsInvalid); 4293 return; 4294 } 4295 4296 if (DestType->isRecordType() && 4297 !S.isCompleteType(InitList->getBeginLoc(), DestType)) { 4298 Sequence.setIncompleteTypeFailure(DestType); 4299 return; 4300 } 4301 4302 // C++11 [dcl.init.list]p3, per DR1467: 4303 // - If T is a class type and the initializer list has a single element of 4304 // type cv U, where U is T or a class derived from T, the object is 4305 // initialized from that element (by copy-initialization for 4306 // copy-list-initialization, or by direct-initialization for 4307 // direct-list-initialization). 4308 // - Otherwise, if T is a character array and the initializer list has a 4309 // single element that is an appropriately-typed string literal 4310 // (8.5.2 [dcl.init.string]), initialization is performed as described 4311 // in that section. 4312 // - Otherwise, if T is an aggregate, [...] (continue below). 4313 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { 4314 if (DestType->isRecordType()) { 4315 QualType InitType = InitList->getInit(0)->getType(); 4316 if (S.Context.hasSameUnqualifiedType(InitType, DestType) || 4317 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { 4318 Expr *InitListAsExpr = InitList; 4319 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4320 DestType, Sequence, 4321 /*InitListSyntax*/false, 4322 /*IsInitListCopy*/true); 4323 return; 4324 } 4325 } 4326 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { 4327 Expr *SubInit[1] = {InitList->getInit(0)}; 4328 if (!isa<VariableArrayType>(DestAT) && 4329 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { 4330 InitializationKind SubKind = 4331 Kind.getKind() == InitializationKind::IK_DirectList 4332 ? InitializationKind::CreateDirect(Kind.getLocation(), 4333 InitList->getLBraceLoc(), 4334 InitList->getRBraceLoc()) 4335 : Kind; 4336 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4337 /*TopLevelOfInitList*/ true, 4338 TreatUnavailableAsInvalid); 4339 4340 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if 4341 // the element is not an appropriately-typed string literal, in which 4342 // case we should proceed as in C++11 (below). 4343 if (Sequence) { 4344 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4345 return; 4346 } 4347 } 4348 } 4349 } 4350 4351 // C++11 [dcl.init.list]p3: 4352 // - If T is an aggregate, aggregate initialization is performed. 4353 if ((DestType->isRecordType() && !DestType->isAggregateType()) || 4354 (S.getLangOpts().CPlusPlus11 && 4355 S.isStdInitializerList(DestType, nullptr))) { 4356 if (S.getLangOpts().CPlusPlus11) { 4357 // - Otherwise, if the initializer list has no elements and T is a 4358 // class type with a default constructor, the object is 4359 // value-initialized. 4360 if (InitList->getNumInits() == 0) { 4361 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); 4362 if (S.LookupDefaultConstructor(RD)) { 4363 TryValueInitialization(S, Entity, Kind, Sequence, InitList); 4364 return; 4365 } 4366 } 4367 4368 // - Otherwise, if T is a specialization of std::initializer_list<E>, 4369 // an initializer_list object constructed [...] 4370 if (TryInitializerListConstruction(S, InitList, DestType, Sequence, 4371 TreatUnavailableAsInvalid)) 4372 return; 4373 4374 // - Otherwise, if T is a class type, constructors are considered. 4375 Expr *InitListAsExpr = InitList; 4376 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4377 DestType, Sequence, /*InitListSyntax*/true); 4378 } else 4379 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 4380 return; 4381 } 4382 4383 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && 4384 InitList->getNumInits() == 1) { 4385 Expr *E = InitList->getInit(0); 4386 4387 // - Otherwise, if T is an enumeration with a fixed underlying type, 4388 // the initializer-list has a single element v, and the initialization 4389 // is direct-list-initialization, the object is initialized with the 4390 // value T(v); if a narrowing conversion is required to convert v to 4391 // the underlying type of T, the program is ill-formed. 4392 auto *ET = DestType->getAs<EnumType>(); 4393 if (S.getLangOpts().CPlusPlus17 && 4394 Kind.getKind() == InitializationKind::IK_DirectList && 4395 ET && ET->getDecl()->isFixed() && 4396 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && 4397 (E->getType()->isIntegralOrEnumerationType() || 4398 E->getType()->isFloatingType())) { 4399 // There are two ways that T(v) can work when T is an enumeration type. 4400 // If there is either an implicit conversion sequence from v to T or 4401 // a conversion function that can convert from v to T, then we use that. 4402 // Otherwise, if v is of integral, enumeration, or floating-point type, 4403 // it is converted to the enumeration type via its underlying type. 4404 // There is no overlap possible between these two cases (except when the 4405 // source value is already of the destination type), and the first 4406 // case is handled by the general case for single-element lists below. 4407 ImplicitConversionSequence ICS; 4408 ICS.setStandard(); 4409 ICS.Standard.setAsIdentityConversion(); 4410 if (!E->isRValue()) 4411 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 4412 // If E is of a floating-point type, then the conversion is ill-formed 4413 // due to narrowing, but go through the motions in order to produce the 4414 // right diagnostic. 4415 ICS.Standard.Second = E->getType()->isFloatingType() 4416 ? ICK_Floating_Integral 4417 : ICK_Integral_Conversion; 4418 ICS.Standard.setFromType(E->getType()); 4419 ICS.Standard.setToType(0, E->getType()); 4420 ICS.Standard.setToType(1, DestType); 4421 ICS.Standard.setToType(2, DestType); 4422 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), 4423 /*TopLevelOfInitList*/true); 4424 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4425 return; 4426 } 4427 4428 // - Otherwise, if the initializer list has a single element of type E 4429 // [...references are handled above...], the object or reference is 4430 // initialized from that element (by copy-initialization for 4431 // copy-list-initialization, or by direct-initialization for 4432 // direct-list-initialization); if a narrowing conversion is required 4433 // to convert the element to T, the program is ill-formed. 4434 // 4435 // Per core-24034, this is direct-initialization if we were performing 4436 // direct-list-initialization and copy-initialization otherwise. 4437 // We can't use InitListChecker for this, because it always performs 4438 // copy-initialization. This only matters if we might use an 'explicit' 4439 // conversion operator, or for the special case conversion of nullptr_t to 4440 // bool, so we only need to handle those cases. 4441 // 4442 // FIXME: Why not do this in all cases? 4443 Expr *Init = InitList->getInit(0); 4444 if (Init->getType()->isRecordType() || 4445 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { 4446 InitializationKind SubKind = 4447 Kind.getKind() == InitializationKind::IK_DirectList 4448 ? InitializationKind::CreateDirect(Kind.getLocation(), 4449 InitList->getLBraceLoc(), 4450 InitList->getRBraceLoc()) 4451 : Kind; 4452 Expr *SubInit[1] = { Init }; 4453 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4454 /*TopLevelOfInitList*/true, 4455 TreatUnavailableAsInvalid); 4456 if (Sequence) 4457 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4458 return; 4459 } 4460 } 4461 4462 InitListChecker CheckInitList(S, Entity, InitList, 4463 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); 4464 if (CheckInitList.HadError()) { 4465 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 4466 return; 4467 } 4468 4469 // Add the list initialization step with the built init list. 4470 Sequence.AddListInitializationStep(DestType); 4471 } 4472 4473 /// Try a reference initialization that involves calling a conversion 4474 /// function. 4475 static OverloadingResult TryRefInitWithConversionFunction( 4476 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, 4477 Expr *Initializer, bool AllowRValues, bool IsLValueRef, 4478 InitializationSequence &Sequence) { 4479 QualType DestType = Entity.getType(); 4480 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4481 QualType T1 = cv1T1.getUnqualifiedType(); 4482 QualType cv2T2 = Initializer->getType(); 4483 QualType T2 = cv2T2.getUnqualifiedType(); 4484 4485 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && 4486 "Must have incompatible references when binding via conversion"); 4487 4488 // Build the candidate set directly in the initialization sequence 4489 // structure, so that it will persist if we fail. 4490 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4491 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4492 4493 // Determine whether we are allowed to call explicit conversion operators. 4494 // Note that none of [over.match.copy], [over.match.conv], nor 4495 // [over.match.ref] permit an explicit constructor to be chosen when 4496 // initializing a reference, not even for direct-initialization. 4497 bool AllowExplicitCtors = false; 4498 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); 4499 4500 const RecordType *T1RecordType = nullptr; 4501 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 4502 S.isCompleteType(Kind.getLocation(), T1)) { 4503 // The type we're converting to is a class type. Enumerate its constructors 4504 // to see if there is a suitable conversion. 4505 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 4506 4507 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { 4508 auto Info = getConstructorInfo(D); 4509 if (!Info.Constructor) 4510 continue; 4511 4512 if (!Info.Constructor->isInvalidDecl() && 4513 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 4514 if (Info.ConstructorTmpl) 4515 S.AddTemplateOverloadCandidate( 4516 Info.ConstructorTmpl, Info.FoundDecl, 4517 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 4518 /*SuppressUserConversions=*/true, 4519 /*PartialOverloading*/ false, AllowExplicitCtors); 4520 else 4521 S.AddOverloadCandidate( 4522 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, 4523 /*SuppressUserConversions=*/true, 4524 /*PartialOverloading*/ false, AllowExplicitCtors); 4525 } 4526 } 4527 } 4528 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 4529 return OR_No_Viable_Function; 4530 4531 const RecordType *T2RecordType = nullptr; 4532 if ((T2RecordType = T2->getAs<RecordType>()) && 4533 S.isCompleteType(Kind.getLocation(), T2)) { 4534 // The type we're converting from is a class type, enumerate its conversion 4535 // functions. 4536 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 4537 4538 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4539 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4540 NamedDecl *D = *I; 4541 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4542 if (isa<UsingShadowDecl>(D)) 4543 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4544 4545 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4546 CXXConversionDecl *Conv; 4547 if (ConvTemplate) 4548 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4549 else 4550 Conv = cast<CXXConversionDecl>(D); 4551 4552 // If the conversion function doesn't return a reference type, 4553 // it can't be considered for this conversion unless we're allowed to 4554 // consider rvalues. 4555 // FIXME: Do we need to make sure that we only consider conversion 4556 // candidates with reference-compatible results? That might be needed to 4557 // break recursion. 4558 if ((AllowRValues || 4559 Conv->getConversionType()->isLValueReferenceType())) { 4560 if (ConvTemplate) 4561 S.AddTemplateConversionCandidate( 4562 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 4563 CandidateSet, 4564 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4565 else 4566 S.AddConversionCandidate( 4567 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, 4568 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4569 } 4570 } 4571 } 4572 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 4573 return OR_No_Viable_Function; 4574 4575 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4576 4577 // Perform overload resolution. If it fails, return the failed result. 4578 OverloadCandidateSet::iterator Best; 4579 if (OverloadingResult Result 4580 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) 4581 return Result; 4582 4583 FunctionDecl *Function = Best->Function; 4584 // This is the overload that will be used for this initialization step if we 4585 // use this initialization. Mark it as referenced. 4586 Function->setReferenced(); 4587 4588 // Compute the returned type and value kind of the conversion. 4589 QualType cv3T3; 4590 if (isa<CXXConversionDecl>(Function)) 4591 cv3T3 = Function->getReturnType(); 4592 else 4593 cv3T3 = T1; 4594 4595 ExprValueKind VK = VK_RValue; 4596 if (cv3T3->isLValueReferenceType()) 4597 VK = VK_LValue; 4598 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) 4599 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 4600 cv3T3 = cv3T3.getNonLValueExprType(S.Context); 4601 4602 // Add the user-defined conversion step. 4603 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4604 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, 4605 HadMultipleCandidates); 4606 4607 // Determine whether we'll need to perform derived-to-base adjustments or 4608 // other conversions. 4609 Sema::ReferenceConversions RefConv; 4610 Sema::ReferenceCompareResult NewRefRelationship = 4611 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); 4612 4613 // Add the final conversion sequence, if necessary. 4614 if (NewRefRelationship == Sema::Ref_Incompatible) { 4615 assert(!isa<CXXConstructorDecl>(Function) && 4616 "should not have conversion after constructor"); 4617 4618 ImplicitConversionSequence ICS; 4619 ICS.setStandard(); 4620 ICS.Standard = Best->FinalConversion; 4621 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); 4622 4623 // Every implicit conversion results in a prvalue, except for a glvalue 4624 // derived-to-base conversion, which we handle below. 4625 cv3T3 = ICS.Standard.getToType(2); 4626 VK = VK_RValue; 4627 } 4628 4629 // If the converted initializer is a prvalue, its type T4 is adjusted to 4630 // type "cv1 T4" and the temporary materialization conversion is applied. 4631 // 4632 // We adjust the cv-qualifications to match the reference regardless of 4633 // whether we have a prvalue so that the AST records the change. In this 4634 // case, T4 is "cv3 T3". 4635 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); 4636 if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) 4637 Sequence.AddQualificationConversionStep(cv1T4, VK); 4638 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); 4639 VK = IsLValueRef ? VK_LValue : VK_XValue; 4640 4641 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4642 Sequence.AddDerivedToBaseCastStep(cv1T1, VK); 4643 else if (RefConv & Sema::ReferenceConversions::ObjC) 4644 Sequence.AddObjCObjectConversionStep(cv1T1); 4645 else if (RefConv & Sema::ReferenceConversions::Function) 4646 Sequence.AddQualificationConversionStep(cv1T1, VK); 4647 else if (RefConv & Sema::ReferenceConversions::Qualification) { 4648 if (!S.Context.hasSameType(cv1T4, cv1T1)) 4649 Sequence.AddQualificationConversionStep(cv1T1, VK); 4650 } 4651 4652 return OR_Success; 4653 } 4654 4655 static void CheckCXX98CompatAccessibleCopy(Sema &S, 4656 const InitializedEntity &Entity, 4657 Expr *CurInitExpr); 4658 4659 /// Attempt reference initialization (C++0x [dcl.init.ref]) 4660 static void TryReferenceInitialization(Sema &S, 4661 const InitializedEntity &Entity, 4662 const InitializationKind &Kind, 4663 Expr *Initializer, 4664 InitializationSequence &Sequence) { 4665 QualType DestType = Entity.getType(); 4666 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4667 Qualifiers T1Quals; 4668 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4669 QualType cv2T2 = Initializer->getType(); 4670 Qualifiers T2Quals; 4671 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4672 4673 // If the initializer is the address of an overloaded function, try 4674 // to resolve the overloaded function. If all goes well, T2 is the 4675 // type of the resulting function. 4676 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4677 T1, Sequence)) 4678 return; 4679 4680 // Delegate everything else to a subfunction. 4681 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4682 T1Quals, cv2T2, T2, T2Quals, Sequence); 4683 } 4684 4685 /// Determine whether an expression is a non-referenceable glvalue (one to 4686 /// which a reference can never bind). Attempting to bind a reference to 4687 /// such a glvalue will always create a temporary. 4688 static bool isNonReferenceableGLValue(Expr *E) { 4689 return E->refersToBitField() || E->refersToVectorElement() || 4690 E->refersToMatrixElement(); 4691 } 4692 4693 /// Reference initialization without resolving overloaded functions. 4694 /// 4695 /// We also can get here in C if we call a builtin which is declared as 4696 /// a function with a parameter of reference type (such as __builtin_va_end()). 4697 static void TryReferenceInitializationCore(Sema &S, 4698 const InitializedEntity &Entity, 4699 const InitializationKind &Kind, 4700 Expr *Initializer, 4701 QualType cv1T1, QualType T1, 4702 Qualifiers T1Quals, 4703 QualType cv2T2, QualType T2, 4704 Qualifiers T2Quals, 4705 InitializationSequence &Sequence) { 4706 QualType DestType = Entity.getType(); 4707 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4708 4709 // Compute some basic properties of the types and the initializer. 4710 bool isLValueRef = DestType->isLValueReferenceType(); 4711 bool isRValueRef = !isLValueRef; 4712 Expr::Classification InitCategory = Initializer->Classify(S.Context); 4713 4714 Sema::ReferenceConversions RefConv; 4715 Sema::ReferenceCompareResult RefRelationship = 4716 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); 4717 4718 // C++0x [dcl.init.ref]p5: 4719 // A reference to type "cv1 T1" is initialized by an expression of type 4720 // "cv2 T2" as follows: 4721 // 4722 // - If the reference is an lvalue reference and the initializer 4723 // expression 4724 // Note the analogous bullet points for rvalue refs to functions. Because 4725 // there are no function rvalues in C++, rvalue refs to functions are treated 4726 // like lvalue refs. 4727 OverloadingResult ConvOvlResult = OR_Success; 4728 bool T1Function = T1->isFunctionType(); 4729 if (isLValueRef || T1Function) { 4730 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && 4731 (RefRelationship == Sema::Ref_Compatible || 4732 (Kind.isCStyleOrFunctionalCast() && 4733 RefRelationship == Sema::Ref_Related))) { 4734 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 4735 // reference-compatible with "cv2 T2," or 4736 if (RefConv & (Sema::ReferenceConversions::DerivedToBase | 4737 Sema::ReferenceConversions::ObjC)) { 4738 // If we're converting the pointee, add any qualifiers first; 4739 // these qualifiers must all be top-level, so just convert to "cv1 T2". 4740 if (RefConv & (Sema::ReferenceConversions::Qualification)) 4741 Sequence.AddQualificationConversionStep( 4742 S.Context.getQualifiedType(T2, T1Quals), 4743 Initializer->getValueKind()); 4744 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4745 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); 4746 else 4747 Sequence.AddObjCObjectConversionStep(cv1T1); 4748 } else if (RefConv & (Sema::ReferenceConversions::Qualification | 4749 Sema::ReferenceConversions::Function)) { 4750 // Perform a (possibly multi-level) qualification conversion. 4751 // FIXME: Should we use a different step kind for function conversions? 4752 Sequence.AddQualificationConversionStep(cv1T1, 4753 Initializer->getValueKind()); 4754 } 4755 4756 // We only create a temporary here when binding a reference to a 4757 // bit-field or vector element. Those cases are't supposed to be 4758 // handled by this bullet, but the outcome is the same either way. 4759 Sequence.AddReferenceBindingStep(cv1T1, false); 4760 return; 4761 } 4762 4763 // - has a class type (i.e., T2 is a class type), where T1 is not 4764 // reference-related to T2, and can be implicitly converted to an 4765 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 4766 // with "cv3 T3" (this conversion is selected by enumerating the 4767 // applicable conversion functions (13.3.1.6) and choosing the best 4768 // one through overload resolution (13.3)), 4769 // If we have an rvalue ref to function type here, the rhs must be 4770 // an rvalue. DR1287 removed the "implicitly" here. 4771 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 4772 (isLValueRef || InitCategory.isRValue())) { 4773 if (S.getLangOpts().CPlusPlus) { 4774 // Try conversion functions only for C++. 4775 ConvOvlResult = TryRefInitWithConversionFunction( 4776 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, 4777 /*IsLValueRef*/ isLValueRef, Sequence); 4778 if (ConvOvlResult == OR_Success) 4779 return; 4780 if (ConvOvlResult != OR_No_Viable_Function) 4781 Sequence.SetOverloadFailure( 4782 InitializationSequence::FK_ReferenceInitOverloadFailed, 4783 ConvOvlResult); 4784 } else { 4785 ConvOvlResult = OR_No_Viable_Function; 4786 } 4787 } 4788 } 4789 4790 // - Otherwise, the reference shall be an lvalue reference to a 4791 // non-volatile const type (i.e., cv1 shall be const), or the reference 4792 // shall be an rvalue reference. 4793 // For address spaces, we interpret this to mean that an addr space 4794 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". 4795 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && 4796 T1Quals.isAddressSpaceSupersetOf(T2Quals))) { 4797 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4798 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4799 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4800 Sequence.SetOverloadFailure( 4801 InitializationSequence::FK_ReferenceInitOverloadFailed, 4802 ConvOvlResult); 4803 else if (!InitCategory.isLValue()) 4804 Sequence.SetFailed( 4805 T1Quals.isAddressSpaceSupersetOf(T2Quals) 4806 ? InitializationSequence:: 4807 FK_NonConstLValueReferenceBindingToTemporary 4808 : InitializationSequence::FK_ReferenceInitDropsQualifiers); 4809 else { 4810 InitializationSequence::FailureKind FK; 4811 switch (RefRelationship) { 4812 case Sema::Ref_Compatible: 4813 if (Initializer->refersToBitField()) 4814 FK = InitializationSequence:: 4815 FK_NonConstLValueReferenceBindingToBitfield; 4816 else if (Initializer->refersToVectorElement()) 4817 FK = InitializationSequence:: 4818 FK_NonConstLValueReferenceBindingToVectorElement; 4819 else if (Initializer->refersToMatrixElement()) 4820 FK = InitializationSequence:: 4821 FK_NonConstLValueReferenceBindingToMatrixElement; 4822 else 4823 llvm_unreachable("unexpected kind of compatible initializer"); 4824 break; 4825 case Sema::Ref_Related: 4826 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; 4827 break; 4828 case Sema::Ref_Incompatible: 4829 FK = InitializationSequence:: 4830 FK_NonConstLValueReferenceBindingToUnrelated; 4831 break; 4832 } 4833 Sequence.SetFailed(FK); 4834 } 4835 return; 4836 } 4837 4838 // - If the initializer expression 4839 // - is an 4840 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or 4841 // [1z] rvalue (but not a bit-field) or 4842 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" 4843 // 4844 // Note: functions are handled above and below rather than here... 4845 if (!T1Function && 4846 (RefRelationship == Sema::Ref_Compatible || 4847 (Kind.isCStyleOrFunctionalCast() && 4848 RefRelationship == Sema::Ref_Related)) && 4849 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || 4850 (InitCategory.isPRValue() && 4851 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || 4852 T2->isArrayType())))) { 4853 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; 4854 if (InitCategory.isPRValue() && T2->isRecordType()) { 4855 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 4856 // compiler the freedom to perform a copy here or bind to the 4857 // object, while C++0x requires that we bind directly to the 4858 // object. Hence, we always bind to the object without making an 4859 // extra copy. However, in C++03 requires that we check for the 4860 // presence of a suitable copy constructor: 4861 // 4862 // The constructor that would be used to make the copy shall 4863 // be callable whether or not the copy is actually done. 4864 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) 4865 Sequence.AddExtraneousCopyToTemporary(cv2T2); 4866 else if (S.getLangOpts().CPlusPlus11) 4867 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 4868 } 4869 4870 // C++1z [dcl.init.ref]/5.2.1.2: 4871 // If the converted initializer is a prvalue, its type T4 is adjusted 4872 // to type "cv1 T4" and the temporary materialization conversion is 4873 // applied. 4874 // Postpone address space conversions to after the temporary materialization 4875 // conversion to allow creating temporaries in the alloca address space. 4876 auto T1QualsIgnoreAS = T1Quals; 4877 auto T2QualsIgnoreAS = T2Quals; 4878 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4879 T1QualsIgnoreAS.removeAddressSpace(); 4880 T2QualsIgnoreAS.removeAddressSpace(); 4881 } 4882 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); 4883 if (T1QualsIgnoreAS != T2QualsIgnoreAS) 4884 Sequence.AddQualificationConversionStep(cv1T4, ValueKind); 4885 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); 4886 ValueKind = isLValueRef ? VK_LValue : VK_XValue; 4887 // Add addr space conversion if required. 4888 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4889 auto T4Quals = cv1T4.getQualifiers(); 4890 T4Quals.addAddressSpace(T1Quals.getAddressSpace()); 4891 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); 4892 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); 4893 cv1T4 = cv1T4WithAS; 4894 } 4895 4896 // In any case, the reference is bound to the resulting glvalue (or to 4897 // an appropriate base class subobject). 4898 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4899 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); 4900 else if (RefConv & Sema::ReferenceConversions::ObjC) 4901 Sequence.AddObjCObjectConversionStep(cv1T1); 4902 else if (RefConv & Sema::ReferenceConversions::Qualification) { 4903 if (!S.Context.hasSameType(cv1T4, cv1T1)) 4904 Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 4905 } 4906 return; 4907 } 4908 4909 // - has a class type (i.e., T2 is a class type), where T1 is not 4910 // reference-related to T2, and can be implicitly converted to an 4911 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 4912 // where "cv1 T1" is reference-compatible with "cv3 T3", 4913 // 4914 // DR1287 removes the "implicitly" here. 4915 if (T2->isRecordType()) { 4916 if (RefRelationship == Sema::Ref_Incompatible) { 4917 ConvOvlResult = TryRefInitWithConversionFunction( 4918 S, Entity, Kind, Initializer, /*AllowRValues*/ true, 4919 /*IsLValueRef*/ isLValueRef, Sequence); 4920 if (ConvOvlResult) 4921 Sequence.SetOverloadFailure( 4922 InitializationSequence::FK_ReferenceInitOverloadFailed, 4923 ConvOvlResult); 4924 4925 return; 4926 } 4927 4928 if (RefRelationship == Sema::Ref_Compatible && 4929 isRValueRef && InitCategory.isLValue()) { 4930 Sequence.SetFailed( 4931 InitializationSequence::FK_RValueReferenceBindingToLValue); 4932 return; 4933 } 4934 4935 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 4936 return; 4937 } 4938 4939 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 4940 // from the initializer expression using the rules for a non-reference 4941 // copy-initialization (8.5). The reference is then bound to the 4942 // temporary. [...] 4943 4944 // Ignore address space of reference type at this point and perform address 4945 // space conversion after the reference binding step. 4946 QualType cv1T1IgnoreAS = 4947 T1Quals.hasAddressSpace() 4948 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) 4949 : cv1T1; 4950 4951 InitializedEntity TempEntity = 4952 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); 4953 4954 // FIXME: Why do we use an implicit conversion here rather than trying 4955 // copy-initialization? 4956 ImplicitConversionSequence ICS 4957 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 4958 /*SuppressUserConversions=*/false, 4959 Sema::AllowedExplicit::None, 4960 /*FIXME:InOverloadResolution=*/false, 4961 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 4962 /*AllowObjCWritebackConversion=*/false); 4963 4964 if (ICS.isBad()) { 4965 // FIXME: Use the conversion function set stored in ICS to turn 4966 // this into an overloading ambiguity diagnostic. However, we need 4967 // to keep that set as an OverloadCandidateSet rather than as some 4968 // other kind of set. 4969 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4970 Sequence.SetOverloadFailure( 4971 InitializationSequence::FK_ReferenceInitOverloadFailed, 4972 ConvOvlResult); 4973 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4974 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4975 else 4976 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 4977 return; 4978 } else { 4979 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 4980 } 4981 4982 // [...] If T1 is reference-related to T2, cv1 must be the 4983 // same cv-qualification as, or greater cv-qualification 4984 // than, cv2; otherwise, the program is ill-formed. 4985 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 4986 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 4987 if ((RefRelationship == Sema::Ref_Related && 4988 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) || 4989 !T1Quals.isAddressSpaceSupersetOf(T2Quals)) { 4990 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 4991 return; 4992 } 4993 4994 // [...] If T1 is reference-related to T2 and the reference is an rvalue 4995 // reference, the initializer expression shall not be an lvalue. 4996 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 4997 InitCategory.isLValue()) { 4998 Sequence.SetFailed( 4999 InitializationSequence::FK_RValueReferenceBindingToLValue); 5000 return; 5001 } 5002 5003 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); 5004 5005 if (T1Quals.hasAddressSpace()) { 5006 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), 5007 LangAS::Default)) { 5008 Sequence.SetFailed( 5009 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); 5010 return; 5011 } 5012 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue 5013 : VK_XValue); 5014 } 5015 } 5016 5017 /// Attempt character array initialization from a string literal 5018 /// (C++ [dcl.init.string], C99 6.7.8). 5019 static void TryStringLiteralInitialization(Sema &S, 5020 const InitializedEntity &Entity, 5021 const InitializationKind &Kind, 5022 Expr *Initializer, 5023 InitializationSequence &Sequence) { 5024 Sequence.AddStringInitStep(Entity.getType()); 5025 } 5026 5027 /// Attempt value initialization (C++ [dcl.init]p7). 5028 static void TryValueInitialization(Sema &S, 5029 const InitializedEntity &Entity, 5030 const InitializationKind &Kind, 5031 InitializationSequence &Sequence, 5032 InitListExpr *InitList) { 5033 assert((!InitList || InitList->getNumInits() == 0) && 5034 "Shouldn't use value-init for non-empty init lists"); 5035 5036 // C++98 [dcl.init]p5, C++11 [dcl.init]p7: 5037 // 5038 // To value-initialize an object of type T means: 5039 QualType T = Entity.getType(); 5040 5041 // -- if T is an array type, then each element is value-initialized; 5042 T = S.Context.getBaseElementType(T); 5043 5044 if (const RecordType *RT = T->getAs<RecordType>()) { 5045 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 5046 bool NeedZeroInitialization = true; 5047 // C++98: 5048 // -- if T is a class type (clause 9) with a user-declared constructor 5049 // (12.1), then the default constructor for T is called (and the 5050 // initialization is ill-formed if T has no accessible default 5051 // constructor); 5052 // C++11: 5053 // -- if T is a class type (clause 9) with either no default constructor 5054 // (12.1 [class.ctor]) or a default constructor that is user-provided 5055 // or deleted, then the object is default-initialized; 5056 // 5057 // Note that the C++11 rule is the same as the C++98 rule if there are no 5058 // defaulted or deleted constructors, so we just use it unconditionally. 5059 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); 5060 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) 5061 NeedZeroInitialization = false; 5062 5063 // -- if T is a (possibly cv-qualified) non-union class type without a 5064 // user-provided or deleted default constructor, then the object is 5065 // zero-initialized and, if T has a non-trivial default constructor, 5066 // default-initialized; 5067 // The 'non-union' here was removed by DR1502. The 'non-trivial default 5068 // constructor' part was removed by DR1507. 5069 if (NeedZeroInitialization) 5070 Sequence.AddZeroInitializationStep(Entity.getType()); 5071 5072 // C++03: 5073 // -- if T is a non-union class type without a user-declared constructor, 5074 // then every non-static data member and base class component of T is 5075 // value-initialized; 5076 // [...] A program that calls for [...] value-initialization of an 5077 // entity of reference type is ill-formed. 5078 // 5079 // C++11 doesn't need this handling, because value-initialization does not 5080 // occur recursively there, and the implicit default constructor is 5081 // defined as deleted in the problematic cases. 5082 if (!S.getLangOpts().CPlusPlus11 && 5083 ClassDecl->hasUninitializedReferenceMember()) { 5084 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); 5085 return; 5086 } 5087 5088 // If this is list-value-initialization, pass the empty init list on when 5089 // building the constructor call. This affects the semantics of a few 5090 // things (such as whether an explicit default constructor can be called). 5091 Expr *InitListAsExpr = InitList; 5092 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); 5093 bool InitListSyntax = InitList; 5094 5095 // FIXME: Instead of creating a CXXConstructExpr of array type here, 5096 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. 5097 return TryConstructorInitialization( 5098 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); 5099 } 5100 } 5101 5102 Sequence.AddZeroInitializationStep(Entity.getType()); 5103 } 5104 5105 /// Attempt default initialization (C++ [dcl.init]p6). 5106 static void TryDefaultInitialization(Sema &S, 5107 const InitializedEntity &Entity, 5108 const InitializationKind &Kind, 5109 InitializationSequence &Sequence) { 5110 assert(Kind.getKind() == InitializationKind::IK_Default); 5111 5112 // C++ [dcl.init]p6: 5113 // To default-initialize an object of type T means: 5114 // - if T is an array type, each element is default-initialized; 5115 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 5116 5117 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 5118 // constructor for T is called (and the initialization is ill-formed if 5119 // T has no accessible default constructor); 5120 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { 5121 TryConstructorInitialization(S, Entity, Kind, None, DestType, 5122 Entity.getType(), Sequence); 5123 return; 5124 } 5125 5126 // - otherwise, no initialization is performed. 5127 5128 // If a program calls for the default initialization of an object of 5129 // a const-qualified type T, T shall be a class type with a user-provided 5130 // default constructor. 5131 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { 5132 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 5133 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 5134 return; 5135 } 5136 5137 // If the destination type has a lifetime property, zero-initialize it. 5138 if (DestType.getQualifiers().hasObjCLifetime()) { 5139 Sequence.AddZeroInitializationStep(Entity.getType()); 5140 return; 5141 } 5142 } 5143 5144 /// Attempt a user-defined conversion between two types (C++ [dcl.init]), 5145 /// which enumerates all conversion functions and performs overload resolution 5146 /// to select the best. 5147 static void TryUserDefinedConversion(Sema &S, 5148 QualType DestType, 5149 const InitializationKind &Kind, 5150 Expr *Initializer, 5151 InitializationSequence &Sequence, 5152 bool TopLevelOfInitList) { 5153 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 5154 QualType SourceType = Initializer->getType(); 5155 assert((DestType->isRecordType() || SourceType->isRecordType()) && 5156 "Must have a class type to perform a user-defined conversion"); 5157 5158 // Build the candidate set directly in the initialization sequence 5159 // structure, so that it will persist if we fail. 5160 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 5161 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 5162 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 5163 5164 // Determine whether we are allowed to call explicit constructors or 5165 // explicit conversion operators. 5166 bool AllowExplicit = Kind.AllowExplicit(); 5167 5168 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 5169 // The type we're converting to is a class type. Enumerate its constructors 5170 // to see if there is a suitable conversion. 5171 CXXRecordDecl *DestRecordDecl 5172 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 5173 5174 // Try to complete the type we're converting to. 5175 if (S.isCompleteType(Kind.getLocation(), DestType)) { 5176 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { 5177 auto Info = getConstructorInfo(D); 5178 if (!Info.Constructor) 5179 continue; 5180 5181 if (!Info.Constructor->isInvalidDecl() && 5182 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 5183 if (Info.ConstructorTmpl) 5184 S.AddTemplateOverloadCandidate( 5185 Info.ConstructorTmpl, Info.FoundDecl, 5186 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 5187 /*SuppressUserConversions=*/true, 5188 /*PartialOverloading*/ false, AllowExplicit); 5189 else 5190 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 5191 Initializer, CandidateSet, 5192 /*SuppressUserConversions=*/true, 5193 /*PartialOverloading*/ false, AllowExplicit); 5194 } 5195 } 5196 } 5197 } 5198 5199 SourceLocation DeclLoc = Initializer->getBeginLoc(); 5200 5201 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 5202 // The type we're converting from is a class type, enumerate its conversion 5203 // functions. 5204 5205 // We can only enumerate the conversion functions for a complete type; if 5206 // the type isn't complete, simply skip this step. 5207 if (S.isCompleteType(DeclLoc, SourceType)) { 5208 CXXRecordDecl *SourceRecordDecl 5209 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 5210 5211 const auto &Conversions = 5212 SourceRecordDecl->getVisibleConversionFunctions(); 5213 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5214 NamedDecl *D = *I; 5215 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 5216 if (isa<UsingShadowDecl>(D)) 5217 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5218 5219 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5220 CXXConversionDecl *Conv; 5221 if (ConvTemplate) 5222 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5223 else 5224 Conv = cast<CXXConversionDecl>(D); 5225 5226 if (ConvTemplate) 5227 S.AddTemplateConversionCandidate( 5228 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 5229 CandidateSet, AllowExplicit, AllowExplicit); 5230 else 5231 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 5232 DestType, CandidateSet, AllowExplicit, 5233 AllowExplicit); 5234 } 5235 } 5236 } 5237 5238 // Perform overload resolution. If it fails, return the failed result. 5239 OverloadCandidateSet::iterator Best; 5240 if (OverloadingResult Result 5241 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 5242 Sequence.SetOverloadFailure( 5243 InitializationSequence::FK_UserConversionOverloadFailed, 5244 Result); 5245 return; 5246 } 5247 5248 FunctionDecl *Function = Best->Function; 5249 Function->setReferenced(); 5250 bool HadMultipleCandidates = (CandidateSet.size() > 1); 5251 5252 if (isa<CXXConstructorDecl>(Function)) { 5253 // Add the user-defined conversion step. Any cv-qualification conversion is 5254 // subsumed by the initialization. Per DR5, the created temporary is of the 5255 // cv-unqualified type of the destination. 5256 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 5257 DestType.getUnqualifiedType(), 5258 HadMultipleCandidates); 5259 5260 // C++14 and before: 5261 // - if the function is a constructor, the call initializes a temporary 5262 // of the cv-unqualified version of the destination type. The [...] 5263 // temporary [...] is then used to direct-initialize, according to the 5264 // rules above, the object that is the destination of the 5265 // copy-initialization. 5266 // Note that this just performs a simple object copy from the temporary. 5267 // 5268 // C++17: 5269 // - if the function is a constructor, the call is a prvalue of the 5270 // cv-unqualified version of the destination type whose return object 5271 // is initialized by the constructor. The call is used to 5272 // direct-initialize, according to the rules above, the object that 5273 // is the destination of the copy-initialization. 5274 // Therefore we need to do nothing further. 5275 // 5276 // FIXME: Mark this copy as extraneous. 5277 if (!S.getLangOpts().CPlusPlus17) 5278 Sequence.AddFinalCopy(DestType); 5279 else if (DestType.hasQualifiers()) 5280 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5281 return; 5282 } 5283 5284 // Add the user-defined conversion step that calls the conversion function. 5285 QualType ConvType = Function->getCallResultType(); 5286 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 5287 HadMultipleCandidates); 5288 5289 if (ConvType->getAs<RecordType>()) { 5290 // The call is used to direct-initialize [...] the object that is the 5291 // destination of the copy-initialization. 5292 // 5293 // In C++17, this does not call a constructor if we enter /17.6.1: 5294 // - If the initializer expression is a prvalue and the cv-unqualified 5295 // version of the source type is the same as the class of the 5296 // destination [... do not make an extra copy] 5297 // 5298 // FIXME: Mark this copy as extraneous. 5299 if (!S.getLangOpts().CPlusPlus17 || 5300 Function->getReturnType()->isReferenceType() || 5301 !S.Context.hasSameUnqualifiedType(ConvType, DestType)) 5302 Sequence.AddFinalCopy(DestType); 5303 else if (!S.Context.hasSameType(ConvType, DestType)) 5304 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5305 return; 5306 } 5307 5308 // If the conversion following the call to the conversion function 5309 // is interesting, add it as a separate step. 5310 if (Best->FinalConversion.First || Best->FinalConversion.Second || 5311 Best->FinalConversion.Third) { 5312 ImplicitConversionSequence ICS; 5313 ICS.setStandard(); 5314 ICS.Standard = Best->FinalConversion; 5315 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5316 } 5317 } 5318 5319 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, 5320 /// a function with a pointer return type contains a 'return false;' statement. 5321 /// In C++11, 'false' is not a null pointer, so this breaks the build of any 5322 /// code using that header. 5323 /// 5324 /// Work around this by treating 'return false;' as zero-initializing the result 5325 /// if it's used in a pointer-returning function in a system header. 5326 static bool isLibstdcxxPointerReturnFalseHack(Sema &S, 5327 const InitializedEntity &Entity, 5328 const Expr *Init) { 5329 return S.getLangOpts().CPlusPlus11 && 5330 Entity.getKind() == InitializedEntity::EK_Result && 5331 Entity.getType()->isPointerType() && 5332 isa<CXXBoolLiteralExpr>(Init) && 5333 !cast<CXXBoolLiteralExpr>(Init)->getValue() && 5334 S.getSourceManager().isInSystemHeader(Init->getExprLoc()); 5335 } 5336 5337 /// The non-zero enum values here are indexes into diagnostic alternatives. 5338 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 5339 5340 /// Determines whether this expression is an acceptable ICR source. 5341 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 5342 bool isAddressOf, bool &isWeakAccess) { 5343 // Skip parens. 5344 e = e->IgnoreParens(); 5345 5346 // Skip address-of nodes. 5347 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 5348 if (op->getOpcode() == UO_AddrOf) 5349 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, 5350 isWeakAccess); 5351 5352 // Skip certain casts. 5353 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 5354 switch (ce->getCastKind()) { 5355 case CK_Dependent: 5356 case CK_BitCast: 5357 case CK_LValueBitCast: 5358 case CK_NoOp: 5359 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); 5360 5361 case CK_ArrayToPointerDecay: 5362 return IIK_nonscalar; 5363 5364 case CK_NullToPointer: 5365 return IIK_okay; 5366 5367 default: 5368 break; 5369 } 5370 5371 // If we have a declaration reference, it had better be a local variable. 5372 } else if (isa<DeclRefExpr>(e)) { 5373 // set isWeakAccess to true, to mean that there will be an implicit 5374 // load which requires a cleanup. 5375 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 5376 isWeakAccess = true; 5377 5378 if (!isAddressOf) return IIK_nonlocal; 5379 5380 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 5381 if (!var) return IIK_nonlocal; 5382 5383 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 5384 5385 // If we have a conditional operator, check both sides. 5386 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 5387 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, 5388 isWeakAccess)) 5389 return iik; 5390 5391 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); 5392 5393 // These are never scalar. 5394 } else if (isa<ArraySubscriptExpr>(e)) { 5395 return IIK_nonscalar; 5396 5397 // Otherwise, it needs to be a null pointer constant. 5398 } else { 5399 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 5400 ? IIK_okay : IIK_nonlocal); 5401 } 5402 5403 return IIK_nonlocal; 5404 } 5405 5406 /// Check whether the given expression is a valid operand for an 5407 /// indirect copy/restore. 5408 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 5409 assert(src->isRValue()); 5410 bool isWeakAccess = false; 5411 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); 5412 // If isWeakAccess to true, there will be an implicit 5413 // load which requires a cleanup. 5414 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) 5415 S.Cleanup.setExprNeedsCleanups(true); 5416 5417 if (iik == IIK_okay) return; 5418 5419 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 5420 << ((unsigned) iik - 1) // shift index into diagnostic explanations 5421 << src->getSourceRange(); 5422 } 5423 5424 /// Determine whether we have compatible array types for the 5425 /// purposes of GNU by-copy array initialization. 5426 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, 5427 const ArrayType *Source) { 5428 // If the source and destination array types are equivalent, we're 5429 // done. 5430 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 5431 return true; 5432 5433 // Make sure that the element types are the same. 5434 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 5435 return false; 5436 5437 // The only mismatch we allow is when the destination is an 5438 // incomplete array type and the source is a constant array type. 5439 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 5440 } 5441 5442 static bool tryObjCWritebackConversion(Sema &S, 5443 InitializationSequence &Sequence, 5444 const InitializedEntity &Entity, 5445 Expr *Initializer) { 5446 bool ArrayDecay = false; 5447 QualType ArgType = Initializer->getType(); 5448 QualType ArgPointee; 5449 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 5450 ArrayDecay = true; 5451 ArgPointee = ArgArrayType->getElementType(); 5452 ArgType = S.Context.getPointerType(ArgPointee); 5453 } 5454 5455 // Handle write-back conversion. 5456 QualType ConvertedArgType; 5457 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 5458 ConvertedArgType)) 5459 return false; 5460 5461 // We should copy unless we're passing to an argument explicitly 5462 // marked 'out'. 5463 bool ShouldCopy = true; 5464 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5465 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5466 5467 // Do we need an lvalue conversion? 5468 if (ArrayDecay || Initializer->isGLValue()) { 5469 ImplicitConversionSequence ICS; 5470 ICS.setStandard(); 5471 ICS.Standard.setAsIdentityConversion(); 5472 5473 QualType ResultType; 5474 if (ArrayDecay) { 5475 ICS.Standard.First = ICK_Array_To_Pointer; 5476 ResultType = S.Context.getPointerType(ArgPointee); 5477 } else { 5478 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 5479 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 5480 } 5481 5482 Sequence.AddConversionSequenceStep(ICS, ResultType); 5483 } 5484 5485 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 5486 return true; 5487 } 5488 5489 static bool TryOCLSamplerInitialization(Sema &S, 5490 InitializationSequence &Sequence, 5491 QualType DestType, 5492 Expr *Initializer) { 5493 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || 5494 (!Initializer->isIntegerConstantExpr(S.Context) && 5495 !Initializer->getType()->isSamplerT())) 5496 return false; 5497 5498 Sequence.AddOCLSamplerInitStep(DestType); 5499 return true; 5500 } 5501 5502 static bool IsZeroInitializer(Expr *Initializer, Sema &S) { 5503 return Initializer->isIntegerConstantExpr(S.getASTContext()) && 5504 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); 5505 } 5506 5507 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, 5508 InitializationSequence &Sequence, 5509 QualType DestType, 5510 Expr *Initializer) { 5511 if (!S.getLangOpts().OpenCL) 5512 return false; 5513 5514 // 5515 // OpenCL 1.2 spec, s6.12.10 5516 // 5517 // The event argument can also be used to associate the 5518 // async_work_group_copy with a previous async copy allowing 5519 // an event to be shared by multiple async copies; otherwise 5520 // event should be zero. 5521 // 5522 if (DestType->isEventT() || DestType->isQueueT()) { 5523 if (!IsZeroInitializer(Initializer, S)) 5524 return false; 5525 5526 Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5527 return true; 5528 } 5529 5530 // We should allow zero initialization for all types defined in the 5531 // cl_intel_device_side_avc_motion_estimation extension, except 5532 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. 5533 if (S.getOpenCLOptions().isEnabled( 5534 "cl_intel_device_side_avc_motion_estimation") && 5535 DestType->isOCLIntelSubgroupAVCType()) { 5536 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || 5537 DestType->isOCLIntelSubgroupAVCMceResultType()) 5538 return false; 5539 if (!IsZeroInitializer(Initializer, S)) 5540 return false; 5541 5542 Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5543 return true; 5544 } 5545 5546 return false; 5547 } 5548 5549 InitializationSequence::InitializationSequence(Sema &S, 5550 const InitializedEntity &Entity, 5551 const InitializationKind &Kind, 5552 MultiExprArg Args, 5553 bool TopLevelOfInitList, 5554 bool TreatUnavailableAsInvalid) 5555 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { 5556 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, 5557 TreatUnavailableAsInvalid); 5558 } 5559 5560 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the 5561 /// address of that function, this returns true. Otherwise, it returns false. 5562 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { 5563 auto *DRE = dyn_cast<DeclRefExpr>(E); 5564 if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) 5565 return false; 5566 5567 return !S.checkAddressOfFunctionIsAvailable( 5568 cast<FunctionDecl>(DRE->getDecl())); 5569 } 5570 5571 /// Determine whether we can perform an elementwise array copy for this kind 5572 /// of entity. 5573 static bool canPerformArrayCopy(const InitializedEntity &Entity) { 5574 switch (Entity.getKind()) { 5575 case InitializedEntity::EK_LambdaCapture: 5576 // C++ [expr.prim.lambda]p24: 5577 // For array members, the array elements are direct-initialized in 5578 // increasing subscript order. 5579 return true; 5580 5581 case InitializedEntity::EK_Variable: 5582 // C++ [dcl.decomp]p1: 5583 // [...] each element is copy-initialized or direct-initialized from the 5584 // corresponding element of the assignment-expression [...] 5585 return isa<DecompositionDecl>(Entity.getDecl()); 5586 5587 case InitializedEntity::EK_Member: 5588 // C++ [class.copy.ctor]p14: 5589 // - if the member is an array, each element is direct-initialized with 5590 // the corresponding subobject of x 5591 return Entity.isImplicitMemberInitializer(); 5592 5593 case InitializedEntity::EK_ArrayElement: 5594 // All the above cases are intended to apply recursively, even though none 5595 // of them actually say that. 5596 if (auto *E = Entity.getParent()) 5597 return canPerformArrayCopy(*E); 5598 break; 5599 5600 default: 5601 break; 5602 } 5603 5604 return false; 5605 } 5606 5607 void InitializationSequence::InitializeFrom(Sema &S, 5608 const InitializedEntity &Entity, 5609 const InitializationKind &Kind, 5610 MultiExprArg Args, 5611 bool TopLevelOfInitList, 5612 bool TreatUnavailableAsInvalid) { 5613 ASTContext &Context = S.Context; 5614 5615 // Eliminate non-overload placeholder types in the arguments. We 5616 // need to do this before checking whether types are dependent 5617 // because lowering a pseudo-object expression might well give us 5618 // something of dependent type. 5619 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5620 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 5621 // FIXME: should we be doing this here? 5622 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 5623 if (result.isInvalid()) { 5624 SetFailed(FK_PlaceholderType); 5625 return; 5626 } 5627 Args[I] = result.get(); 5628 } 5629 5630 // C++0x [dcl.init]p16: 5631 // The semantics of initializers are as follows. The destination type is 5632 // the type of the object or reference being initialized and the source 5633 // type is the type of the initializer expression. The source type is not 5634 // defined when the initializer is a braced-init-list or when it is a 5635 // parenthesized list of expressions. 5636 QualType DestType = Entity.getType(); 5637 5638 if (DestType->isDependentType() || 5639 Expr::hasAnyTypeDependentArguments(Args)) { 5640 SequenceKind = DependentSequence; 5641 return; 5642 } 5643 5644 // Almost everything is a normal sequence. 5645 setSequenceKind(NormalSequence); 5646 5647 QualType SourceType; 5648 Expr *Initializer = nullptr; 5649 if (Args.size() == 1) { 5650 Initializer = Args[0]; 5651 if (S.getLangOpts().ObjC) { 5652 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), 5653 DestType, Initializer->getType(), 5654 Initializer) || 5655 S.CheckConversionToObjCLiteral(DestType, Initializer)) 5656 Args[0] = Initializer; 5657 } 5658 if (!isa<InitListExpr>(Initializer)) 5659 SourceType = Initializer->getType(); 5660 } 5661 5662 // - If the initializer is a (non-parenthesized) braced-init-list, the 5663 // object is list-initialized (8.5.4). 5664 if (Kind.getKind() != InitializationKind::IK_Direct) { 5665 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 5666 TryListInitialization(S, Entity, Kind, InitList, *this, 5667 TreatUnavailableAsInvalid); 5668 return; 5669 } 5670 } 5671 5672 // - If the destination type is a reference type, see 8.5.3. 5673 if (DestType->isReferenceType()) { 5674 // C++0x [dcl.init.ref]p1: 5675 // A variable declared to be a T& or T&&, that is, "reference to type T" 5676 // (8.3.2), shall be initialized by an object, or function, of type T or 5677 // by an object that can be converted into a T. 5678 // (Therefore, multiple arguments are not permitted.) 5679 if (Args.size() != 1) 5680 SetFailed(FK_TooManyInitsForReference); 5681 // C++17 [dcl.init.ref]p5: 5682 // A reference [...] is initialized by an expression [...] as follows: 5683 // If the initializer is not an expression, presumably we should reject, 5684 // but the standard fails to actually say so. 5685 else if (isa<InitListExpr>(Args[0])) 5686 SetFailed(FK_ParenthesizedListInitForReference); 5687 else 5688 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 5689 return; 5690 } 5691 5692 // - If the initializer is (), the object is value-initialized. 5693 if (Kind.getKind() == InitializationKind::IK_Value || 5694 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 5695 TryValueInitialization(S, Entity, Kind, *this); 5696 return; 5697 } 5698 5699 // Handle default initialization. 5700 if (Kind.getKind() == InitializationKind::IK_Default) { 5701 TryDefaultInitialization(S, Entity, Kind, *this); 5702 return; 5703 } 5704 5705 // - If the destination type is an array of characters, an array of 5706 // char16_t, an array of char32_t, or an array of wchar_t, and the 5707 // initializer is a string literal, see 8.5.2. 5708 // - Otherwise, if the destination type is an array, the program is 5709 // ill-formed. 5710 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 5711 if (Initializer && isa<VariableArrayType>(DestAT)) { 5712 SetFailed(FK_VariableLengthArrayHasInitializer); 5713 return; 5714 } 5715 5716 if (Initializer) { 5717 switch (IsStringInit(Initializer, DestAT, Context)) { 5718 case SIF_None: 5719 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 5720 return; 5721 case SIF_NarrowStringIntoWideChar: 5722 SetFailed(FK_NarrowStringIntoWideCharArray); 5723 return; 5724 case SIF_WideStringIntoChar: 5725 SetFailed(FK_WideStringIntoCharArray); 5726 return; 5727 case SIF_IncompatWideStringIntoWideChar: 5728 SetFailed(FK_IncompatWideStringIntoWideChar); 5729 return; 5730 case SIF_PlainStringIntoUTF8Char: 5731 SetFailed(FK_PlainStringIntoUTF8Char); 5732 return; 5733 case SIF_UTF8StringIntoPlainChar: 5734 SetFailed(FK_UTF8StringIntoPlainChar); 5735 return; 5736 case SIF_Other: 5737 break; 5738 } 5739 } 5740 5741 // Some kinds of initialization permit an array to be initialized from 5742 // another array of the same type, and perform elementwise initialization. 5743 if (Initializer && isa<ConstantArrayType>(DestAT) && 5744 S.Context.hasSameUnqualifiedType(Initializer->getType(), 5745 Entity.getType()) && 5746 canPerformArrayCopy(Entity)) { 5747 // If source is a prvalue, use it directly. 5748 if (Initializer->getValueKind() == VK_RValue) { 5749 AddArrayInitStep(DestType, /*IsGNUExtension*/false); 5750 return; 5751 } 5752 5753 // Emit element-at-a-time copy loop. 5754 InitializedEntity Element = 5755 InitializedEntity::InitializeElement(S.Context, 0, Entity); 5756 QualType InitEltT = 5757 Context.getAsArrayType(Initializer->getType())->getElementType(); 5758 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, 5759 Initializer->getValueKind(), 5760 Initializer->getObjectKind()); 5761 Expr *OVEAsExpr = &OVE; 5762 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, 5763 TreatUnavailableAsInvalid); 5764 if (!Failed()) 5765 AddArrayInitLoopStep(Entity.getType(), InitEltT); 5766 return; 5767 } 5768 5769 // Note: as an GNU C extension, we allow initialization of an 5770 // array from a compound literal that creates an array of the same 5771 // type, so long as the initializer has no side effects. 5772 if (!S.getLangOpts().CPlusPlus && Initializer && 5773 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 5774 Initializer->getType()->isArrayType()) { 5775 const ArrayType *SourceAT 5776 = Context.getAsArrayType(Initializer->getType()); 5777 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 5778 SetFailed(FK_ArrayTypeMismatch); 5779 else if (Initializer->HasSideEffects(S.Context)) 5780 SetFailed(FK_NonConstantArrayInit); 5781 else { 5782 AddArrayInitStep(DestType, /*IsGNUExtension*/true); 5783 } 5784 } 5785 // Note: as a GNU C++ extension, we allow list-initialization of a 5786 // class member of array type from a parenthesized initializer list. 5787 else if (S.getLangOpts().CPlusPlus && 5788 Entity.getKind() == InitializedEntity::EK_Member && 5789 Initializer && isa<InitListExpr>(Initializer)) { 5790 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 5791 *this, TreatUnavailableAsInvalid); 5792 AddParenthesizedArrayInitStep(DestType); 5793 } else if (DestAT->getElementType()->isCharType()) 5794 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 5795 else if (IsWideCharCompatible(DestAT->getElementType(), Context)) 5796 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); 5797 else 5798 SetFailed(FK_ArrayNeedsInitList); 5799 5800 return; 5801 } 5802 5803 // Determine whether we should consider writeback conversions for 5804 // Objective-C ARC. 5805 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 5806 Entity.isParameterKind(); 5807 5808 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 5809 return; 5810 5811 // We're at the end of the line for C: it's either a write-back conversion 5812 // or it's a C assignment. There's no need to check anything else. 5813 if (!S.getLangOpts().CPlusPlus) { 5814 // If allowed, check whether this is an Objective-C writeback conversion. 5815 if (allowObjCWritebackConversion && 5816 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 5817 return; 5818 } 5819 5820 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) 5821 return; 5822 5823 // Handle initialization in C 5824 AddCAssignmentStep(DestType); 5825 MaybeProduceObjCObject(S, *this, Entity); 5826 return; 5827 } 5828 5829 assert(S.getLangOpts().CPlusPlus); 5830 5831 // - If the destination type is a (possibly cv-qualified) class type: 5832 if (DestType->isRecordType()) { 5833 // - If the initialization is direct-initialization, or if it is 5834 // copy-initialization where the cv-unqualified version of the 5835 // source type is the same class as, or a derived class of, the 5836 // class of the destination, constructors are considered. [...] 5837 if (Kind.getKind() == InitializationKind::IK_Direct || 5838 (Kind.getKind() == InitializationKind::IK_Copy && 5839 (Context.hasSameUnqualifiedType(SourceType, DestType) || 5840 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) 5841 TryConstructorInitialization(S, Entity, Kind, Args, 5842 DestType, DestType, *this); 5843 // - Otherwise (i.e., for the remaining copy-initialization cases), 5844 // user-defined conversion sequences that can convert from the source 5845 // type to the destination type or (when a conversion function is 5846 // used) to a derived class thereof are enumerated as described in 5847 // 13.3.1.4, and the best one is chosen through overload resolution 5848 // (13.3). 5849 else 5850 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5851 TopLevelOfInitList); 5852 return; 5853 } 5854 5855 assert(Args.size() >= 1 && "Zero-argument case handled above"); 5856 5857 // The remaining cases all need a source type. 5858 if (Args.size() > 1) { 5859 SetFailed(FK_TooManyInitsForScalar); 5860 return; 5861 } else if (isa<InitListExpr>(Args[0])) { 5862 SetFailed(FK_ParenthesizedListInitForScalar); 5863 return; 5864 } 5865 5866 // - Otherwise, if the source type is a (possibly cv-qualified) class 5867 // type, conversion functions are considered. 5868 if (!SourceType.isNull() && SourceType->isRecordType()) { 5869 // For a conversion to _Atomic(T) from either T or a class type derived 5870 // from T, initialize the T object then convert to _Atomic type. 5871 bool NeedAtomicConversion = false; 5872 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { 5873 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || 5874 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, 5875 Atomic->getValueType())) { 5876 DestType = Atomic->getValueType(); 5877 NeedAtomicConversion = true; 5878 } 5879 } 5880 5881 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5882 TopLevelOfInitList); 5883 MaybeProduceObjCObject(S, *this, Entity); 5884 if (!Failed() && NeedAtomicConversion) 5885 AddAtomicConversionStep(Entity.getType()); 5886 return; 5887 } 5888 5889 // - Otherwise, if the initialization is direct-initialization, the source 5890 // type is std::nullptr_t, and the destination type is bool, the initial 5891 // value of the object being initialized is false. 5892 if (!SourceType.isNull() && SourceType->isNullPtrType() && 5893 DestType->isBooleanType() && 5894 Kind.getKind() == InitializationKind::IK_Direct) { 5895 AddConversionSequenceStep( 5896 ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, 5897 Initializer->isGLValue()), 5898 DestType); 5899 return; 5900 } 5901 5902 // - Otherwise, the initial value of the object being initialized is the 5903 // (possibly converted) value of the initializer expression. Standard 5904 // conversions (Clause 4) will be used, if necessary, to convert the 5905 // initializer expression to the cv-unqualified version of the 5906 // destination type; no user-defined conversions are considered. 5907 5908 ImplicitConversionSequence ICS 5909 = S.TryImplicitConversion(Initializer, DestType, 5910 /*SuppressUserConversions*/true, 5911 Sema::AllowedExplicit::None, 5912 /*InOverloadResolution*/ false, 5913 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5914 allowObjCWritebackConversion); 5915 5916 if (ICS.isStandard() && 5917 ICS.Standard.Second == ICK_Writeback_Conversion) { 5918 // Objective-C ARC writeback conversion. 5919 5920 // We should copy unless we're passing to an argument explicitly 5921 // marked 'out'. 5922 bool ShouldCopy = true; 5923 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5924 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5925 5926 // If there was an lvalue adjustment, add it as a separate conversion. 5927 if (ICS.Standard.First == ICK_Array_To_Pointer || 5928 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5929 ImplicitConversionSequence LvalueICS; 5930 LvalueICS.setStandard(); 5931 LvalueICS.Standard.setAsIdentityConversion(); 5932 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 5933 LvalueICS.Standard.First = ICS.Standard.First; 5934 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 5935 } 5936 5937 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); 5938 } else if (ICS.isBad()) { 5939 DeclAccessPair dap; 5940 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { 5941 AddZeroInitializationStep(Entity.getType()); 5942 } else if (Initializer->getType() == Context.OverloadTy && 5943 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, 5944 false, dap)) 5945 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 5946 else if (Initializer->getType()->isFunctionType() && 5947 isExprAnUnaddressableFunction(S, Initializer)) 5948 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); 5949 else 5950 SetFailed(InitializationSequence::FK_ConversionFailed); 5951 } else { 5952 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5953 5954 MaybeProduceObjCObject(S, *this, Entity); 5955 } 5956 } 5957 5958 InitializationSequence::~InitializationSequence() { 5959 for (auto &S : Steps) 5960 S.Destroy(); 5961 } 5962 5963 //===----------------------------------------------------------------------===// 5964 // Perform initialization 5965 //===----------------------------------------------------------------------===// 5966 static Sema::AssignmentAction 5967 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { 5968 switch(Entity.getKind()) { 5969 case InitializedEntity::EK_Variable: 5970 case InitializedEntity::EK_New: 5971 case InitializedEntity::EK_Exception: 5972 case InitializedEntity::EK_Base: 5973 case InitializedEntity::EK_Delegating: 5974 return Sema::AA_Initializing; 5975 5976 case InitializedEntity::EK_Parameter: 5977 if (Entity.getDecl() && 5978 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5979 return Sema::AA_Sending; 5980 5981 return Sema::AA_Passing; 5982 5983 case InitializedEntity::EK_Parameter_CF_Audited: 5984 if (Entity.getDecl() && 5985 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5986 return Sema::AA_Sending; 5987 5988 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; 5989 5990 case InitializedEntity::EK_Result: 5991 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. 5992 return Sema::AA_Returning; 5993 5994 case InitializedEntity::EK_Temporary: 5995 case InitializedEntity::EK_RelatedResult: 5996 // FIXME: Can we tell apart casting vs. converting? 5997 return Sema::AA_Casting; 5998 5999 case InitializedEntity::EK_Member: 6000 case InitializedEntity::EK_Binding: 6001 case InitializedEntity::EK_ArrayElement: 6002 case InitializedEntity::EK_VectorElement: 6003 case InitializedEntity::EK_ComplexElement: 6004 case InitializedEntity::EK_BlockElement: 6005 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6006 case InitializedEntity::EK_LambdaCapture: 6007 case InitializedEntity::EK_CompoundLiteralInit: 6008 return Sema::AA_Initializing; 6009 } 6010 6011 llvm_unreachable("Invalid EntityKind!"); 6012 } 6013 6014 /// Whether we should bind a created object as a temporary when 6015 /// initializing the given entity. 6016 static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 6017 switch (Entity.getKind()) { 6018 case InitializedEntity::EK_ArrayElement: 6019 case InitializedEntity::EK_Member: 6020 case InitializedEntity::EK_Result: 6021 case InitializedEntity::EK_StmtExprResult: 6022 case InitializedEntity::EK_New: 6023 case InitializedEntity::EK_Variable: 6024 case InitializedEntity::EK_Base: 6025 case InitializedEntity::EK_Delegating: 6026 case InitializedEntity::EK_VectorElement: 6027 case InitializedEntity::EK_ComplexElement: 6028 case InitializedEntity::EK_Exception: 6029 case InitializedEntity::EK_BlockElement: 6030 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6031 case InitializedEntity::EK_LambdaCapture: 6032 case InitializedEntity::EK_CompoundLiteralInit: 6033 return false; 6034 6035 case InitializedEntity::EK_Parameter: 6036 case InitializedEntity::EK_Parameter_CF_Audited: 6037 case InitializedEntity::EK_Temporary: 6038 case InitializedEntity::EK_RelatedResult: 6039 case InitializedEntity::EK_Binding: 6040 return true; 6041 } 6042 6043 llvm_unreachable("missed an InitializedEntity kind?"); 6044 } 6045 6046 /// Whether the given entity, when initialized with an object 6047 /// created for that initialization, requires destruction. 6048 static bool shouldDestroyEntity(const InitializedEntity &Entity) { 6049 switch (Entity.getKind()) { 6050 case InitializedEntity::EK_Result: 6051 case InitializedEntity::EK_StmtExprResult: 6052 case InitializedEntity::EK_New: 6053 case InitializedEntity::EK_Base: 6054 case InitializedEntity::EK_Delegating: 6055 case InitializedEntity::EK_VectorElement: 6056 case InitializedEntity::EK_ComplexElement: 6057 case InitializedEntity::EK_BlockElement: 6058 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6059 case InitializedEntity::EK_LambdaCapture: 6060 return false; 6061 6062 case InitializedEntity::EK_Member: 6063 case InitializedEntity::EK_Binding: 6064 case InitializedEntity::EK_Variable: 6065 case InitializedEntity::EK_Parameter: 6066 case InitializedEntity::EK_Parameter_CF_Audited: 6067 case InitializedEntity::EK_Temporary: 6068 case InitializedEntity::EK_ArrayElement: 6069 case InitializedEntity::EK_Exception: 6070 case InitializedEntity::EK_CompoundLiteralInit: 6071 case InitializedEntity::EK_RelatedResult: 6072 return true; 6073 } 6074 6075 llvm_unreachable("missed an InitializedEntity kind?"); 6076 } 6077 6078 /// Get the location at which initialization diagnostics should appear. 6079 static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 6080 Expr *Initializer) { 6081 switch (Entity.getKind()) { 6082 case InitializedEntity::EK_Result: 6083 case InitializedEntity::EK_StmtExprResult: 6084 return Entity.getReturnLoc(); 6085 6086 case InitializedEntity::EK_Exception: 6087 return Entity.getThrowLoc(); 6088 6089 case InitializedEntity::EK_Variable: 6090 case InitializedEntity::EK_Binding: 6091 return Entity.getDecl()->getLocation(); 6092 6093 case InitializedEntity::EK_LambdaCapture: 6094 return Entity.getCaptureLoc(); 6095 6096 case InitializedEntity::EK_ArrayElement: 6097 case InitializedEntity::EK_Member: 6098 case InitializedEntity::EK_Parameter: 6099 case InitializedEntity::EK_Parameter_CF_Audited: 6100 case InitializedEntity::EK_Temporary: 6101 case InitializedEntity::EK_New: 6102 case InitializedEntity::EK_Base: 6103 case InitializedEntity::EK_Delegating: 6104 case InitializedEntity::EK_VectorElement: 6105 case InitializedEntity::EK_ComplexElement: 6106 case InitializedEntity::EK_BlockElement: 6107 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6108 case InitializedEntity::EK_CompoundLiteralInit: 6109 case InitializedEntity::EK_RelatedResult: 6110 return Initializer->getBeginLoc(); 6111 } 6112 llvm_unreachable("missed an InitializedEntity kind?"); 6113 } 6114 6115 /// Make a (potentially elidable) temporary copy of the object 6116 /// provided by the given initializer by calling the appropriate copy 6117 /// constructor. 6118 /// 6119 /// \param S The Sema object used for type-checking. 6120 /// 6121 /// \param T The type of the temporary object, which must either be 6122 /// the type of the initializer expression or a superclass thereof. 6123 /// 6124 /// \param Entity The entity being initialized. 6125 /// 6126 /// \param CurInit The initializer expression. 6127 /// 6128 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that 6129 /// is permitted in C++03 (but not C++0x) when binding a reference to 6130 /// an rvalue. 6131 /// 6132 /// \returns An expression that copies the initializer expression into 6133 /// a temporary object, or an error expression if a copy could not be 6134 /// created. 6135 static ExprResult CopyObject(Sema &S, 6136 QualType T, 6137 const InitializedEntity &Entity, 6138 ExprResult CurInit, 6139 bool IsExtraneousCopy) { 6140 if (CurInit.isInvalid()) 6141 return CurInit; 6142 // Determine which class type we're copying to. 6143 Expr *CurInitExpr = (Expr *)CurInit.get(); 6144 CXXRecordDecl *Class = nullptr; 6145 if (const RecordType *Record = T->getAs<RecordType>()) 6146 Class = cast<CXXRecordDecl>(Record->getDecl()); 6147 if (!Class) 6148 return CurInit; 6149 6150 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 6151 6152 // Make sure that the type we are copying is complete. 6153 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 6154 return CurInit; 6155 6156 // Perform overload resolution using the class's constructors. Per 6157 // C++11 [dcl.init]p16, second bullet for class types, this initialization 6158 // is direct-initialization. 6159 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6160 DeclContext::lookup_result Ctors = S.LookupConstructors(Class); 6161 6162 OverloadCandidateSet::iterator Best; 6163 switch (ResolveConstructorOverload( 6164 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, 6165 /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6166 /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6167 /*SecondStepOfCopyInit=*/true)) { 6168 case OR_Success: 6169 break; 6170 6171 case OR_No_Viable_Function: 6172 CandidateSet.NoteCandidates( 6173 PartialDiagnosticAt( 6174 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() 6175 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 6176 : diag::err_temp_copy_no_viable) 6177 << (int)Entity.getKind() << CurInitExpr->getType() 6178 << CurInitExpr->getSourceRange()), 6179 S, OCD_AllCandidates, CurInitExpr); 6180 if (!IsExtraneousCopy || S.isSFINAEContext()) 6181 return ExprError(); 6182 return CurInit; 6183 6184 case OR_Ambiguous: 6185 CandidateSet.NoteCandidates( 6186 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) 6187 << (int)Entity.getKind() 6188 << CurInitExpr->getType() 6189 << CurInitExpr->getSourceRange()), 6190 S, OCD_AmbiguousCandidates, CurInitExpr); 6191 return ExprError(); 6192 6193 case OR_Deleted: 6194 S.Diag(Loc, diag::err_temp_copy_deleted) 6195 << (int)Entity.getKind() << CurInitExpr->getType() 6196 << CurInitExpr->getSourceRange(); 6197 S.NoteDeletedFunction(Best->Function); 6198 return ExprError(); 6199 } 6200 6201 bool HadMultipleCandidates = CandidateSet.size() > 1; 6202 6203 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 6204 SmallVector<Expr*, 8> ConstructorArgs; 6205 CurInit.get(); // Ownership transferred into MultiExprArg, below. 6206 6207 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, 6208 IsExtraneousCopy); 6209 6210 if (IsExtraneousCopy) { 6211 // If this is a totally extraneous copy for C++03 reference 6212 // binding purposes, just return the original initialization 6213 // expression. We don't generate an (elided) copy operation here 6214 // because doing so would require us to pass down a flag to avoid 6215 // infinite recursion, where each step adds another extraneous, 6216 // elidable copy. 6217 6218 // Instantiate the default arguments of any extra parameters in 6219 // the selected copy constructor, as if we were going to create a 6220 // proper call to the copy constructor. 6221 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 6222 ParmVarDecl *Parm = Constructor->getParamDecl(I); 6223 if (S.RequireCompleteType(Loc, Parm->getType(), 6224 diag::err_call_incomplete_argument)) 6225 break; 6226 6227 // Build the default argument expression; we don't actually care 6228 // if this succeeds or not, because this routine will complain 6229 // if there was a problem. 6230 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 6231 } 6232 6233 return CurInitExpr; 6234 } 6235 6236 // Determine the arguments required to actually perform the 6237 // constructor call (we might have derived-to-base conversions, or 6238 // the copy constructor may have default arguments). 6239 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) 6240 return ExprError(); 6241 6242 // C++0x [class.copy]p32: 6243 // When certain criteria are met, an implementation is allowed to 6244 // omit the copy/move construction of a class object, even if the 6245 // copy/move constructor and/or destructor for the object have 6246 // side effects. [...] 6247 // - when a temporary class object that has not been bound to a 6248 // reference (12.2) would be copied/moved to a class object 6249 // with the same cv-unqualified type, the copy/move operation 6250 // can be omitted by constructing the temporary object 6251 // directly into the target of the omitted copy/move 6252 // 6253 // Note that the other three bullets are handled elsewhere. Copy 6254 // elision for return statements and throw expressions are handled as part 6255 // of constructor initialization, while copy elision for exception handlers 6256 // is handled by the run-time. 6257 // 6258 // FIXME: If the function parameter is not the same type as the temporary, we 6259 // should still be able to elide the copy, but we don't have a way to 6260 // represent in the AST how much should be elided in this case. 6261 bool Elidable = 6262 CurInitExpr->isTemporaryObject(S.Context, Class) && 6263 S.Context.hasSameUnqualifiedType( 6264 Best->Function->getParamDecl(0)->getType().getNonReferenceType(), 6265 CurInitExpr->getType()); 6266 6267 // Actually perform the constructor call. 6268 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, 6269 Elidable, 6270 ConstructorArgs, 6271 HadMultipleCandidates, 6272 /*ListInit*/ false, 6273 /*StdInitListInit*/ false, 6274 /*ZeroInit*/ false, 6275 CXXConstructExpr::CK_Complete, 6276 SourceRange()); 6277 6278 // If we're supposed to bind temporaries, do so. 6279 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 6280 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 6281 return CurInit; 6282 } 6283 6284 /// Check whether elidable copy construction for binding a reference to 6285 /// a temporary would have succeeded if we were building in C++98 mode, for 6286 /// -Wc++98-compat. 6287 static void CheckCXX98CompatAccessibleCopy(Sema &S, 6288 const InitializedEntity &Entity, 6289 Expr *CurInitExpr) { 6290 assert(S.getLangOpts().CPlusPlus11); 6291 6292 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 6293 if (!Record) 6294 return; 6295 6296 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 6297 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) 6298 return; 6299 6300 // Find constructors which would have been considered. 6301 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6302 DeclContext::lookup_result Ctors = 6303 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); 6304 6305 // Perform overload resolution. 6306 OverloadCandidateSet::iterator Best; 6307 OverloadingResult OR = ResolveConstructorOverload( 6308 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, 6309 /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6310 /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6311 /*SecondStepOfCopyInit=*/true); 6312 6313 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 6314 << OR << (int)Entity.getKind() << CurInitExpr->getType() 6315 << CurInitExpr->getSourceRange(); 6316 6317 switch (OR) { 6318 case OR_Success: 6319 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 6320 Best->FoundDecl, Entity, Diag); 6321 // FIXME: Check default arguments as far as that's possible. 6322 break; 6323 6324 case OR_No_Viable_Function: 6325 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6326 OCD_AllCandidates, CurInitExpr); 6327 break; 6328 6329 case OR_Ambiguous: 6330 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6331 OCD_AmbiguousCandidates, CurInitExpr); 6332 break; 6333 6334 case OR_Deleted: 6335 S.Diag(Loc, Diag); 6336 S.NoteDeletedFunction(Best->Function); 6337 break; 6338 } 6339 } 6340 6341 void InitializationSequence::PrintInitLocationNote(Sema &S, 6342 const InitializedEntity &Entity) { 6343 if (Entity.isParameterKind() && Entity.getDecl()) { 6344 if (Entity.getDecl()->getLocation().isInvalid()) 6345 return; 6346 6347 if (Entity.getDecl()->getDeclName()) 6348 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 6349 << Entity.getDecl()->getDeclName(); 6350 else 6351 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 6352 } 6353 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && 6354 Entity.getMethodDecl()) 6355 S.Diag(Entity.getMethodDecl()->getLocation(), 6356 diag::note_method_return_type_change) 6357 << Entity.getMethodDecl()->getDeclName(); 6358 } 6359 6360 /// Returns true if the parameters describe a constructor initialization of 6361 /// an explicit temporary object, e.g. "Point(x, y)". 6362 static bool isExplicitTemporary(const InitializedEntity &Entity, 6363 const InitializationKind &Kind, 6364 unsigned NumArgs) { 6365 switch (Entity.getKind()) { 6366 case InitializedEntity::EK_Temporary: 6367 case InitializedEntity::EK_CompoundLiteralInit: 6368 case InitializedEntity::EK_RelatedResult: 6369 break; 6370 default: 6371 return false; 6372 } 6373 6374 switch (Kind.getKind()) { 6375 case InitializationKind::IK_DirectList: 6376 return true; 6377 // FIXME: Hack to work around cast weirdness. 6378 case InitializationKind::IK_Direct: 6379 case InitializationKind::IK_Value: 6380 return NumArgs != 1; 6381 default: 6382 return false; 6383 } 6384 } 6385 6386 static ExprResult 6387 PerformConstructorInitialization(Sema &S, 6388 const InitializedEntity &Entity, 6389 const InitializationKind &Kind, 6390 MultiExprArg Args, 6391 const InitializationSequence::Step& Step, 6392 bool &ConstructorInitRequiresZeroInit, 6393 bool IsListInitialization, 6394 bool IsStdInitListInitialization, 6395 SourceLocation LBraceLoc, 6396 SourceLocation RBraceLoc) { 6397 unsigned NumArgs = Args.size(); 6398 CXXConstructorDecl *Constructor 6399 = cast<CXXConstructorDecl>(Step.Function.Function); 6400 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 6401 6402 // Build a call to the selected constructor. 6403 SmallVector<Expr*, 8> ConstructorArgs; 6404 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 6405 ? Kind.getEqualLoc() 6406 : Kind.getLocation(); 6407 6408 if (Kind.getKind() == InitializationKind::IK_Default) { 6409 // Force even a trivial, implicit default constructor to be 6410 // semantically checked. We do this explicitly because we don't build 6411 // the definition for completely trivial constructors. 6412 assert(Constructor->getParent() && "No parent class for constructor."); 6413 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6414 Constructor->isTrivial() && !Constructor->isUsed(false)) { 6415 S.runWithSufficientStackSpace(Loc, [&] { 6416 S.DefineImplicitDefaultConstructor(Loc, Constructor); 6417 }); 6418 } 6419 } 6420 6421 ExprResult CurInit((Expr *)nullptr); 6422 6423 // C++ [over.match.copy]p1: 6424 // - When initializing a temporary to be bound to the first parameter 6425 // of a constructor that takes a reference to possibly cv-qualified 6426 // T as its first argument, called with a single argument in the 6427 // context of direct-initialization, explicit conversion functions 6428 // are also considered. 6429 bool AllowExplicitConv = 6430 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && 6431 hasCopyOrMoveCtorParam(S.Context, 6432 getConstructorInfo(Step.Function.FoundDecl)); 6433 6434 // Determine the arguments required to actually perform the constructor 6435 // call. 6436 if (S.CompleteConstructorCall(Constructor, Args, 6437 Loc, ConstructorArgs, 6438 AllowExplicitConv, 6439 IsListInitialization)) 6440 return ExprError(); 6441 6442 6443 if (isExplicitTemporary(Entity, Kind, NumArgs)) { 6444 // An explicitly-constructed temporary, e.g., X(1, 2). 6445 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 6446 return ExprError(); 6447 6448 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 6449 if (!TSInfo) 6450 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 6451 SourceRange ParenOrBraceRange = 6452 (Kind.getKind() == InitializationKind::IK_DirectList) 6453 ? SourceRange(LBraceLoc, RBraceLoc) 6454 : Kind.getParenOrBraceRange(); 6455 6456 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( 6457 Step.Function.FoundDecl.getDecl())) { 6458 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow); 6459 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 6460 return ExprError(); 6461 } 6462 S.MarkFunctionReferenced(Loc, Constructor); 6463 6464 CurInit = S.CheckForImmediateInvocation( 6465 CXXTemporaryObjectExpr::Create( 6466 S.Context, Constructor, 6467 Entity.getType().getNonLValueExprType(S.Context), TSInfo, 6468 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, 6469 IsListInitialization, IsStdInitListInitialization, 6470 ConstructorInitRequiresZeroInit), 6471 Constructor); 6472 } else { 6473 CXXConstructExpr::ConstructionKind ConstructKind = 6474 CXXConstructExpr::CK_Complete; 6475 6476 if (Entity.getKind() == InitializedEntity::EK_Base) { 6477 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 6478 CXXConstructExpr::CK_VirtualBase : 6479 CXXConstructExpr::CK_NonVirtualBase; 6480 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 6481 ConstructKind = CXXConstructExpr::CK_Delegating; 6482 } 6483 6484 // Only get the parenthesis or brace range if it is a list initialization or 6485 // direct construction. 6486 SourceRange ParenOrBraceRange; 6487 if (IsListInitialization) 6488 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); 6489 else if (Kind.getKind() == InitializationKind::IK_Direct) 6490 ParenOrBraceRange = Kind.getParenOrBraceRange(); 6491 6492 // If the entity allows NRVO, mark the construction as elidable 6493 // unconditionally. 6494 if (Entity.allowsNRVO()) 6495 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6496 Step.Function.FoundDecl, 6497 Constructor, /*Elidable=*/true, 6498 ConstructorArgs, 6499 HadMultipleCandidates, 6500 IsListInitialization, 6501 IsStdInitListInitialization, 6502 ConstructorInitRequiresZeroInit, 6503 ConstructKind, 6504 ParenOrBraceRange); 6505 else 6506 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6507 Step.Function.FoundDecl, 6508 Constructor, 6509 ConstructorArgs, 6510 HadMultipleCandidates, 6511 IsListInitialization, 6512 IsStdInitListInitialization, 6513 ConstructorInitRequiresZeroInit, 6514 ConstructKind, 6515 ParenOrBraceRange); 6516 } 6517 if (CurInit.isInvalid()) 6518 return ExprError(); 6519 6520 // Only check access if all of that succeeded. 6521 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); 6522 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 6523 return ExprError(); 6524 6525 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) 6526 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) 6527 return ExprError(); 6528 6529 if (shouldBindAsTemporary(Entity)) 6530 CurInit = S.MaybeBindToTemporary(CurInit.get()); 6531 6532 return CurInit; 6533 } 6534 6535 namespace { 6536 enum LifetimeKind { 6537 /// The lifetime of a temporary bound to this entity ends at the end of the 6538 /// full-expression, and that's (probably) fine. 6539 LK_FullExpression, 6540 6541 /// The lifetime of a temporary bound to this entity is extended to the 6542 /// lifeitme of the entity itself. 6543 LK_Extended, 6544 6545 /// The lifetime of a temporary bound to this entity probably ends too soon, 6546 /// because the entity is allocated in a new-expression. 6547 LK_New, 6548 6549 /// The lifetime of a temporary bound to this entity ends too soon, because 6550 /// the entity is a return object. 6551 LK_Return, 6552 6553 /// The lifetime of a temporary bound to this entity ends too soon, because 6554 /// the entity is the result of a statement expression. 6555 LK_StmtExprResult, 6556 6557 /// This is a mem-initializer: if it would extend a temporary (other than via 6558 /// a default member initializer), the program is ill-formed. 6559 LK_MemInitializer, 6560 }; 6561 using LifetimeResult = 6562 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; 6563 } 6564 6565 /// Determine the declaration which an initialized entity ultimately refers to, 6566 /// for the purpose of lifetime-extending a temporary bound to a reference in 6567 /// the initialization of \p Entity. 6568 static LifetimeResult getEntityLifetime( 6569 const InitializedEntity *Entity, 6570 const InitializedEntity *InitField = nullptr) { 6571 // C++11 [class.temporary]p5: 6572 switch (Entity->getKind()) { 6573 case InitializedEntity::EK_Variable: 6574 // The temporary [...] persists for the lifetime of the reference 6575 return {Entity, LK_Extended}; 6576 6577 case InitializedEntity::EK_Member: 6578 // For subobjects, we look at the complete object. 6579 if (Entity->getParent()) 6580 return getEntityLifetime(Entity->getParent(), Entity); 6581 6582 // except: 6583 // C++17 [class.base.init]p8: 6584 // A temporary expression bound to a reference member in a 6585 // mem-initializer is ill-formed. 6586 // C++17 [class.base.init]p11: 6587 // A temporary expression bound to a reference member from a 6588 // default member initializer is ill-formed. 6589 // 6590 // The context of p11 and its example suggest that it's only the use of a 6591 // default member initializer from a constructor that makes the program 6592 // ill-formed, not its mere existence, and that it can even be used by 6593 // aggregate initialization. 6594 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended 6595 : LK_MemInitializer}; 6596 6597 case InitializedEntity::EK_Binding: 6598 // Per [dcl.decomp]p3, the binding is treated as a variable of reference 6599 // type. 6600 return {Entity, LK_Extended}; 6601 6602 case InitializedEntity::EK_Parameter: 6603 case InitializedEntity::EK_Parameter_CF_Audited: 6604 // -- A temporary bound to a reference parameter in a function call 6605 // persists until the completion of the full-expression containing 6606 // the call. 6607 return {nullptr, LK_FullExpression}; 6608 6609 case InitializedEntity::EK_Result: 6610 // -- The lifetime of a temporary bound to the returned value in a 6611 // function return statement is not extended; the temporary is 6612 // destroyed at the end of the full-expression in the return statement. 6613 return {nullptr, LK_Return}; 6614 6615 case InitializedEntity::EK_StmtExprResult: 6616 // FIXME: Should we lifetime-extend through the result of a statement 6617 // expression? 6618 return {nullptr, LK_StmtExprResult}; 6619 6620 case InitializedEntity::EK_New: 6621 // -- A temporary bound to a reference in a new-initializer persists 6622 // until the completion of the full-expression containing the 6623 // new-initializer. 6624 return {nullptr, LK_New}; 6625 6626 case InitializedEntity::EK_Temporary: 6627 case InitializedEntity::EK_CompoundLiteralInit: 6628 case InitializedEntity::EK_RelatedResult: 6629 // We don't yet know the storage duration of the surrounding temporary. 6630 // Assume it's got full-expression duration for now, it will patch up our 6631 // storage duration if that's not correct. 6632 return {nullptr, LK_FullExpression}; 6633 6634 case InitializedEntity::EK_ArrayElement: 6635 // For subobjects, we look at the complete object. 6636 return getEntityLifetime(Entity->getParent(), InitField); 6637 6638 case InitializedEntity::EK_Base: 6639 // For subobjects, we look at the complete object. 6640 if (Entity->getParent()) 6641 return getEntityLifetime(Entity->getParent(), InitField); 6642 return {InitField, LK_MemInitializer}; 6643 6644 case InitializedEntity::EK_Delegating: 6645 // We can reach this case for aggregate initialization in a constructor: 6646 // struct A { int &&r; }; 6647 // struct B : A { B() : A{0} {} }; 6648 // In this case, use the outermost field decl as the context. 6649 return {InitField, LK_MemInitializer}; 6650 6651 case InitializedEntity::EK_BlockElement: 6652 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6653 case InitializedEntity::EK_LambdaCapture: 6654 case InitializedEntity::EK_VectorElement: 6655 case InitializedEntity::EK_ComplexElement: 6656 return {nullptr, LK_FullExpression}; 6657 6658 case InitializedEntity::EK_Exception: 6659 // FIXME: Can we diagnose lifetime problems with exceptions? 6660 return {nullptr, LK_FullExpression}; 6661 } 6662 llvm_unreachable("unknown entity kind"); 6663 } 6664 6665 namespace { 6666 enum ReferenceKind { 6667 /// Lifetime would be extended by a reference binding to a temporary. 6668 RK_ReferenceBinding, 6669 /// Lifetime would be extended by a std::initializer_list object binding to 6670 /// its backing array. 6671 RK_StdInitializerList, 6672 }; 6673 6674 /// A temporary or local variable. This will be one of: 6675 /// * A MaterializeTemporaryExpr. 6676 /// * A DeclRefExpr whose declaration is a local. 6677 /// * An AddrLabelExpr. 6678 /// * A BlockExpr for a block with captures. 6679 using Local = Expr*; 6680 6681 /// Expressions we stepped over when looking for the local state. Any steps 6682 /// that would inhibit lifetime extension or take us out of subexpressions of 6683 /// the initializer are included. 6684 struct IndirectLocalPathEntry { 6685 enum EntryKind { 6686 DefaultInit, 6687 AddressOf, 6688 VarInit, 6689 LValToRVal, 6690 LifetimeBoundCall, 6691 GslReferenceInit, 6692 GslPointerInit 6693 } Kind; 6694 Expr *E; 6695 const Decl *D = nullptr; 6696 IndirectLocalPathEntry() {} 6697 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} 6698 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) 6699 : Kind(K), E(E), D(D) {} 6700 }; 6701 6702 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; 6703 6704 struct RevertToOldSizeRAII { 6705 IndirectLocalPath &Path; 6706 unsigned OldSize = Path.size(); 6707 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} 6708 ~RevertToOldSizeRAII() { Path.resize(OldSize); } 6709 }; 6710 6711 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, 6712 ReferenceKind RK)>; 6713 } 6714 6715 static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { 6716 for (auto E : Path) 6717 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) 6718 return true; 6719 return false; 6720 } 6721 6722 static bool pathContainsInit(IndirectLocalPath &Path) { 6723 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { 6724 return E.Kind == IndirectLocalPathEntry::DefaultInit || 6725 E.Kind == IndirectLocalPathEntry::VarInit; 6726 }); 6727 } 6728 6729 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 6730 Expr *Init, LocalVisitor Visit, 6731 bool RevisitSubinits, 6732 bool EnableLifetimeWarnings); 6733 6734 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 6735 Expr *Init, ReferenceKind RK, 6736 LocalVisitor Visit, 6737 bool EnableLifetimeWarnings); 6738 6739 template <typename T> static bool isRecordWithAttr(QualType Type) { 6740 if (auto *RD = Type->getAsCXXRecordDecl()) 6741 return RD->hasAttr<T>(); 6742 return false; 6743 } 6744 6745 // Decl::isInStdNamespace will return false for iterators in some STL 6746 // implementations due to them being defined in a namespace outside of the std 6747 // namespace. 6748 static bool isInStlNamespace(const Decl *D) { 6749 const DeclContext *DC = D->getDeclContext(); 6750 if (!DC) 6751 return false; 6752 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) 6753 if (const IdentifierInfo *II = ND->getIdentifier()) { 6754 StringRef Name = II->getName(); 6755 if (Name.size() >= 2 && Name.front() == '_' && 6756 (Name[1] == '_' || isUppercase(Name[1]))) 6757 return true; 6758 } 6759 6760 return DC->isStdNamespace(); 6761 } 6762 6763 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { 6764 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) 6765 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) 6766 return true; 6767 if (!isInStlNamespace(Callee->getParent())) 6768 return false; 6769 if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && 6770 !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) 6771 return false; 6772 if (Callee->getReturnType()->isPointerType() || 6773 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { 6774 if (!Callee->getIdentifier()) 6775 return false; 6776 return llvm::StringSwitch<bool>(Callee->getName()) 6777 .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6778 .Cases("end", "rend", "cend", "crend", true) 6779 .Cases("c_str", "data", "get", true) 6780 // Map and set types. 6781 .Cases("find", "equal_range", "lower_bound", "upper_bound", true) 6782 .Default(false); 6783 } else if (Callee->getReturnType()->isReferenceType()) { 6784 if (!Callee->getIdentifier()) { 6785 auto OO = Callee->getOverloadedOperator(); 6786 return OO == OverloadedOperatorKind::OO_Subscript || 6787 OO == OverloadedOperatorKind::OO_Star; 6788 } 6789 return llvm::StringSwitch<bool>(Callee->getName()) 6790 .Cases("front", "back", "at", "top", "value", true) 6791 .Default(false); 6792 } 6793 return false; 6794 } 6795 6796 static bool shouldTrackFirstArgument(const FunctionDecl *FD) { 6797 if (!FD->getIdentifier() || FD->getNumParams() != 1) 6798 return false; 6799 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); 6800 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) 6801 return false; 6802 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && 6803 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) 6804 return false; 6805 if (FD->getReturnType()->isPointerType() || 6806 isRecordWithAttr<PointerAttr>(FD->getReturnType())) { 6807 return llvm::StringSwitch<bool>(FD->getName()) 6808 .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6809 .Cases("end", "rend", "cend", "crend", true) 6810 .Case("data", true) 6811 .Default(false); 6812 } else if (FD->getReturnType()->isReferenceType()) { 6813 return llvm::StringSwitch<bool>(FD->getName()) 6814 .Cases("get", "any_cast", true) 6815 .Default(false); 6816 } 6817 return false; 6818 } 6819 6820 static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, 6821 LocalVisitor Visit) { 6822 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { 6823 // We are not interested in the temporary base objects of gsl Pointers: 6824 // Temp().ptr; // Here ptr might not dangle. 6825 if (isa<MemberExpr>(Arg->IgnoreImpCasts())) 6826 return; 6827 // Once we initialized a value with a reference, it can no longer dangle. 6828 if (!Value) { 6829 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 6830 if (It->Kind == IndirectLocalPathEntry::GslReferenceInit) 6831 continue; 6832 if (It->Kind == IndirectLocalPathEntry::GslPointerInit) 6833 return; 6834 break; 6835 } 6836 } 6837 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit 6838 : IndirectLocalPathEntry::GslReferenceInit, 6839 Arg, D}); 6840 if (Arg->isGLValue()) 6841 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 6842 Visit, 6843 /*EnableLifetimeWarnings=*/true); 6844 else 6845 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 6846 /*EnableLifetimeWarnings=*/true); 6847 Path.pop_back(); 6848 }; 6849 6850 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 6851 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); 6852 if (MD && shouldTrackImplicitObjectArg(MD)) 6853 VisitPointerArg(MD, MCE->getImplicitObjectArgument(), 6854 !MD->getReturnType()->isReferenceType()); 6855 return; 6856 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { 6857 FunctionDecl *Callee = OCE->getDirectCallee(); 6858 if (Callee && Callee->isCXXInstanceMember() && 6859 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) 6860 VisitPointerArg(Callee, OCE->getArg(0), 6861 !Callee->getReturnType()->isReferenceType()); 6862 return; 6863 } else if (auto *CE = dyn_cast<CallExpr>(Call)) { 6864 FunctionDecl *Callee = CE->getDirectCallee(); 6865 if (Callee && shouldTrackFirstArgument(Callee)) 6866 VisitPointerArg(Callee, CE->getArg(0), 6867 !Callee->getReturnType()->isReferenceType()); 6868 return; 6869 } 6870 6871 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { 6872 const auto *Ctor = CCE->getConstructor(); 6873 const CXXRecordDecl *RD = Ctor->getParent(); 6874 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) 6875 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); 6876 } 6877 } 6878 6879 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { 6880 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6881 if (!TSI) 6882 return false; 6883 // Don't declare this variable in the second operand of the for-statement; 6884 // GCC miscompiles that by ending its lifetime before evaluating the 6885 // third operand. See gcc.gnu.org/PR86769. 6886 AttributedTypeLoc ATL; 6887 for (TypeLoc TL = TSI->getTypeLoc(); 6888 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6889 TL = ATL.getModifiedLoc()) { 6890 if (ATL.getAttrAs<LifetimeBoundAttr>()) 6891 return true; 6892 } 6893 return false; 6894 } 6895 6896 static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, 6897 LocalVisitor Visit) { 6898 const FunctionDecl *Callee; 6899 ArrayRef<Expr*> Args; 6900 6901 if (auto *CE = dyn_cast<CallExpr>(Call)) { 6902 Callee = CE->getDirectCallee(); 6903 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); 6904 } else { 6905 auto *CCE = cast<CXXConstructExpr>(Call); 6906 Callee = CCE->getConstructor(); 6907 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); 6908 } 6909 if (!Callee) 6910 return; 6911 6912 Expr *ObjectArg = nullptr; 6913 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { 6914 ObjectArg = Args[0]; 6915 Args = Args.slice(1); 6916 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 6917 ObjectArg = MCE->getImplicitObjectArgument(); 6918 } 6919 6920 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { 6921 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); 6922 if (Arg->isGLValue()) 6923 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 6924 Visit, 6925 /*EnableLifetimeWarnings=*/false); 6926 else 6927 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 6928 /*EnableLifetimeWarnings=*/false); 6929 Path.pop_back(); 6930 }; 6931 6932 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) 6933 VisitLifetimeBoundArg(Callee, ObjectArg); 6934 6935 for (unsigned I = 0, 6936 N = std::min<unsigned>(Callee->getNumParams(), Args.size()); 6937 I != N; ++I) { 6938 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) 6939 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); 6940 } 6941 } 6942 6943 /// Visit the locals that would be reachable through a reference bound to the 6944 /// glvalue expression \c Init. 6945 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 6946 Expr *Init, ReferenceKind RK, 6947 LocalVisitor Visit, 6948 bool EnableLifetimeWarnings) { 6949 RevertToOldSizeRAII RAII(Path); 6950 6951 // Walk past any constructs which we can lifetime-extend across. 6952 Expr *Old; 6953 do { 6954 Old = Init; 6955 6956 if (auto *FE = dyn_cast<FullExpr>(Init)) 6957 Init = FE->getSubExpr(); 6958 6959 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 6960 // If this is just redundant braces around an initializer, step over it. 6961 if (ILE->isTransparent()) 6962 Init = ILE->getInit(0); 6963 } 6964 6965 // Step over any subobject adjustments; we may have a materialized 6966 // temporary inside them. 6967 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 6968 6969 // Per current approach for DR1376, look through casts to reference type 6970 // when performing lifetime extension. 6971 if (CastExpr *CE = dyn_cast<CastExpr>(Init)) 6972 if (CE->getSubExpr()->isGLValue()) 6973 Init = CE->getSubExpr(); 6974 6975 // Per the current approach for DR1299, look through array element access 6976 // on array glvalues when performing lifetime extension. 6977 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { 6978 Init = ASE->getBase(); 6979 auto *ICE = dyn_cast<ImplicitCastExpr>(Init); 6980 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) 6981 Init = ICE->getSubExpr(); 6982 else 6983 // We can't lifetime extend through this but we might still find some 6984 // retained temporaries. 6985 return visitLocalsRetainedByInitializer(Path, Init, Visit, true, 6986 EnableLifetimeWarnings); 6987 } 6988 6989 // Step into CXXDefaultInitExprs so we can diagnose cases where a 6990 // constructor inherits one as an implicit mem-initializer. 6991 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 6992 Path.push_back( 6993 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 6994 Init = DIE->getExpr(); 6995 } 6996 } while (Init != Old); 6997 6998 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { 6999 if (Visit(Path, Local(MTE), RK)) 7000 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, 7001 EnableLifetimeWarnings); 7002 } 7003 7004 if (isa<CallExpr>(Init)) { 7005 if (EnableLifetimeWarnings) 7006 handleGslAnnotatedTypes(Path, Init, Visit); 7007 return visitLifetimeBoundArguments(Path, Init, Visit); 7008 } 7009 7010 switch (Init->getStmtClass()) { 7011 case Stmt::DeclRefExprClass: { 7012 // If we find the name of a local non-reference parameter, we could have a 7013 // lifetime problem. 7014 auto *DRE = cast<DeclRefExpr>(Init); 7015 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7016 if (VD && VD->hasLocalStorage() && 7017 !DRE->refersToEnclosingVariableOrCapture()) { 7018 if (!VD->getType()->isReferenceType()) { 7019 Visit(Path, Local(DRE), RK); 7020 } else if (isa<ParmVarDecl>(DRE->getDecl())) { 7021 // The lifetime of a reference parameter is unknown; assume it's OK 7022 // for now. 7023 break; 7024 } else if (VD->getInit() && !isVarOnPath(Path, VD)) { 7025 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7026 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), 7027 RK_ReferenceBinding, Visit, 7028 EnableLifetimeWarnings); 7029 } 7030 } 7031 break; 7032 } 7033 7034 case Stmt::UnaryOperatorClass: { 7035 // The only unary operator that make sense to handle here 7036 // is Deref. All others don't resolve to a "name." This includes 7037 // handling all sorts of rvalues passed to a unary operator. 7038 const UnaryOperator *U = cast<UnaryOperator>(Init); 7039 if (U->getOpcode() == UO_Deref) 7040 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, 7041 EnableLifetimeWarnings); 7042 break; 7043 } 7044 7045 case Stmt::OMPArraySectionExprClass: { 7046 visitLocalsRetainedByInitializer(Path, 7047 cast<OMPArraySectionExpr>(Init)->getBase(), 7048 Visit, true, EnableLifetimeWarnings); 7049 break; 7050 } 7051 7052 case Stmt::ConditionalOperatorClass: 7053 case Stmt::BinaryConditionalOperatorClass: { 7054 auto *C = cast<AbstractConditionalOperator>(Init); 7055 if (!C->getTrueExpr()->getType()->isVoidType()) 7056 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, 7057 EnableLifetimeWarnings); 7058 if (!C->getFalseExpr()->getType()->isVoidType()) 7059 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, 7060 EnableLifetimeWarnings); 7061 break; 7062 } 7063 7064 // FIXME: Visit the left-hand side of an -> or ->*. 7065 7066 default: 7067 break; 7068 } 7069 } 7070 7071 /// Visit the locals that would be reachable through an object initialized by 7072 /// the prvalue expression \c Init. 7073 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 7074 Expr *Init, LocalVisitor Visit, 7075 bool RevisitSubinits, 7076 bool EnableLifetimeWarnings) { 7077 RevertToOldSizeRAII RAII(Path); 7078 7079 Expr *Old; 7080 do { 7081 Old = Init; 7082 7083 // Step into CXXDefaultInitExprs so we can diagnose cases where a 7084 // constructor inherits one as an implicit mem-initializer. 7085 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 7086 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 7087 Init = DIE->getExpr(); 7088 } 7089 7090 if (auto *FE = dyn_cast<FullExpr>(Init)) 7091 Init = FE->getSubExpr(); 7092 7093 // Dig out the expression which constructs the extended temporary. 7094 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 7095 7096 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) 7097 Init = BTE->getSubExpr(); 7098 7099 Init = Init->IgnoreParens(); 7100 7101 // Step over value-preserving rvalue casts. 7102 if (auto *CE = dyn_cast<CastExpr>(Init)) { 7103 switch (CE->getCastKind()) { 7104 case CK_LValueToRValue: 7105 // If we can match the lvalue to a const object, we can look at its 7106 // initializer. 7107 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); 7108 return visitLocalsRetainedByReferenceBinding( 7109 Path, Init, RK_ReferenceBinding, 7110 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { 7111 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7112 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7113 if (VD && VD->getType().isConstQualified() && VD->getInit() && 7114 !isVarOnPath(Path, VD)) { 7115 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7116 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, 7117 EnableLifetimeWarnings); 7118 } 7119 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { 7120 if (MTE->getType().isConstQualified()) 7121 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, 7122 true, EnableLifetimeWarnings); 7123 } 7124 return false; 7125 }, EnableLifetimeWarnings); 7126 7127 // We assume that objects can be retained by pointers cast to integers, 7128 // but not if the integer is cast to floating-point type or to _Complex. 7129 // We assume that casts to 'bool' do not preserve enough information to 7130 // retain a local object. 7131 case CK_NoOp: 7132 case CK_BitCast: 7133 case CK_BaseToDerived: 7134 case CK_DerivedToBase: 7135 case CK_UncheckedDerivedToBase: 7136 case CK_Dynamic: 7137 case CK_ToUnion: 7138 case CK_UserDefinedConversion: 7139 case CK_ConstructorConversion: 7140 case CK_IntegralToPointer: 7141 case CK_PointerToIntegral: 7142 case CK_VectorSplat: 7143 case CK_IntegralCast: 7144 case CK_CPointerToObjCPointerCast: 7145 case CK_BlockPointerToObjCPointerCast: 7146 case CK_AnyPointerToBlockPointerCast: 7147 case CK_AddressSpaceConversion: 7148 break; 7149 7150 case CK_ArrayToPointerDecay: 7151 // Model array-to-pointer decay as taking the address of the array 7152 // lvalue. 7153 Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); 7154 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), 7155 RK_ReferenceBinding, Visit, 7156 EnableLifetimeWarnings); 7157 7158 default: 7159 return; 7160 } 7161 7162 Init = CE->getSubExpr(); 7163 } 7164 } while (Old != Init); 7165 7166 // C++17 [dcl.init.list]p6: 7167 // initializing an initializer_list object from the array extends the 7168 // lifetime of the array exactly like binding a reference to a temporary. 7169 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) 7170 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), 7171 RK_StdInitializerList, Visit, 7172 EnableLifetimeWarnings); 7173 7174 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 7175 // We already visited the elements of this initializer list while 7176 // performing the initialization. Don't visit them again unless we've 7177 // changed the lifetime of the initialized entity. 7178 if (!RevisitSubinits) 7179 return; 7180 7181 if (ILE->isTransparent()) 7182 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, 7183 RevisitSubinits, 7184 EnableLifetimeWarnings); 7185 7186 if (ILE->getType()->isArrayType()) { 7187 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) 7188 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, 7189 RevisitSubinits, 7190 EnableLifetimeWarnings); 7191 return; 7192 } 7193 7194 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { 7195 assert(RD->isAggregate() && "aggregate init on non-aggregate"); 7196 7197 // If we lifetime-extend a braced initializer which is initializing an 7198 // aggregate, and that aggregate contains reference members which are 7199 // bound to temporaries, those temporaries are also lifetime-extended. 7200 if (RD->isUnion() && ILE->getInitializedFieldInUnion() && 7201 ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) 7202 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), 7203 RK_ReferenceBinding, Visit, 7204 EnableLifetimeWarnings); 7205 else { 7206 unsigned Index = 0; 7207 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) 7208 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, 7209 RevisitSubinits, 7210 EnableLifetimeWarnings); 7211 for (const auto *I : RD->fields()) { 7212 if (Index >= ILE->getNumInits()) 7213 break; 7214 if (I->isUnnamedBitfield()) 7215 continue; 7216 Expr *SubInit = ILE->getInit(Index); 7217 if (I->getType()->isReferenceType()) 7218 visitLocalsRetainedByReferenceBinding(Path, SubInit, 7219 RK_ReferenceBinding, Visit, 7220 EnableLifetimeWarnings); 7221 else 7222 // This might be either aggregate-initialization of a member or 7223 // initialization of a std::initializer_list object. Regardless, 7224 // we should recursively lifetime-extend that initializer. 7225 visitLocalsRetainedByInitializer(Path, SubInit, Visit, 7226 RevisitSubinits, 7227 EnableLifetimeWarnings); 7228 ++Index; 7229 } 7230 } 7231 } 7232 return; 7233 } 7234 7235 // The lifetime of an init-capture is that of the closure object constructed 7236 // by a lambda-expression. 7237 if (auto *LE = dyn_cast<LambdaExpr>(Init)) { 7238 for (Expr *E : LE->capture_inits()) { 7239 if (!E) 7240 continue; 7241 if (E->isGLValue()) 7242 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, 7243 Visit, EnableLifetimeWarnings); 7244 else 7245 visitLocalsRetainedByInitializer(Path, E, Visit, true, 7246 EnableLifetimeWarnings); 7247 } 7248 } 7249 7250 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { 7251 if (EnableLifetimeWarnings) 7252 handleGslAnnotatedTypes(Path, Init, Visit); 7253 return visitLifetimeBoundArguments(Path, Init, Visit); 7254 } 7255 7256 switch (Init->getStmtClass()) { 7257 case Stmt::UnaryOperatorClass: { 7258 auto *UO = cast<UnaryOperator>(Init); 7259 // If the initializer is the address of a local, we could have a lifetime 7260 // problem. 7261 if (UO->getOpcode() == UO_AddrOf) { 7262 // If this is &rvalue, then it's ill-formed and we have already diagnosed 7263 // it. Don't produce a redundant warning about the lifetime of the 7264 // temporary. 7265 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) 7266 return; 7267 7268 Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); 7269 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), 7270 RK_ReferenceBinding, Visit, 7271 EnableLifetimeWarnings); 7272 } 7273 break; 7274 } 7275 7276 case Stmt::BinaryOperatorClass: { 7277 // Handle pointer arithmetic. 7278 auto *BO = cast<BinaryOperator>(Init); 7279 BinaryOperatorKind BOK = BO->getOpcode(); 7280 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) 7281 break; 7282 7283 if (BO->getLHS()->getType()->isPointerType()) 7284 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, 7285 EnableLifetimeWarnings); 7286 else if (BO->getRHS()->getType()->isPointerType()) 7287 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, 7288 EnableLifetimeWarnings); 7289 break; 7290 } 7291 7292 case Stmt::ConditionalOperatorClass: 7293 case Stmt::BinaryConditionalOperatorClass: { 7294 auto *C = cast<AbstractConditionalOperator>(Init); 7295 // In C++, we can have a throw-expression operand, which has 'void' type 7296 // and isn't interesting from a lifetime perspective. 7297 if (!C->getTrueExpr()->getType()->isVoidType()) 7298 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, 7299 EnableLifetimeWarnings); 7300 if (!C->getFalseExpr()->getType()->isVoidType()) 7301 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, 7302 EnableLifetimeWarnings); 7303 break; 7304 } 7305 7306 case Stmt::BlockExprClass: 7307 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { 7308 // This is a local block, whose lifetime is that of the function. 7309 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); 7310 } 7311 break; 7312 7313 case Stmt::AddrLabelExprClass: 7314 // We want to warn if the address of a label would escape the function. 7315 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); 7316 break; 7317 7318 default: 7319 break; 7320 } 7321 } 7322 7323 /// Determine whether this is an indirect path to a temporary that we are 7324 /// supposed to lifetime-extend along (but don't). 7325 static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { 7326 for (auto Elem : Path) { 7327 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit) 7328 return false; 7329 } 7330 return true; 7331 } 7332 7333 /// Find the range for the first interesting entry in the path at or after I. 7334 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, 7335 Expr *E) { 7336 for (unsigned N = Path.size(); I != N; ++I) { 7337 switch (Path[I].Kind) { 7338 case IndirectLocalPathEntry::AddressOf: 7339 case IndirectLocalPathEntry::LValToRVal: 7340 case IndirectLocalPathEntry::LifetimeBoundCall: 7341 case IndirectLocalPathEntry::GslReferenceInit: 7342 case IndirectLocalPathEntry::GslPointerInit: 7343 // These exist primarily to mark the path as not permitting or 7344 // supporting lifetime extension. 7345 break; 7346 7347 case IndirectLocalPathEntry::VarInit: 7348 if (cast<VarDecl>(Path[I].D)->isImplicit()) 7349 return SourceRange(); 7350 LLVM_FALLTHROUGH; 7351 case IndirectLocalPathEntry::DefaultInit: 7352 return Path[I].E->getSourceRange(); 7353 } 7354 } 7355 return E->getSourceRange(); 7356 } 7357 7358 static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { 7359 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 7360 if (It->Kind == IndirectLocalPathEntry::VarInit) 7361 continue; 7362 if (It->Kind == IndirectLocalPathEntry::AddressOf) 7363 continue; 7364 return It->Kind == IndirectLocalPathEntry::GslPointerInit || 7365 It->Kind == IndirectLocalPathEntry::GslReferenceInit; 7366 } 7367 return false; 7368 } 7369 7370 void Sema::checkInitializerLifetime(const InitializedEntity &Entity, 7371 Expr *Init) { 7372 LifetimeResult LR = getEntityLifetime(&Entity); 7373 LifetimeKind LK = LR.getInt(); 7374 const InitializedEntity *ExtendingEntity = LR.getPointer(); 7375 7376 // If this entity doesn't have an interesting lifetime, don't bother looking 7377 // for temporaries within its initializer. 7378 if (LK == LK_FullExpression) 7379 return; 7380 7381 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, 7382 ReferenceKind RK) -> bool { 7383 SourceRange DiagRange = nextPathEntryRange(Path, 0, L); 7384 SourceLocation DiagLoc = DiagRange.getBegin(); 7385 7386 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); 7387 7388 bool IsGslPtrInitWithGslTempOwner = false; 7389 bool IsLocalGslOwner = false; 7390 if (pathOnlyInitializesGslPointer(Path)) { 7391 if (isa<DeclRefExpr>(L)) { 7392 // We do not want to follow the references when returning a pointer originating 7393 // from a local owner to avoid the following false positive: 7394 // int &p = *localUniquePtr; 7395 // someContainer.add(std::move(localUniquePtr)); 7396 // return p; 7397 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); 7398 if (pathContainsInit(Path) || !IsLocalGslOwner) 7399 return false; 7400 } else { 7401 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && 7402 isRecordWithAttr<OwnerAttr>(MTE->getType()); 7403 // Skipping a chain of initializing gsl::Pointer annotated objects. 7404 // We are looking only for the final source to find out if it was 7405 // a local or temporary owner or the address of a local variable/param. 7406 if (!IsGslPtrInitWithGslTempOwner) 7407 return true; 7408 } 7409 } 7410 7411 switch (LK) { 7412 case LK_FullExpression: 7413 llvm_unreachable("already handled this"); 7414 7415 case LK_Extended: { 7416 if (!MTE) { 7417 // The initialized entity has lifetime beyond the full-expression, 7418 // and the local entity does too, so don't warn. 7419 // 7420 // FIXME: We should consider warning if a static / thread storage 7421 // duration variable retains an automatic storage duration local. 7422 return false; 7423 } 7424 7425 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { 7426 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; 7427 return false; 7428 } 7429 7430 // Lifetime-extend the temporary. 7431 if (Path.empty()) { 7432 // Update the storage duration of the materialized temporary. 7433 // FIXME: Rebuild the expression instead of mutating it. 7434 MTE->setExtendingDecl(ExtendingEntity->getDecl(), 7435 ExtendingEntity->allocateManglingNumber()); 7436 // Also visit the temporaries lifetime-extended by this initializer. 7437 return true; 7438 } 7439 7440 if (shouldLifetimeExtendThroughPath(Path)) { 7441 // We're supposed to lifetime-extend the temporary along this path (per 7442 // the resolution of DR1815), but we don't support that yet. 7443 // 7444 // FIXME: Properly handle this situation. Perhaps the easiest approach 7445 // would be to clone the initializer expression on each use that would 7446 // lifetime extend its temporaries. 7447 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) 7448 << RK << DiagRange; 7449 } else { 7450 // If the path goes through the initialization of a variable or field, 7451 // it can't possibly reach a temporary created in this full-expression. 7452 // We will have already diagnosed any problems with the initializer. 7453 if (pathContainsInit(Path)) 7454 return false; 7455 7456 Diag(DiagLoc, diag::warn_dangling_variable) 7457 << RK << !Entity.getParent() 7458 << ExtendingEntity->getDecl()->isImplicit() 7459 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; 7460 } 7461 break; 7462 } 7463 7464 case LK_MemInitializer: { 7465 if (isa<MaterializeTemporaryExpr>(L)) { 7466 // Under C++ DR1696, if a mem-initializer (or a default member 7467 // initializer used by the absence of one) would lifetime-extend a 7468 // temporary, the program is ill-formed. 7469 if (auto *ExtendingDecl = 7470 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { 7471 if (IsGslPtrInitWithGslTempOwner) { 7472 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) 7473 << ExtendingDecl << DiagRange; 7474 Diag(ExtendingDecl->getLocation(), 7475 diag::note_ref_or_ptr_member_declared_here) 7476 << true; 7477 return false; 7478 } 7479 bool IsSubobjectMember = ExtendingEntity != &Entity; 7480 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) 7481 ? diag::err_dangling_member 7482 : diag::warn_dangling_member) 7483 << ExtendingDecl << IsSubobjectMember << RK << DiagRange; 7484 // Don't bother adding a note pointing to the field if we're inside 7485 // its default member initializer; our primary diagnostic points to 7486 // the same place in that case. 7487 if (Path.empty() || 7488 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { 7489 Diag(ExtendingDecl->getLocation(), 7490 diag::note_lifetime_extending_member_declared_here) 7491 << RK << IsSubobjectMember; 7492 } 7493 } else { 7494 // We have a mem-initializer but no particular field within it; this 7495 // is either a base class or a delegating initializer directly 7496 // initializing the base-class from something that doesn't live long 7497 // enough. 7498 // 7499 // FIXME: Warn on this. 7500 return false; 7501 } 7502 } else { 7503 // Paths via a default initializer can only occur during error recovery 7504 // (there's no other way that a default initializer can refer to a 7505 // local). Don't produce a bogus warning on those cases. 7506 if (pathContainsInit(Path)) 7507 return false; 7508 7509 // Suppress false positives for code like the one below: 7510 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} 7511 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) 7512 return false; 7513 7514 auto *DRE = dyn_cast<DeclRefExpr>(L); 7515 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; 7516 if (!VD) { 7517 // A member was initialized to a local block. 7518 // FIXME: Warn on this. 7519 return false; 7520 } 7521 7522 if (auto *Member = 7523 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { 7524 bool IsPointer = !Member->getType()->isReferenceType(); 7525 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 7526 : diag::warn_bind_ref_member_to_parameter) 7527 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; 7528 Diag(Member->getLocation(), 7529 diag::note_ref_or_ptr_member_declared_here) 7530 << (unsigned)IsPointer; 7531 } 7532 } 7533 break; 7534 } 7535 7536 case LK_New: 7537 if (isa<MaterializeTemporaryExpr>(L)) { 7538 if (IsGslPtrInitWithGslTempOwner) 7539 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; 7540 else 7541 Diag(DiagLoc, RK == RK_ReferenceBinding 7542 ? diag::warn_new_dangling_reference 7543 : diag::warn_new_dangling_initializer_list) 7544 << !Entity.getParent() << DiagRange; 7545 } else { 7546 // We can't determine if the allocation outlives the local declaration. 7547 return false; 7548 } 7549 break; 7550 7551 case LK_Return: 7552 case LK_StmtExprResult: 7553 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7554 // We can't determine if the local variable outlives the statement 7555 // expression. 7556 if (LK == LK_StmtExprResult) 7557 return false; 7558 Diag(DiagLoc, diag::warn_ret_stack_addr_ref) 7559 << Entity.getType()->isReferenceType() << DRE->getDecl() 7560 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; 7561 } else if (isa<BlockExpr>(L)) { 7562 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; 7563 } else if (isa<AddrLabelExpr>(L)) { 7564 // Don't warn when returning a label from a statement expression. 7565 // Leaving the scope doesn't end its lifetime. 7566 if (LK == LK_StmtExprResult) 7567 return false; 7568 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; 7569 } else { 7570 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) 7571 << Entity.getType()->isReferenceType() << DiagRange; 7572 } 7573 break; 7574 } 7575 7576 for (unsigned I = 0; I != Path.size(); ++I) { 7577 auto Elem = Path[I]; 7578 7579 switch (Elem.Kind) { 7580 case IndirectLocalPathEntry::AddressOf: 7581 case IndirectLocalPathEntry::LValToRVal: 7582 // These exist primarily to mark the path as not permitting or 7583 // supporting lifetime extension. 7584 break; 7585 7586 case IndirectLocalPathEntry::LifetimeBoundCall: 7587 case IndirectLocalPathEntry::GslPointerInit: 7588 case IndirectLocalPathEntry::GslReferenceInit: 7589 // FIXME: Consider adding a note for these. 7590 break; 7591 7592 case IndirectLocalPathEntry::DefaultInit: { 7593 auto *FD = cast<FieldDecl>(Elem.D); 7594 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) 7595 << FD << nextPathEntryRange(Path, I + 1, L); 7596 break; 7597 } 7598 7599 case IndirectLocalPathEntry::VarInit: 7600 const VarDecl *VD = cast<VarDecl>(Elem.D); 7601 Diag(VD->getLocation(), diag::note_local_var_initializer) 7602 << VD->getType()->isReferenceType() 7603 << VD->isImplicit() << VD->getDeclName() 7604 << nextPathEntryRange(Path, I + 1, L); 7605 break; 7606 } 7607 } 7608 7609 // We didn't lifetime-extend, so don't go any further; we don't need more 7610 // warnings or errors on inner temporaries within this one's initializer. 7611 return false; 7612 }; 7613 7614 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( 7615 diag::warn_dangling_lifetime_pointer, SourceLocation()); 7616 llvm::SmallVector<IndirectLocalPathEntry, 8> Path; 7617 if (Init->isGLValue()) 7618 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, 7619 TemporaryVisitor, 7620 EnableLifetimeWarnings); 7621 else 7622 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, 7623 EnableLifetimeWarnings); 7624 } 7625 7626 static void DiagnoseNarrowingInInitList(Sema &S, 7627 const ImplicitConversionSequence &ICS, 7628 QualType PreNarrowingType, 7629 QualType EntityType, 7630 const Expr *PostInit); 7631 7632 /// Provide warnings when std::move is used on construction. 7633 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, 7634 bool IsReturnStmt) { 7635 if (!InitExpr) 7636 return; 7637 7638 if (S.inTemplateInstantiation()) 7639 return; 7640 7641 QualType DestType = InitExpr->getType(); 7642 if (!DestType->isRecordType()) 7643 return; 7644 7645 unsigned DiagID = 0; 7646 if (IsReturnStmt) { 7647 const CXXConstructExpr *CCE = 7648 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); 7649 if (!CCE || CCE->getNumArgs() != 1) 7650 return; 7651 7652 if (!CCE->getConstructor()->isCopyOrMoveConstructor()) 7653 return; 7654 7655 InitExpr = CCE->getArg(0)->IgnoreImpCasts(); 7656 } 7657 7658 // Find the std::move call and get the argument. 7659 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); 7660 if (!CE || !CE->isCallToStdMove()) 7661 return; 7662 7663 const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); 7664 7665 if (IsReturnStmt) { 7666 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); 7667 if (!DRE || DRE->refersToEnclosingVariableOrCapture()) 7668 return; 7669 7670 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7671 if (!VD || !VD->hasLocalStorage()) 7672 return; 7673 7674 // __block variables are not moved implicitly. 7675 if (VD->hasAttr<BlocksAttr>()) 7676 return; 7677 7678 QualType SourceType = VD->getType(); 7679 if (!SourceType->isRecordType()) 7680 return; 7681 7682 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { 7683 return; 7684 } 7685 7686 // If we're returning a function parameter, copy elision 7687 // is not possible. 7688 if (isa<ParmVarDecl>(VD)) 7689 DiagID = diag::warn_redundant_move_on_return; 7690 else 7691 DiagID = diag::warn_pessimizing_move_on_return; 7692 } else { 7693 DiagID = diag::warn_pessimizing_move_on_initialization; 7694 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); 7695 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) 7696 return; 7697 } 7698 7699 S.Diag(CE->getBeginLoc(), DiagID); 7700 7701 // Get all the locations for a fix-it. Don't emit the fix-it if any location 7702 // is within a macro. 7703 SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); 7704 if (CallBegin.isMacroID()) 7705 return; 7706 SourceLocation RParen = CE->getRParenLoc(); 7707 if (RParen.isMacroID()) 7708 return; 7709 SourceLocation LParen; 7710 SourceLocation ArgLoc = Arg->getBeginLoc(); 7711 7712 // Special testing for the argument location. Since the fix-it needs the 7713 // location right before the argument, the argument location can be in a 7714 // macro only if it is at the beginning of the macro. 7715 while (ArgLoc.isMacroID() && 7716 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { 7717 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); 7718 } 7719 7720 if (LParen.isMacroID()) 7721 return; 7722 7723 LParen = ArgLoc.getLocWithOffset(-1); 7724 7725 S.Diag(CE->getBeginLoc(), diag::note_remove_move) 7726 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) 7727 << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); 7728 } 7729 7730 static void CheckForNullPointerDereference(Sema &S, const Expr *E) { 7731 // Check to see if we are dereferencing a null pointer. If so, this is 7732 // undefined behavior, so warn about it. This only handles the pattern 7733 // "*null", which is a very syntactic check. 7734 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 7735 if (UO->getOpcode() == UO_Deref && 7736 UO->getSubExpr()->IgnoreParenCasts()-> 7737 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { 7738 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 7739 S.PDiag(diag::warn_binding_null_to_reference) 7740 << UO->getSubExpr()->getSourceRange()); 7741 } 7742 } 7743 7744 MaterializeTemporaryExpr * 7745 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 7746 bool BoundToLvalueReference) { 7747 auto MTE = new (Context) 7748 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); 7749 7750 // Order an ExprWithCleanups for lifetime marks. 7751 // 7752 // TODO: It'll be good to have a single place to check the access of the 7753 // destructor and generate ExprWithCleanups for various uses. Currently these 7754 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, 7755 // but there may be a chance to merge them. 7756 Cleanup.setExprNeedsCleanups(false); 7757 return MTE; 7758 } 7759 7760 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { 7761 // In C++98, we don't want to implicitly create an xvalue. 7762 // FIXME: This means that AST consumers need to deal with "prvalues" that 7763 // denote materialized temporaries. Maybe we should add another ValueKind 7764 // for "xvalue pretending to be a prvalue" for C++98 support. 7765 if (!E->isRValue() || !getLangOpts().CPlusPlus11) 7766 return E; 7767 7768 // C++1z [conv.rval]/1: T shall be a complete type. 7769 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? 7770 // If so, we should check for a non-abstract class type here too. 7771 QualType T = E->getType(); 7772 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) 7773 return ExprError(); 7774 7775 return CreateMaterializeTemporaryExpr(E->getType(), E, false); 7776 } 7777 7778 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, 7779 ExprValueKind VK, 7780 CheckedConversionKind CCK) { 7781 7782 CastKind CK = CK_NoOp; 7783 7784 if (VK == VK_RValue) { 7785 auto PointeeTy = Ty->getPointeeType(); 7786 auto ExprPointeeTy = E->getType()->getPointeeType(); 7787 if (!PointeeTy.isNull() && 7788 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) 7789 CK = CK_AddressSpaceConversion; 7790 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { 7791 CK = CK_AddressSpaceConversion; 7792 } 7793 7794 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); 7795 } 7796 7797 ExprResult InitializationSequence::Perform(Sema &S, 7798 const InitializedEntity &Entity, 7799 const InitializationKind &Kind, 7800 MultiExprArg Args, 7801 QualType *ResultType) { 7802 if (Failed()) { 7803 Diagnose(S, Entity, Kind, Args); 7804 return ExprError(); 7805 } 7806 if (!ZeroInitializationFixit.empty()) { 7807 unsigned DiagID = diag::err_default_init_const; 7808 if (Decl *D = Entity.getDecl()) 7809 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) 7810 DiagID = diag::ext_default_init_const; 7811 7812 // The initialization would have succeeded with this fixit. Since the fixit 7813 // is on the error, we need to build a valid AST in this case, so this isn't 7814 // handled in the Failed() branch above. 7815 QualType DestType = Entity.getType(); 7816 S.Diag(Kind.getLocation(), DiagID) 7817 << DestType << (bool)DestType->getAs<RecordType>() 7818 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, 7819 ZeroInitializationFixit); 7820 } 7821 7822 if (getKind() == DependentSequence) { 7823 // If the declaration is a non-dependent, incomplete array type 7824 // that has an initializer, then its type will be completed once 7825 // the initializer is instantiated. 7826 if (ResultType && !Entity.getType()->isDependentType() && 7827 Args.size() == 1) { 7828 QualType DeclType = Entity.getType(); 7829 if (const IncompleteArrayType *ArrayT 7830 = S.Context.getAsIncompleteArrayType(DeclType)) { 7831 // FIXME: We don't currently have the ability to accurately 7832 // compute the length of an initializer list without 7833 // performing full type-checking of the initializer list 7834 // (since we have to determine where braces are implicitly 7835 // introduced and such). So, we fall back to making the array 7836 // type a dependently-sized array type with no specified 7837 // bound. 7838 if (isa<InitListExpr>((Expr *)Args[0])) { 7839 SourceRange Brackets; 7840 7841 // Scavange the location of the brackets from the entity, if we can. 7842 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { 7843 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 7844 TypeLoc TL = TInfo->getTypeLoc(); 7845 if (IncompleteArrayTypeLoc ArrayLoc = 7846 TL.getAs<IncompleteArrayTypeLoc>()) 7847 Brackets = ArrayLoc.getBracketsRange(); 7848 } 7849 } 7850 7851 *ResultType 7852 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 7853 /*NumElts=*/nullptr, 7854 ArrayT->getSizeModifier(), 7855 ArrayT->getIndexTypeCVRQualifiers(), 7856 Brackets); 7857 } 7858 7859 } 7860 } 7861 if (Kind.getKind() == InitializationKind::IK_Direct && 7862 !Kind.isExplicitCast()) { 7863 // Rebuild the ParenListExpr. 7864 SourceRange ParenRange = Kind.getParenOrBraceRange(); 7865 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), 7866 Args); 7867 } 7868 assert(Kind.getKind() == InitializationKind::IK_Copy || 7869 Kind.isExplicitCast() || 7870 Kind.getKind() == InitializationKind::IK_DirectList); 7871 return ExprResult(Args[0]); 7872 } 7873 7874 // No steps means no initialization. 7875 if (Steps.empty()) 7876 return ExprResult((Expr *)nullptr); 7877 7878 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && 7879 Args.size() == 1 && isa<InitListExpr>(Args[0]) && 7880 !Entity.isParameterKind()) { 7881 // Produce a C++98 compatibility warning if we are initializing a reference 7882 // from an initializer list. For parameters, we produce a better warning 7883 // elsewhere. 7884 Expr *Init = Args[0]; 7885 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) 7886 << Init->getSourceRange(); 7887 } 7888 7889 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope 7890 QualType ETy = Entity.getType(); 7891 bool HasGlobalAS = ETy.hasAddressSpace() && 7892 ETy.getAddressSpace() == LangAS::opencl_global; 7893 7894 if (S.getLangOpts().OpenCLVersion >= 200 && 7895 ETy->isAtomicType() && !HasGlobalAS && 7896 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { 7897 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) 7898 << 1 7899 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); 7900 return ExprError(); 7901 } 7902 7903 QualType DestType = Entity.getType().getNonReferenceType(); 7904 // FIXME: Ugly hack around the fact that Entity.getType() is not 7905 // the same as Entity.getDecl()->getType() in cases involving type merging, 7906 // and we want latter when it makes sense. 7907 if (ResultType) 7908 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 7909 Entity.getType(); 7910 7911 ExprResult CurInit((Expr *)nullptr); 7912 SmallVector<Expr*, 4> ArrayLoopCommonExprs; 7913 7914 // For initialization steps that start with a single initializer, 7915 // grab the only argument out the Args and place it into the "current" 7916 // initializer. 7917 switch (Steps.front().Kind) { 7918 case SK_ResolveAddressOfOverloadedFunction: 7919 case SK_CastDerivedToBaseRValue: 7920 case SK_CastDerivedToBaseXValue: 7921 case SK_CastDerivedToBaseLValue: 7922 case SK_BindReference: 7923 case SK_BindReferenceToTemporary: 7924 case SK_FinalCopy: 7925 case SK_ExtraneousCopyToTemporary: 7926 case SK_UserConversion: 7927 case SK_QualificationConversionLValue: 7928 case SK_QualificationConversionXValue: 7929 case SK_QualificationConversionRValue: 7930 case SK_AtomicConversion: 7931 case SK_ConversionSequence: 7932 case SK_ConversionSequenceNoNarrowing: 7933 case SK_ListInitialization: 7934 case SK_UnwrapInitList: 7935 case SK_RewrapInitList: 7936 case SK_CAssignment: 7937 case SK_StringInit: 7938 case SK_ObjCObjectConversion: 7939 case SK_ArrayLoopIndex: 7940 case SK_ArrayLoopInit: 7941 case SK_ArrayInit: 7942 case SK_GNUArrayInit: 7943 case SK_ParenthesizedArrayInit: 7944 case SK_PassByIndirectCopyRestore: 7945 case SK_PassByIndirectRestore: 7946 case SK_ProduceObjCObject: 7947 case SK_StdInitializerList: 7948 case SK_OCLSamplerInit: 7949 case SK_OCLZeroOpaqueType: { 7950 assert(Args.size() == 1); 7951 CurInit = Args[0]; 7952 if (!CurInit.get()) return ExprError(); 7953 break; 7954 } 7955 7956 case SK_ConstructorInitialization: 7957 case SK_ConstructorInitializationFromList: 7958 case SK_StdInitializerListConstructorCall: 7959 case SK_ZeroInitialization: 7960 break; 7961 } 7962 7963 // Promote from an unevaluated context to an unevaluated list context in 7964 // C++11 list-initialization; we need to instantiate entities usable in 7965 // constant expressions here in order to perform narrowing checks =( 7966 EnterExpressionEvaluationContext Evaluated( 7967 S, EnterExpressionEvaluationContext::InitList, 7968 CurInit.get() && isa<InitListExpr>(CurInit.get())); 7969 7970 // C++ [class.abstract]p2: 7971 // no objects of an abstract class can be created except as subobjects 7972 // of a class derived from it 7973 auto checkAbstractType = [&](QualType T) -> bool { 7974 if (Entity.getKind() == InitializedEntity::EK_Base || 7975 Entity.getKind() == InitializedEntity::EK_Delegating) 7976 return false; 7977 return S.RequireNonAbstractType(Kind.getLocation(), T, 7978 diag::err_allocation_of_abstract_type); 7979 }; 7980 7981 // Walk through the computed steps for the initialization sequence, 7982 // performing the specified conversions along the way. 7983 bool ConstructorInitRequiresZeroInit = false; 7984 for (step_iterator Step = step_begin(), StepEnd = step_end(); 7985 Step != StepEnd; ++Step) { 7986 if (CurInit.isInvalid()) 7987 return ExprError(); 7988 7989 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 7990 7991 switch (Step->Kind) { 7992 case SK_ResolveAddressOfOverloadedFunction: 7993 // Overload resolution determined which function invoke; update the 7994 // initializer to reflect that choice. 7995 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 7996 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) 7997 return ExprError(); 7998 CurInit = S.FixOverloadedFunctionReference(CurInit, 7999 Step->Function.FoundDecl, 8000 Step->Function.Function); 8001 break; 8002 8003 case SK_CastDerivedToBaseRValue: 8004 case SK_CastDerivedToBaseXValue: 8005 case SK_CastDerivedToBaseLValue: { 8006 // We have a derived-to-base cast that produces either an rvalue or an 8007 // lvalue. Perform that cast. 8008 8009 CXXCastPath BasePath; 8010 8011 // Casts to inaccessible base classes are allowed with C-style casts. 8012 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 8013 if (S.CheckDerivedToBaseConversion( 8014 SourceType, Step->Type, CurInit.get()->getBeginLoc(), 8015 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) 8016 return ExprError(); 8017 8018 ExprValueKind VK = 8019 Step->Kind == SK_CastDerivedToBaseLValue ? 8020 VK_LValue : 8021 (Step->Kind == SK_CastDerivedToBaseXValue ? 8022 VK_XValue : 8023 VK_RValue); 8024 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, 8025 CK_DerivedToBase, CurInit.get(), 8026 &BasePath, VK, FPOptionsOverride()); 8027 break; 8028 } 8029 8030 case SK_BindReference: 8031 // Reference binding does not have any corresponding ASTs. 8032 8033 // Check exception specifications 8034 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 8035 return ExprError(); 8036 8037 // We don't check for e.g. function pointers here, since address 8038 // availability checks should only occur when the function first decays 8039 // into a pointer or reference. 8040 if (CurInit.get()->getType()->isFunctionProtoType()) { 8041 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { 8042 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 8043 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 8044 DRE->getBeginLoc())) 8045 return ExprError(); 8046 } 8047 } 8048 } 8049 8050 CheckForNullPointerDereference(S, CurInit.get()); 8051 break; 8052 8053 case SK_BindReferenceToTemporary: { 8054 // Make sure the "temporary" is actually an rvalue. 8055 assert(CurInit.get()->isRValue() && "not a temporary"); 8056 8057 // Check exception specifications 8058 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 8059 return ExprError(); 8060 8061 // Materialize the temporary into memory. 8062 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 8063 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType()); 8064 CurInit = MTE; 8065 8066 // If we're extending this temporary to automatic storage duration -- we 8067 // need to register its cleanup during the full-expression's cleanups. 8068 if (MTE->getStorageDuration() == SD_Automatic && 8069 MTE->getType().isDestructedType()) 8070 S.Cleanup.setExprNeedsCleanups(true); 8071 break; 8072 } 8073 8074 case SK_FinalCopy: 8075 if (checkAbstractType(Step->Type)) 8076 return ExprError(); 8077 8078 // If the overall initialization is initializing a temporary, we already 8079 // bound our argument if it was necessary to do so. If not (if we're 8080 // ultimately initializing a non-temporary), our argument needs to be 8081 // bound since it's initializing a function parameter. 8082 // FIXME: This is a mess. Rationalize temporary destruction. 8083 if (!shouldBindAsTemporary(Entity)) 8084 CurInit = S.MaybeBindToTemporary(CurInit.get()); 8085 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 8086 /*IsExtraneousCopy=*/false); 8087 break; 8088 8089 case SK_ExtraneousCopyToTemporary: 8090 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 8091 /*IsExtraneousCopy=*/true); 8092 break; 8093 8094 case SK_UserConversion: { 8095 // We have a user-defined conversion that invokes either a constructor 8096 // or a conversion function. 8097 CastKind CastKind; 8098 FunctionDecl *Fn = Step->Function.Function; 8099 DeclAccessPair FoundFn = Step->Function.FoundDecl; 8100 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 8101 bool CreatedObject = false; 8102 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 8103 // Build a call to the selected constructor. 8104 SmallVector<Expr*, 8> ConstructorArgs; 8105 SourceLocation Loc = CurInit.get()->getBeginLoc(); 8106 8107 // Determine the arguments required to actually perform the constructor 8108 // call. 8109 Expr *Arg = CurInit.get(); 8110 if (S.CompleteConstructorCall(Constructor, 8111 MultiExprArg(&Arg, 1), 8112 Loc, ConstructorArgs)) 8113 return ExprError(); 8114 8115 // Build an expression that constructs a temporary. 8116 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, 8117 FoundFn, Constructor, 8118 ConstructorArgs, 8119 HadMultipleCandidates, 8120 /*ListInit*/ false, 8121 /*StdInitListInit*/ false, 8122 /*ZeroInit*/ false, 8123 CXXConstructExpr::CK_Complete, 8124 SourceRange()); 8125 if (CurInit.isInvalid()) 8126 return ExprError(); 8127 8128 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, 8129 Entity); 8130 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 8131 return ExprError(); 8132 8133 CastKind = CK_ConstructorConversion; 8134 CreatedObject = true; 8135 } else { 8136 // Build a call to the conversion function. 8137 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 8138 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, 8139 FoundFn); 8140 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 8141 return ExprError(); 8142 8143 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 8144 HadMultipleCandidates); 8145 if (CurInit.isInvalid()) 8146 return ExprError(); 8147 8148 CastKind = CK_UserDefinedConversion; 8149 CreatedObject = Conversion->getReturnType()->isRecordType(); 8150 } 8151 8152 if (CreatedObject && checkAbstractType(CurInit.get()->getType())) 8153 return ExprError(); 8154 8155 CurInit = ImplicitCastExpr::Create( 8156 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr, 8157 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides()); 8158 8159 if (shouldBindAsTemporary(Entity)) 8160 // The overall entity is temporary, so this expression should be 8161 // destroyed at the end of its full-expression. 8162 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 8163 else if (CreatedObject && shouldDestroyEntity(Entity)) { 8164 // The object outlasts the full-expression, but we need to prepare for 8165 // a destructor being run on it. 8166 // FIXME: It makes no sense to do this here. This should happen 8167 // regardless of how we initialized the entity. 8168 QualType T = CurInit.get()->getType(); 8169 if (const RecordType *Record = T->getAs<RecordType>()) { 8170 CXXDestructorDecl *Destructor 8171 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 8172 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, 8173 S.PDiag(diag::err_access_dtor_temp) << T); 8174 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); 8175 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) 8176 return ExprError(); 8177 } 8178 } 8179 break; 8180 } 8181 8182 case SK_QualificationConversionLValue: 8183 case SK_QualificationConversionXValue: 8184 case SK_QualificationConversionRValue: { 8185 // Perform a qualification conversion; these can never go wrong. 8186 ExprValueKind VK = 8187 Step->Kind == SK_QualificationConversionLValue 8188 ? VK_LValue 8189 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue 8190 : VK_RValue); 8191 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); 8192 break; 8193 } 8194 8195 case SK_AtomicConversion: { 8196 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic"); 8197 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8198 CK_NonAtomicToAtomic, VK_RValue); 8199 break; 8200 } 8201 8202 case SK_ConversionSequence: 8203 case SK_ConversionSequenceNoNarrowing: { 8204 if (const auto *FromPtrType = 8205 CurInit.get()->getType()->getAs<PointerType>()) { 8206 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { 8207 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8208 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8209 // Do not check static casts here because they are checked earlier 8210 // in Sema::ActOnCXXNamedCast() 8211 if (!Kind.isStaticCast()) { 8212 S.Diag(CurInit.get()->getExprLoc(), 8213 diag::warn_noderef_to_dereferenceable_pointer) 8214 << CurInit.get()->getSourceRange(); 8215 } 8216 } 8217 } 8218 } 8219 8220 Sema::CheckedConversionKind CCK 8221 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 8222 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 8223 : Kind.isExplicitCast()? Sema::CCK_OtherCast 8224 : Sema::CCK_ImplicitConversion; 8225 ExprResult CurInitExprRes = 8226 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 8227 getAssignmentAction(Entity), CCK); 8228 if (CurInitExprRes.isInvalid()) 8229 return ExprError(); 8230 8231 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); 8232 8233 CurInit = CurInitExprRes; 8234 8235 if (Step->Kind == SK_ConversionSequenceNoNarrowing && 8236 S.getLangOpts().CPlusPlus) 8237 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), 8238 CurInit.get()); 8239 8240 break; 8241 } 8242 8243 case SK_ListInitialization: { 8244 if (checkAbstractType(Step->Type)) 8245 return ExprError(); 8246 8247 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 8248 // If we're not initializing the top-level entity, we need to create an 8249 // InitializeTemporary entity for our target type. 8250 QualType Ty = Step->Type; 8251 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); 8252 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 8253 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; 8254 InitListChecker PerformInitList(S, InitEntity, 8255 InitList, Ty, /*VerifyOnly=*/false, 8256 /*TreatUnavailableAsInvalid=*/false); 8257 if (PerformInitList.HadError()) 8258 return ExprError(); 8259 8260 // Hack: We must update *ResultType if available in order to set the 8261 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 8262 // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 8263 if (ResultType && 8264 ResultType->getNonReferenceType()->isIncompleteArrayType()) { 8265 if ((*ResultType)->isRValueReferenceType()) 8266 Ty = S.Context.getRValueReferenceType(Ty); 8267 else if ((*ResultType)->isLValueReferenceType()) 8268 Ty = S.Context.getLValueReferenceType(Ty, 8269 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); 8270 *ResultType = Ty; 8271 } 8272 8273 InitListExpr *StructuredInitList = 8274 PerformInitList.getFullyStructuredList(); 8275 CurInit.get(); 8276 CurInit = shouldBindAsTemporary(InitEntity) 8277 ? S.MaybeBindToTemporary(StructuredInitList) 8278 : StructuredInitList; 8279 break; 8280 } 8281 8282 case SK_ConstructorInitializationFromList: { 8283 if (checkAbstractType(Step->Type)) 8284 return ExprError(); 8285 8286 // When an initializer list is passed for a parameter of type "reference 8287 // to object", we don't get an EK_Temporary entity, but instead an 8288 // EK_Parameter entity with reference type. 8289 // FIXME: This is a hack. What we really should do is create a user 8290 // conversion step for this case, but this makes it considerably more 8291 // complicated. For now, this will do. 8292 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 8293 Entity.getType().getNonReferenceType()); 8294 bool UseTemporary = Entity.getType()->isReferenceType(); 8295 assert(Args.size() == 1 && "expected a single argument for list init"); 8296 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 8297 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) 8298 << InitList->getSourceRange(); 8299 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 8300 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : 8301 Entity, 8302 Kind, Arg, *Step, 8303 ConstructorInitRequiresZeroInit, 8304 /*IsListInitialization*/true, 8305 /*IsStdInitListInit*/false, 8306 InitList->getLBraceLoc(), 8307 InitList->getRBraceLoc()); 8308 break; 8309 } 8310 8311 case SK_UnwrapInitList: 8312 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); 8313 break; 8314 8315 case SK_RewrapInitList: { 8316 Expr *E = CurInit.get(); 8317 InitListExpr *Syntactic = Step->WrappingSyntacticList; 8318 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 8319 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); 8320 ILE->setSyntacticForm(Syntactic); 8321 ILE->setType(E->getType()); 8322 ILE->setValueKind(E->getValueKind()); 8323 CurInit = ILE; 8324 break; 8325 } 8326 8327 case SK_ConstructorInitialization: 8328 case SK_StdInitializerListConstructorCall: { 8329 if (checkAbstractType(Step->Type)) 8330 return ExprError(); 8331 8332 // When an initializer list is passed for a parameter of type "reference 8333 // to object", we don't get an EK_Temporary entity, but instead an 8334 // EK_Parameter entity with reference type. 8335 // FIXME: This is a hack. What we really should do is create a user 8336 // conversion step for this case, but this makes it considerably more 8337 // complicated. For now, this will do. 8338 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 8339 Entity.getType().getNonReferenceType()); 8340 bool UseTemporary = Entity.getType()->isReferenceType(); 8341 bool IsStdInitListInit = 8342 Step->Kind == SK_StdInitializerListConstructorCall; 8343 Expr *Source = CurInit.get(); 8344 SourceRange Range = Kind.hasParenOrBraceRange() 8345 ? Kind.getParenOrBraceRange() 8346 : SourceRange(); 8347 CurInit = PerformConstructorInitialization( 8348 S, UseTemporary ? TempEntity : Entity, Kind, 8349 Source ? MultiExprArg(Source) : Args, *Step, 8350 ConstructorInitRequiresZeroInit, 8351 /*IsListInitialization*/ IsStdInitListInit, 8352 /*IsStdInitListInitialization*/ IsStdInitListInit, 8353 /*LBraceLoc*/ Range.getBegin(), 8354 /*RBraceLoc*/ Range.getEnd()); 8355 break; 8356 } 8357 8358 case SK_ZeroInitialization: { 8359 step_iterator NextStep = Step; 8360 ++NextStep; 8361 if (NextStep != StepEnd && 8362 (NextStep->Kind == SK_ConstructorInitialization || 8363 NextStep->Kind == SK_ConstructorInitializationFromList)) { 8364 // The need for zero-initialization is recorded directly into 8365 // the call to the object's constructor within the next step. 8366 ConstructorInitRequiresZeroInit = true; 8367 } else if (Kind.getKind() == InitializationKind::IK_Value && 8368 S.getLangOpts().CPlusPlus && 8369 !Kind.isImplicitValueInit()) { 8370 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 8371 if (!TSInfo) 8372 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 8373 Kind.getRange().getBegin()); 8374 8375 CurInit = new (S.Context) CXXScalarValueInitExpr( 8376 Entity.getType().getNonLValueExprType(S.Context), TSInfo, 8377 Kind.getRange().getEnd()); 8378 } else { 8379 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); 8380 } 8381 break; 8382 } 8383 8384 case SK_CAssignment: { 8385 QualType SourceType = CurInit.get()->getType(); 8386 8387 // Save off the initial CurInit in case we need to emit a diagnostic 8388 ExprResult InitialCurInit = CurInit; 8389 ExprResult Result = CurInit; 8390 Sema::AssignConvertType ConvTy = 8391 S.CheckSingleAssignmentConstraints(Step->Type, Result, true, 8392 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); 8393 if (Result.isInvalid()) 8394 return ExprError(); 8395 CurInit = Result; 8396 8397 // If this is a call, allow conversion to a transparent union. 8398 ExprResult CurInitExprRes = CurInit; 8399 if (ConvTy != Sema::Compatible && 8400 Entity.isParameterKind() && 8401 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 8402 == Sema::Compatible) 8403 ConvTy = Sema::Compatible; 8404 if (CurInitExprRes.isInvalid()) 8405 return ExprError(); 8406 CurInit = CurInitExprRes; 8407 8408 bool Complained; 8409 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 8410 Step->Type, SourceType, 8411 InitialCurInit.get(), 8412 getAssignmentAction(Entity, true), 8413 &Complained)) { 8414 PrintInitLocationNote(S, Entity); 8415 return ExprError(); 8416 } else if (Complained) 8417 PrintInitLocationNote(S, Entity); 8418 break; 8419 } 8420 8421 case SK_StringInit: { 8422 QualType Ty = Step->Type; 8423 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); 8424 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty, 8425 S.Context.getAsArrayType(Ty), S); 8426 break; 8427 } 8428 8429 case SK_ObjCObjectConversion: 8430 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8431 CK_ObjCObjectLValueCast, 8432 CurInit.get()->getValueKind()); 8433 break; 8434 8435 case SK_ArrayLoopIndex: { 8436 Expr *Cur = CurInit.get(); 8437 Expr *BaseExpr = new (S.Context) 8438 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), 8439 Cur->getValueKind(), Cur->getObjectKind(), Cur); 8440 Expr *IndexExpr = 8441 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); 8442 CurInit = S.CreateBuiltinArraySubscriptExpr( 8443 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); 8444 ArrayLoopCommonExprs.push_back(BaseExpr); 8445 break; 8446 } 8447 8448 case SK_ArrayLoopInit: { 8449 assert(!ArrayLoopCommonExprs.empty() && 8450 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit"); 8451 Expr *Common = ArrayLoopCommonExprs.pop_back_val(); 8452 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, 8453 CurInit.get()); 8454 break; 8455 } 8456 8457 case SK_GNUArrayInit: 8458 // Okay: we checked everything before creating this step. Note that 8459 // this is a GNU extension. 8460 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 8461 << Step->Type << CurInit.get()->getType() 8462 << CurInit.get()->getSourceRange(); 8463 updateGNUCompoundLiteralRValue(CurInit.get()); 8464 LLVM_FALLTHROUGH; 8465 case SK_ArrayInit: 8466 // If the destination type is an incomplete array type, update the 8467 // type accordingly. 8468 if (ResultType) { 8469 if (const IncompleteArrayType *IncompleteDest 8470 = S.Context.getAsIncompleteArrayType(Step->Type)) { 8471 if (const ConstantArrayType *ConstantSource 8472 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 8473 *ResultType = S.Context.getConstantArrayType( 8474 IncompleteDest->getElementType(), 8475 ConstantSource->getSize(), 8476 ConstantSource->getSizeExpr(), 8477 ArrayType::Normal, 0); 8478 } 8479 } 8480 } 8481 break; 8482 8483 case SK_ParenthesizedArrayInit: 8484 // Okay: we checked everything before creating this step. Note that 8485 // this is a GNU extension. 8486 S.Diag(Kind.getLocation(), diag::ext_array_init_parens) 8487 << CurInit.get()->getSourceRange(); 8488 break; 8489 8490 case SK_PassByIndirectCopyRestore: 8491 case SK_PassByIndirectRestore: 8492 checkIndirectCopyRestoreSource(S, CurInit.get()); 8493 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( 8494 CurInit.get(), Step->Type, 8495 Step->Kind == SK_PassByIndirectCopyRestore); 8496 break; 8497 8498 case SK_ProduceObjCObject: 8499 CurInit = ImplicitCastExpr::Create( 8500 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr, 8501 VK_RValue, FPOptionsOverride()); 8502 break; 8503 8504 case SK_StdInitializerList: { 8505 S.Diag(CurInit.get()->getExprLoc(), 8506 diag::warn_cxx98_compat_initializer_list_init) 8507 << CurInit.get()->getSourceRange(); 8508 8509 // Materialize the temporary into memory. 8510 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 8511 CurInit.get()->getType(), CurInit.get(), 8512 /*BoundToLvalueReference=*/false); 8513 8514 // Wrap it in a construction of a std::initializer_list<T>. 8515 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); 8516 8517 // Bind the result, in case the library has given initializer_list a 8518 // non-trivial destructor. 8519 if (shouldBindAsTemporary(Entity)) 8520 CurInit = S.MaybeBindToTemporary(CurInit.get()); 8521 break; 8522 } 8523 8524 case SK_OCLSamplerInit: { 8525 // Sampler initialization have 5 cases: 8526 // 1. function argument passing 8527 // 1a. argument is a file-scope variable 8528 // 1b. argument is a function-scope variable 8529 // 1c. argument is one of caller function's parameters 8530 // 2. variable initialization 8531 // 2a. initializing a file-scope variable 8532 // 2b. initializing a function-scope variable 8533 // 8534 // For file-scope variables, since they cannot be initialized by function 8535 // call of __translate_sampler_initializer in LLVM IR, their references 8536 // need to be replaced by a cast from their literal initializers to 8537 // sampler type. Since sampler variables can only be used in function 8538 // calls as arguments, we only need to replace them when handling the 8539 // argument passing. 8540 assert(Step->Type->isSamplerT() && 8541 "Sampler initialization on non-sampler type."); 8542 Expr *Init = CurInit.get()->IgnoreParens(); 8543 QualType SourceType = Init->getType(); 8544 // Case 1 8545 if (Entity.isParameterKind()) { 8546 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { 8547 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) 8548 << SourceType; 8549 break; 8550 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { 8551 auto Var = cast<VarDecl>(DRE->getDecl()); 8552 // Case 1b and 1c 8553 // No cast from integer to sampler is needed. 8554 if (!Var->hasGlobalStorage()) { 8555 CurInit = ImplicitCastExpr::Create( 8556 S.Context, Step->Type, CK_LValueToRValue, Init, 8557 /*BasePath=*/nullptr, VK_RValue, FPOptionsOverride()); 8558 break; 8559 } 8560 // Case 1a 8561 // For function call with a file-scope sampler variable as argument, 8562 // get the integer literal. 8563 // Do not diagnose if the file-scope variable does not have initializer 8564 // since this has already been diagnosed when parsing the variable 8565 // declaration. 8566 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) 8567 break; 8568 Init = cast<ImplicitCastExpr>(const_cast<Expr*>( 8569 Var->getInit()))->getSubExpr(); 8570 SourceType = Init->getType(); 8571 } 8572 } else { 8573 // Case 2 8574 // Check initializer is 32 bit integer constant. 8575 // If the initializer is taken from global variable, do not diagnose since 8576 // this has already been done when parsing the variable declaration. 8577 if (!Init->isConstantInitializer(S.Context, false)) 8578 break; 8579 8580 if (!SourceType->isIntegerType() || 8581 32 != S.Context.getIntWidth(SourceType)) { 8582 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) 8583 << SourceType; 8584 break; 8585 } 8586 8587 Expr::EvalResult EVResult; 8588 Init->EvaluateAsInt(EVResult, S.Context); 8589 llvm::APSInt Result = EVResult.Val.getInt(); 8590 const uint64_t SamplerValue = Result.getLimitedValue(); 8591 // 32-bit value of sampler's initializer is interpreted as 8592 // bit-field with the following structure: 8593 // |unspecified|Filter|Addressing Mode| Normalized Coords| 8594 // |31 6|5 4|3 1| 0| 8595 // This structure corresponds to enum values of sampler properties 8596 // defined in SPIR spec v1.2 and also opencl-c.h 8597 unsigned AddressingMode = (0x0E & SamplerValue) >> 1; 8598 unsigned FilterMode = (0x30 & SamplerValue) >> 4; 8599 if (FilterMode != 1 && FilterMode != 2 && 8600 !S.getOpenCLOptions().isEnabled( 8601 "cl_intel_device_side_avc_motion_estimation")) 8602 S.Diag(Kind.getLocation(), 8603 diag::warn_sampler_initializer_invalid_bits) 8604 << "Filter Mode"; 8605 if (AddressingMode > 4) 8606 S.Diag(Kind.getLocation(), 8607 diag::warn_sampler_initializer_invalid_bits) 8608 << "Addressing Mode"; 8609 } 8610 8611 // Cases 1a, 2a and 2b 8612 // Insert cast from integer to sampler. 8613 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, 8614 CK_IntToOCLSampler); 8615 break; 8616 } 8617 case SK_OCLZeroOpaqueType: { 8618 assert((Step->Type->isEventT() || Step->Type->isQueueT() || 8619 Step->Type->isOCLIntelSubgroupAVCType()) && 8620 "Wrong type for initialization of OpenCL opaque type."); 8621 8622 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8623 CK_ZeroToOCLOpaqueType, 8624 CurInit.get()->getValueKind()); 8625 break; 8626 } 8627 } 8628 } 8629 8630 // Check whether the initializer has a shorter lifetime than the initialized 8631 // entity, and if not, either lifetime-extend or warn as appropriate. 8632 if (auto *Init = CurInit.get()) 8633 S.checkInitializerLifetime(Entity, Init); 8634 8635 // Diagnose non-fatal problems with the completed initialization. 8636 if (Entity.getKind() == InitializedEntity::EK_Member && 8637 cast<FieldDecl>(Entity.getDecl())->isBitField()) 8638 S.CheckBitFieldInitialization(Kind.getLocation(), 8639 cast<FieldDecl>(Entity.getDecl()), 8640 CurInit.get()); 8641 8642 // Check for std::move on construction. 8643 if (const Expr *E = CurInit.get()) { 8644 CheckMoveOnConstruction(S, E, 8645 Entity.getKind() == InitializedEntity::EK_Result); 8646 } 8647 8648 return CurInit; 8649 } 8650 8651 /// Somewhere within T there is an uninitialized reference subobject. 8652 /// Dig it out and diagnose it. 8653 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, 8654 QualType T) { 8655 if (T->isReferenceType()) { 8656 S.Diag(Loc, diag::err_reference_without_init) 8657 << T.getNonReferenceType(); 8658 return true; 8659 } 8660 8661 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 8662 if (!RD || !RD->hasUninitializedReferenceMember()) 8663 return false; 8664 8665 for (const auto *FI : RD->fields()) { 8666 if (FI->isUnnamedBitfield()) 8667 continue; 8668 8669 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { 8670 S.Diag(Loc, diag::note_value_initialization_here) << RD; 8671 return true; 8672 } 8673 } 8674 8675 for (const auto &BI : RD->bases()) { 8676 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { 8677 S.Diag(Loc, diag::note_value_initialization_here) << RD; 8678 return true; 8679 } 8680 } 8681 8682 return false; 8683 } 8684 8685 8686 //===----------------------------------------------------------------------===// 8687 // Diagnose initialization failures 8688 //===----------------------------------------------------------------------===// 8689 8690 /// Emit notes associated with an initialization that failed due to a 8691 /// "simple" conversion failure. 8692 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, 8693 Expr *op) { 8694 QualType destType = entity.getType(); 8695 if (destType.getNonReferenceType()->isObjCObjectPointerType() && 8696 op->getType()->isObjCObjectPointerType()) { 8697 8698 // Emit a possible note about the conversion failing because the 8699 // operand is a message send with a related result type. 8700 S.EmitRelatedResultTypeNote(op); 8701 8702 // Emit a possible note about a return failing because we're 8703 // expecting a related result type. 8704 if (entity.getKind() == InitializedEntity::EK_Result) 8705 S.EmitRelatedResultTypeNoteForReturn(destType); 8706 } 8707 QualType fromType = op->getType(); 8708 auto *fromDecl = fromType.getTypePtr()->getPointeeCXXRecordDecl(); 8709 auto *destDecl = destType.getTypePtr()->getPointeeCXXRecordDecl(); 8710 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && 8711 destDecl->getDeclKind() == Decl::CXXRecord && 8712 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && 8713 !fromDecl->hasDefinition()) 8714 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion) 8715 << S.getASTContext().getTagDeclType(fromDecl) 8716 << S.getASTContext().getTagDeclType(destDecl); 8717 } 8718 8719 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, 8720 InitListExpr *InitList) { 8721 QualType DestType = Entity.getType(); 8722 8723 QualType E; 8724 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { 8725 QualType ArrayType = S.Context.getConstantArrayType( 8726 E.withConst(), 8727 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 8728 InitList->getNumInits()), 8729 nullptr, clang::ArrayType::Normal, 0); 8730 InitializedEntity HiddenArray = 8731 InitializedEntity::InitializeTemporary(ArrayType); 8732 return diagnoseListInit(S, HiddenArray, InitList); 8733 } 8734 8735 if (DestType->isReferenceType()) { 8736 // A list-initialization failure for a reference means that we tried to 8737 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the 8738 // inner initialization failed. 8739 QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); 8740 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); 8741 SourceLocation Loc = InitList->getBeginLoc(); 8742 if (auto *D = Entity.getDecl()) 8743 Loc = D->getLocation(); 8744 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; 8745 return; 8746 } 8747 8748 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, 8749 /*VerifyOnly=*/false, 8750 /*TreatUnavailableAsInvalid=*/false); 8751 assert(DiagnoseInitList.HadError() && 8752 "Inconsistent init list check result."); 8753 } 8754 8755 bool InitializationSequence::Diagnose(Sema &S, 8756 const InitializedEntity &Entity, 8757 const InitializationKind &Kind, 8758 ArrayRef<Expr *> Args) { 8759 if (!Failed()) 8760 return false; 8761 8762 // When we want to diagnose only one element of a braced-init-list, 8763 // we need to factor it out. 8764 Expr *OnlyArg; 8765 if (Args.size() == 1) { 8766 auto *List = dyn_cast<InitListExpr>(Args[0]); 8767 if (List && List->getNumInits() == 1) 8768 OnlyArg = List->getInit(0); 8769 else 8770 OnlyArg = Args[0]; 8771 } 8772 else 8773 OnlyArg = nullptr; 8774 8775 QualType DestType = Entity.getType(); 8776 switch (Failure) { 8777 case FK_TooManyInitsForReference: 8778 // FIXME: Customize for the initialized entity? 8779 if (Args.empty()) { 8780 // Dig out the reference subobject which is uninitialized and diagnose it. 8781 // If this is value-initialization, this could be nested some way within 8782 // the target type. 8783 assert(Kind.getKind() == InitializationKind::IK_Value || 8784 DestType->isReferenceType()); 8785 bool Diagnosed = 8786 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); 8787 assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); 8788 (void)Diagnosed; 8789 } else // FIXME: diagnostic below could be better! 8790 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 8791 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); 8792 break; 8793 case FK_ParenthesizedListInitForReference: 8794 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) 8795 << 1 << Entity.getType() << Args[0]->getSourceRange(); 8796 break; 8797 8798 case FK_ArrayNeedsInitList: 8799 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; 8800 break; 8801 case FK_ArrayNeedsInitListOrStringLiteral: 8802 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; 8803 break; 8804 case FK_ArrayNeedsInitListOrWideStringLiteral: 8805 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; 8806 break; 8807 case FK_NarrowStringIntoWideCharArray: 8808 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); 8809 break; 8810 case FK_WideStringIntoCharArray: 8811 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); 8812 break; 8813 case FK_IncompatWideStringIntoWideChar: 8814 S.Diag(Kind.getLocation(), 8815 diag::err_array_init_incompat_wide_string_into_wchar); 8816 break; 8817 case FK_PlainStringIntoUTF8Char: 8818 S.Diag(Kind.getLocation(), 8819 diag::err_array_init_plain_string_into_char8_t); 8820 S.Diag(Args.front()->getBeginLoc(), 8821 diag::note_array_init_plain_string_into_char8_t) 8822 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); 8823 break; 8824 case FK_UTF8StringIntoPlainChar: 8825 S.Diag(Kind.getLocation(), 8826 diag::err_array_init_utf8_string_into_char) 8827 << S.getLangOpts().CPlusPlus20; 8828 break; 8829 case FK_ArrayTypeMismatch: 8830 case FK_NonConstantArrayInit: 8831 S.Diag(Kind.getLocation(), 8832 (Failure == FK_ArrayTypeMismatch 8833 ? diag::err_array_init_different_type 8834 : diag::err_array_init_non_constant_array)) 8835 << DestType.getNonReferenceType() 8836 << OnlyArg->getType() 8837 << Args[0]->getSourceRange(); 8838 break; 8839 8840 case FK_VariableLengthArrayHasInitializer: 8841 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 8842 << Args[0]->getSourceRange(); 8843 break; 8844 8845 case FK_AddressOfOverloadFailed: { 8846 DeclAccessPair Found; 8847 S.ResolveAddressOfOverloadedFunction(OnlyArg, 8848 DestType.getNonReferenceType(), 8849 true, 8850 Found); 8851 break; 8852 } 8853 8854 case FK_AddressOfUnaddressableFunction: { 8855 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); 8856 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 8857 OnlyArg->getBeginLoc()); 8858 break; 8859 } 8860 8861 case FK_ReferenceInitOverloadFailed: 8862 case FK_UserConversionOverloadFailed: 8863 switch (FailedOverloadResult) { 8864 case OR_Ambiguous: 8865 8866 FailedCandidateSet.NoteCandidates( 8867 PartialDiagnosticAt( 8868 Kind.getLocation(), 8869 Failure == FK_UserConversionOverloadFailed 8870 ? (S.PDiag(diag::err_typecheck_ambiguous_condition) 8871 << OnlyArg->getType() << DestType 8872 << Args[0]->getSourceRange()) 8873 : (S.PDiag(diag::err_ref_init_ambiguous) 8874 << DestType << OnlyArg->getType() 8875 << Args[0]->getSourceRange())), 8876 S, OCD_AmbiguousCandidates, Args); 8877 break; 8878 8879 case OR_No_Viable_Function: { 8880 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); 8881 if (!S.RequireCompleteType(Kind.getLocation(), 8882 DestType.getNonReferenceType(), 8883 diag::err_typecheck_nonviable_condition_incomplete, 8884 OnlyArg->getType(), Args[0]->getSourceRange())) 8885 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 8886 << (Entity.getKind() == InitializedEntity::EK_Result) 8887 << OnlyArg->getType() << Args[0]->getSourceRange() 8888 << DestType.getNonReferenceType(); 8889 8890 FailedCandidateSet.NoteCandidates(S, Args, Cands); 8891 break; 8892 } 8893 case OR_Deleted: { 8894 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 8895 << OnlyArg->getType() << DestType.getNonReferenceType() 8896 << Args[0]->getSourceRange(); 8897 OverloadCandidateSet::iterator Best; 8898 OverloadingResult Ovl 8899 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 8900 if (Ovl == OR_Deleted) { 8901 S.NoteDeletedFunction(Best->Function); 8902 } else { 8903 llvm_unreachable("Inconsistent overload resolution?"); 8904 } 8905 break; 8906 } 8907 8908 case OR_Success: 8909 llvm_unreachable("Conversion did not fail!"); 8910 } 8911 break; 8912 8913 case FK_NonConstLValueReferenceBindingToTemporary: 8914 if (isa<InitListExpr>(Args[0])) { 8915 S.Diag(Kind.getLocation(), 8916 diag::err_lvalue_reference_bind_to_initlist) 8917 << DestType.getNonReferenceType().isVolatileQualified() 8918 << DestType.getNonReferenceType() 8919 << Args[0]->getSourceRange(); 8920 break; 8921 } 8922 LLVM_FALLTHROUGH; 8923 8924 case FK_NonConstLValueReferenceBindingToUnrelated: 8925 S.Diag(Kind.getLocation(), 8926 Failure == FK_NonConstLValueReferenceBindingToTemporary 8927 ? diag::err_lvalue_reference_bind_to_temporary 8928 : diag::err_lvalue_reference_bind_to_unrelated) 8929 << DestType.getNonReferenceType().isVolatileQualified() 8930 << DestType.getNonReferenceType() 8931 << OnlyArg->getType() 8932 << Args[0]->getSourceRange(); 8933 break; 8934 8935 case FK_NonConstLValueReferenceBindingToBitfield: { 8936 // We don't necessarily have an unambiguous source bit-field. 8937 FieldDecl *BitField = Args[0]->getSourceBitField(); 8938 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 8939 << DestType.isVolatileQualified() 8940 << (BitField ? BitField->getDeclName() : DeclarationName()) 8941 << (BitField != nullptr) 8942 << Args[0]->getSourceRange(); 8943 if (BitField) 8944 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 8945 break; 8946 } 8947 8948 case FK_NonConstLValueReferenceBindingToVectorElement: 8949 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 8950 << DestType.isVolatileQualified() 8951 << Args[0]->getSourceRange(); 8952 break; 8953 8954 case FK_NonConstLValueReferenceBindingToMatrixElement: 8955 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element) 8956 << DestType.isVolatileQualified() << Args[0]->getSourceRange(); 8957 break; 8958 8959 case FK_RValueReferenceBindingToLValue: 8960 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 8961 << DestType.getNonReferenceType() << OnlyArg->getType() 8962 << Args[0]->getSourceRange(); 8963 break; 8964 8965 case FK_ReferenceAddrspaceMismatchTemporary: 8966 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) 8967 << DestType << Args[0]->getSourceRange(); 8968 break; 8969 8970 case FK_ReferenceInitDropsQualifiers: { 8971 QualType SourceType = OnlyArg->getType(); 8972 QualType NonRefType = DestType.getNonReferenceType(); 8973 Qualifiers DroppedQualifiers = 8974 SourceType.getQualifiers() - NonRefType.getQualifiers(); 8975 8976 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( 8977 SourceType.getQualifiers())) 8978 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 8979 << NonRefType << SourceType << 1 /*addr space*/ 8980 << Args[0]->getSourceRange(); 8981 else if (DroppedQualifiers.hasQualifiers()) 8982 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 8983 << NonRefType << SourceType << 0 /*cv quals*/ 8984 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) 8985 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); 8986 else 8987 // FIXME: Consider decomposing the type and explaining which qualifiers 8988 // were dropped where, or on which level a 'const' is missing, etc. 8989 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 8990 << NonRefType << SourceType << 2 /*incompatible quals*/ 8991 << Args[0]->getSourceRange(); 8992 break; 8993 } 8994 8995 case FK_ReferenceInitFailed: 8996 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 8997 << DestType.getNonReferenceType() 8998 << DestType.getNonReferenceType()->isIncompleteType() 8999 << OnlyArg->isLValue() 9000 << OnlyArg->getType() 9001 << Args[0]->getSourceRange(); 9002 emitBadConversionNotes(S, Entity, Args[0]); 9003 break; 9004 9005 case FK_ConversionFailed: { 9006 QualType FromType = OnlyArg->getType(); 9007 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 9008 << (int)Entity.getKind() 9009 << DestType 9010 << OnlyArg->isLValue() 9011 << FromType 9012 << Args[0]->getSourceRange(); 9013 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 9014 S.Diag(Kind.getLocation(), PDiag); 9015 emitBadConversionNotes(S, Entity, Args[0]); 9016 break; 9017 } 9018 9019 case FK_ConversionFromPropertyFailed: 9020 // No-op. This error has already been reported. 9021 break; 9022 9023 case FK_TooManyInitsForScalar: { 9024 SourceRange R; 9025 9026 auto *InitList = dyn_cast<InitListExpr>(Args[0]); 9027 if (InitList && InitList->getNumInits() >= 1) { 9028 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); 9029 } else { 9030 assert(Args.size() > 1 && "Expected multiple initializers!"); 9031 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); 9032 } 9033 9034 R.setBegin(S.getLocForEndOfToken(R.getBegin())); 9035 if (Kind.isCStyleOrFunctionalCast()) 9036 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 9037 << R; 9038 else 9039 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 9040 << /*scalar=*/2 << R; 9041 break; 9042 } 9043 9044 case FK_ParenthesizedListInitForScalar: 9045 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) 9046 << 0 << Entity.getType() << Args[0]->getSourceRange(); 9047 break; 9048 9049 case FK_ReferenceBindingToInitList: 9050 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 9051 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 9052 break; 9053 9054 case FK_InitListBadDestinationType: 9055 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 9056 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 9057 break; 9058 9059 case FK_ListConstructorOverloadFailed: 9060 case FK_ConstructorOverloadFailed: { 9061 SourceRange ArgsRange; 9062 if (Args.size()) 9063 ArgsRange = 9064 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); 9065 9066 if (Failure == FK_ListConstructorOverloadFailed) { 9067 assert(Args.size() == 1 && 9068 "List construction from other than 1 argument."); 9069 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 9070 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 9071 } 9072 9073 // FIXME: Using "DestType" for the entity we're printing is probably 9074 // bad. 9075 switch (FailedOverloadResult) { 9076 case OR_Ambiguous: 9077 FailedCandidateSet.NoteCandidates( 9078 PartialDiagnosticAt(Kind.getLocation(), 9079 S.PDiag(diag::err_ovl_ambiguous_init) 9080 << DestType << ArgsRange), 9081 S, OCD_AmbiguousCandidates, Args); 9082 break; 9083 9084 case OR_No_Viable_Function: 9085 if (Kind.getKind() == InitializationKind::IK_Default && 9086 (Entity.getKind() == InitializedEntity::EK_Base || 9087 Entity.getKind() == InitializedEntity::EK_Member) && 9088 isa<CXXConstructorDecl>(S.CurContext)) { 9089 // This is implicit default initialization of a member or 9090 // base within a constructor. If no viable function was 9091 // found, notify the user that they need to explicitly 9092 // initialize this base/member. 9093 CXXConstructorDecl *Constructor 9094 = cast<CXXConstructorDecl>(S.CurContext); 9095 const CXXRecordDecl *InheritedFrom = nullptr; 9096 if (auto Inherited = Constructor->getInheritedConstructor()) 9097 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); 9098 if (Entity.getKind() == InitializedEntity::EK_Base) { 9099 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 9100 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 9101 << S.Context.getTypeDeclType(Constructor->getParent()) 9102 << /*base=*/0 9103 << Entity.getType() 9104 << InheritedFrom; 9105 9106 RecordDecl *BaseDecl 9107 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() 9108 ->getDecl(); 9109 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 9110 << S.Context.getTagDeclType(BaseDecl); 9111 } else { 9112 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 9113 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 9114 << S.Context.getTypeDeclType(Constructor->getParent()) 9115 << /*member=*/1 9116 << Entity.getName() 9117 << InheritedFrom; 9118 S.Diag(Entity.getDecl()->getLocation(), 9119 diag::note_member_declared_at); 9120 9121 if (const RecordType *Record 9122 = Entity.getType()->getAs<RecordType>()) 9123 S.Diag(Record->getDecl()->getLocation(), 9124 diag::note_previous_decl) 9125 << S.Context.getTagDeclType(Record->getDecl()); 9126 } 9127 break; 9128 } 9129 9130 FailedCandidateSet.NoteCandidates( 9131 PartialDiagnosticAt( 9132 Kind.getLocation(), 9133 S.PDiag(diag::err_ovl_no_viable_function_in_init) 9134 << DestType << ArgsRange), 9135 S, OCD_AllCandidates, Args); 9136 break; 9137 9138 case OR_Deleted: { 9139 OverloadCandidateSet::iterator Best; 9140 OverloadingResult Ovl 9141 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9142 if (Ovl != OR_Deleted) { 9143 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 9144 << DestType << ArgsRange; 9145 llvm_unreachable("Inconsistent overload resolution?"); 9146 break; 9147 } 9148 9149 // If this is a defaulted or implicitly-declared function, then 9150 // it was implicitly deleted. Make it clear that the deletion was 9151 // implicit. 9152 if (S.isImplicitlyDeleted(Best->Function)) 9153 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) 9154 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) 9155 << DestType << ArgsRange; 9156 else 9157 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 9158 << DestType << ArgsRange; 9159 9160 S.NoteDeletedFunction(Best->Function); 9161 break; 9162 } 9163 9164 case OR_Success: 9165 llvm_unreachable("Conversion did not fail!"); 9166 } 9167 } 9168 break; 9169 9170 case FK_DefaultInitOfConst: 9171 if (Entity.getKind() == InitializedEntity::EK_Member && 9172 isa<CXXConstructorDecl>(S.CurContext)) { 9173 // This is implicit default-initialization of a const member in 9174 // a constructor. Complain that it needs to be explicitly 9175 // initialized. 9176 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 9177 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 9178 << (Constructor->getInheritedConstructor() ? 2 : 9179 Constructor->isImplicit() ? 1 : 0) 9180 << S.Context.getTypeDeclType(Constructor->getParent()) 9181 << /*const=*/1 9182 << Entity.getName(); 9183 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 9184 << Entity.getName(); 9185 } else { 9186 S.Diag(Kind.getLocation(), diag::err_default_init_const) 9187 << DestType << (bool)DestType->getAs<RecordType>(); 9188 } 9189 break; 9190 9191 case FK_Incomplete: 9192 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, 9193 diag::err_init_incomplete_type); 9194 break; 9195 9196 case FK_ListInitializationFailed: { 9197 // Run the init list checker again to emit diagnostics. 9198 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 9199 diagnoseListInit(S, Entity, InitList); 9200 break; 9201 } 9202 9203 case FK_PlaceholderType: { 9204 // FIXME: Already diagnosed! 9205 break; 9206 } 9207 9208 case FK_ExplicitConstructor: { 9209 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) 9210 << Args[0]->getSourceRange(); 9211 OverloadCandidateSet::iterator Best; 9212 OverloadingResult Ovl 9213 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9214 (void)Ovl; 9215 assert(Ovl == OR_Success && "Inconsistent overload resolution"); 9216 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 9217 S.Diag(CtorDecl->getLocation(), 9218 diag::note_explicit_ctor_deduction_guide_here) << false; 9219 break; 9220 } 9221 } 9222 9223 PrintInitLocationNote(S, Entity); 9224 return true; 9225 } 9226 9227 void InitializationSequence::dump(raw_ostream &OS) const { 9228 switch (SequenceKind) { 9229 case FailedSequence: { 9230 OS << "Failed sequence: "; 9231 switch (Failure) { 9232 case FK_TooManyInitsForReference: 9233 OS << "too many initializers for reference"; 9234 break; 9235 9236 case FK_ParenthesizedListInitForReference: 9237 OS << "parenthesized list init for reference"; 9238 break; 9239 9240 case FK_ArrayNeedsInitList: 9241 OS << "array requires initializer list"; 9242 break; 9243 9244 case FK_AddressOfUnaddressableFunction: 9245 OS << "address of unaddressable function was taken"; 9246 break; 9247 9248 case FK_ArrayNeedsInitListOrStringLiteral: 9249 OS << "array requires initializer list or string literal"; 9250 break; 9251 9252 case FK_ArrayNeedsInitListOrWideStringLiteral: 9253 OS << "array requires initializer list or wide string literal"; 9254 break; 9255 9256 case FK_NarrowStringIntoWideCharArray: 9257 OS << "narrow string into wide char array"; 9258 break; 9259 9260 case FK_WideStringIntoCharArray: 9261 OS << "wide string into char array"; 9262 break; 9263 9264 case FK_IncompatWideStringIntoWideChar: 9265 OS << "incompatible wide string into wide char array"; 9266 break; 9267 9268 case FK_PlainStringIntoUTF8Char: 9269 OS << "plain string literal into char8_t array"; 9270 break; 9271 9272 case FK_UTF8StringIntoPlainChar: 9273 OS << "u8 string literal into char array"; 9274 break; 9275 9276 case FK_ArrayTypeMismatch: 9277 OS << "array type mismatch"; 9278 break; 9279 9280 case FK_NonConstantArrayInit: 9281 OS << "non-constant array initializer"; 9282 break; 9283 9284 case FK_AddressOfOverloadFailed: 9285 OS << "address of overloaded function failed"; 9286 break; 9287 9288 case FK_ReferenceInitOverloadFailed: 9289 OS << "overload resolution for reference initialization failed"; 9290 break; 9291 9292 case FK_NonConstLValueReferenceBindingToTemporary: 9293 OS << "non-const lvalue reference bound to temporary"; 9294 break; 9295 9296 case FK_NonConstLValueReferenceBindingToBitfield: 9297 OS << "non-const lvalue reference bound to bit-field"; 9298 break; 9299 9300 case FK_NonConstLValueReferenceBindingToVectorElement: 9301 OS << "non-const lvalue reference bound to vector element"; 9302 break; 9303 9304 case FK_NonConstLValueReferenceBindingToMatrixElement: 9305 OS << "non-const lvalue reference bound to matrix element"; 9306 break; 9307 9308 case FK_NonConstLValueReferenceBindingToUnrelated: 9309 OS << "non-const lvalue reference bound to unrelated type"; 9310 break; 9311 9312 case FK_RValueReferenceBindingToLValue: 9313 OS << "rvalue reference bound to an lvalue"; 9314 break; 9315 9316 case FK_ReferenceInitDropsQualifiers: 9317 OS << "reference initialization drops qualifiers"; 9318 break; 9319 9320 case FK_ReferenceAddrspaceMismatchTemporary: 9321 OS << "reference with mismatching address space bound to temporary"; 9322 break; 9323 9324 case FK_ReferenceInitFailed: 9325 OS << "reference initialization failed"; 9326 break; 9327 9328 case FK_ConversionFailed: 9329 OS << "conversion failed"; 9330 break; 9331 9332 case FK_ConversionFromPropertyFailed: 9333 OS << "conversion from property failed"; 9334 break; 9335 9336 case FK_TooManyInitsForScalar: 9337 OS << "too many initializers for scalar"; 9338 break; 9339 9340 case FK_ParenthesizedListInitForScalar: 9341 OS << "parenthesized list init for reference"; 9342 break; 9343 9344 case FK_ReferenceBindingToInitList: 9345 OS << "referencing binding to initializer list"; 9346 break; 9347 9348 case FK_InitListBadDestinationType: 9349 OS << "initializer list for non-aggregate, non-scalar type"; 9350 break; 9351 9352 case FK_UserConversionOverloadFailed: 9353 OS << "overloading failed for user-defined conversion"; 9354 break; 9355 9356 case FK_ConstructorOverloadFailed: 9357 OS << "constructor overloading failed"; 9358 break; 9359 9360 case FK_DefaultInitOfConst: 9361 OS << "default initialization of a const variable"; 9362 break; 9363 9364 case FK_Incomplete: 9365 OS << "initialization of incomplete type"; 9366 break; 9367 9368 case FK_ListInitializationFailed: 9369 OS << "list initialization checker failure"; 9370 break; 9371 9372 case FK_VariableLengthArrayHasInitializer: 9373 OS << "variable length array has an initializer"; 9374 break; 9375 9376 case FK_PlaceholderType: 9377 OS << "initializer expression isn't contextually valid"; 9378 break; 9379 9380 case FK_ListConstructorOverloadFailed: 9381 OS << "list constructor overloading failed"; 9382 break; 9383 9384 case FK_ExplicitConstructor: 9385 OS << "list copy initialization chose explicit constructor"; 9386 break; 9387 } 9388 OS << '\n'; 9389 return; 9390 } 9391 9392 case DependentSequence: 9393 OS << "Dependent sequence\n"; 9394 return; 9395 9396 case NormalSequence: 9397 OS << "Normal sequence: "; 9398 break; 9399 } 9400 9401 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 9402 if (S != step_begin()) { 9403 OS << " -> "; 9404 } 9405 9406 switch (S->Kind) { 9407 case SK_ResolveAddressOfOverloadedFunction: 9408 OS << "resolve address of overloaded function"; 9409 break; 9410 9411 case SK_CastDerivedToBaseRValue: 9412 OS << "derived-to-base (rvalue)"; 9413 break; 9414 9415 case SK_CastDerivedToBaseXValue: 9416 OS << "derived-to-base (xvalue)"; 9417 break; 9418 9419 case SK_CastDerivedToBaseLValue: 9420 OS << "derived-to-base (lvalue)"; 9421 break; 9422 9423 case SK_BindReference: 9424 OS << "bind reference to lvalue"; 9425 break; 9426 9427 case SK_BindReferenceToTemporary: 9428 OS << "bind reference to a temporary"; 9429 break; 9430 9431 case SK_FinalCopy: 9432 OS << "final copy in class direct-initialization"; 9433 break; 9434 9435 case SK_ExtraneousCopyToTemporary: 9436 OS << "extraneous C++03 copy to temporary"; 9437 break; 9438 9439 case SK_UserConversion: 9440 OS << "user-defined conversion via " << *S->Function.Function; 9441 break; 9442 9443 case SK_QualificationConversionRValue: 9444 OS << "qualification conversion (rvalue)"; 9445 break; 9446 9447 case SK_QualificationConversionXValue: 9448 OS << "qualification conversion (xvalue)"; 9449 break; 9450 9451 case SK_QualificationConversionLValue: 9452 OS << "qualification conversion (lvalue)"; 9453 break; 9454 9455 case SK_AtomicConversion: 9456 OS << "non-atomic-to-atomic conversion"; 9457 break; 9458 9459 case SK_ConversionSequence: 9460 OS << "implicit conversion sequence ("; 9461 S->ICS->dump(); // FIXME: use OS 9462 OS << ")"; 9463 break; 9464 9465 case SK_ConversionSequenceNoNarrowing: 9466 OS << "implicit conversion sequence with narrowing prohibited ("; 9467 S->ICS->dump(); // FIXME: use OS 9468 OS << ")"; 9469 break; 9470 9471 case SK_ListInitialization: 9472 OS << "list aggregate initialization"; 9473 break; 9474 9475 case SK_UnwrapInitList: 9476 OS << "unwrap reference initializer list"; 9477 break; 9478 9479 case SK_RewrapInitList: 9480 OS << "rewrap reference initializer list"; 9481 break; 9482 9483 case SK_ConstructorInitialization: 9484 OS << "constructor initialization"; 9485 break; 9486 9487 case SK_ConstructorInitializationFromList: 9488 OS << "list initialization via constructor"; 9489 break; 9490 9491 case SK_ZeroInitialization: 9492 OS << "zero initialization"; 9493 break; 9494 9495 case SK_CAssignment: 9496 OS << "C assignment"; 9497 break; 9498 9499 case SK_StringInit: 9500 OS << "string initialization"; 9501 break; 9502 9503 case SK_ObjCObjectConversion: 9504 OS << "Objective-C object conversion"; 9505 break; 9506 9507 case SK_ArrayLoopIndex: 9508 OS << "indexing for array initialization loop"; 9509 break; 9510 9511 case SK_ArrayLoopInit: 9512 OS << "array initialization loop"; 9513 break; 9514 9515 case SK_ArrayInit: 9516 OS << "array initialization"; 9517 break; 9518 9519 case SK_GNUArrayInit: 9520 OS << "array initialization (GNU extension)"; 9521 break; 9522 9523 case SK_ParenthesizedArrayInit: 9524 OS << "parenthesized array initialization"; 9525 break; 9526 9527 case SK_PassByIndirectCopyRestore: 9528 OS << "pass by indirect copy and restore"; 9529 break; 9530 9531 case SK_PassByIndirectRestore: 9532 OS << "pass by indirect restore"; 9533 break; 9534 9535 case SK_ProduceObjCObject: 9536 OS << "Objective-C object retension"; 9537 break; 9538 9539 case SK_StdInitializerList: 9540 OS << "std::initializer_list from initializer list"; 9541 break; 9542 9543 case SK_StdInitializerListConstructorCall: 9544 OS << "list initialization from std::initializer_list"; 9545 break; 9546 9547 case SK_OCLSamplerInit: 9548 OS << "OpenCL sampler_t from integer constant"; 9549 break; 9550 9551 case SK_OCLZeroOpaqueType: 9552 OS << "OpenCL opaque type from zero"; 9553 break; 9554 } 9555 9556 OS << " [" << S->Type.getAsString() << ']'; 9557 } 9558 9559 OS << '\n'; 9560 } 9561 9562 void InitializationSequence::dump() const { 9563 dump(llvm::errs()); 9564 } 9565 9566 static bool NarrowingErrs(const LangOptions &L) { 9567 return L.CPlusPlus11 && 9568 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); 9569 } 9570 9571 static void DiagnoseNarrowingInInitList(Sema &S, 9572 const ImplicitConversionSequence &ICS, 9573 QualType PreNarrowingType, 9574 QualType EntityType, 9575 const Expr *PostInit) { 9576 const StandardConversionSequence *SCS = nullptr; 9577 switch (ICS.getKind()) { 9578 case ImplicitConversionSequence::StandardConversion: 9579 SCS = &ICS.Standard; 9580 break; 9581 case ImplicitConversionSequence::UserDefinedConversion: 9582 SCS = &ICS.UserDefined.After; 9583 break; 9584 case ImplicitConversionSequence::AmbiguousConversion: 9585 case ImplicitConversionSequence::EllipsisConversion: 9586 case ImplicitConversionSequence::BadConversion: 9587 return; 9588 } 9589 9590 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. 9591 APValue ConstantValue; 9592 QualType ConstantType; 9593 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, 9594 ConstantType)) { 9595 case NK_Not_Narrowing: 9596 case NK_Dependent_Narrowing: 9597 // No narrowing occurred. 9598 return; 9599 9600 case NK_Type_Narrowing: 9601 // This was a floating-to-integer conversion, which is always considered a 9602 // narrowing conversion even if the value is a constant and can be 9603 // represented exactly as an integer. 9604 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) 9605 ? diag::ext_init_list_type_narrowing 9606 : diag::warn_init_list_type_narrowing) 9607 << PostInit->getSourceRange() 9608 << PreNarrowingType.getLocalUnqualifiedType() 9609 << EntityType.getLocalUnqualifiedType(); 9610 break; 9611 9612 case NK_Constant_Narrowing: 9613 // A constant value was narrowed. 9614 S.Diag(PostInit->getBeginLoc(), 9615 NarrowingErrs(S.getLangOpts()) 9616 ? diag::ext_init_list_constant_narrowing 9617 : diag::warn_init_list_constant_narrowing) 9618 << PostInit->getSourceRange() 9619 << ConstantValue.getAsString(S.getASTContext(), ConstantType) 9620 << EntityType.getLocalUnqualifiedType(); 9621 break; 9622 9623 case NK_Variable_Narrowing: 9624 // A variable's value may have been narrowed. 9625 S.Diag(PostInit->getBeginLoc(), 9626 NarrowingErrs(S.getLangOpts()) 9627 ? diag::ext_init_list_variable_narrowing 9628 : diag::warn_init_list_variable_narrowing) 9629 << PostInit->getSourceRange() 9630 << PreNarrowingType.getLocalUnqualifiedType() 9631 << EntityType.getLocalUnqualifiedType(); 9632 break; 9633 } 9634 9635 SmallString<128> StaticCast; 9636 llvm::raw_svector_ostream OS(StaticCast); 9637 OS << "static_cast<"; 9638 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 9639 // It's important to use the typedef's name if there is one so that the 9640 // fixit doesn't break code using types like int64_t. 9641 // 9642 // FIXME: This will break if the typedef requires qualification. But 9643 // getQualifiedNameAsString() includes non-machine-parsable components. 9644 OS << *TT->getDecl(); 9645 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 9646 OS << BT->getName(S.getLangOpts()); 9647 else { 9648 // Oops, we didn't find the actual type of the variable. Don't emit a fixit 9649 // with a broken cast. 9650 return; 9651 } 9652 OS << ">("; 9653 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) 9654 << PostInit->getSourceRange() 9655 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) 9656 << FixItHint::CreateInsertion( 9657 S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); 9658 } 9659 9660 //===----------------------------------------------------------------------===// 9661 // Initialization helper functions 9662 //===----------------------------------------------------------------------===// 9663 bool 9664 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 9665 ExprResult Init) { 9666 if (Init.isInvalid()) 9667 return false; 9668 9669 Expr *InitE = Init.get(); 9670 assert(InitE && "No initialization expression"); 9671 9672 InitializationKind Kind = 9673 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); 9674 InitializationSequence Seq(*this, Entity, Kind, InitE); 9675 return !Seq.Failed(); 9676 } 9677 9678 ExprResult 9679 Sema::PerformCopyInitialization(const InitializedEntity &Entity, 9680 SourceLocation EqualLoc, 9681 ExprResult Init, 9682 bool TopLevelOfInitList, 9683 bool AllowExplicit) { 9684 if (Init.isInvalid()) 9685 return ExprError(); 9686 9687 Expr *InitE = Init.get(); 9688 assert(InitE && "No initialization expression?"); 9689 9690 if (EqualLoc.isInvalid()) 9691 EqualLoc = InitE->getBeginLoc(); 9692 9693 InitializationKind Kind = InitializationKind::CreateCopy( 9694 InitE->getBeginLoc(), EqualLoc, AllowExplicit); 9695 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); 9696 9697 // Prevent infinite recursion when performing parameter copy-initialization. 9698 const bool ShouldTrackCopy = 9699 Entity.isParameterKind() && Seq.isConstructorInitialization(); 9700 if (ShouldTrackCopy) { 9701 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != 9702 CurrentParameterCopyTypes.end()) { 9703 Seq.SetOverloadFailure( 9704 InitializationSequence::FK_ConstructorOverloadFailed, 9705 OR_No_Viable_Function); 9706 9707 // Try to give a meaningful diagnostic note for the problematic 9708 // constructor. 9709 const auto LastStep = Seq.step_end() - 1; 9710 assert(LastStep->Kind == 9711 InitializationSequence::SK_ConstructorInitialization); 9712 const FunctionDecl *Function = LastStep->Function.Function; 9713 auto Candidate = 9714 llvm::find_if(Seq.getFailedCandidateSet(), 9715 [Function](const OverloadCandidate &Candidate) -> bool { 9716 return Candidate.Viable && 9717 Candidate.Function == Function && 9718 Candidate.Conversions.size() > 0; 9719 }); 9720 if (Candidate != Seq.getFailedCandidateSet().end() && 9721 Function->getNumParams() > 0) { 9722 Candidate->Viable = false; 9723 Candidate->FailureKind = ovl_fail_bad_conversion; 9724 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, 9725 InitE, 9726 Function->getParamDecl(0)->getType()); 9727 } 9728 } 9729 CurrentParameterCopyTypes.push_back(Entity.getType()); 9730 } 9731 9732 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); 9733 9734 if (ShouldTrackCopy) 9735 CurrentParameterCopyTypes.pop_back(); 9736 9737 return Result; 9738 } 9739 9740 /// Determine whether RD is, or is derived from, a specialization of CTD. 9741 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, 9742 ClassTemplateDecl *CTD) { 9743 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { 9744 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); 9745 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); 9746 }; 9747 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); 9748 } 9749 9750 QualType Sema::DeduceTemplateSpecializationFromInitializer( 9751 TypeSourceInfo *TSInfo, const InitializedEntity &Entity, 9752 const InitializationKind &Kind, MultiExprArg Inits) { 9753 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( 9754 TSInfo->getType()->getContainedDeducedType()); 9755 assert(DeducedTST && "not a deduced template specialization type"); 9756 9757 auto TemplateName = DeducedTST->getTemplateName(); 9758 if (TemplateName.isDependent()) 9759 return Context.DependentTy; 9760 9761 // We can only perform deduction for class templates. 9762 auto *Template = 9763 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); 9764 if (!Template) { 9765 Diag(Kind.getLocation(), 9766 diag::err_deduced_non_class_template_specialization_type) 9767 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; 9768 if (auto *TD = TemplateName.getAsTemplateDecl()) 9769 Diag(TD->getLocation(), diag::note_template_decl_here); 9770 return QualType(); 9771 } 9772 9773 // Can't deduce from dependent arguments. 9774 if (Expr::hasAnyTypeDependentArguments(Inits)) { 9775 Diag(TSInfo->getTypeLoc().getBeginLoc(), 9776 diag::warn_cxx14_compat_class_template_argument_deduction) 9777 << TSInfo->getTypeLoc().getSourceRange() << 0; 9778 return Context.DependentTy; 9779 } 9780 9781 // FIXME: Perform "exact type" matching first, per CWG discussion? 9782 // Or implement this via an implied 'T(T) -> T' deduction guide? 9783 9784 // FIXME: Do we need/want a std::initializer_list<T> special case? 9785 9786 // Look up deduction guides, including those synthesized from constructors. 9787 // 9788 // C++1z [over.match.class.deduct]p1: 9789 // A set of functions and function templates is formed comprising: 9790 // - For each constructor of the class template designated by the 9791 // template-name, a function template [...] 9792 // - For each deduction-guide, a function or function template [...] 9793 DeclarationNameInfo NameInfo( 9794 Context.DeclarationNames.getCXXDeductionGuideName(Template), 9795 TSInfo->getTypeLoc().getEndLoc()); 9796 LookupResult Guides(*this, NameInfo, LookupOrdinaryName); 9797 LookupQualifiedName(Guides, Template->getDeclContext()); 9798 9799 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't 9800 // clear on this, but they're not found by name so access does not apply. 9801 Guides.suppressDiagnostics(); 9802 9803 // Figure out if this is list-initialization. 9804 InitListExpr *ListInit = 9805 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) 9806 ? dyn_cast<InitListExpr>(Inits[0]) 9807 : nullptr; 9808 9809 // C++1z [over.match.class.deduct]p1: 9810 // Initialization and overload resolution are performed as described in 9811 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] 9812 // (as appropriate for the type of initialization performed) for an object 9813 // of a hypothetical class type, where the selected functions and function 9814 // templates are considered to be the constructors of that class type 9815 // 9816 // Since we know we're initializing a class type of a type unrelated to that 9817 // of the initializer, this reduces to something fairly reasonable. 9818 OverloadCandidateSet Candidates(Kind.getLocation(), 9819 OverloadCandidateSet::CSK_Normal); 9820 OverloadCandidateSet::iterator Best; 9821 9822 bool HasAnyDeductionGuide = false; 9823 bool AllowExplicit = !Kind.isCopyInit() || ListInit; 9824 9825 auto tryToResolveOverload = 9826 [&](bool OnlyListConstructors) -> OverloadingResult { 9827 Candidates.clear(OverloadCandidateSet::CSK_Normal); 9828 HasAnyDeductionGuide = false; 9829 9830 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { 9831 NamedDecl *D = (*I)->getUnderlyingDecl(); 9832 if (D->isInvalidDecl()) 9833 continue; 9834 9835 auto *TD = dyn_cast<FunctionTemplateDecl>(D); 9836 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( 9837 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); 9838 if (!GD) 9839 continue; 9840 9841 if (!GD->isImplicit()) 9842 HasAnyDeductionGuide = true; 9843 9844 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) 9845 // For copy-initialization, the candidate functions are all the 9846 // converting constructors (12.3.1) of that class. 9847 // C++ [over.match.copy]p1: (non-list copy-initialization from class) 9848 // The converting constructors of T are candidate functions. 9849 if (!AllowExplicit) { 9850 // Overload resolution checks whether the deduction guide is declared 9851 // explicit for us. 9852 9853 // When looking for a converting constructor, deduction guides that 9854 // could never be called with one argument are not interesting to 9855 // check or note. 9856 if (GD->getMinRequiredArguments() > 1 || 9857 (GD->getNumParams() == 0 && !GD->isVariadic())) 9858 continue; 9859 } 9860 9861 // C++ [over.match.list]p1.1: (first phase list initialization) 9862 // Initially, the candidate functions are the initializer-list 9863 // constructors of the class T 9864 if (OnlyListConstructors && !isInitListConstructor(GD)) 9865 continue; 9866 9867 // C++ [over.match.list]p1.2: (second phase list initialization) 9868 // the candidate functions are all the constructors of the class T 9869 // C++ [over.match.ctor]p1: (all other cases) 9870 // the candidate functions are all the constructors of the class of 9871 // the object being initialized 9872 9873 // C++ [over.best.ics]p4: 9874 // When [...] the constructor [...] is a candidate by 9875 // - [over.match.copy] (in all cases) 9876 // FIXME: The "second phase of [over.match.list] case can also 9877 // theoretically happen here, but it's not clear whether we can 9878 // ever have a parameter of the right type. 9879 bool SuppressUserConversions = Kind.isCopyInit(); 9880 9881 if (TD) 9882 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, 9883 Inits, Candidates, SuppressUserConversions, 9884 /*PartialOverloading*/ false, 9885 AllowExplicit); 9886 else 9887 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, 9888 SuppressUserConversions, 9889 /*PartialOverloading*/ false, AllowExplicit); 9890 } 9891 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); 9892 }; 9893 9894 OverloadingResult Result = OR_No_Viable_Function; 9895 9896 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first 9897 // try initializer-list constructors. 9898 if (ListInit) { 9899 bool TryListConstructors = true; 9900 9901 // Try list constructors unless the list is empty and the class has one or 9902 // more default constructors, in which case those constructors win. 9903 if (!ListInit->getNumInits()) { 9904 for (NamedDecl *D : Guides) { 9905 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); 9906 if (FD && FD->getMinRequiredArguments() == 0) { 9907 TryListConstructors = false; 9908 break; 9909 } 9910 } 9911 } else if (ListInit->getNumInits() == 1) { 9912 // C++ [over.match.class.deduct]: 9913 // As an exception, the first phase in [over.match.list] (considering 9914 // initializer-list constructors) is omitted if the initializer list 9915 // consists of a single expression of type cv U, where U is a 9916 // specialization of C or a class derived from a specialization of C. 9917 Expr *E = ListInit->getInit(0); 9918 auto *RD = E->getType()->getAsCXXRecordDecl(); 9919 if (!isa<InitListExpr>(E) && RD && 9920 isCompleteType(Kind.getLocation(), E->getType()) && 9921 isOrIsDerivedFromSpecializationOf(RD, Template)) 9922 TryListConstructors = false; 9923 } 9924 9925 if (TryListConstructors) 9926 Result = tryToResolveOverload(/*OnlyListConstructor*/true); 9927 // Then unwrap the initializer list and try again considering all 9928 // constructors. 9929 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); 9930 } 9931 9932 // If list-initialization fails, or if we're doing any other kind of 9933 // initialization, we (eventually) consider constructors. 9934 if (Result == OR_No_Viable_Function) 9935 Result = tryToResolveOverload(/*OnlyListConstructor*/false); 9936 9937 switch (Result) { 9938 case OR_Ambiguous: 9939 // FIXME: For list-initialization candidates, it'd usually be better to 9940 // list why they were not viable when given the initializer list itself as 9941 // an argument. 9942 Candidates.NoteCandidates( 9943 PartialDiagnosticAt( 9944 Kind.getLocation(), 9945 PDiag(diag::err_deduced_class_template_ctor_ambiguous) 9946 << TemplateName), 9947 *this, OCD_AmbiguousCandidates, Inits); 9948 return QualType(); 9949 9950 case OR_No_Viable_Function: { 9951 CXXRecordDecl *Primary = 9952 cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); 9953 bool Complete = 9954 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); 9955 Candidates.NoteCandidates( 9956 PartialDiagnosticAt( 9957 Kind.getLocation(), 9958 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable 9959 : diag::err_deduced_class_template_incomplete) 9960 << TemplateName << !Guides.empty()), 9961 *this, OCD_AllCandidates, Inits); 9962 return QualType(); 9963 } 9964 9965 case OR_Deleted: { 9966 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) 9967 << TemplateName; 9968 NoteDeletedFunction(Best->Function); 9969 return QualType(); 9970 } 9971 9972 case OR_Success: 9973 // C++ [over.match.list]p1: 9974 // In copy-list-initialization, if an explicit constructor is chosen, the 9975 // initialization is ill-formed. 9976 if (Kind.isCopyInit() && ListInit && 9977 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { 9978 bool IsDeductionGuide = !Best->Function->isImplicit(); 9979 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) 9980 << TemplateName << IsDeductionGuide; 9981 Diag(Best->Function->getLocation(), 9982 diag::note_explicit_ctor_deduction_guide_here) 9983 << IsDeductionGuide; 9984 return QualType(); 9985 } 9986 9987 // Make sure we didn't select an unusable deduction guide, and mark it 9988 // as referenced. 9989 DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); 9990 MarkFunctionReferenced(Kind.getLocation(), Best->Function); 9991 break; 9992 } 9993 9994 // C++ [dcl.type.class.deduct]p1: 9995 // The placeholder is replaced by the return type of the function selected 9996 // by overload resolution for class template deduction. 9997 QualType DeducedType = 9998 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); 9999 Diag(TSInfo->getTypeLoc().getBeginLoc(), 10000 diag::warn_cxx14_compat_class_template_argument_deduction) 10001 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; 10002 10003 // Warn if CTAD was used on a type that does not have any user-defined 10004 // deduction guides. 10005 if (!HasAnyDeductionGuide) { 10006 Diag(TSInfo->getTypeLoc().getBeginLoc(), 10007 diag::warn_ctad_maybe_unsupported) 10008 << TemplateName; 10009 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); 10010 } 10011 10012 return DeducedType; 10013 } 10014