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