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