1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/ 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 // This file implements semantic analysis for C++0x variadic templates. 9 //===----------------------------------------------------------------------===/ 10 11 #include "TypeLocBuilder.h" 12 #include "clang/AST/DynamicRecursiveASTVisitor.h" 13 #include "clang/AST/Expr.h" 14 #include "clang/AST/ExprObjC.h" 15 #include "clang/AST/TypeLoc.h" 16 #include "clang/Sema/Lookup.h" 17 #include "clang/Sema/ParsedTemplate.h" 18 #include "clang/Sema/ScopeInfo.h" 19 #include "clang/Sema/Sema.h" 20 #include "clang/Sema/SemaInternal.h" 21 #include "clang/Sema/Template.h" 22 #include "llvm/Support/SaveAndRestore.h" 23 #include <optional> 24 25 using namespace clang; 26 27 //---------------------------------------------------------------------------- 28 // Visitor that collects unexpanded parameter packs 29 //---------------------------------------------------------------------------- 30 31 namespace { 32 /// A class that collects unexpanded parameter packs. 33 class CollectUnexpandedParameterPacksVisitor 34 : public DynamicRecursiveASTVisitor { 35 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded; 36 37 bool InLambdaOrBlock = false; 38 unsigned DepthLimit = (unsigned)-1; 39 40 #ifndef NDEBUG 41 bool ContainsIntermediatePacks = false; 42 #endif 43 44 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) { 45 if (auto *VD = dyn_cast<VarDecl>(ND)) { 46 // For now, the only problematic case is a generic lambda's templated 47 // call operator, so we don't need to look for all the other ways we 48 // could have reached a dependent parameter pack. 49 auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext()); 50 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr; 51 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit) 52 return; 53 } else if (auto *BD = dyn_cast<BindingDecl>(ND)) { 54 Expr *E = BD->getBinding(); 55 if (auto *RP = cast_if_present<ResolvedUnexpandedPackExpr>(E)) { 56 addUnexpanded(RP); 57 return; 58 } 59 } else if (getDepthAndIndex(ND).first >= DepthLimit) { 60 return; 61 } 62 63 Unexpanded.push_back({ND, Loc}); 64 } 65 66 void addUnexpanded(const TemplateTypeParmType *T, 67 SourceLocation Loc = SourceLocation()) { 68 if (T->getDepth() < DepthLimit) 69 Unexpanded.push_back({T, Loc}); 70 } 71 72 void addUnexpanded(ResolvedUnexpandedPackExpr *E) { 73 Unexpanded.push_back({E, E->getBeginLoc()}); 74 } 75 76 public: 77 explicit CollectUnexpandedParameterPacksVisitor( 78 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) 79 : Unexpanded(Unexpanded) { 80 ShouldWalkTypesOfTypeLocs = false; 81 82 // We need this so we can find e.g. attributes on lambdas. 83 ShouldVisitImplicitCode = true; 84 } 85 86 //------------------------------------------------------------------------ 87 // Recording occurrences of (unexpanded) parameter packs. 88 //------------------------------------------------------------------------ 89 90 /// Record occurrences of template type parameter packs. 91 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override { 92 if (TL.getTypePtr()->isParameterPack()) 93 addUnexpanded(TL.getTypePtr(), TL.getNameLoc()); 94 return true; 95 } 96 97 /// Record occurrences of template type parameter packs 98 /// when we don't have proper source-location information for 99 /// them. 100 /// 101 /// Ideally, this routine would never be used. 102 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override { 103 if (T->isParameterPack()) 104 addUnexpanded(T); 105 106 return true; 107 } 108 109 /// Record occurrences of function and non-type template 110 /// parameter packs in an expression. 111 bool VisitDeclRefExpr(DeclRefExpr *E) override { 112 if (E->getDecl()->isParameterPack()) 113 addUnexpanded(E->getDecl(), E->getLocation()); 114 115 return true; 116 } 117 118 bool 119 VisitResolvedUnexpandedPackExpr(ResolvedUnexpandedPackExpr *E) override { 120 addUnexpanded(E); 121 return true; 122 } 123 124 /// Record occurrences of template template parameter packs. 125 bool TraverseTemplateName(TemplateName Template) override { 126 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>( 127 Template.getAsTemplateDecl())) { 128 if (TTP->isParameterPack()) 129 addUnexpanded(TTP); 130 } 131 132 #ifndef NDEBUG 133 ContainsIntermediatePacks |= 134 (bool)Template.getAsSubstTemplateTemplateParmPack(); 135 #endif 136 137 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template); 138 } 139 140 /// Suppress traversal into Objective-C container literal 141 /// elements that are pack expansions. 142 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) override { 143 if (!E->containsUnexpandedParameterPack()) 144 return true; 145 146 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) { 147 ObjCDictionaryElement Element = E->getKeyValueElement(I); 148 if (Element.isPackExpansion()) 149 continue; 150 151 TraverseStmt(Element.Key); 152 TraverseStmt(Element.Value); 153 } 154 return true; 155 } 156 //------------------------------------------------------------------------ 157 // Pruning the search for unexpanded parameter packs. 158 //------------------------------------------------------------------------ 159 160 /// Suppress traversal into statements and expressions that 161 /// do not contain unexpanded parameter packs. 162 bool TraverseStmt(Stmt *S) override { 163 Expr *E = dyn_cast_or_null<Expr>(S); 164 if ((E && E->containsUnexpandedParameterPack()) || InLambdaOrBlock) 165 return DynamicRecursiveASTVisitor::TraverseStmt(S); 166 167 return true; 168 } 169 170 /// Suppress traversal into types that do not contain 171 /// unexpanded parameter packs. 172 bool TraverseType(QualType T) override { 173 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || 174 InLambdaOrBlock) 175 return DynamicRecursiveASTVisitor::TraverseType(T); 176 177 return true; 178 } 179 180 /// Suppress traversal into types with location information 181 /// that do not contain unexpanded parameter packs. 182 bool TraverseTypeLoc(TypeLoc TL) override { 183 if ((!TL.getType().isNull() && 184 TL.getType()->containsUnexpandedParameterPack()) || 185 InLambdaOrBlock) 186 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL); 187 188 return true; 189 } 190 191 /// Suppress traversal of parameter packs. 192 bool TraverseDecl(Decl *D) override { 193 // A function parameter pack is a pack expansion, so cannot contain 194 // an unexpanded parameter pack. Likewise for a template parameter 195 // pack that contains any references to other packs. 196 if (D && D->isParameterPack()) 197 return true; 198 199 return DynamicRecursiveASTVisitor::TraverseDecl(D); 200 } 201 202 /// Suppress traversal of pack-expanded attributes. 203 bool TraverseAttr(Attr *A) override { 204 if (A->isPackExpansion()) 205 return true; 206 207 return DynamicRecursiveASTVisitor::TraverseAttr(A); 208 } 209 210 /// Suppress traversal of pack expansion expressions and types. 211 ///@{ 212 bool TraversePackExpansionType(PackExpansionType *T) override { 213 return true; 214 } 215 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) override { 216 return true; 217 } 218 bool TraversePackExpansionExpr(PackExpansionExpr *E) override { 219 return true; 220 } 221 bool TraverseCXXFoldExpr(CXXFoldExpr *E) override { return true; } 222 bool TraversePackIndexingExpr(PackIndexingExpr *E) override { 223 return DynamicRecursiveASTVisitor::TraverseStmt(E->getIndexExpr()); 224 } 225 bool TraversePackIndexingType(PackIndexingType *E) override { 226 return DynamicRecursiveASTVisitor::TraverseStmt(E->getIndexExpr()); 227 } 228 bool TraversePackIndexingTypeLoc(PackIndexingTypeLoc TL) override { 229 return DynamicRecursiveASTVisitor::TraverseStmt(TL.getIndexExpr()); 230 } 231 232 ///@} 233 234 /// Suppress traversal of using-declaration pack expansion. 235 bool 236 TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) override { 237 if (D->isPackExpansion()) 238 return true; 239 240 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingValueDecl(D); 241 } 242 243 /// Suppress traversal of using-declaration pack expansion. 244 bool TraverseUnresolvedUsingTypenameDecl( 245 UnresolvedUsingTypenameDecl *D) override { 246 if (D->isPackExpansion()) 247 return true; 248 249 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingTypenameDecl(D); 250 } 251 252 /// Suppress traversal of template argument pack expansions. 253 bool TraverseTemplateArgument(const TemplateArgument &Arg) override { 254 if (Arg.isPackExpansion()) 255 return true; 256 257 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg); 258 } 259 260 /// Suppress traversal of template argument pack expansions. 261 bool 262 TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) override { 263 if (ArgLoc.getArgument().isPackExpansion()) 264 return true; 265 266 return DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc); 267 } 268 269 /// Suppress traversal of base specifier pack expansions. 270 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) override { 271 if (Base.isPackExpansion()) 272 return true; 273 274 return DynamicRecursiveASTVisitor::TraverseCXXBaseSpecifier(Base); 275 } 276 277 /// Suppress traversal of mem-initializer pack expansions. 278 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override { 279 if (Init->isPackExpansion()) 280 return true; 281 282 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init); 283 } 284 285 /// Note whether we're traversing a lambda containing an unexpanded 286 /// parameter pack. In this case, the unexpanded pack can occur anywhere, 287 /// including all the places where we normally wouldn't look. Within a 288 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit 289 /// outside an expression. 290 bool TraverseLambdaExpr(LambdaExpr *Lambda) override { 291 // The ContainsUnexpandedParameterPack bit on a lambda is always correct, 292 // even if it's contained within another lambda. 293 if (!Lambda->containsUnexpandedParameterPack()) 294 return true; 295 296 SaveAndRestore _(InLambdaOrBlock, true); 297 unsigned OldDepthLimit = DepthLimit; 298 299 if (auto *TPL = Lambda->getTemplateParameterList()) 300 DepthLimit = TPL->getDepth(); 301 302 DynamicRecursiveASTVisitor::TraverseLambdaExpr(Lambda); 303 304 DepthLimit = OldDepthLimit; 305 return true; 306 } 307 308 /// Analogously for blocks. 309 bool TraverseBlockExpr(BlockExpr *Block) override { 310 if (!Block->containsUnexpandedParameterPack()) 311 return true; 312 313 SaveAndRestore _(InLambdaOrBlock, true); 314 DynamicRecursiveASTVisitor::TraverseBlockExpr(Block); 315 return true; 316 } 317 318 /// Suppress traversal within pack expansions in lambda captures. 319 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C, 320 Expr *Init) override { 321 if (C->isPackExpansion()) 322 return true; 323 324 return DynamicRecursiveASTVisitor::TraverseLambdaCapture(Lambda, C, Init); 325 } 326 327 #ifndef NDEBUG 328 bool TraverseFunctionParmPackExpr(FunctionParmPackExpr *) override { 329 ContainsIntermediatePacks = true; 330 return true; 331 } 332 333 bool TraverseSubstNonTypeTemplateParmPackExpr( 334 SubstNonTypeTemplateParmPackExpr *) override { 335 ContainsIntermediatePacks = true; 336 return true; 337 } 338 339 bool VisitSubstTemplateTypeParmPackType( 340 SubstTemplateTypeParmPackType *) override { 341 ContainsIntermediatePacks = true; 342 return true; 343 } 344 345 bool VisitSubstTemplateTypeParmPackTypeLoc( 346 SubstTemplateTypeParmPackTypeLoc) override { 347 ContainsIntermediatePacks = true; 348 return true; 349 } 350 351 bool containsIntermediatePacks() const { return ContainsIntermediatePacks; } 352 #endif 353 }; 354 } 355 356 /// Determine whether it's possible for an unexpanded parameter pack to 357 /// be valid in this location. This only happens when we're in a declaration 358 /// that is nested within an expression that could be expanded, such as a 359 /// lambda-expression within a function call. 360 /// 361 /// This is conservatively correct, but may claim that some unexpanded packs are 362 /// permitted when they are not. 363 bool Sema::isUnexpandedParameterPackPermitted() { 364 for (auto *SI : FunctionScopes) 365 if (isa<sema::LambdaScopeInfo>(SI)) 366 return true; 367 return false; 368 } 369 370 /// Diagnose all of the unexpanded parameter packs in the given 371 /// vector. 372 bool 373 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 374 UnexpandedParameterPackContext UPPC, 375 ArrayRef<UnexpandedParameterPack> Unexpanded) { 376 if (Unexpanded.empty()) 377 return false; 378 379 // If we are within a lambda expression and referencing a pack that is not 380 // declared within the lambda itself, that lambda contains an unexpanded 381 // parameter pack, and we are done. Analogously for blocks. 382 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it 383 // later. 384 SmallVector<UnexpandedParameterPack, 4> ParamPackReferences; 385 if (sema::CapturingScopeInfo *CSI = getEnclosingLambdaOrBlock()) { 386 for (auto &Pack : Unexpanded) { 387 auto DeclaresThisPack = [&](NamedDecl *LocalPack) { 388 if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) { 389 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack); 390 return TTPD && TTPD->getTypeForDecl() == TTPT; 391 } 392 return declaresSameEntity(cast<NamedDecl *>(Pack.first), LocalPack); 393 }; 394 if (llvm::any_of(CSI->LocalPacks, DeclaresThisPack)) 395 ParamPackReferences.push_back(Pack); 396 } 397 398 if (ParamPackReferences.empty()) { 399 // Construct in lambda only references packs declared outside the lambda. 400 // That's OK for now, but the lambda itself is considered to contain an 401 // unexpanded pack in this case, which will require expansion outside the 402 // lambda. 403 404 // We do not permit pack expansion that would duplicate a statement 405 // expression, not even within a lambda. 406 // FIXME: We could probably support this for statement expressions that 407 // do not contain labels. 408 // FIXME: This is insufficient to detect this problem; consider 409 // f( ({ bad: 0; }) + pack ... ); 410 bool EnclosingStmtExpr = false; 411 for (unsigned N = FunctionScopes.size(); N; --N) { 412 sema::FunctionScopeInfo *Func = FunctionScopes[N-1]; 413 if (llvm::any_of( 414 Func->CompoundScopes, 415 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) { 416 EnclosingStmtExpr = true; 417 break; 418 } 419 // Coumpound-statements outside the lambda are OK for now; we'll check 420 // for those when we finish handling the lambda. 421 if (Func == CSI) 422 break; 423 } 424 425 if (!EnclosingStmtExpr) { 426 CSI->ContainsUnexpandedParameterPack = true; 427 return false; 428 } 429 } else { 430 Unexpanded = ParamPackReferences; 431 } 432 } 433 434 SmallVector<SourceLocation, 4> Locations; 435 SmallVector<IdentifierInfo *, 4> Names; 436 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown; 437 438 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 439 IdentifierInfo *Name = nullptr; 440 if (const TemplateTypeParmType *TTP 441 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) 442 Name = TTP->getIdentifier(); 443 else if (NamedDecl *ND = Unexpanded[I].first.dyn_cast<NamedDecl *>()) 444 Name = ND->getIdentifier(); 445 446 if (Name && NamesKnown.insert(Name).second) 447 Names.push_back(Name); 448 449 if (Unexpanded[I].second.isValid()) 450 Locations.push_back(Unexpanded[I].second); 451 } 452 453 auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack) 454 << (int)UPPC << (int)Names.size(); 455 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I) 456 DB << Names[I]; 457 458 for (unsigned I = 0, N = Locations.size(); I != N; ++I) 459 DB << SourceRange(Locations[I]); 460 return true; 461 } 462 463 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, 464 TypeSourceInfo *T, 465 UnexpandedParameterPackContext UPPC) { 466 // C++0x [temp.variadic]p5: 467 // An appearance of a name of a parameter pack that is not expanded is 468 // ill-formed. 469 if (!T->getType()->containsUnexpandedParameterPack()) 470 return false; 471 472 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 473 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc( 474 T->getTypeLoc()); 475 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 476 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded); 477 } 478 479 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E, 480 UnexpandedParameterPackContext UPPC) { 481 // C++0x [temp.variadic]p5: 482 // An appearance of a name of a parameter pack that is not expanded is 483 // ill-formed. 484 if (!E->containsUnexpandedParameterPack()) 485 return false; 486 487 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 488 CollectUnexpandedParameterPacksVisitor Visitor(Unexpanded); 489 Visitor.TraverseStmt(E); 490 #ifndef NDEBUG 491 // The expression might contain a type/subexpression that has been substituted 492 // but has the expansion held off, e.g. a FunctionParmPackExpr which a larger 493 // CXXFoldExpr would expand. It's only possible when expanding a lambda as a 494 // pattern of a fold expression, so don't fire on an empty result in that 495 // case. 496 bool LambdaReferencingOuterPacks = 497 getEnclosingLambdaOrBlock() && Visitor.containsIntermediatePacks(); 498 assert((!Unexpanded.empty() || LambdaReferencingOuterPacks) && 499 "Unable to find unexpanded parameter packs"); 500 #endif 501 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded); 502 } 503 504 bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) { 505 if (!RE->containsUnexpandedParameterPack()) 506 return false; 507 508 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 509 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE); 510 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 511 512 // We only care about unexpanded references to the RequiresExpr's own 513 // parameter packs. 514 auto Parms = RE->getLocalParameters(); 515 llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end()); 516 SmallVector<UnexpandedParameterPack, 2> UnexpandedParms; 517 for (auto Parm : Unexpanded) 518 if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl *>())) 519 UnexpandedParms.push_back(Parm); 520 if (UnexpandedParms.empty()) 521 return false; 522 523 return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement, 524 UnexpandedParms); 525 } 526 527 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 528 UnexpandedParameterPackContext UPPC) { 529 // C++0x [temp.variadic]p5: 530 // An appearance of a name of a parameter pack that is not expanded is 531 // ill-formed. 532 if (!SS.getScopeRep() || 533 !SS.getScopeRep()->containsUnexpandedParameterPack()) 534 return false; 535 536 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 537 CollectUnexpandedParameterPacksVisitor(Unexpanded) 538 .TraverseNestedNameSpecifier(SS.getScopeRep()); 539 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 540 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(), 541 UPPC, Unexpanded); 542 } 543 544 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 545 UnexpandedParameterPackContext UPPC) { 546 // C++0x [temp.variadic]p5: 547 // An appearance of a name of a parameter pack that is not expanded is 548 // ill-formed. 549 switch (NameInfo.getName().getNameKind()) { 550 case DeclarationName::Identifier: 551 case DeclarationName::ObjCZeroArgSelector: 552 case DeclarationName::ObjCOneArgSelector: 553 case DeclarationName::ObjCMultiArgSelector: 554 case DeclarationName::CXXOperatorName: 555 case DeclarationName::CXXLiteralOperatorName: 556 case DeclarationName::CXXUsingDirective: 557 case DeclarationName::CXXDeductionGuideName: 558 return false; 559 560 case DeclarationName::CXXConstructorName: 561 case DeclarationName::CXXDestructorName: 562 case DeclarationName::CXXConversionFunctionName: 563 // FIXME: We shouldn't need this null check! 564 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo()) 565 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC); 566 567 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack()) 568 return false; 569 570 break; 571 } 572 573 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 574 CollectUnexpandedParameterPacksVisitor(Unexpanded) 575 .TraverseType(NameInfo.getName().getCXXNameType()); 576 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 577 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded); 578 } 579 580 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, 581 TemplateName Template, 582 UnexpandedParameterPackContext UPPC) { 583 584 if (Template.isNull() || !Template.containsUnexpandedParameterPack()) 585 return false; 586 587 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 588 CollectUnexpandedParameterPacksVisitor(Unexpanded) 589 .TraverseTemplateName(Template); 590 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 591 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded); 592 } 593 594 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 595 UnexpandedParameterPackContext UPPC) { 596 if (Arg.getArgument().isNull() || 597 !Arg.getArgument().containsUnexpandedParameterPack()) 598 return false; 599 600 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 601 CollectUnexpandedParameterPacksVisitor(Unexpanded) 602 .TraverseTemplateArgumentLoc(Arg); 603 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs"); 604 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded); 605 } 606 607 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg, 608 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 609 CollectUnexpandedParameterPacksVisitor(Unexpanded) 610 .TraverseTemplateArgument(Arg); 611 } 612 613 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 614 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 615 CollectUnexpandedParameterPacksVisitor(Unexpanded) 616 .TraverseTemplateArgumentLoc(Arg); 617 } 618 619 void Sema::collectUnexpandedParameterPacks(QualType T, 620 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 621 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T); 622 } 623 624 void Sema::collectUnexpandedParameterPacks(TypeLoc TL, 625 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 626 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); 627 } 628 629 void Sema::collectUnexpandedParameterPacks( 630 NestedNameSpecifierLoc NNS, 631 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 632 CollectUnexpandedParameterPacksVisitor(Unexpanded) 633 .TraverseNestedNameSpecifierLoc(NNS); 634 } 635 636 void Sema::collectUnexpandedParameterPacks( 637 const DeclarationNameInfo &NameInfo, 638 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 639 CollectUnexpandedParameterPacksVisitor(Unexpanded) 640 .TraverseDeclarationNameInfo(NameInfo); 641 } 642 643 void Sema::collectUnexpandedParameterPacks( 644 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 645 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E); 646 } 647 648 ParsedTemplateArgument 649 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, 650 SourceLocation EllipsisLoc) { 651 if (Arg.isInvalid()) 652 return Arg; 653 654 switch (Arg.getKind()) { 655 case ParsedTemplateArgument::Type: { 656 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc); 657 if (Result.isInvalid()) 658 return ParsedTemplateArgument(); 659 660 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), 661 Arg.getLocation()); 662 } 663 664 case ParsedTemplateArgument::NonType: { 665 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc); 666 if (Result.isInvalid()) 667 return ParsedTemplateArgument(); 668 669 return ParsedTemplateArgument(Arg.getKind(), Result.get(), 670 Arg.getLocation()); 671 } 672 673 case ParsedTemplateArgument::Template: 674 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) { 675 SourceRange R(Arg.getLocation()); 676 if (Arg.getScopeSpec().isValid()) 677 R.setBegin(Arg.getScopeSpec().getBeginLoc()); 678 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 679 << R; 680 return ParsedTemplateArgument(); 681 } 682 683 return Arg.getTemplatePackExpansion(EllipsisLoc); 684 } 685 llvm_unreachable("Unhandled template argument kind?"); 686 } 687 688 TypeResult Sema::ActOnPackExpansion(ParsedType Type, 689 SourceLocation EllipsisLoc) { 690 TypeSourceInfo *TSInfo; 691 GetTypeFromParser(Type, &TSInfo); 692 if (!TSInfo) 693 return true; 694 695 TypeSourceInfo *TSResult = 696 CheckPackExpansion(TSInfo, EllipsisLoc, std::nullopt); 697 if (!TSResult) 698 return true; 699 700 return CreateParsedType(TSResult->getType(), TSResult); 701 } 702 703 TypeSourceInfo * 704 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, 705 std::optional<unsigned> NumExpansions) { 706 // Create the pack expansion type and source-location information. 707 QualType Result = CheckPackExpansion(Pattern->getType(), 708 Pattern->getTypeLoc().getSourceRange(), 709 EllipsisLoc, NumExpansions); 710 if (Result.isNull()) 711 return nullptr; 712 713 TypeLocBuilder TLB; 714 TLB.pushFullCopy(Pattern->getTypeLoc()); 715 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result); 716 TL.setEllipsisLoc(EllipsisLoc); 717 718 return TLB.getTypeSourceInfo(Context, Result); 719 } 720 721 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange, 722 SourceLocation EllipsisLoc, 723 std::optional<unsigned> NumExpansions) { 724 // C++11 [temp.variadic]p5: 725 // The pattern of a pack expansion shall name one or more 726 // parameter packs that are not expanded by a nested pack 727 // expansion. 728 // 729 // A pattern containing a deduced type can't occur "naturally" but arises in 730 // the desugaring of an init-capture pack. 731 if (!Pattern->containsUnexpandedParameterPack() && 732 !Pattern->getContainedDeducedType()) { 733 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 734 << PatternRange; 735 return QualType(); 736 } 737 738 return Context.getPackExpansionType(Pattern, NumExpansions, 739 /*ExpectPackInType=*/false); 740 } 741 742 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) { 743 return CheckPackExpansion(Pattern, EllipsisLoc, std::nullopt); 744 } 745 746 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 747 std::optional<unsigned> NumExpansions) { 748 if (!Pattern) 749 return ExprError(); 750 751 // C++0x [temp.variadic]p5: 752 // The pattern of a pack expansion shall name one or more 753 // parameter packs that are not expanded by a nested pack 754 // expansion. 755 if (!Pattern->containsUnexpandedParameterPack()) { 756 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 757 << Pattern->getSourceRange(); 758 CorrectDelayedTyposInExpr(Pattern); 759 return ExprError(); 760 } 761 762 // Create the pack expansion expression and source-location information. 763 return new (Context) 764 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions); 765 } 766 767 bool Sema::CheckParameterPacksForExpansion( 768 SourceLocation EllipsisLoc, SourceRange PatternRange, 769 ArrayRef<UnexpandedParameterPack> Unexpanded, 770 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, 771 bool &RetainExpansion, std::optional<unsigned> &NumExpansions) { 772 ShouldExpand = true; 773 RetainExpansion = false; 774 std::pair<IdentifierInfo *, SourceLocation> FirstPack; 775 bool HaveFirstPack = false; 776 std::optional<unsigned> NumPartialExpansions; 777 SourceLocation PartiallySubstitutedPackLoc; 778 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 779 780 for (UnexpandedParameterPack ParmPack : Unexpanded) { 781 // Compute the depth and index for this parameter pack. 782 unsigned Depth = 0, Index = 0; 783 IdentifierInfo *Name; 784 bool IsVarDeclPack = false; 785 ResolvedUnexpandedPackExpr *ResolvedPack = nullptr; 786 787 if (const TemplateTypeParmType *TTP = 788 ParmPack.first.dyn_cast<const TemplateTypeParmType *>()) { 789 Depth = TTP->getDepth(); 790 Index = TTP->getIndex(); 791 Name = TTP->getIdentifier(); 792 } else if (auto *RP = 793 ParmPack.first.dyn_cast<ResolvedUnexpandedPackExpr *>()) { 794 ResolvedPack = RP; 795 } else { 796 NamedDecl *ND = cast<NamedDecl *>(ParmPack.first); 797 if (isa<VarDecl>(ND)) 798 IsVarDeclPack = true; 799 else if (isa<BindingDecl>(ND)) { 800 // Find the instantiated BindingDecl and check it for a resolved pack. 801 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = 802 CurrentInstantiationScope->findInstantiationOf(ND); 803 Decl *B = cast<Decl *>(*Instantiation); 804 Expr *BindingExpr = cast<BindingDecl>(B)->getBinding(); 805 ResolvedPack = cast_if_present<ResolvedUnexpandedPackExpr>(BindingExpr); 806 if (!ResolvedPack) { 807 ShouldExpand = false; 808 continue; 809 } 810 } else 811 std::tie(Depth, Index) = getDepthAndIndex(ND); 812 813 Name = ND->getIdentifier(); 814 } 815 816 // Determine the size of this argument pack. 817 unsigned NewPackSize, PendingPackExpansionSize = 0; 818 if (IsVarDeclPack) { 819 // Figure out whether we're instantiating to an argument pack or not. 820 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = 821 CurrentInstantiationScope->findInstantiationOf( 822 cast<NamedDecl *>(ParmPack.first)); 823 if (isa<DeclArgumentPack *>(*Instantiation)) { 824 // We could expand this function parameter pack. 825 NewPackSize = cast<DeclArgumentPack *>(*Instantiation)->size(); 826 } else { 827 // We can't expand this function parameter pack, so we can't expand 828 // the pack expansion. 829 ShouldExpand = false; 830 continue; 831 } 832 } else if (ResolvedPack) { 833 NewPackSize = ResolvedPack->getNumExprs(); 834 } else { 835 // If we don't have a template argument at this depth/index, then we 836 // cannot expand the pack expansion. Make a note of this, but we still 837 // want to check any parameter packs we *do* have arguments for. 838 if (Depth >= TemplateArgs.getNumLevels() || 839 !TemplateArgs.hasTemplateArgument(Depth, Index)) { 840 ShouldExpand = false; 841 continue; 842 } 843 844 // Determine the size of the argument pack. 845 ArrayRef<TemplateArgument> Pack = 846 TemplateArgs(Depth, Index).getPackAsArray(); 847 NewPackSize = Pack.size(); 848 PendingPackExpansionSize = 849 llvm::count_if(Pack, [](const TemplateArgument &TA) { 850 if (!TA.isPackExpansion()) 851 return false; 852 853 if (TA.getKind() == TemplateArgument::Type) 854 return !TA.getAsType() 855 ->getAs<PackExpansionType>() 856 ->getNumExpansions(); 857 858 if (TA.getKind() == TemplateArgument::Expression) 859 return !cast<PackExpansionExpr>(TA.getAsExpr()) 860 ->getNumExpansions(); 861 862 return !TA.getNumTemplateExpansions(); 863 }); 864 } 865 866 // C++0x [temp.arg.explicit]p9: 867 // Template argument deduction can extend the sequence of template 868 // arguments corresponding to a template parameter pack, even when the 869 // sequence contains explicitly specified template arguments. 870 if (!IsVarDeclPack && !ResolvedPack && CurrentInstantiationScope) { 871 if (NamedDecl *PartialPack = 872 CurrentInstantiationScope->getPartiallySubstitutedPack()) { 873 unsigned PartialDepth, PartialIndex; 874 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack); 875 if (PartialDepth == Depth && PartialIndex == Index) { 876 RetainExpansion = true; 877 // We don't actually know the new pack size yet. 878 NumPartialExpansions = NewPackSize; 879 PartiallySubstitutedPackLoc = ParmPack.second; 880 continue; 881 } 882 } 883 } 884 885 if (!NumExpansions) { 886 // This is the first pack we've seen for which we have an argument. 887 // Record it. 888 NumExpansions = NewPackSize; 889 FirstPack.first = Name; 890 FirstPack.second = ParmPack.second; 891 HaveFirstPack = true; 892 continue; 893 } 894 895 if (NewPackSize != *NumExpansions) { 896 // In some cases, we might be handling packs with unexpanded template 897 // arguments. For example, this can occur when substituting into a type 898 // alias declaration that uses its injected template parameters as 899 // arguments: 900 // 901 // template <class... Outer> struct S { 902 // template <class... Inner> using Alias = S<void(Outer, Inner)...>; 903 // }; 904 // 905 // Consider an instantiation attempt like 'S<int>::Alias<Pack...>', where 906 // Pack comes from another template parameter. 'S<int>' is first 907 // instantiated, expanding the outer pack 'Outer' to <int>. The alias 908 // declaration is accordingly substituted, leaving the template arguments 909 // as unexpanded 910 // '<Pack...>'. 911 // 912 // Since we have no idea of the size of '<Pack...>' until its expansion, 913 // we shouldn't assume its pack size for validation. However if we are 914 // certain that there are extra arguments beyond unexpanded packs, in 915 // which case the pack size is already larger than the previous expansion, 916 // we can complain that before instantiation. 917 unsigned LeastNewPackSize = NewPackSize - PendingPackExpansionSize; 918 if (PendingPackExpansionSize && LeastNewPackSize <= *NumExpansions) { 919 ShouldExpand = false; 920 continue; 921 } 922 // C++0x [temp.variadic]p5: 923 // All of the parameter packs expanded by a pack expansion shall have 924 // the same number of arguments specified. 925 if (HaveFirstPack) 926 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) 927 << FirstPack.first << Name << *NumExpansions 928 << (LeastNewPackSize != NewPackSize) << LeastNewPackSize 929 << SourceRange(FirstPack.second) << SourceRange(ParmPack.second); 930 else 931 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel) 932 << Name << *NumExpansions << (LeastNewPackSize != NewPackSize) 933 << LeastNewPackSize << SourceRange(ParmPack.second); 934 return true; 935 } 936 } 937 938 // If we're performing a partial expansion but we also have a full expansion, 939 // expand to the number of common arguments. For example, given: 940 // 941 // template<typename ...T> struct A { 942 // template<typename ...U> void f(pair<T, U>...); 943 // }; 944 // 945 // ... a call to 'A<int, int>().f<int>' should expand the pack once and 946 // retain an expansion. 947 if (NumPartialExpansions) { 948 if (NumExpansions && *NumExpansions < *NumPartialExpansions) { 949 NamedDecl *PartialPack = 950 CurrentInstantiationScope->getPartiallySubstitutedPack(); 951 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial) 952 << PartialPack << *NumPartialExpansions << *NumExpansions 953 << SourceRange(PartiallySubstitutedPackLoc); 954 return true; 955 } 956 957 NumExpansions = NumPartialExpansions; 958 } 959 960 return false; 961 } 962 963 std::optional<unsigned> Sema::getNumArgumentsInExpansionFromUnexpanded( 964 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 965 const MultiLevelTemplateArgumentList &TemplateArgs) { 966 std::optional<unsigned> Result; 967 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 968 // Compute the depth and index for this parameter pack. 969 unsigned Depth; 970 unsigned Index; 971 972 if (const TemplateTypeParmType *TTP = 973 Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) { 974 Depth = TTP->getDepth(); 975 Index = TTP->getIndex(); 976 } else if (auto *PE = Unexpanded[I] 977 .first.dyn_cast<ResolvedUnexpandedPackExpr *>()) { 978 unsigned Size = PE->getNumExprs(); 979 assert((!Result || *Result == Size) && "inconsistent pack sizes"); 980 Result = Size; 981 continue; 982 } else { 983 NamedDecl *ND = cast<NamedDecl *>(Unexpanded[I].first); 984 if (isa<VarDecl>(ND)) { 985 // Function parameter pack or init-capture pack. 986 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 987 988 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = 989 CurrentInstantiationScope->findInstantiationOf( 990 cast<NamedDecl *>(Unexpanded[I].first)); 991 if (isa<Decl *>(*Instantiation)) 992 // The pattern refers to an unexpanded pack. We're not ready to expand 993 // this pack yet. 994 return std::nullopt; 995 996 unsigned Size = cast<DeclArgumentPack *>(*Instantiation)->size(); 997 assert((!Result || *Result == Size) && "inconsistent pack sizes"); 998 Result = Size; 999 continue; 1000 } 1001 1002 std::tie(Depth, Index) = getDepthAndIndex(ND); 1003 } 1004 if (Depth >= TemplateArgs.getNumLevels() || 1005 !TemplateArgs.hasTemplateArgument(Depth, Index)) 1006 // The pattern refers to an unknown template argument. We're not ready to 1007 // expand this pack yet. 1008 return std::nullopt; 1009 1010 // Determine the size of the argument pack. 1011 unsigned Size = TemplateArgs(Depth, Index).pack_size(); 1012 assert((!Result || *Result == Size) && "inconsistent pack sizes"); 1013 Result = Size; 1014 } 1015 1016 return Result; 1017 } 1018 1019 std::optional<unsigned> Sema::getNumArgumentsInExpansion( 1020 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) { 1021 QualType Pattern = cast<PackExpansionType>(T)->getPattern(); 1022 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1023 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern); 1024 return getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs); 1025 } 1026 1027 bool Sema::containsUnexpandedParameterPacks(Declarator &D) { 1028 const DeclSpec &DS = D.getDeclSpec(); 1029 switch (DS.getTypeSpecType()) { 1030 case TST_typename_pack_indexing: 1031 case TST_typename: 1032 case TST_typeof_unqualType: 1033 case TST_typeofType: 1034 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait: 1035 #include "clang/Basic/TransformTypeTraits.def" 1036 case TST_atomic: { 1037 QualType T = DS.getRepAsType().get(); 1038 if (!T.isNull() && T->containsUnexpandedParameterPack()) 1039 return true; 1040 break; 1041 } 1042 1043 case TST_typeof_unqualExpr: 1044 case TST_typeofExpr: 1045 case TST_decltype: 1046 case TST_bitint: 1047 if (DS.getRepAsExpr() && 1048 DS.getRepAsExpr()->containsUnexpandedParameterPack()) 1049 return true; 1050 break; 1051 1052 case TST_unspecified: 1053 case TST_void: 1054 case TST_char: 1055 case TST_wchar: 1056 case TST_char8: 1057 case TST_char16: 1058 case TST_char32: 1059 case TST_int: 1060 case TST_int128: 1061 case TST_half: 1062 case TST_float: 1063 case TST_double: 1064 case TST_Accum: 1065 case TST_Fract: 1066 case TST_Float16: 1067 case TST_float128: 1068 case TST_ibm128: 1069 case TST_bool: 1070 case TST_decimal32: 1071 case TST_decimal64: 1072 case TST_decimal128: 1073 case TST_enum: 1074 case TST_union: 1075 case TST_struct: 1076 case TST_interface: 1077 case TST_class: 1078 case TST_auto: 1079 case TST_auto_type: 1080 case TST_decltype_auto: 1081 case TST_BFloat16: 1082 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t: 1083 #include "clang/Basic/OpenCLImageTypes.def" 1084 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case TST_##Name: 1085 #include "clang/Basic/HLSLIntangibleTypes.def" 1086 case TST_unknown_anytype: 1087 case TST_error: 1088 break; 1089 } 1090 1091 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) { 1092 const DeclaratorChunk &Chunk = D.getTypeObject(I); 1093 switch (Chunk.Kind) { 1094 case DeclaratorChunk::Pointer: 1095 case DeclaratorChunk::Reference: 1096 case DeclaratorChunk::Paren: 1097 case DeclaratorChunk::Pipe: 1098 case DeclaratorChunk::BlockPointer: 1099 // These declarator chunks cannot contain any parameter packs. 1100 break; 1101 1102 case DeclaratorChunk::Array: 1103 if (Chunk.Arr.NumElts && 1104 Chunk.Arr.NumElts->containsUnexpandedParameterPack()) 1105 return true; 1106 break; 1107 case DeclaratorChunk::Function: 1108 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) { 1109 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param); 1110 QualType ParamTy = Param->getType(); 1111 assert(!ParamTy.isNull() && "Couldn't parse type?"); 1112 if (ParamTy->containsUnexpandedParameterPack()) return true; 1113 } 1114 1115 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) { 1116 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) { 1117 if (Chunk.Fun.Exceptions[i] 1118 .Ty.get() 1119 ->containsUnexpandedParameterPack()) 1120 return true; 1121 } 1122 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) && 1123 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack()) 1124 return true; 1125 1126 if (Chunk.Fun.hasTrailingReturnType()) { 1127 QualType T = Chunk.Fun.getTrailingReturnType().get(); 1128 if (!T.isNull() && T->containsUnexpandedParameterPack()) 1129 return true; 1130 } 1131 break; 1132 1133 case DeclaratorChunk::MemberPointer: 1134 if (Chunk.Mem.Scope().getScopeRep() && 1135 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack()) 1136 return true; 1137 break; 1138 } 1139 } 1140 1141 if (Expr *TRC = D.getTrailingRequiresClause()) 1142 if (TRC->containsUnexpandedParameterPack()) 1143 return true; 1144 1145 return false; 1146 } 1147 1148 namespace { 1149 1150 // Callback to only accept typo corrections that refer to parameter packs. 1151 class ParameterPackValidatorCCC final : public CorrectionCandidateCallback { 1152 public: 1153 bool ValidateCandidate(const TypoCorrection &candidate) override { 1154 NamedDecl *ND = candidate.getCorrectionDecl(); 1155 return ND && ND->isParameterPack(); 1156 } 1157 1158 std::unique_ptr<CorrectionCandidateCallback> clone() override { 1159 return std::make_unique<ParameterPackValidatorCCC>(*this); 1160 } 1161 }; 1162 1163 } 1164 1165 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, 1166 SourceLocation OpLoc, 1167 IdentifierInfo &Name, 1168 SourceLocation NameLoc, 1169 SourceLocation RParenLoc) { 1170 // C++0x [expr.sizeof]p5: 1171 // The identifier in a sizeof... expression shall name a parameter pack. 1172 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName); 1173 LookupName(R, S); 1174 1175 NamedDecl *ParameterPack = nullptr; 1176 switch (R.getResultKind()) { 1177 case LookupResult::Found: 1178 ParameterPack = R.getFoundDecl(); 1179 break; 1180 1181 case LookupResult::NotFound: 1182 case LookupResult::NotFoundInCurrentInstantiation: { 1183 ParameterPackValidatorCCC CCC{}; 1184 if (TypoCorrection Corrected = 1185 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr, 1186 CCC, CTK_ErrorRecovery)) { 1187 diagnoseTypo(Corrected, 1188 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name, 1189 PDiag(diag::note_parameter_pack_here)); 1190 ParameterPack = Corrected.getCorrectionDecl(); 1191 } 1192 break; 1193 } 1194 case LookupResult::FoundOverloaded: 1195 case LookupResult::FoundUnresolvedValue: 1196 break; 1197 1198 case LookupResult::Ambiguous: 1199 DiagnoseAmbiguousLookup(R); 1200 return ExprError(); 1201 } 1202 1203 if (!ParameterPack || !ParameterPack->isParameterPack()) { 1204 Diag(NameLoc, diag::err_expected_name_of_pack) << &Name; 1205 return ExprError(); 1206 } 1207 1208 MarkAnyDeclReferenced(OpLoc, ParameterPack, true); 1209 1210 std::optional<unsigned> Length; 1211 if (auto *RP = ResolvedUnexpandedPackExpr::getFromDecl(ParameterPack)) 1212 Length = RP->getNumExprs(); 1213 1214 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc, 1215 RParenLoc, Length); 1216 } 1217 1218 static bool isParameterPack(Expr *PackExpression) { 1219 if (auto *D = dyn_cast<DeclRefExpr>(PackExpression); D) { 1220 ValueDecl *VD = D->getDecl(); 1221 return VD->isParameterPack(); 1222 } 1223 return false; 1224 } 1225 1226 ExprResult Sema::ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, 1227 SourceLocation EllipsisLoc, 1228 SourceLocation LSquareLoc, 1229 Expr *IndexExpr, 1230 SourceLocation RSquareLoc) { 1231 bool isParameterPack = ::isParameterPack(PackExpression); 1232 if (!isParameterPack) { 1233 if (!PackExpression->containsErrors()) { 1234 CorrectDelayedTyposInExpr(IndexExpr); 1235 Diag(PackExpression->getBeginLoc(), diag::err_expected_name_of_pack) 1236 << PackExpression; 1237 } 1238 return ExprError(); 1239 } 1240 ExprResult Res = 1241 BuildPackIndexingExpr(PackExpression, EllipsisLoc, IndexExpr, RSquareLoc); 1242 if (!Res.isInvalid()) 1243 Diag(Res.get()->getBeginLoc(), getLangOpts().CPlusPlus26 1244 ? diag::warn_cxx23_pack_indexing 1245 : diag::ext_pack_indexing); 1246 return Res; 1247 } 1248 1249 ExprResult Sema::BuildPackIndexingExpr(Expr *PackExpression, 1250 SourceLocation EllipsisLoc, 1251 Expr *IndexExpr, 1252 SourceLocation RSquareLoc, 1253 ArrayRef<Expr *> ExpandedExprs, 1254 bool FullySubstituted) { 1255 1256 std::optional<int64_t> Index; 1257 if (!IndexExpr->isInstantiationDependent()) { 1258 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 1259 1260 ExprResult Res = CheckConvertedConstantExpression( 1261 IndexExpr, Context.getSizeType(), Value, CCEK_ArrayBound); 1262 if (!Res.isUsable()) 1263 return ExprError(); 1264 Index = Value.getExtValue(); 1265 IndexExpr = Res.get(); 1266 } 1267 1268 if (Index && FullySubstituted) { 1269 if (*Index < 0 || *Index >= int64_t(ExpandedExprs.size())) { 1270 Diag(PackExpression->getBeginLoc(), diag::err_pack_index_out_of_bound) 1271 << *Index << PackExpression << ExpandedExprs.size(); 1272 return ExprError(); 1273 } 1274 } 1275 1276 return PackIndexingExpr::Create(getASTContext(), EllipsisLoc, RSquareLoc, 1277 PackExpression, IndexExpr, Index, 1278 ExpandedExprs, FullySubstituted); 1279 } 1280 1281 TemplateArgumentLoc Sema::getTemplateArgumentPackExpansionPattern( 1282 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, 1283 std::optional<unsigned> &NumExpansions) const { 1284 const TemplateArgument &Argument = OrigLoc.getArgument(); 1285 assert(Argument.isPackExpansion()); 1286 switch (Argument.getKind()) { 1287 case TemplateArgument::Type: { 1288 // FIXME: We shouldn't ever have to worry about missing 1289 // type-source info! 1290 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo(); 1291 if (!ExpansionTSInfo) 1292 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(), 1293 Ellipsis); 1294 PackExpansionTypeLoc Expansion = 1295 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>(); 1296 Ellipsis = Expansion.getEllipsisLoc(); 1297 1298 TypeLoc Pattern = Expansion.getPatternLoc(); 1299 NumExpansions = Expansion.getTypePtr()->getNumExpansions(); 1300 1301 // We need to copy the TypeLoc because TemplateArgumentLocs store a 1302 // TypeSourceInfo. 1303 // FIXME: Find some way to avoid the copy? 1304 TypeLocBuilder TLB; 1305 TLB.pushFullCopy(Pattern); 1306 TypeSourceInfo *PatternTSInfo = 1307 TLB.getTypeSourceInfo(Context, Pattern.getType()); 1308 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()), 1309 PatternTSInfo); 1310 } 1311 1312 case TemplateArgument::Expression: { 1313 PackExpansionExpr *Expansion 1314 = cast<PackExpansionExpr>(Argument.getAsExpr()); 1315 Expr *Pattern = Expansion->getPattern(); 1316 Ellipsis = Expansion->getEllipsisLoc(); 1317 NumExpansions = Expansion->getNumExpansions(); 1318 return TemplateArgumentLoc(Pattern, Pattern); 1319 } 1320 1321 case TemplateArgument::TemplateExpansion: 1322 Ellipsis = OrigLoc.getTemplateEllipsisLoc(); 1323 NumExpansions = Argument.getNumTemplateExpansions(); 1324 return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(), 1325 OrigLoc.getTemplateQualifierLoc(), 1326 OrigLoc.getTemplateNameLoc()); 1327 1328 case TemplateArgument::Declaration: 1329 case TemplateArgument::NullPtr: 1330 case TemplateArgument::Template: 1331 case TemplateArgument::Integral: 1332 case TemplateArgument::StructuralValue: 1333 case TemplateArgument::Pack: 1334 case TemplateArgument::Null: 1335 return TemplateArgumentLoc(); 1336 } 1337 1338 llvm_unreachable("Invalid TemplateArgument Kind!"); 1339 } 1340 1341 std::optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) { 1342 assert(Arg.containsUnexpandedParameterPack()); 1343 1344 // If this is a substituted pack, grab that pack. If not, we don't know 1345 // the size yet. 1346 // FIXME: We could find a size in more cases by looking for a substituted 1347 // pack anywhere within this argument, but that's not necessary in the common 1348 // case for 'sizeof...(A)' handling. 1349 TemplateArgument Pack; 1350 switch (Arg.getKind()) { 1351 case TemplateArgument::Type: 1352 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>()) 1353 Pack = Subst->getArgumentPack(); 1354 else 1355 return std::nullopt; 1356 break; 1357 1358 case TemplateArgument::Expression: 1359 if (auto *Subst = 1360 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr())) 1361 Pack = Subst->getArgumentPack(); 1362 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) { 1363 for (VarDecl *PD : *Subst) 1364 if (PD->isParameterPack()) 1365 return std::nullopt; 1366 return Subst->getNumExpansions(); 1367 } else 1368 return std::nullopt; 1369 break; 1370 1371 case TemplateArgument::Template: 1372 if (SubstTemplateTemplateParmPackStorage *Subst = 1373 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack()) 1374 Pack = Subst->getArgumentPack(); 1375 else 1376 return std::nullopt; 1377 break; 1378 1379 case TemplateArgument::Declaration: 1380 case TemplateArgument::NullPtr: 1381 case TemplateArgument::TemplateExpansion: 1382 case TemplateArgument::Integral: 1383 case TemplateArgument::StructuralValue: 1384 case TemplateArgument::Pack: 1385 case TemplateArgument::Null: 1386 return std::nullopt; 1387 } 1388 1389 // Check that no argument in the pack is itself a pack expansion. 1390 for (TemplateArgument Elem : Pack.pack_elements()) { 1391 // There's no point recursing in this case; we would have already 1392 // expanded this pack expansion into the enclosing pack if we could. 1393 if (Elem.isPackExpansion()) 1394 return std::nullopt; 1395 // Don't guess the size of unexpanded packs. The pack within a template 1396 // argument may have yet to be of a PackExpansion type before we see the 1397 // ellipsis in the annotation stage. 1398 // 1399 // This doesn't mean we would invalidate the optimization: Arg can be an 1400 // unexpanded pack regardless of Elem's dependence. For instance, 1401 // A TemplateArgument that contains either a SubstTemplateTypeParmPackType 1402 // or SubstNonTypeTemplateParmPackExpr is always considered Unexpanded, but 1403 // the underlying TemplateArgument thereof may not. 1404 if (Elem.containsUnexpandedParameterPack()) 1405 return std::nullopt; 1406 } 1407 return Pack.pack_size(); 1408 } 1409 1410 static void CheckFoldOperand(Sema &S, Expr *E) { 1411 if (!E) 1412 return; 1413 1414 E = E->IgnoreImpCasts(); 1415 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 1416 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) || 1417 isa<AbstractConditionalOperator>(E)) { 1418 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand) 1419 << E->getSourceRange() 1420 << FixItHint::CreateInsertion(E->getBeginLoc(), "(") 1421 << FixItHint::CreateInsertion(E->getEndLoc(), ")"); 1422 } 1423 } 1424 1425 ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, 1426 tok::TokenKind Operator, 1427 SourceLocation EllipsisLoc, Expr *RHS, 1428 SourceLocation RParenLoc) { 1429 // LHS and RHS must be cast-expressions. We allow an arbitrary expression 1430 // in the parser and reduce down to just cast-expressions here. 1431 CheckFoldOperand(*this, LHS); 1432 CheckFoldOperand(*this, RHS); 1433 1434 auto DiscardOperands = [&] { 1435 CorrectDelayedTyposInExpr(LHS); 1436 CorrectDelayedTyposInExpr(RHS); 1437 }; 1438 1439 // [expr.prim.fold]p3: 1440 // In a binary fold, op1 and op2 shall be the same fold-operator, and 1441 // either e1 shall contain an unexpanded parameter pack or e2 shall contain 1442 // an unexpanded parameter pack, but not both. 1443 if (LHS && RHS && 1444 LHS->containsUnexpandedParameterPack() == 1445 RHS->containsUnexpandedParameterPack()) { 1446 DiscardOperands(); 1447 return Diag(EllipsisLoc, 1448 LHS->containsUnexpandedParameterPack() 1449 ? diag::err_fold_expression_packs_both_sides 1450 : diag::err_pack_expansion_without_parameter_packs) 1451 << LHS->getSourceRange() << RHS->getSourceRange(); 1452 } 1453 1454 // [expr.prim.fold]p2: 1455 // In a unary fold, the cast-expression shall contain an unexpanded 1456 // parameter pack. 1457 if (!LHS || !RHS) { 1458 Expr *Pack = LHS ? LHS : RHS; 1459 assert(Pack && "fold expression with neither LHS nor RHS"); 1460 if (!Pack->containsUnexpandedParameterPack()) { 1461 DiscardOperands(); 1462 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1463 << Pack->getSourceRange(); 1464 } 1465 } 1466 1467 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator); 1468 1469 // Perform first-phase name lookup now. 1470 UnresolvedLookupExpr *ULE = nullptr; 1471 { 1472 UnresolvedSet<16> Functions; 1473 LookupBinOp(S, EllipsisLoc, Opc, Functions); 1474 if (!Functions.empty()) { 1475 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName( 1476 BinaryOperator::getOverloadedOperator(Opc)); 1477 ExprResult Callee = CreateUnresolvedLookupExpr( 1478 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(), 1479 DeclarationNameInfo(OpName, EllipsisLoc), Functions); 1480 if (Callee.isInvalid()) 1481 return ExprError(); 1482 ULE = cast<UnresolvedLookupExpr>(Callee.get()); 1483 } 1484 } 1485 1486 return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc, 1487 std::nullopt); 1488 } 1489 1490 ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 1491 SourceLocation LParenLoc, Expr *LHS, 1492 BinaryOperatorKind Operator, 1493 SourceLocation EllipsisLoc, Expr *RHS, 1494 SourceLocation RParenLoc, 1495 std::optional<unsigned> NumExpansions) { 1496 return new (Context) 1497 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator, 1498 EllipsisLoc, RHS, RParenLoc, NumExpansions); 1499 } 1500 1501 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 1502 BinaryOperatorKind Operator) { 1503 // [temp.variadic]p9: 1504 // If N is zero for a unary fold-expression, the value of the expression is 1505 // && -> true 1506 // || -> false 1507 // , -> void() 1508 // if the operator is not listed [above], the instantiation is ill-formed. 1509 // 1510 // Note that we need to use something like int() here, not merely 0, to 1511 // prevent the result from being a null pointer constant. 1512 QualType ScalarType; 1513 switch (Operator) { 1514 case BO_LOr: 1515 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false); 1516 case BO_LAnd: 1517 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true); 1518 case BO_Comma: 1519 ScalarType = Context.VoidTy; 1520 break; 1521 1522 default: 1523 return Diag(EllipsisLoc, diag::err_fold_expression_empty) 1524 << BinaryOperator::getOpcodeStr(Operator); 1525 } 1526 1527 return new (Context) CXXScalarValueInitExpr( 1528 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc), 1529 EllipsisLoc); 1530 } 1531