1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
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 //===----------------------------------------------------------------------===/
8 // This file implements semantic analysis for C++0x variadic templates.
9 //===----------------------------------------------------------------------===/
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"
25 using namespace clang
;
27 //----------------------------------------------------------------------------
28 // Visitor that collects unexpanded parameter packs
29 //----------------------------------------------------------------------------
32 /// A class that collects unexpanded parameter packs.
33 class CollectUnexpandedParameterPacksVisitor
34 : public DynamicRecursiveASTVisitor
{
35 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
;
37 bool InLambdaOrBlock
= false;
38 unsigned DepthLimit
= (unsigned)-1;
41 bool ContainsIntermediatePacks
= false;
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
)
53 } else if (getDepthAndIndex(ND
).first
>= DepthLimit
)
56 Unexpanded
.push_back({ND
, Loc
});
58 void addUnexpanded(const TemplateTypeParmType
*T
,
59 SourceLocation Loc
= SourceLocation()) {
60 if (T
->getDepth() < DepthLimit
)
61 Unexpanded
.push_back({T
, Loc
});
65 explicit CollectUnexpandedParameterPacksVisitor(
66 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
)
67 : Unexpanded(Unexpanded
) {
68 ShouldWalkTypesOfTypeLocs
= false;
70 // We need this so we can find e.g. attributes on lambdas.
71 ShouldVisitImplicitCode
= true;
74 //------------------------------------------------------------------------
75 // Recording occurrences of (unexpanded) parameter packs.
76 //------------------------------------------------------------------------
78 /// Record occurrences of template type parameter packs.
79 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL
) override
{
80 if (TL
.getTypePtr()->isParameterPack())
81 addUnexpanded(TL
.getTypePtr(), TL
.getNameLoc());
85 /// Record occurrences of template type parameter packs
86 /// when we don't have proper source-location information for
89 /// Ideally, this routine would never be used.
90 bool VisitTemplateTypeParmType(TemplateTypeParmType
*T
) override
{
91 if (T
->isParameterPack())
97 /// Record occurrences of function and non-type template
98 /// parameter packs in an expression.
99 bool VisitDeclRefExpr(DeclRefExpr
*E
) override
{
100 if (E
->getDecl()->isParameterPack())
101 addUnexpanded(E
->getDecl(), E
->getLocation());
106 /// Record occurrences of template template parameter packs.
107 bool TraverseTemplateName(TemplateName Template
) override
{
108 if (auto *TTP
= dyn_cast_or_null
<TemplateTemplateParmDecl
>(
109 Template
.getAsTemplateDecl())) {
110 if (TTP
->isParameterPack())
115 ContainsIntermediatePacks
|=
116 (bool)Template
.getAsSubstTemplateTemplateParmPack();
119 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template
);
122 /// Suppress traversal into Objective-C container literal
123 /// elements that are pack expansions.
124 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral
*E
) override
{
125 if (!E
->containsUnexpandedParameterPack())
128 for (unsigned I
= 0, N
= E
->getNumElements(); I
!= N
; ++I
) {
129 ObjCDictionaryElement Element
= E
->getKeyValueElement(I
);
130 if (Element
.isPackExpansion())
133 TraverseStmt(Element
.Key
);
134 TraverseStmt(Element
.Value
);
138 //------------------------------------------------------------------------
139 // Pruning the search for unexpanded parameter packs.
140 //------------------------------------------------------------------------
142 /// Suppress traversal into statements and expressions that
143 /// do not contain unexpanded parameter packs.
144 bool TraverseStmt(Stmt
*S
) override
{
145 Expr
*E
= dyn_cast_or_null
<Expr
>(S
);
146 if ((E
&& E
->containsUnexpandedParameterPack()) || InLambdaOrBlock
)
147 return DynamicRecursiveASTVisitor::TraverseStmt(S
);
152 /// Suppress traversal into types that do not contain
153 /// unexpanded parameter packs.
154 bool TraverseType(QualType T
) override
{
155 if ((!T
.isNull() && T
->containsUnexpandedParameterPack()) ||
157 return DynamicRecursiveASTVisitor::TraverseType(T
);
162 /// Suppress traversal into types with location information
163 /// that do not contain unexpanded parameter packs.
164 bool TraverseTypeLoc(TypeLoc TL
) override
{
165 if ((!TL
.getType().isNull() &&
166 TL
.getType()->containsUnexpandedParameterPack()) ||
168 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL
);
173 /// Suppress traversal of parameter packs.
174 bool TraverseDecl(Decl
*D
) override
{
175 // A function parameter pack is a pack expansion, so cannot contain
176 // an unexpanded parameter pack. Likewise for a template parameter
177 // pack that contains any references to other packs.
178 if (D
&& D
->isParameterPack())
181 return DynamicRecursiveASTVisitor::TraverseDecl(D
);
184 /// Suppress traversal of pack-expanded attributes.
185 bool TraverseAttr(Attr
*A
) override
{
186 if (A
->isPackExpansion())
189 return DynamicRecursiveASTVisitor::TraverseAttr(A
);
192 /// Suppress traversal of pack expansion expressions and types.
194 bool TraversePackExpansionType(PackExpansionType
*T
) override
{
197 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL
) override
{
200 bool TraversePackExpansionExpr(PackExpansionExpr
*E
) override
{
203 bool TraverseCXXFoldExpr(CXXFoldExpr
*E
) override
{ return true; }
204 bool TraversePackIndexingExpr(PackIndexingExpr
*E
) override
{
205 return DynamicRecursiveASTVisitor::TraverseStmt(E
->getIndexExpr());
207 bool TraversePackIndexingType(PackIndexingType
*E
) override
{
208 return DynamicRecursiveASTVisitor::TraverseStmt(E
->getIndexExpr());
210 bool TraversePackIndexingTypeLoc(PackIndexingTypeLoc TL
) override
{
211 return DynamicRecursiveASTVisitor::TraverseStmt(TL
.getIndexExpr());
216 /// Suppress traversal of using-declaration pack expansion.
218 TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl
*D
) override
{
219 if (D
->isPackExpansion())
222 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingValueDecl(D
);
225 /// Suppress traversal of using-declaration pack expansion.
226 bool TraverseUnresolvedUsingTypenameDecl(
227 UnresolvedUsingTypenameDecl
*D
) override
{
228 if (D
->isPackExpansion())
231 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingTypenameDecl(D
);
234 /// Suppress traversal of template argument pack expansions.
235 bool TraverseTemplateArgument(const TemplateArgument
&Arg
) override
{
236 if (Arg
.isPackExpansion())
239 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg
);
242 /// Suppress traversal of template argument pack expansions.
244 TraverseTemplateArgumentLoc(const TemplateArgumentLoc
&ArgLoc
) override
{
245 if (ArgLoc
.getArgument().isPackExpansion())
248 return DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc
);
251 /// Suppress traversal of base specifier pack expansions.
252 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier
&Base
) override
{
253 if (Base
.isPackExpansion())
256 return DynamicRecursiveASTVisitor::TraverseCXXBaseSpecifier(Base
);
259 /// Suppress traversal of mem-initializer pack expansions.
260 bool TraverseConstructorInitializer(CXXCtorInitializer
*Init
) override
{
261 if (Init
->isPackExpansion())
264 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init
);
267 /// Note whether we're traversing a lambda containing an unexpanded
268 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
269 /// including all the places where we normally wouldn't look. Within a
270 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
271 /// outside an expression.
272 bool TraverseLambdaExpr(LambdaExpr
*Lambda
) override
{
273 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
274 // even if it's contained within another lambda.
275 if (!Lambda
->containsUnexpandedParameterPack())
278 SaveAndRestore
_(InLambdaOrBlock
, true);
279 unsigned OldDepthLimit
= DepthLimit
;
281 if (auto *TPL
= Lambda
->getTemplateParameterList())
282 DepthLimit
= TPL
->getDepth();
284 DynamicRecursiveASTVisitor::TraverseLambdaExpr(Lambda
);
286 DepthLimit
= OldDepthLimit
;
290 /// Analogously for blocks.
291 bool TraverseBlockExpr(BlockExpr
*Block
) override
{
292 if (!Block
->containsUnexpandedParameterPack())
295 SaveAndRestore
_(InLambdaOrBlock
, true);
296 DynamicRecursiveASTVisitor::TraverseBlockExpr(Block
);
300 /// Suppress traversal within pack expansions in lambda captures.
301 bool TraverseLambdaCapture(LambdaExpr
*Lambda
, const LambdaCapture
*C
,
302 Expr
*Init
) override
{
303 if (C
->isPackExpansion())
306 return DynamicRecursiveASTVisitor::TraverseLambdaCapture(Lambda
, C
, Init
);
310 bool TraverseFunctionParmPackExpr(FunctionParmPackExpr
*) override
{
311 ContainsIntermediatePacks
= true;
315 bool TraverseSubstNonTypeTemplateParmPackExpr(
316 SubstNonTypeTemplateParmPackExpr
*) override
{
317 ContainsIntermediatePacks
= true;
321 bool VisitSubstTemplateTypeParmPackType(
322 SubstTemplateTypeParmPackType
*) override
{
323 ContainsIntermediatePacks
= true;
327 bool VisitSubstTemplateTypeParmPackTypeLoc(
328 SubstTemplateTypeParmPackTypeLoc
) override
{
329 ContainsIntermediatePacks
= true;
333 bool containsIntermediatePacks() const { return ContainsIntermediatePacks
; }
338 /// Determine whether it's possible for an unexpanded parameter pack to
339 /// be valid in this location. This only happens when we're in a declaration
340 /// that is nested within an expression that could be expanded, such as a
341 /// lambda-expression within a function call.
343 /// This is conservatively correct, but may claim that some unexpanded packs are
344 /// permitted when they are not.
345 bool Sema::isUnexpandedParameterPackPermitted() {
346 for (auto *SI
: FunctionScopes
)
347 if (isa
<sema::LambdaScopeInfo
>(SI
))
352 /// Diagnose all of the unexpanded parameter packs in the given
355 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc
,
356 UnexpandedParameterPackContext UPPC
,
357 ArrayRef
<UnexpandedParameterPack
> Unexpanded
) {
358 if (Unexpanded
.empty())
361 // If we are within a lambda expression and referencing a pack that is not
362 // declared within the lambda itself, that lambda contains an unexpanded
363 // parameter pack, and we are done. Analogously for blocks.
364 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
366 SmallVector
<UnexpandedParameterPack
, 4> ParamPackReferences
;
367 if (sema::CapturingScopeInfo
*CSI
= getEnclosingLambdaOrBlock()) {
368 for (auto &Pack
: Unexpanded
) {
369 auto DeclaresThisPack
= [&](NamedDecl
*LocalPack
) {
370 if (auto *TTPT
= Pack
.first
.dyn_cast
<const TemplateTypeParmType
*>()) {
371 auto *TTPD
= dyn_cast
<TemplateTypeParmDecl
>(LocalPack
);
372 return TTPD
&& TTPD
->getTypeForDecl() == TTPT
;
374 return declaresSameEntity(cast
<NamedDecl
*>(Pack
.first
), LocalPack
);
376 if (llvm::any_of(CSI
->LocalPacks
, DeclaresThisPack
))
377 ParamPackReferences
.push_back(Pack
);
380 if (ParamPackReferences
.empty()) {
381 // Construct in lambda only references packs declared outside the lambda.
382 // That's OK for now, but the lambda itself is considered to contain an
383 // unexpanded pack in this case, which will require expansion outside the
386 // We do not permit pack expansion that would duplicate a statement
387 // expression, not even within a lambda.
388 // FIXME: We could probably support this for statement expressions that
389 // do not contain labels.
390 // FIXME: This is insufficient to detect this problem; consider
391 // f( ({ bad: 0; }) + pack ... );
392 bool EnclosingStmtExpr
= false;
393 for (unsigned N
= FunctionScopes
.size(); N
; --N
) {
394 sema::FunctionScopeInfo
*Func
= FunctionScopes
[N
-1];
396 Func
->CompoundScopes
,
397 [](sema::CompoundScopeInfo
&CSI
) { return CSI
.IsStmtExpr
; })) {
398 EnclosingStmtExpr
= true;
401 // Coumpound-statements outside the lambda are OK for now; we'll check
402 // for those when we finish handling the lambda.
407 if (!EnclosingStmtExpr
) {
408 CSI
->ContainsUnexpandedParameterPack
= true;
412 Unexpanded
= ParamPackReferences
;
416 SmallVector
<SourceLocation
, 4> Locations
;
417 SmallVector
<IdentifierInfo
*, 4> Names
;
418 llvm::SmallPtrSet
<IdentifierInfo
*, 4> NamesKnown
;
420 for (unsigned I
= 0, N
= Unexpanded
.size(); I
!= N
; ++I
) {
421 IdentifierInfo
*Name
= nullptr;
422 if (const TemplateTypeParmType
*TTP
423 = Unexpanded
[I
].first
.dyn_cast
<const TemplateTypeParmType
*>())
424 Name
= TTP
->getIdentifier();
426 Name
= cast
<NamedDecl
*>(Unexpanded
[I
].first
)->getIdentifier();
428 if (Name
&& NamesKnown
.insert(Name
).second
)
429 Names
.push_back(Name
);
431 if (Unexpanded
[I
].second
.isValid())
432 Locations
.push_back(Unexpanded
[I
].second
);
435 auto DB
= Diag(Loc
, diag::err_unexpanded_parameter_pack
)
436 << (int)UPPC
<< (int)Names
.size();
437 for (size_t I
= 0, E
= std::min(Names
.size(), (size_t)2); I
!= E
; ++I
)
440 for (unsigned I
= 0, N
= Locations
.size(); I
!= N
; ++I
)
441 DB
<< SourceRange(Locations
[I
]);
445 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc
,
447 UnexpandedParameterPackContext UPPC
) {
448 // C++0x [temp.variadic]p5:
449 // An appearance of a name of a parameter pack that is not expanded is
451 if (!T
->getType()->containsUnexpandedParameterPack())
454 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
455 CollectUnexpandedParameterPacksVisitor(Unexpanded
).TraverseTypeLoc(
457 assert(!Unexpanded
.empty() && "Unable to find unexpanded parameter packs");
458 return DiagnoseUnexpandedParameterPacks(Loc
, UPPC
, Unexpanded
);
461 bool Sema::DiagnoseUnexpandedParameterPack(Expr
*E
,
462 UnexpandedParameterPackContext UPPC
) {
463 // C++0x [temp.variadic]p5:
464 // An appearance of a name of a parameter pack that is not expanded is
466 if (!E
->containsUnexpandedParameterPack())
469 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
470 CollectUnexpandedParameterPacksVisitor
Visitor(Unexpanded
);
471 Visitor
.TraverseStmt(E
);
473 // The expression might contain a type/subexpression that has been substituted
474 // but has the expansion held off, e.g. a FunctionParmPackExpr which a larger
475 // CXXFoldExpr would expand. It's only possible when expanding a lambda as a
476 // pattern of a fold expression, so don't fire on an empty result in that
478 bool LambdaReferencingOuterPacks
=
479 getEnclosingLambdaOrBlock() && Visitor
.containsIntermediatePacks();
480 assert((!Unexpanded
.empty() || LambdaReferencingOuterPacks
) &&
481 "Unable to find unexpanded parameter packs");
483 return DiagnoseUnexpandedParameterPacks(E
->getBeginLoc(), UPPC
, Unexpanded
);
486 bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr
*RE
) {
487 if (!RE
->containsUnexpandedParameterPack())
490 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
491 CollectUnexpandedParameterPacksVisitor(Unexpanded
).TraverseStmt(RE
);
492 assert(!Unexpanded
.empty() && "Unable to find unexpanded parameter packs");
494 // We only care about unexpanded references to the RequiresExpr's own
496 auto Parms
= RE
->getLocalParameters();
497 llvm::SmallPtrSet
<NamedDecl
*, 8> ParmSet(Parms
.begin(), Parms
.end());
498 SmallVector
<UnexpandedParameterPack
, 2> UnexpandedParms
;
499 for (auto Parm
: Unexpanded
)
500 if (ParmSet
.contains(Parm
.first
.dyn_cast
<NamedDecl
*>()))
501 UnexpandedParms
.push_back(Parm
);
502 if (UnexpandedParms
.empty())
505 return DiagnoseUnexpandedParameterPacks(RE
->getBeginLoc(), UPPC_Requirement
,
509 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec
&SS
,
510 UnexpandedParameterPackContext UPPC
) {
511 // C++0x [temp.variadic]p5:
512 // An appearance of a name of a parameter pack that is not expanded is
514 if (!SS
.getScopeRep() ||
515 !SS
.getScopeRep()->containsUnexpandedParameterPack())
518 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
519 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
520 .TraverseNestedNameSpecifier(SS
.getScopeRep());
521 assert(!Unexpanded
.empty() && "Unable to find unexpanded parameter packs");
522 return DiagnoseUnexpandedParameterPacks(SS
.getRange().getBegin(),
526 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo
&NameInfo
,
527 UnexpandedParameterPackContext UPPC
) {
528 // C++0x [temp.variadic]p5:
529 // An appearance of a name of a parameter pack that is not expanded is
531 switch (NameInfo
.getName().getNameKind()) {
532 case DeclarationName::Identifier
:
533 case DeclarationName::ObjCZeroArgSelector
:
534 case DeclarationName::ObjCOneArgSelector
:
535 case DeclarationName::ObjCMultiArgSelector
:
536 case DeclarationName::CXXOperatorName
:
537 case DeclarationName::CXXLiteralOperatorName
:
538 case DeclarationName::CXXUsingDirective
:
539 case DeclarationName::CXXDeductionGuideName
:
542 case DeclarationName::CXXConstructorName
:
543 case DeclarationName::CXXDestructorName
:
544 case DeclarationName::CXXConversionFunctionName
:
545 // FIXME: We shouldn't need this null check!
546 if (TypeSourceInfo
*TSInfo
= NameInfo
.getNamedTypeInfo())
547 return DiagnoseUnexpandedParameterPack(NameInfo
.getLoc(), TSInfo
, UPPC
);
549 if (!NameInfo
.getName().getCXXNameType()->containsUnexpandedParameterPack())
555 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
556 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
557 .TraverseType(NameInfo
.getName().getCXXNameType());
558 assert(!Unexpanded
.empty() && "Unable to find unexpanded parameter packs");
559 return DiagnoseUnexpandedParameterPacks(NameInfo
.getLoc(), UPPC
, Unexpanded
);
562 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc
,
563 TemplateName Template
,
564 UnexpandedParameterPackContext UPPC
) {
566 if (Template
.isNull() || !Template
.containsUnexpandedParameterPack())
569 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
570 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
571 .TraverseTemplateName(Template
);
572 assert(!Unexpanded
.empty() && "Unable to find unexpanded parameter packs");
573 return DiagnoseUnexpandedParameterPacks(Loc
, UPPC
, Unexpanded
);
576 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg
,
577 UnexpandedParameterPackContext UPPC
) {
578 if (Arg
.getArgument().isNull() ||
579 !Arg
.getArgument().containsUnexpandedParameterPack())
582 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
583 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
584 .TraverseTemplateArgumentLoc(Arg
);
585 assert(!Unexpanded
.empty() && "Unable to find unexpanded parameter packs");
586 return DiagnoseUnexpandedParameterPacks(Arg
.getLocation(), UPPC
, Unexpanded
);
589 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg
,
590 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
591 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
592 .TraverseTemplateArgument(Arg
);
595 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg
,
596 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
597 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
598 .TraverseTemplateArgumentLoc(Arg
);
601 void Sema::collectUnexpandedParameterPacks(QualType T
,
602 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
603 CollectUnexpandedParameterPacksVisitor(Unexpanded
).TraverseType(T
);
606 void Sema::collectUnexpandedParameterPacks(TypeLoc TL
,
607 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
608 CollectUnexpandedParameterPacksVisitor(Unexpanded
).TraverseTypeLoc(TL
);
611 void Sema::collectUnexpandedParameterPacks(
612 NestedNameSpecifierLoc NNS
,
613 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
614 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
615 .TraverseNestedNameSpecifierLoc(NNS
);
618 void Sema::collectUnexpandedParameterPacks(
619 const DeclarationNameInfo
&NameInfo
,
620 SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
621 CollectUnexpandedParameterPacksVisitor(Unexpanded
)
622 .TraverseDeclarationNameInfo(NameInfo
);
625 void Sema::collectUnexpandedParameterPacks(
626 Expr
*E
, SmallVectorImpl
<UnexpandedParameterPack
> &Unexpanded
) {
627 CollectUnexpandedParameterPacksVisitor(Unexpanded
).TraverseStmt(E
);
630 ParsedTemplateArgument
631 Sema::ActOnPackExpansion(const ParsedTemplateArgument
&Arg
,
632 SourceLocation EllipsisLoc
) {
636 switch (Arg
.getKind()) {
637 case ParsedTemplateArgument::Type
: {
638 TypeResult Result
= ActOnPackExpansion(Arg
.getAsType(), EllipsisLoc
);
639 if (Result
.isInvalid())
640 return ParsedTemplateArgument();
642 return ParsedTemplateArgument(Arg
.getKind(), Result
.get().getAsOpaquePtr(),
646 case ParsedTemplateArgument::NonType
: {
647 ExprResult Result
= ActOnPackExpansion(Arg
.getAsExpr(), EllipsisLoc
);
648 if (Result
.isInvalid())
649 return ParsedTemplateArgument();
651 return ParsedTemplateArgument(Arg
.getKind(), Result
.get(),
655 case ParsedTemplateArgument::Template
:
656 if (!Arg
.getAsTemplate().get().containsUnexpandedParameterPack()) {
657 SourceRange
R(Arg
.getLocation());
658 if (Arg
.getScopeSpec().isValid())
659 R
.setBegin(Arg
.getScopeSpec().getBeginLoc());
660 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
662 return ParsedTemplateArgument();
665 return Arg
.getTemplatePackExpansion(EllipsisLoc
);
667 llvm_unreachable("Unhandled template argument kind?");
670 TypeResult
Sema::ActOnPackExpansion(ParsedType Type
,
671 SourceLocation EllipsisLoc
) {
672 TypeSourceInfo
*TSInfo
;
673 GetTypeFromParser(Type
, &TSInfo
);
677 TypeSourceInfo
*TSResult
=
678 CheckPackExpansion(TSInfo
, EllipsisLoc
, std::nullopt
);
682 return CreateParsedType(TSResult
->getType(), TSResult
);
686 Sema::CheckPackExpansion(TypeSourceInfo
*Pattern
, SourceLocation EllipsisLoc
,
687 std::optional
<unsigned> NumExpansions
) {
688 // Create the pack expansion type and source-location information.
689 QualType Result
= CheckPackExpansion(Pattern
->getType(),
690 Pattern
->getTypeLoc().getSourceRange(),
691 EllipsisLoc
, NumExpansions
);
696 TLB
.pushFullCopy(Pattern
->getTypeLoc());
697 PackExpansionTypeLoc TL
= TLB
.push
<PackExpansionTypeLoc
>(Result
);
698 TL
.setEllipsisLoc(EllipsisLoc
);
700 return TLB
.getTypeSourceInfo(Context
, Result
);
703 QualType
Sema::CheckPackExpansion(QualType Pattern
, SourceRange PatternRange
,
704 SourceLocation EllipsisLoc
,
705 std::optional
<unsigned> NumExpansions
) {
706 // C++11 [temp.variadic]p5:
707 // The pattern of a pack expansion shall name one or more
708 // parameter packs that are not expanded by a nested pack
711 // A pattern containing a deduced type can't occur "naturally" but arises in
712 // the desugaring of an init-capture pack.
713 if (!Pattern
->containsUnexpandedParameterPack() &&
714 !Pattern
->getContainedDeducedType()) {
715 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
720 return Context
.getPackExpansionType(Pattern
, NumExpansions
,
721 /*ExpectPackInType=*/false);
724 ExprResult
Sema::ActOnPackExpansion(Expr
*Pattern
, SourceLocation EllipsisLoc
) {
725 return CheckPackExpansion(Pattern
, EllipsisLoc
, std::nullopt
);
728 ExprResult
Sema::CheckPackExpansion(Expr
*Pattern
, SourceLocation EllipsisLoc
,
729 std::optional
<unsigned> NumExpansions
) {
733 // C++0x [temp.variadic]p5:
734 // The pattern of a pack expansion shall name one or more
735 // parameter packs that are not expanded by a nested pack
737 if (!Pattern
->containsUnexpandedParameterPack()) {
738 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
739 << Pattern
->getSourceRange();
740 CorrectDelayedTyposInExpr(Pattern
);
744 // Create the pack expansion expression and source-location information.
746 PackExpansionExpr(Context
.DependentTy
, Pattern
, EllipsisLoc
, NumExpansions
);
749 bool Sema::CheckParameterPacksForExpansion(
750 SourceLocation EllipsisLoc
, SourceRange PatternRange
,
751 ArrayRef
<UnexpandedParameterPack
> Unexpanded
,
752 const MultiLevelTemplateArgumentList
&TemplateArgs
, bool &ShouldExpand
,
753 bool &RetainExpansion
, std::optional
<unsigned> &NumExpansions
) {
755 RetainExpansion
= false;
756 std::pair
<IdentifierInfo
*, SourceLocation
> FirstPack
;
757 bool HaveFirstPack
= false;
758 std::optional
<unsigned> NumPartialExpansions
;
759 SourceLocation PartiallySubstitutedPackLoc
;
761 for (UnexpandedParameterPack ParmPack
: Unexpanded
) {
762 // Compute the depth and index for this parameter pack.
763 unsigned Depth
= 0, Index
= 0;
764 IdentifierInfo
*Name
;
765 bool IsVarDeclPack
= false;
767 if (const TemplateTypeParmType
*TTP
=
768 ParmPack
.first
.dyn_cast
<const TemplateTypeParmType
*>()) {
769 Depth
= TTP
->getDepth();
770 Index
= TTP
->getIndex();
771 Name
= TTP
->getIdentifier();
773 NamedDecl
*ND
= cast
<NamedDecl
*>(ParmPack
.first
);
774 if (isa
<VarDecl
>(ND
))
775 IsVarDeclPack
= true;
777 std::tie(Depth
, Index
) = getDepthAndIndex(ND
);
779 Name
= ND
->getIdentifier();
782 // Determine the size of this argument pack.
783 unsigned NewPackSize
;
785 // Figure out whether we're instantiating to an argument pack or not.
786 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack
;
788 llvm::PointerUnion
<Decl
*, DeclArgumentPack
*> *Instantiation
=
789 CurrentInstantiationScope
->findInstantiationOf(
790 cast
<NamedDecl
*>(ParmPack
.first
));
791 if (isa
<DeclArgumentPack
*>(*Instantiation
)) {
792 // We could expand this function parameter pack.
793 NewPackSize
= cast
<DeclArgumentPack
*>(*Instantiation
)->size();
795 // We can't expand this function parameter pack, so we can't expand
796 // the pack expansion.
797 ShouldExpand
= false;
801 // If we don't have a template argument at this depth/index, then we
802 // cannot expand the pack expansion. Make a note of this, but we still
803 // want to check any parameter packs we *do* have arguments for.
804 if (Depth
>= TemplateArgs
.getNumLevels() ||
805 !TemplateArgs
.hasTemplateArgument(Depth
, Index
)) {
806 ShouldExpand
= false;
810 // Determine the size of the argument pack.
811 NewPackSize
= TemplateArgs(Depth
, Index
).pack_size();
814 // C++0x [temp.arg.explicit]p9:
815 // Template argument deduction can extend the sequence of template
816 // arguments corresponding to a template parameter pack, even when the
817 // sequence contains explicitly specified template arguments.
818 if (!IsVarDeclPack
&& CurrentInstantiationScope
) {
819 if (NamedDecl
*PartialPack
=
820 CurrentInstantiationScope
->getPartiallySubstitutedPack()) {
821 unsigned PartialDepth
, PartialIndex
;
822 std::tie(PartialDepth
, PartialIndex
) = getDepthAndIndex(PartialPack
);
823 if (PartialDepth
== Depth
&& PartialIndex
== Index
) {
824 RetainExpansion
= true;
825 // We don't actually know the new pack size yet.
826 NumPartialExpansions
= NewPackSize
;
827 PartiallySubstitutedPackLoc
= ParmPack
.second
;
833 if (!NumExpansions
) {
834 // The is the first pack we've seen for which we have an argument.
836 NumExpansions
= NewPackSize
;
837 FirstPack
.first
= Name
;
838 FirstPack
.second
= ParmPack
.second
;
839 HaveFirstPack
= true;
843 if (NewPackSize
!= *NumExpansions
) {
844 // C++0x [temp.variadic]p5:
845 // All of the parameter packs expanded by a pack expansion shall have
846 // the same number of arguments specified.
848 Diag(EllipsisLoc
, diag::err_pack_expansion_length_conflict
)
849 << FirstPack
.first
<< Name
<< *NumExpansions
<< NewPackSize
850 << SourceRange(FirstPack
.second
) << SourceRange(ParmPack
.second
);
852 Diag(EllipsisLoc
, diag::err_pack_expansion_length_conflict_multilevel
)
853 << Name
<< *NumExpansions
<< NewPackSize
854 << SourceRange(ParmPack
.second
);
859 // If we're performing a partial expansion but we also have a full expansion,
860 // expand to the number of common arguments. For example, given:
862 // template<typename ...T> struct A {
863 // template<typename ...U> void f(pair<T, U>...);
866 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
867 // retain an expansion.
868 if (NumPartialExpansions
) {
869 if (NumExpansions
&& *NumExpansions
< *NumPartialExpansions
) {
870 NamedDecl
*PartialPack
=
871 CurrentInstantiationScope
->getPartiallySubstitutedPack();
872 Diag(EllipsisLoc
, diag::err_pack_expansion_length_conflict_partial
)
873 << PartialPack
<< *NumPartialExpansions
<< *NumExpansions
874 << SourceRange(PartiallySubstitutedPackLoc
);
878 NumExpansions
= NumPartialExpansions
;
884 std::optional
<unsigned> Sema::getNumArgumentsInExpansionFromUnexpanded(
885 llvm::ArrayRef
<UnexpandedParameterPack
> Unexpanded
,
886 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
887 std::optional
<unsigned> Result
;
888 for (unsigned I
= 0, N
= Unexpanded
.size(); I
!= N
; ++I
) {
889 // Compute the depth and index for this parameter pack.
893 if (const TemplateTypeParmType
*TTP
=
894 Unexpanded
[I
].first
.dyn_cast
<const TemplateTypeParmType
*>()) {
895 Depth
= TTP
->getDepth();
896 Index
= TTP
->getIndex();
898 NamedDecl
*ND
= cast
<NamedDecl
*>(Unexpanded
[I
].first
);
899 if (isa
<VarDecl
>(ND
)) {
900 // Function parameter pack or init-capture pack.
901 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack
;
903 llvm::PointerUnion
<Decl
*, DeclArgumentPack
*> *Instantiation
=
904 CurrentInstantiationScope
->findInstantiationOf(
905 cast
<NamedDecl
*>(Unexpanded
[I
].first
));
906 if (isa
<Decl
*>(*Instantiation
))
907 // The pattern refers to an unexpanded pack. We're not ready to expand
911 unsigned Size
= cast
<DeclArgumentPack
*>(*Instantiation
)->size();
912 assert((!Result
|| *Result
== Size
) && "inconsistent pack sizes");
917 std::tie(Depth
, Index
) = getDepthAndIndex(ND
);
919 if (Depth
>= TemplateArgs
.getNumLevels() ||
920 !TemplateArgs
.hasTemplateArgument(Depth
, Index
))
921 // The pattern refers to an unknown template argument. We're not ready to
922 // expand this pack yet.
925 // Determine the size of the argument pack.
926 unsigned Size
= TemplateArgs(Depth
, Index
).pack_size();
927 assert((!Result
|| *Result
== Size
) && "inconsistent pack sizes");
934 std::optional
<unsigned> Sema::getNumArgumentsInExpansion(
935 QualType T
, const MultiLevelTemplateArgumentList
&TemplateArgs
) {
936 QualType Pattern
= cast
<PackExpansionType
>(T
)->getPattern();
937 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
938 CollectUnexpandedParameterPacksVisitor(Unexpanded
).TraverseType(Pattern
);
939 return getNumArgumentsInExpansionFromUnexpanded(Unexpanded
, TemplateArgs
);
942 bool Sema::containsUnexpandedParameterPacks(Declarator
&D
) {
943 const DeclSpec
&DS
= D
.getDeclSpec();
944 switch (DS
.getTypeSpecType()) {
945 case TST_typename_pack_indexing
:
947 case TST_typeof_unqualType
:
949 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
950 #include "clang/Basic/TransformTypeTraits.def"
952 QualType T
= DS
.getRepAsType().get();
953 if (!T
.isNull() && T
->containsUnexpandedParameterPack())
958 case TST_typeof_unqualExpr
:
962 if (DS
.getRepAsExpr() &&
963 DS
.getRepAsExpr()->containsUnexpandedParameterPack())
967 case TST_unspecified
:
995 case TST_decltype_auto
:
997 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
998 #include "clang/Basic/OpenCLImageTypes.def"
999 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case TST_##Name:
1000 #include "clang/Basic/HLSLIntangibleTypes.def"
1001 case TST_unknown_anytype
:
1006 for (unsigned I
= 0, N
= D
.getNumTypeObjects(); I
!= N
; ++I
) {
1007 const DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
1008 switch (Chunk
.Kind
) {
1009 case DeclaratorChunk::Pointer
:
1010 case DeclaratorChunk::Reference
:
1011 case DeclaratorChunk::Paren
:
1012 case DeclaratorChunk::Pipe
:
1013 case DeclaratorChunk::BlockPointer
:
1014 // These declarator chunks cannot contain any parameter packs.
1017 case DeclaratorChunk::Array
:
1018 if (Chunk
.Arr
.NumElts
&&
1019 Chunk
.Arr
.NumElts
->containsUnexpandedParameterPack())
1022 case DeclaratorChunk::Function
:
1023 for (unsigned i
= 0, e
= Chunk
.Fun
.NumParams
; i
!= e
; ++i
) {
1024 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(Chunk
.Fun
.Params
[i
].Param
);
1025 QualType ParamTy
= Param
->getType();
1026 assert(!ParamTy
.isNull() && "Couldn't parse type?");
1027 if (ParamTy
->containsUnexpandedParameterPack()) return true;
1030 if (Chunk
.Fun
.getExceptionSpecType() == EST_Dynamic
) {
1031 for (unsigned i
= 0; i
!= Chunk
.Fun
.getNumExceptions(); ++i
) {
1032 if (Chunk
.Fun
.Exceptions
[i
]
1034 ->containsUnexpandedParameterPack())
1037 } else if (isComputedNoexcept(Chunk
.Fun
.getExceptionSpecType()) &&
1038 Chunk
.Fun
.NoexceptExpr
->containsUnexpandedParameterPack())
1041 if (Chunk
.Fun
.hasTrailingReturnType()) {
1042 QualType T
= Chunk
.Fun
.getTrailingReturnType().get();
1043 if (!T
.isNull() && T
->containsUnexpandedParameterPack())
1048 case DeclaratorChunk::MemberPointer
:
1049 if (Chunk
.Mem
.Scope().getScopeRep() &&
1050 Chunk
.Mem
.Scope().getScopeRep()->containsUnexpandedParameterPack())
1056 if (Expr
*TRC
= D
.getTrailingRequiresClause())
1057 if (TRC
->containsUnexpandedParameterPack())
1065 // Callback to only accept typo corrections that refer to parameter packs.
1066 class ParameterPackValidatorCCC final
: public CorrectionCandidateCallback
{
1068 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
1069 NamedDecl
*ND
= candidate
.getCorrectionDecl();
1070 return ND
&& ND
->isParameterPack();
1073 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
1074 return std::make_unique
<ParameterPackValidatorCCC
>(*this);
1080 ExprResult
Sema::ActOnSizeofParameterPackExpr(Scope
*S
,
1081 SourceLocation OpLoc
,
1082 IdentifierInfo
&Name
,
1083 SourceLocation NameLoc
,
1084 SourceLocation RParenLoc
) {
1085 // C++0x [expr.sizeof]p5:
1086 // The identifier in a sizeof... expression shall name a parameter pack.
1087 LookupResult
R(*this, &Name
, NameLoc
, LookupOrdinaryName
);
1090 NamedDecl
*ParameterPack
= nullptr;
1091 switch (R
.getResultKind()) {
1092 case LookupResult::Found
:
1093 ParameterPack
= R
.getFoundDecl();
1096 case LookupResult::NotFound
:
1097 case LookupResult::NotFoundInCurrentInstantiation
: {
1098 ParameterPackValidatorCCC CCC
{};
1099 if (TypoCorrection Corrected
=
1100 CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
, nullptr,
1101 CCC
, CTK_ErrorRecovery
)) {
1102 diagnoseTypo(Corrected
,
1103 PDiag(diag::err_sizeof_pack_no_pack_name_suggest
) << &Name
,
1104 PDiag(diag::note_parameter_pack_here
));
1105 ParameterPack
= Corrected
.getCorrectionDecl();
1109 case LookupResult::FoundOverloaded
:
1110 case LookupResult::FoundUnresolvedValue
:
1113 case LookupResult::Ambiguous
:
1114 DiagnoseAmbiguousLookup(R
);
1118 if (!ParameterPack
|| !ParameterPack
->isParameterPack()) {
1119 Diag(NameLoc
, diag::err_expected_name_of_pack
) << &Name
;
1123 MarkAnyDeclReferenced(OpLoc
, ParameterPack
, true);
1125 return SizeOfPackExpr::Create(Context
, OpLoc
, ParameterPack
, NameLoc
,
1129 static bool isParameterPack(Expr
*PackExpression
) {
1130 if (auto *D
= dyn_cast
<DeclRefExpr
>(PackExpression
); D
) {
1131 ValueDecl
*VD
= D
->getDecl();
1132 return VD
->isParameterPack();
1137 ExprResult
Sema::ActOnPackIndexingExpr(Scope
*S
, Expr
*PackExpression
,
1138 SourceLocation EllipsisLoc
,
1139 SourceLocation LSquareLoc
,
1141 SourceLocation RSquareLoc
) {
1142 bool isParameterPack
= ::isParameterPack(PackExpression
);
1143 if (!isParameterPack
) {
1144 if (!PackExpression
->containsErrors()) {
1145 CorrectDelayedTyposInExpr(IndexExpr
);
1146 Diag(PackExpression
->getBeginLoc(), diag::err_expected_name_of_pack
)
1152 BuildPackIndexingExpr(PackExpression
, EllipsisLoc
, IndexExpr
, RSquareLoc
);
1153 if (!Res
.isInvalid())
1154 Diag(Res
.get()->getBeginLoc(), getLangOpts().CPlusPlus26
1155 ? diag::warn_cxx23_pack_indexing
1156 : diag::ext_pack_indexing
);
1160 ExprResult
Sema::BuildPackIndexingExpr(Expr
*PackExpression
,
1161 SourceLocation EllipsisLoc
,
1163 SourceLocation RSquareLoc
,
1164 ArrayRef
<Expr
*> ExpandedExprs
,
1165 bool FullySubstituted
) {
1167 std::optional
<int64_t> Index
;
1168 if (!IndexExpr
->isInstantiationDependent()) {
1169 llvm::APSInt
Value(Context
.getIntWidth(Context
.getSizeType()));
1171 ExprResult Res
= CheckConvertedConstantExpression(
1172 IndexExpr
, Context
.getSizeType(), Value
, CCEK_ArrayBound
);
1173 if (!Res
.isUsable())
1175 Index
= Value
.getExtValue();
1176 IndexExpr
= Res
.get();
1179 if (Index
&& FullySubstituted
) {
1180 if (*Index
< 0 || *Index
>= int64_t(ExpandedExprs
.size())) {
1181 Diag(PackExpression
->getBeginLoc(), diag::err_pack_index_out_of_bound
)
1182 << *Index
<< PackExpression
<< ExpandedExprs
.size();
1187 return PackIndexingExpr::Create(getASTContext(), EllipsisLoc
, RSquareLoc
,
1188 PackExpression
, IndexExpr
, Index
,
1189 ExpandedExprs
, FullySubstituted
);
1192 TemplateArgumentLoc
Sema::getTemplateArgumentPackExpansionPattern(
1193 TemplateArgumentLoc OrigLoc
, SourceLocation
&Ellipsis
,
1194 std::optional
<unsigned> &NumExpansions
) const {
1195 const TemplateArgument
&Argument
= OrigLoc
.getArgument();
1196 assert(Argument
.isPackExpansion());
1197 switch (Argument
.getKind()) {
1198 case TemplateArgument::Type
: {
1199 // FIXME: We shouldn't ever have to worry about missing
1200 // type-source info!
1201 TypeSourceInfo
*ExpansionTSInfo
= OrigLoc
.getTypeSourceInfo();
1202 if (!ExpansionTSInfo
)
1203 ExpansionTSInfo
= Context
.getTrivialTypeSourceInfo(Argument
.getAsType(),
1205 PackExpansionTypeLoc Expansion
=
1206 ExpansionTSInfo
->getTypeLoc().castAs
<PackExpansionTypeLoc
>();
1207 Ellipsis
= Expansion
.getEllipsisLoc();
1209 TypeLoc Pattern
= Expansion
.getPatternLoc();
1210 NumExpansions
= Expansion
.getTypePtr()->getNumExpansions();
1212 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1214 // FIXME: Find some way to avoid the copy?
1216 TLB
.pushFullCopy(Pattern
);
1217 TypeSourceInfo
*PatternTSInfo
=
1218 TLB
.getTypeSourceInfo(Context
, Pattern
.getType());
1219 return TemplateArgumentLoc(TemplateArgument(Pattern
.getType()),
1223 case TemplateArgument::Expression
: {
1224 PackExpansionExpr
*Expansion
1225 = cast
<PackExpansionExpr
>(Argument
.getAsExpr());
1226 Expr
*Pattern
= Expansion
->getPattern();
1227 Ellipsis
= Expansion
->getEllipsisLoc();
1228 NumExpansions
= Expansion
->getNumExpansions();
1229 return TemplateArgumentLoc(Pattern
, Pattern
);
1232 case TemplateArgument::TemplateExpansion
:
1233 Ellipsis
= OrigLoc
.getTemplateEllipsisLoc();
1234 NumExpansions
= Argument
.getNumTemplateExpansions();
1235 return TemplateArgumentLoc(Context
, Argument
.getPackExpansionPattern(),
1236 OrigLoc
.getTemplateQualifierLoc(),
1237 OrigLoc
.getTemplateNameLoc());
1239 case TemplateArgument::Declaration
:
1240 case TemplateArgument::NullPtr
:
1241 case TemplateArgument::Template
:
1242 case TemplateArgument::Integral
:
1243 case TemplateArgument::StructuralValue
:
1244 case TemplateArgument::Pack
:
1245 case TemplateArgument::Null
:
1246 return TemplateArgumentLoc();
1249 llvm_unreachable("Invalid TemplateArgument Kind!");
1252 std::optional
<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg
) {
1253 assert(Arg
.containsUnexpandedParameterPack());
1255 // If this is a substituted pack, grab that pack. If not, we don't know
1257 // FIXME: We could find a size in more cases by looking for a substituted
1258 // pack anywhere within this argument, but that's not necessary in the common
1259 // case for 'sizeof...(A)' handling.
1260 TemplateArgument Pack
;
1261 switch (Arg
.getKind()) {
1262 case TemplateArgument::Type
:
1263 if (auto *Subst
= Arg
.getAsType()->getAs
<SubstTemplateTypeParmPackType
>())
1264 Pack
= Subst
->getArgumentPack();
1266 return std::nullopt
;
1269 case TemplateArgument::Expression
:
1271 dyn_cast
<SubstNonTypeTemplateParmPackExpr
>(Arg
.getAsExpr()))
1272 Pack
= Subst
->getArgumentPack();
1273 else if (auto *Subst
= dyn_cast
<FunctionParmPackExpr
>(Arg
.getAsExpr())) {
1274 for (VarDecl
*PD
: *Subst
)
1275 if (PD
->isParameterPack())
1276 return std::nullopt
;
1277 return Subst
->getNumExpansions();
1279 return std::nullopt
;
1282 case TemplateArgument::Template
:
1283 if (SubstTemplateTemplateParmPackStorage
*Subst
=
1284 Arg
.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1285 Pack
= Subst
->getArgumentPack();
1287 return std::nullopt
;
1290 case TemplateArgument::Declaration
:
1291 case TemplateArgument::NullPtr
:
1292 case TemplateArgument::TemplateExpansion
:
1293 case TemplateArgument::Integral
:
1294 case TemplateArgument::StructuralValue
:
1295 case TemplateArgument::Pack
:
1296 case TemplateArgument::Null
:
1297 return std::nullopt
;
1300 // Check that no argument in the pack is itself a pack expansion.
1301 for (TemplateArgument Elem
: Pack
.pack_elements()) {
1302 // There's no point recursing in this case; we would have already
1303 // expanded this pack expansion into the enclosing pack if we could.
1304 if (Elem
.isPackExpansion())
1305 return std::nullopt
;
1306 // Don't guess the size of unexpanded packs. The pack within a template
1307 // argument may have yet to be of a PackExpansion type before we see the
1308 // ellipsis in the annotation stage.
1310 // This doesn't mean we would invalidate the optimization: Arg can be an
1311 // unexpanded pack regardless of Elem's dependence. For instance,
1312 // A TemplateArgument that contains either a SubstTemplateTypeParmPackType
1313 // or SubstNonTypeTemplateParmPackExpr is always considered Unexpanded, but
1314 // the underlying TemplateArgument thereof may not.
1315 if (Elem
.containsUnexpandedParameterPack())
1316 return std::nullopt
;
1318 return Pack
.pack_size();
1321 static void CheckFoldOperand(Sema
&S
, Expr
*E
) {
1325 E
= E
->IgnoreImpCasts();
1326 auto *OCE
= dyn_cast
<CXXOperatorCallExpr
>(E
);
1327 if ((OCE
&& OCE
->isInfixBinaryOp()) || isa
<BinaryOperator
>(E
) ||
1328 isa
<AbstractConditionalOperator
>(E
)) {
1329 S
.Diag(E
->getExprLoc(), diag::err_fold_expression_bad_operand
)
1330 << E
->getSourceRange()
1331 << FixItHint::CreateInsertion(E
->getBeginLoc(), "(")
1332 << FixItHint::CreateInsertion(E
->getEndLoc(), ")");
1336 ExprResult
Sema::ActOnCXXFoldExpr(Scope
*S
, SourceLocation LParenLoc
, Expr
*LHS
,
1337 tok::TokenKind Operator
,
1338 SourceLocation EllipsisLoc
, Expr
*RHS
,
1339 SourceLocation RParenLoc
) {
1340 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1341 // in the parser and reduce down to just cast-expressions here.
1342 CheckFoldOperand(*this, LHS
);
1343 CheckFoldOperand(*this, RHS
);
1345 auto DiscardOperands
= [&] {
1346 CorrectDelayedTyposInExpr(LHS
);
1347 CorrectDelayedTyposInExpr(RHS
);
1350 // [expr.prim.fold]p3:
1351 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1352 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1353 // an unexpanded parameter pack, but not both.
1355 LHS
->containsUnexpandedParameterPack() ==
1356 RHS
->containsUnexpandedParameterPack()) {
1358 return Diag(EllipsisLoc
,
1359 LHS
->containsUnexpandedParameterPack()
1360 ? diag::err_fold_expression_packs_both_sides
1361 : diag::err_pack_expansion_without_parameter_packs
)
1362 << LHS
->getSourceRange() << RHS
->getSourceRange();
1365 // [expr.prim.fold]p2:
1366 // In a unary fold, the cast-expression shall contain an unexpanded
1369 Expr
*Pack
= LHS
? LHS
: RHS
;
1370 assert(Pack
&& "fold expression with neither LHS nor RHS");
1371 if (!Pack
->containsUnexpandedParameterPack()) {
1373 return Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
1374 << Pack
->getSourceRange();
1378 BinaryOperatorKind Opc
= ConvertTokenKindToBinaryOpcode(Operator
);
1380 // Perform first-phase name lookup now.
1381 UnresolvedLookupExpr
*ULE
= nullptr;
1383 UnresolvedSet
<16> Functions
;
1384 LookupBinOp(S
, EllipsisLoc
, Opc
, Functions
);
1385 if (!Functions
.empty()) {
1386 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(
1387 BinaryOperator::getOverloadedOperator(Opc
));
1388 ExprResult Callee
= CreateUnresolvedLookupExpr(
1389 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1390 DeclarationNameInfo(OpName
, EllipsisLoc
), Functions
);
1391 if (Callee
.isInvalid())
1393 ULE
= cast
<UnresolvedLookupExpr
>(Callee
.get());
1397 return BuildCXXFoldExpr(ULE
, LParenLoc
, LHS
, Opc
, EllipsisLoc
, RHS
, RParenLoc
,
1401 ExprResult
Sema::BuildCXXFoldExpr(UnresolvedLookupExpr
*Callee
,
1402 SourceLocation LParenLoc
, Expr
*LHS
,
1403 BinaryOperatorKind Operator
,
1404 SourceLocation EllipsisLoc
, Expr
*RHS
,
1405 SourceLocation RParenLoc
,
1406 std::optional
<unsigned> NumExpansions
) {
1407 return new (Context
)
1408 CXXFoldExpr(Context
.DependentTy
, Callee
, LParenLoc
, LHS
, Operator
,
1409 EllipsisLoc
, RHS
, RParenLoc
, NumExpansions
);
1412 ExprResult
Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc
,
1413 BinaryOperatorKind Operator
) {
1414 // [temp.variadic]p9:
1415 // If N is zero for a unary fold-expression, the value of the expression is
1419 // if the operator is not listed [above], the instantiation is ill-formed.
1421 // Note that we need to use something like int() here, not merely 0, to
1422 // prevent the result from being a null pointer constant.
1423 QualType ScalarType
;
1426 return ActOnCXXBoolLiteral(EllipsisLoc
, tok::kw_false
);
1428 return ActOnCXXBoolLiteral(EllipsisLoc
, tok::kw_true
);
1430 ScalarType
= Context
.VoidTy
;
1434 return Diag(EllipsisLoc
, diag::err_fold_expression_empty
)
1435 << BinaryOperator::getOpcodeStr(Operator
);
1438 return new (Context
) CXXScalarValueInitExpr(
1439 ScalarType
, Context
.getTrivialTypeSourceInfo(ScalarType
, EllipsisLoc
),