clang 22.0.0git
SemaTemplateVariadic.cpp
Go to the documentation of this file.
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"
13#include "clang/AST/Expr.h"
14#include "clang/AST/ExprObjC.h"
15#include "clang/AST/TypeLoc.h"
16#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Sema.h"
22#include "clang/Sema/Template.h"
23#include "llvm/Support/SaveAndRestore.h"
24#include <optional>
25
26using namespace clang;
27
28//----------------------------------------------------------------------------
29// Visitor that collects unexpanded parameter packs
30//----------------------------------------------------------------------------
31
32namespace {
33 /// A class that collects unexpanded parameter packs.
34class CollectUnexpandedParameterPacksVisitor
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>(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>(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({ND, Loc});
60 }
61
62 void addUnexpanded(const TemplateTypeParmType *T,
63 SourceLocation Loc = SourceLocation()) {
64 if (T->getDepth() < DepthLimit)
65 Unexpanded.push_back({T, Loc});
66 }
67
68 bool addUnexpanded(const SubstBuiltinTemplatePackType *T,
69 SourceLocation Loc = SourceLocation()) {
70 Unexpanded.push_back({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({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(T->getTemplateName()))
88 return false;
89 // Canonical types are inputs to the initial substitution. Report them and
90 // do not recurse any further.
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.
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(TL.getTypePtr(), 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(E->getDecl(), 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 Template.getAsTemplateDecl())) {
149 if (TTP->isParameterPack())
150 addUnexpanded(TTP);
151 }
152
153#ifndef NDEBUG
154 ContainsIntermediatePacks |=
155 (bool)Template.getAsSubstTemplateTemplateParmPack();
156#endif
157
159 }
160
161 bool
162 TraverseTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc T,
163 bool TraverseQualifier) override {
164 if (TryTraverseSpecializationProducingPacks(T.getTypePtr(),
165 T.getBeginLoc()))
166 return true;
167 return DynamicRecursiveASTVisitor::TraverseTemplateSpecializationTypeLoc(
168 T, TraverseQualifier);
169 }
170
171 bool TraverseTemplateSpecializationType(TemplateSpecializationType *T,
172 bool TraverseQualfier) override {
173 if (TryTraverseSpecializationProducingPacks(T, 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 {
182 return true;
183
184 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
185 ObjCDictionaryElement Element = E->getKeyValueElement(I);
186 if (Element.isPackExpansion())
187 continue;
188
189 TraverseStmt(Element.Key);
190 TraverseStmt(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>(S);
202 if ((E && E->containsUnexpandedParameterPack()) || InLambdaOrBlock)
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() &&
223 InLambdaOrBlock)
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
239 }
240
241 /// Suppress traversal of pack-expanded attributes.
242 bool TraverseAttr(Attr *A) override {
243 if (A->isPackExpansion())
244 return true;
245
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 {
265 }
266 bool TraversePackIndexingType(PackIndexingType *E,
267 bool TraverseQualifier) override {
268 return DynamicRecursiveASTVisitor::TraverseStmt(E->getIndexExpr());
269 }
270 bool TraversePackIndexingTypeLoc(PackIndexingTypeLoc TL,
271 bool TraverseQualifier) override {
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
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
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
318 }
319
320 /// Suppress traversal of mem-initializer pack expansions.
321 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
322 if (Init->isPackExpansion())
323 return true;
324
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(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(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
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>(ND);
374 TTP && TTP->isParameterPack())
375 addUnexpanded(ND, E->getBeginLoc());
376 }
377 return DynamicRecursiveASTVisitor::TraverseUnresolvedLookupExpr(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.
425 for (auto *SI : FunctionScopes)
427 return true;
428 return false;
429}
430
431/// Diagnose all of the unexpanded parameter packs in the given
432/// vector.
433bool
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;
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>(LocalPack);
451 return TTPD && TTPD->getTypeForDecl() == TTPT;
452 }
453 return declaresSameEntity(cast<NamedDecl *>(Pack.first), LocalPack);
454 };
455 if (llvm::any_of(CSI->LocalPacks, DeclaresThisPack))
456 ParamPackReferences.push_back(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) {
474 if (llvm::any_of(
475 Func->CompoundScopes,
476 [](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
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(Name).second)
508 Names.push_back(Name);
509
510 if (Unexpanded[I].second.isValid())
511 Locations.push_back(Unexpanded[I].second);
512 }
513
514 auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
515 << (int)UPPC << (int)Names.size();
516 for (size_t I = 0, E = std::min(Names.size(), (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
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
534 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
535 T->getTypeLoc());
536 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
537 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
538}
539
542 // C++0x [temp.variadic]p5:
543 // An appearance of a name of a parameter pack that is not expanded is
544 // ill-formed.
546 return false;
547
549 CollectUnexpandedParameterPacksVisitor Visitor(Unexpanded);
550 Visitor.TraverseStmt(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(E->getBeginLoc(), UPPC, Unexpanded);
563}
564
567 return false;
568
570 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(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);
578 for (auto Parm : Unexpanded)
579 if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl *>()))
580 UnexpandedParms.push_back(Parm);
581 if (UnexpandedParms.empty())
582 return false;
583
585 UnexpandedParms);
586}
587
590 // C++0x [temp.variadic]p5:
591 // An appearance of a name of a parameter pack that is not expanded is
592 // ill-formed.
594 return false;
595
597 CollectUnexpandedParameterPacksVisitor(Unexpanded)
598 .TraverseNestedNameSpecifier(SS.getScopeRep());
599 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
601 UPPC, Unexpanded);
602}
603
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()) {
618 return false;
619
623 // FIXME: We shouldn't need this null check!
624 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
625 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
626
628 return false;
629
630 break;
631 }
632
634 CollectUnexpandedParameterPacksVisitor(Unexpanded)
635 .TraverseType(NameInfo.getName().getCXXNameType());
636 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
637 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
638}
639
643
644 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
645 return false;
646
648 CollectUnexpandedParameterPacksVisitor(Unexpanded)
649 .TraverseTemplateName(Template);
650 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
651 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
652}
653
656 if (Arg.getArgument().isNull() ||
658 return false;
659
661 CollectUnexpandedParameterPacksVisitor(Unexpanded)
662 .TraverseTemplateArgumentLoc(Arg);
663 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
664 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
665}
666
669 CollectUnexpandedParameterPacksVisitor(Unexpanded)
670 .TraverseTemplateArgument(Arg);
671}
672
675 CollectUnexpandedParameterPacksVisitor(Unexpanded)
676 .TraverseTemplateArgumentLoc(Arg);
677}
678
681 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
682}
683
686 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
687}
688
692 CollectUnexpandedParameterPacksVisitor(Unexpanded)
693 .TraverseNestedNameSpecifierLoc(NNS);
694}
695
697 const DeclarationNameInfo &NameInfo,
699 CollectUnexpandedParameterPacksVisitor(Unexpanded)
700 .TraverseDeclarationNameInfo(NameInfo);
701}
702
705 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
706}
707
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>(
718 if (T && T->isPackProducingBuiltinTemplate())
720 Arg.getNameLoc());
721
722 return Arg;
723}
724
727 SourceLocation EllipsisLoc) {
728 if (Arg.isInvalid())
729 return Arg;
730
731 switch (Arg.getKind()) {
733 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
734 if (Result.isInvalid())
735 return ParsedTemplateArgument();
736
737 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
738 Arg.getNameLoc());
739 }
740
742 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
743 if (Result.isInvalid())
744 return ParsedTemplateArgument();
745
746 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
747 Arg.getNameLoc());
748 }
749
752 SourceRange R(Arg.getNameLoc());
753 if (Arg.getScopeSpec().isValid())
755 Diag(EllipsisLoc, 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
766 SourceLocation EllipsisLoc) {
767 TypeSourceInfo *TSInfo;
768 GetTypeFromParser(Type, &TSInfo);
769 if (!TSInfo)
770 return true;
771
772 TypeSourceInfo *TSResult =
773 CheckPackExpansion(TSInfo, EllipsisLoc, std::nullopt);
774 if (!TSResult)
775 return true;
776
777 return CreateParsedType(TSResult->getType(), TSResult);
778}
779
781 SourceLocation EllipsisLoc,
782 UnsignedOrNone NumExpansions) {
783 // Create the pack expansion type and source-location information.
785 Pattern->getTypeLoc().getSourceRange(),
786 EllipsisLoc, NumExpansions);
787 if (Result.isNull())
788 return nullptr;
789
790 TypeLocBuilder TLB;
791 TLB.pushFullCopy(Pattern->getTypeLoc());
793 TL.setEllipsisLoc(EllipsisLoc);
794
795 return TLB.getTypeSourceInfo(Context, Result);
796}
797
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(EllipsisLoc, 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
820 return CheckPackExpansion(Pattern, EllipsisLoc, std::nullopt);
821}
822
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(EllipsisLoc, 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
843 SourceLocation EllipsisLoc, SourceRange PatternRange,
845 const MultiLevelTemplateArgumentList &TemplateArgs,
846 bool FailOnPackProducingTemplates, bool &ShouldExpand,
847 bool &RetainExpansion, UnsignedOrNone &NumExpansions) {
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 // It is not yet supported in certain contexts.
878 return Diag(PatternRange.getBegin().isValid() ? PatternRange.getBegin()
879 : EllipsisLoc,
880 diag::err_unsupported_builtin_template_pack_expansion)
881 << TST->getTemplateName();
882 } else if (auto *S =
883 ParmPack.first
884 .dyn_cast<const SubstBuiltinTemplatePackType *>()) {
885 Name = nullptr;
886 NumPrecomputedArguments = S->getNumArgs();
887 } else {
888 NamedDecl *ND = cast<NamedDecl *>(ParmPack.first);
889 if (isa<VarDecl>(ND))
890 IsVarDeclPack = true;
891 else if (isa<BindingDecl>(ND)) {
892 // Find the instantiated BindingDecl and check it for a resolved pack.
893 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
894 CurrentInstantiationScope->findInstantiationOf(ND);
895 Decl *B = cast<Decl *>(*Instantiation);
896 Expr *BindingExpr = cast<BindingDecl>(B)->getBinding();
897 BindingPack = cast_if_present<FunctionParmPackExpr>(BindingExpr);
898 if (!BindingPack) {
899 ShouldExpand = false;
900 continue;
901 }
902 } else
903 std::tie(Depth, Index) = getDepthAndIndex(ND);
904
905 Name = ND->getIdentifier();
906 }
907
908 // Determine the size of this argument pack.
909 unsigned NewPackSize, PendingPackExpansionSize = 0;
910 if (IsVarDeclPack) {
911 // Figure out whether we're instantiating to an argument pack or not.
912 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
913 CurrentInstantiationScope->findInstantiationOf(
914 cast<NamedDecl *>(ParmPack.first));
915 if (isa<DeclArgumentPack *>(*Instantiation)) {
916 // We could expand this function parameter pack.
917 NewPackSize = cast<DeclArgumentPack *>(*Instantiation)->size();
918 } else {
919 // We can't expand this function parameter pack, so we can't expand
920 // the pack expansion.
921 ShouldExpand = false;
922 continue;
923 }
924 } else if (BindingPack) {
925 NewPackSize = BindingPack->getNumExpansions();
926 } else if (NumPrecomputedArguments) {
927 NewPackSize = *NumPrecomputedArguments;
928 } else {
929 // If we don't have a template argument at this depth/index, then we
930 // cannot expand the pack expansion. Make a note of this, but we still
931 // want to check any parameter packs we *do* have arguments for.
932 if (Depth >= TemplateArgs.getNumLevels() ||
933 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
934 ShouldExpand = false;
935 continue;
936 }
937
938 // Determine the size of the argument pack.
940 TemplateArgs(Depth, Index).getPackAsArray();
941 NewPackSize = Pack.size();
942 PendingPackExpansionSize =
943 llvm::count_if(Pack, [](const TemplateArgument &TA) {
944 if (!TA.isPackExpansion())
945 return false;
946
948 return !TA.getAsType()
949 ->castAs<PackExpansionType>()
950 ->getNumExpansions();
951
954 ->getNumExpansions();
955
956 return !TA.getNumTemplateExpansions();
957 });
958 }
959
960 // C++0x [temp.arg.explicit]p9:
961 // Template argument deduction can extend the sequence of template
962 // arguments corresponding to a template parameter pack, even when the
963 // sequence contains explicitly specified template arguments.
964 if (!IsVarDeclPack && CurrentInstantiationScope) {
965 if (NamedDecl *PartialPack =
966 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
967 unsigned PartialDepth, PartialIndex;
968 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
969 if (PartialDepth == Depth && PartialIndex == Index) {
970 RetainExpansion = true;
971 // We don't actually know the new pack size yet.
972 NumPartialExpansions = NewPackSize;
973 PartiallySubstitutedPackLoc = ParmPack.second;
974 continue;
975 }
976 }
977 }
978
979 if (!NumExpansions) {
980 // This is the first pack we've seen for which we have an argument.
981 // Record it.
982 NumExpansions = NewPackSize;
983 FirstPack = IdentifierLoc(ParmPack.second, Name);
984 HaveFirstPack = true;
985 continue;
986 }
987
988 if (NewPackSize != *NumExpansions) {
989 // In some cases, we might be handling packs with unexpanded template
990 // arguments. For example, this can occur when substituting into a type
991 // alias declaration that uses its injected template parameters as
992 // arguments:
993 //
994 // template <class... Outer> struct S {
995 // template <class... Inner> using Alias = S<void(Outer, Inner)...>;
996 // };
997 //
998 // Consider an instantiation attempt like 'S<int>::Alias<Pack...>', where
999 // Pack comes from another template parameter. 'S<int>' is first
1000 // instantiated, expanding the outer pack 'Outer' to <int>. The alias
1001 // declaration is accordingly substituted, leaving the template arguments
1002 // as unexpanded
1003 // '<Pack...>'.
1004 //
1005 // Since we have no idea of the size of '<Pack...>' until its expansion,
1006 // we shouldn't assume its pack size for validation. However if we are
1007 // certain that there are extra arguments beyond unexpanded packs, in
1008 // which case the pack size is already larger than the previous expansion,
1009 // we can complain that before instantiation.
1010 unsigned LeastNewPackSize = NewPackSize - PendingPackExpansionSize;
1011 if (PendingPackExpansionSize && LeastNewPackSize <= *NumExpansions) {
1012 ShouldExpand = false;
1013 continue;
1014 }
1015 // C++0x [temp.variadic]p5:
1016 // All of the parameter packs expanded by a pack expansion shall have
1017 // the same number of arguments specified.
1018 if (HaveFirstPack)
1019 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
1020 << FirstPack.getIdentifierInfo() << Name << *NumExpansions
1021 << (LeastNewPackSize != NewPackSize) << LeastNewPackSize
1022 << SourceRange(FirstPack.getLoc()) << SourceRange(ParmPack.second);
1023 else
1024 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
1025 << Name << *NumExpansions << (LeastNewPackSize != NewPackSize)
1026 << LeastNewPackSize << SourceRange(ParmPack.second);
1027 return true;
1028 }
1029 }
1030
1031 // If we're performing a partial expansion but we also have a full expansion,
1032 // expand to the number of common arguments. For example, given:
1033 //
1034 // template<typename ...T> struct A {
1035 // template<typename ...U> void f(pair<T, U>...);
1036 // };
1037 //
1038 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
1039 // retain an expansion.
1040 if (NumPartialExpansions) {
1041 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
1042 NamedDecl *PartialPack =
1043 CurrentInstantiationScope->getPartiallySubstitutedPack();
1044 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
1045 << PartialPack << *NumPartialExpansions << *NumExpansions
1046 << SourceRange(PartiallySubstitutedPackLoc);
1047 return true;
1048 }
1049
1050 NumExpansions = NumPartialExpansions;
1051 }
1052
1053 return false;
1054}
1055
1058 const MultiLevelTemplateArgumentList &TemplateArgs) {
1059 UnsignedOrNone Result = std::nullopt;
1060 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1061 // Compute the depth and index for this parameter pack.
1062 unsigned Depth;
1063 unsigned Index;
1064
1065 if (const TemplateTypeParmType *TTP =
1066 Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
1067 Depth = TTP->getDepth();
1068 Index = TTP->getIndex();
1069 } else if (auto *TST =
1070 Unexpanded[I]
1071 .first.dyn_cast<const TemplateSpecializationType *>()) {
1072 // This is a dependent pack, we are not ready to expand it yet.
1073 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
1074 (void)TST;
1075 return std::nullopt;
1076 } else if (auto *PST =
1077 Unexpanded[I]
1078 .first
1079 .dyn_cast<const SubstBuiltinTemplatePackType *>()) {
1080 assert((!Result || *Result == PST->getNumArgs()) &&
1081 "inconsistent pack sizes");
1082 Result = PST->getNumArgs();
1083 continue;
1084 } else {
1085 NamedDecl *ND = cast<NamedDecl *>(Unexpanded[I].first);
1086 if (isa<VarDecl>(ND)) {
1087 // Function parameter pack or init-capture pack.
1088 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1089
1090 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
1091 CurrentInstantiationScope->findInstantiationOf(
1092 cast<NamedDecl *>(Unexpanded[I].first));
1093 if (isa<Decl *>(*Instantiation))
1094 // The pattern refers to an unexpanded pack. We're not ready to expand
1095 // this pack yet.
1096 return std::nullopt;
1097
1098 unsigned Size = cast<DeclArgumentPack *>(*Instantiation)->size();
1099 assert((!Result || *Result == Size) && "inconsistent pack sizes");
1100 Result = Size;
1101 continue;
1102 }
1103
1104 std::tie(Depth, Index) = getDepthAndIndex(ND);
1105 }
1106 if (Depth >= TemplateArgs.getNumLevels() ||
1107 !TemplateArgs.hasTemplateArgument(Depth, Index))
1108 // The pattern refers to an unknown template argument. We're not ready to
1109 // expand this pack yet.
1110 return std::nullopt;
1111
1112 // Determine the size of the argument pack.
1113 unsigned Size = TemplateArgs(Depth, Index).pack_size();
1114 assert((!Result || *Result == Size) && "inconsistent pack sizes");
1115 Result = Size;
1116 }
1117
1118 return Result;
1119}
1120
1122 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) {
1123 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
1125 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
1126 return getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
1127}
1128
1130 const DeclSpec &DS = D.getDeclSpec();
1131 switch (DS.getTypeSpecType()) {
1133 case TST_typename:
1135 case TST_typeofType:
1136#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
1137#include "clang/Basic/TransformTypeTraits.def"
1138 case TST_atomic: {
1139 QualType T = DS.getRepAsType().get();
1140 if (!T.isNull() && T->containsUnexpandedParameterPack())
1141 return true;
1142 break;
1143 }
1144
1146 case TST_typeofExpr:
1147 case TST_decltype:
1148 case TST_bitint:
1149 if (DS.getRepAsExpr() &&
1151 return true;
1152 break;
1153
1154 case TST_unspecified:
1155 case TST_void:
1156 case TST_char:
1157 case TST_wchar:
1158 case TST_char8:
1159 case TST_char16:
1160 case TST_char32:
1161 case TST_int:
1162 case TST_int128:
1163 case TST_half:
1164 case TST_float:
1165 case TST_double:
1166 case TST_Accum:
1167 case TST_Fract:
1168 case TST_Float16:
1169 case TST_float128:
1170 case TST_ibm128:
1171 case TST_bool:
1172 case TST_decimal32:
1173 case TST_decimal64:
1174 case TST_decimal128:
1175 case TST_enum:
1176 case TST_union:
1177 case TST_struct:
1178 case TST_interface:
1179 case TST_class:
1180 case TST_auto:
1181 case TST_auto_type:
1182 case TST_decltype_auto:
1183 case TST_BFloat16:
1184#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
1185#include "clang/Basic/OpenCLImageTypes.def"
1186#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case TST_##Name:
1187#include "clang/Basic/HLSLIntangibleTypes.def"
1189 case TST_error:
1190 break;
1191 }
1192
1193 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
1194 const DeclaratorChunk &Chunk = D.getTypeObject(I);
1195 switch (Chunk.Kind) {
1201 // These declarator chunks cannot contain any parameter packs.
1202 break;
1203
1205 if (Chunk.Arr.NumElts &&
1207 return true;
1208 break;
1210 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
1211 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
1212 QualType ParamTy = Param->getType();
1213 assert(!ParamTy.isNull() && "Couldn't parse type?");
1214 if (ParamTy->containsUnexpandedParameterPack()) return true;
1215 }
1216
1217 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
1218 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
1219 if (Chunk.Fun.Exceptions[i]
1220 .Ty.get()
1222 return true;
1223 }
1224 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
1226 return true;
1227
1228 if (Chunk.Fun.hasTrailingReturnType()) {
1230 if (!T.isNull() && T->containsUnexpandedParameterPack())
1231 return true;
1232 }
1233 break;
1234
1237 return true;
1238 break;
1239 }
1240 }
1241
1242 if (Expr *TRC = D.getTrailingRequiresClause())
1243 if (TRC->containsUnexpandedParameterPack())
1244 return true;
1245
1246 return false;
1247}
1248
1249namespace {
1250
1251// Callback to only accept typo corrections that refer to parameter packs.
1252class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
1253 public:
1254 bool ValidateCandidate(const TypoCorrection &candidate) override {
1255 NamedDecl *ND = candidate.getCorrectionDecl();
1256 return ND && ND->isParameterPack();
1257 }
1258
1259 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1260 return std::make_unique<ParameterPackValidatorCCC>(*this);
1261 }
1262};
1263
1264}
1265
1267 SourceLocation OpLoc,
1268 IdentifierInfo &Name,
1269 SourceLocation NameLoc,
1270 SourceLocation RParenLoc) {
1271 // C++0x [expr.sizeof]p5:
1272 // The identifier in a sizeof... expression shall name a parameter pack.
1273 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1274 LookupName(R, S);
1275
1276 NamedDecl *ParameterPack = nullptr;
1277 switch (R.getResultKind()) {
1279 ParameterPack = R.getFoundDecl();
1280 break;
1281
1284 ParameterPackValidatorCCC CCC{};
1285 if (TypoCorrection Corrected =
1286 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1288 diagnoseTypo(Corrected,
1289 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1290 PDiag(diag::note_parameter_pack_here));
1291 ParameterPack = Corrected.getCorrectionDecl();
1292 }
1293 break;
1294 }
1297 break;
1298
1301 return ExprError();
1302 }
1303
1304 if (!ParameterPack || !ParameterPack->isParameterPack()) {
1305 Diag(NameLoc, diag::err_expected_name_of_pack) << &Name;
1306 return ExprError();
1307 }
1308
1309 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1310
1311 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1312 RParenLoc);
1313}
1314
1315static bool isParameterPack(Expr *PackExpression) {
1316 if (auto *D = dyn_cast<DeclRefExpr>(PackExpression); D) {
1317 ValueDecl *VD = D->getDecl();
1318 return VD->isParameterPack();
1319 }
1320 return false;
1321}
1322
1324 SourceLocation EllipsisLoc,
1325 SourceLocation LSquareLoc,
1326 Expr *IndexExpr,
1327 SourceLocation RSquareLoc) {
1328 bool isParameterPack = ::isParameterPack(PackExpression);
1329 if (!isParameterPack) {
1330 if (!PackExpression->containsErrors())
1331 Diag(PackExpression->getBeginLoc(), diag::err_expected_name_of_pack)
1332 << PackExpression;
1333 return ExprError();
1334 }
1335 ExprResult Res =
1336 BuildPackIndexingExpr(PackExpression, EllipsisLoc, IndexExpr, RSquareLoc);
1337 if (!Res.isInvalid())
1339 ? diag::warn_cxx23_pack_indexing
1340 : diag::ext_pack_indexing);
1341 return Res;
1342}
1343
1345 SourceLocation EllipsisLoc,
1346 Expr *IndexExpr,
1347 SourceLocation RSquareLoc,
1348 ArrayRef<Expr *> ExpandedExprs,
1349 bool FullySubstituted) {
1350
1351 std::optional<int64_t> Index;
1352 if (!IndexExpr->isInstantiationDependent()) {
1353 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1354
1356 IndexExpr, Context.getSizeType(), Value, CCEKind::ArrayBound);
1357 if (!Res.isUsable())
1358 return ExprError();
1359 Index = Value.getExtValue();
1360 IndexExpr = Res.get();
1361 }
1362
1363 if (Index && FullySubstituted) {
1364 if (*Index < 0 || *Index >= int64_t(ExpandedExprs.size())) {
1365 Diag(PackExpression->getBeginLoc(), diag::err_pack_index_out_of_bound)
1366 << *Index << PackExpression << ExpandedExprs.size();
1367 return ExprError();
1368 }
1369 }
1370
1371 return PackIndexingExpr::Create(getASTContext(), EllipsisLoc, RSquareLoc,
1372 PackExpression, IndexExpr, Index,
1373 ExpandedExprs, FullySubstituted);
1374}
1375
1377 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
1378 UnsignedOrNone &NumExpansions) const {
1379 const TemplateArgument &Argument = OrigLoc.getArgument();
1380 assert(Argument.isPackExpansion());
1381 switch (Argument.getKind()) {
1383 // FIXME: We shouldn't ever have to worry about missing
1384 // type-source info!
1385 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1386 if (!ExpansionTSInfo)
1387 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1388 Ellipsis);
1389 PackExpansionTypeLoc Expansion =
1390 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1391 Ellipsis = Expansion.getEllipsisLoc();
1392
1393 TypeLoc Pattern = Expansion.getPatternLoc();
1394 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1395
1396 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1397 // TypeSourceInfo.
1398 // FIXME: Find some way to avoid the copy?
1399 TypeLocBuilder TLB;
1400 TLB.pushFullCopy(Pattern);
1401 TypeSourceInfo *PatternTSInfo =
1402 TLB.getTypeSourceInfo(Context, Pattern.getType());
1404 PatternTSInfo);
1405 }
1406
1408 PackExpansionExpr *Expansion
1409 = cast<PackExpansionExpr>(Argument.getAsExpr());
1410 Expr *Pattern = Expansion->getPattern();
1411 Ellipsis = Expansion->getEllipsisLoc();
1412 NumExpansions = Expansion->getNumExpansions();
1413 return TemplateArgumentLoc(
1414 TemplateArgument(Pattern, Argument.isCanonicalExpr()), Pattern);
1415 }
1416
1418 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1419 NumExpansions = Argument.getNumTemplateExpansions();
1420 return TemplateArgumentLoc(
1421 Context, Argument.getPackExpansionPattern(), OrigLoc.getTemplateKWLoc(),
1422 OrigLoc.getTemplateQualifierLoc(), OrigLoc.getTemplateNameLoc());
1423
1431 return TemplateArgumentLoc();
1432 }
1433
1434 llvm_unreachable("Invalid TemplateArgument Kind!");
1435}
1436
1438 assert(Arg.containsUnexpandedParameterPack());
1439
1440 // If this is a substituted pack, grab that pack. If not, we don't know
1441 // the size yet.
1442 // FIXME: We could find a size in more cases by looking for a substituted
1443 // pack anywhere within this argument, but that's not necessary in the common
1444 // case for 'sizeof...(A)' handling.
1445 TemplateArgument Pack;
1446 switch (Arg.getKind()) {
1448 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1449 Pack = Subst->getArgumentPack();
1450 else
1451 return std::nullopt;
1452 break;
1453
1455 if (auto *Subst =
1456 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1457 Pack = Subst->getArgumentPack();
1458 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1459 for (ValueDecl *PD : *Subst)
1460 if (PD->isParameterPack())
1461 return std::nullopt;
1462 return Subst->getNumExpansions();
1463 } else
1464 return std::nullopt;
1465 break;
1466
1470 Pack = Subst->getArgumentPack();
1471 else
1472 return std::nullopt;
1473 break;
1474
1482 return std::nullopt;
1483 }
1484
1485 // Check that no argument in the pack is itself a pack expansion.
1486 for (TemplateArgument Elem : Pack.pack_elements()) {
1487 // There's no point recursing in this case; we would have already
1488 // expanded this pack expansion into the enclosing pack if we could.
1489 if (Elem.isPackExpansion())
1490 return std::nullopt;
1491 // Don't guess the size of unexpanded packs. The pack within a template
1492 // argument may have yet to be of a PackExpansion type before we see the
1493 // ellipsis in the annotation stage.
1494 //
1495 // This doesn't mean we would invalidate the optimization: Arg can be an
1496 // unexpanded pack regardless of Elem's dependence. For instance,
1497 // A TemplateArgument that contains either a SubstTemplateTypeParmPackType
1498 // or SubstNonTypeTemplateParmPackExpr is always considered Unexpanded, but
1499 // the underlying TemplateArgument thereof may not.
1500 if (Elem.containsUnexpandedParameterPack())
1501 return std::nullopt;
1502 }
1503 return Pack.pack_size();
1504}
1505
1506static void CheckFoldOperand(Sema &S, Expr *E) {
1507 if (!E)
1508 return;
1509
1510 E = E->IgnoreImpCasts();
1511 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1512 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1514 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1515 << E->getSourceRange()
1518 ")");
1519 }
1520}
1521
1523 tok::TokenKind Operator,
1524 SourceLocation EllipsisLoc, Expr *RHS,
1525 SourceLocation RParenLoc) {
1526 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1527 // in the parser and reduce down to just cast-expressions here.
1528 CheckFoldOperand(*this, LHS);
1529 CheckFoldOperand(*this, RHS);
1530
1531 // [expr.prim.fold]p3:
1532 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1533 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1534 // an unexpanded parameter pack, but not both.
1535 if (LHS && RHS &&
1538 return Diag(EllipsisLoc,
1540 ? diag::err_fold_expression_packs_both_sides
1541 : diag::err_pack_expansion_without_parameter_packs)
1542 << LHS->getSourceRange() << RHS->getSourceRange();
1543 }
1544
1545 // [expr.prim.fold]p2:
1546 // In a unary fold, the cast-expression shall contain an unexpanded
1547 // parameter pack.
1548 if (!LHS || !RHS) {
1549 Expr *Pack = LHS ? LHS : RHS;
1550 assert(Pack && "fold expression with neither LHS nor RHS");
1551 if (!Pack->containsUnexpandedParameterPack()) {
1552 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1553 << Pack->getSourceRange();
1554 }
1555 }
1556
1557 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1558
1559 // Perform first-phase name lookup now.
1560 UnresolvedLookupExpr *ULE = nullptr;
1561 {
1562 UnresolvedSet<16> Functions;
1563 LookupBinOp(S, EllipsisLoc, Opc, Functions);
1564 if (!Functions.empty()) {
1565 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1568 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1569 DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1570 if (Callee.isInvalid())
1571 return ExprError();
1572 ULE = cast<UnresolvedLookupExpr>(Callee.get());
1573 }
1574 }
1575
1576 return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1577 std::nullopt);
1578}
1579
1581 SourceLocation LParenLoc, Expr *LHS,
1582 BinaryOperatorKind Operator,
1583 SourceLocation EllipsisLoc, Expr *RHS,
1584 SourceLocation RParenLoc,
1585 UnsignedOrNone NumExpansions) {
1586 return new (Context)
1587 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1588 EllipsisLoc, RHS, RParenLoc, NumExpansions);
1589}
1590
1592 BinaryOperatorKind Operator) {
1593 // [temp.variadic]p9:
1594 // If N is zero for a unary fold-expression, the value of the expression is
1595 // && -> true
1596 // || -> false
1597 // , -> void()
1598 // if the operator is not listed [above], the instantiation is ill-formed.
1599 //
1600 // Note that we need to use something like int() here, not merely 0, to
1601 // prevent the result from being a null pointer constant.
1602 QualType ScalarType;
1603 switch (Operator) {
1604 case BO_LOr:
1605 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1606 case BO_LAnd:
1607 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1608 case BO_Comma:
1609 ScalarType = Context.VoidTy;
1610 break;
1611
1612 default:
1613 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1614 << BinaryOperator::getOpcodeStr(Operator);
1615 }
1616
1617 return new (Context) CXXScalarValueInitExpr(
1618 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1619 EllipsisLoc);
1620}
static void CheckFoldOperand(Sema &S, Expr *E)
static bool isParameterPack(Expr *PackExpression)
Defines the clang::TypeLoc interface and its subclasses.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
bool isPackExpansion() const
Definition Attr.h:107
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2175
StringRef getOpcodeStr() const
Definition Expr.h:4040
Represents a folding of a pack over an operator.
Definition ExprCXX.h:5026
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2198
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
const TypeClass * getTypePtr() const
Definition TypeLoc.h:438
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
ValueDecl * getDecl()
Definition Expr.h:1340
SourceLocation getLocation() const
Definition Expr.h:1348
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
TST getTypeSpecType() const
Definition DeclSpec.h:507
ParsedType getRepAsType() const
Definition DeclSpec.h:517
Expr * getRepAsExpr() const
Definition DeclSpec.h:525
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:244
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:234
The name of a declaration.
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2607
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
virtual bool TraverseDecl(MaybeConst< Decl > *D)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseAttr(MaybeConst< Attr > *At)
virtual bool TraverseLambdaCapture(MaybeConst< LambdaExpr > *LE, const LambdaCapture *C, MaybeConst< Expr > *Init)
virtual bool TraverseTemplateName(TemplateName Template)
virtual bool TraverseType(QualType T, bool TraverseQualifier=true)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
This represents one expression.
Definition Expr.h:112
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3053
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4835
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4873
QualType desugar() const
Definition TypeBase.h:5863
One of these records is kept for each identifier that is lexed.
A simple pair of identifier info and location.
SourceLocation getLoc() const
IdentifierInfo * getIdentifierInfo() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
TemplateParameterList * getTemplateParameterList() const
If this is a generic lambda expression, retrieve the template parameter list associated with it,...
Definition ExprCXX.cpp:1414
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:368
Represents the results of name lookup.
Definition Lookup.h:147
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
LookupResultKind getResultKind() const
Definition Lookup.h:344
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition Template.h:175
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition Template.h:123
This represents a decl that may have a name.
Definition Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
A C++ nested-name-specifier augmented with source location information.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition ExprObjC.h:359
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition ExprObjC.h:361
PtrTy get() const
Definition Ownership.h:81
decls_iterator decls_begin() const
Definition ExprCXX.h:3215
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3226
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4357
Expr * getPattern()
Retrieve the pattern of the pack expansion.
Definition ExprCXX.h:4386
UnsignedOrNone getNumExpansions() const
Determine the number of expansions that will be produced when this pack expansion is instantiated,...
Definition ExprCXX.h:4397
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that describes this pack expansion.
Definition ExprCXX.h:4393
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2741
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2737
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2753
Expr * getIndexExpr() const
Definition ExprCXX.h:4622
static PackIndexingExpr * Create(ASTContext &Context, SourceLocation EllipsisLoc, SourceLocation RSquareLoc, Expr *PackIdExpr, Expr *IndexExpr, std::optional< int64_t > Index, ArrayRef< Expr * > SubstitutedExprs={}, bool FullySubstituted=false)
Definition ExprCXX.cpp:1733
Expr * getIndexExpr() const
Definition TypeLoc.h:2292
Represents a parameter to a function.
Definition Decl.h:1789
Represents the parsed form of a C++ template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
bool isInvalid() const
Determine whether the given template argument is invalid.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
SourceLocation getBeginLoc() const LLVM_READONLY
ArrayRef< ParmVarDecl * > getLocalParameters() const
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:850
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12937
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9281
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1216
ASTContext & Context
Definition Sema.h:1276
ExprResult BuildPackIndexingExpr(Expr *PackExpression, SourceLocation EllipsisLoc, Expr *IndexExpr, SourceLocation RSquareLoc, ArrayRef< Expr * > ExpandedExprs={}, bool FullySubstituted=false)
ASTContext & getASTContext() const
Definition Sema.h:918
bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE)
If the given requirees-expression contains an unexpanded reference to one of its own parameter packs,...
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
UnexpandedParameterPackContext
The context in which an unexpanded parameter pack is being diagnosed.
Definition Sema.h:14218
@ UPPC_Requirement
Definition Sema.h:14286
const LangOptions & getLangOpts() const
Definition Sema.h:911
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool isUnexpandedParameterPackPermitted()
Determine whether an unexpanded parameter pack might be permitted in this location.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ParsedTemplateArgument ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg)
Invoked when parsing a template argument.
ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, SourceLocation EllipsisLoc, SourceLocation LSquareLoc, Expr *IndexExpr, SourceLocation RSquareLoc)
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg)
Given a template argument that contains an unexpanded parameter pack, but which has already been subs...
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc)
Called when an expression computing the size of a parameter pack is parsed.
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc)
Handle a C++1z fold-expression: ( expr op ... op expr ).
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, UnsignedOrNone &NumExpansions) const
Returns the pattern of the pack expansion for a template argument.
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
static SizeOfPackExpr * Create(ASTContext &Context, SourceLocation OperatorLoc, NamedDecl *Pack, SourceLocation PackLoc, SourceLocation RParenLoc, UnsignedOrNone Length=std::nullopt, ArrayRef< TemplateArgument > PartialArgs={})
Definition ExprCXX.cpp:1709
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
A structure for storing an already-substituted template template parameter pack.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
SourceLocation getTemplateKWLoc() const
TypeSourceInfo * getTypeSourceInfo() const
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool containsUnexpandedParameterPack() const
Whether this template argument contains an unexpanded parameter pack.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isCanonicalExpr() const
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool containsUnexpandedParameterPack() const
Determines whether this template name contains an unexpanded parameter pack (for C++0x variadic templ...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
A container of type source information.
Definition TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8325
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
The base class of the type hierarchy.
Definition TypeBase.h:1833
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9226
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2060
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2423
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9159
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3384
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:3461
A set of unresolved declarations.
bool isPackExpansion() const
Determine whether this is a pack expansion.
Definition DeclCXX.h:4077
bool isPackExpansion() const
Determine whether this is a pack expansion.
Definition DeclCXX.h:3987
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5461
Contains information about the compound statement currently being parsed.
Definition ScopeInfo.h:67
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
#define bool
Definition gpuintrin.h:32
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ TST_typeof_unqualType
Definition Specifiers.h:87
@ TST_ibm128
Definition Specifiers.h:74
@ TST_decimal64
Definition Specifiers.h:77
@ TST_float
Definition Specifiers.h:71
@ TST_auto_type
Definition Specifiers.h:94
@ TST_auto
Definition Specifiers.h:92
@ TST_typeof_unqualExpr
Definition Specifiers.h:88
@ TST_decimal32
Definition Specifiers.h:76
@ TST_int128
Definition Specifiers.h:64
@ TST_atomic
Definition Specifiers.h:96
@ TST_half
Definition Specifiers.h:66
@ TST_decltype
Definition Specifiers.h:89
@ TST_typename_pack_indexing
Definition Specifiers.h:97
@ TST_char32
Definition Specifiers.h:62
@ TST_struct
Definition Specifiers.h:81
@ TST_typeofType
Definition Specifiers.h:85
@ TST_bitint
Definition Specifiers.h:65
@ TST_wchar
Definition Specifiers.h:59
@ TST_BFloat16
Definition Specifiers.h:70
@ TST_char16
Definition Specifiers.h:61
@ TST_char
Definition Specifiers.h:58
@ TST_unspecified
Definition Specifiers.h:56
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_Fract
Definition Specifiers.h:69
@ TST_float128
Definition Specifiers.h:73
@ TST_double
Definition Specifiers.h:72
@ TST_Accum
Definition Specifiers.h:68
@ TST_int
Definition Specifiers.h:63
@ TST_bool
Definition Specifiers.h:75
@ TST_typeofExpr
Definition Specifiers.h:86
@ TST_typename
Definition Specifiers.h:84
@ TST_void
Definition Specifiers.h:57
@ TST_unknown_anytype
Definition Specifiers.h:95
@ TST_enum
Definition Specifiers.h:79
@ TST_error
Definition Specifiers.h:104
@ TST_decltype_auto
Definition Specifiers.h:93
@ TST_interface
Definition Specifiers.h:83
@ TST_Float16
Definition Specifiers.h:67
@ TST_char8
Definition Specifiers.h:60
@ TST_decimal128
Definition Specifiers.h:78
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus26
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:235
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ExprResult ExprError()
Definition Ownership.h:265
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
Definition Address.h:327
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_Dynamic
throw(T1, T2)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
TypeSourceInfo * getNamedTypeInfo() const
getNamedTypeInfo - Returns the source type info associated to the name.
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1291
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1556
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1410
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1398
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1559
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1373
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1542
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1537
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1414
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1221
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1614
ArrayTypeInfo Arr
Definition DeclSpec.h:1611
FunctionTypeInfo Fun
Definition DeclSpec.h:1612
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
Expr * Value
The value of the dictionary element.
Definition ExprObjC.h:266
bool isPackExpansion() const
Determines whether this dictionary element is a pack expansion.
Definition ExprObjC.h:276
Expr * Key
The key for the dictionary element.
Definition ExprObjC.h:263