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