clang 24.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,
147 bool TraverseQualifier = true) override {
148
149 if (PackIndexingTemplateStorage *PI =
150 Template.getAsPackIndexingTemplate())
151 return DynamicRecursiveASTVisitor::TraverseStmt(PI->getIndexExpr());
152
153 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
154 Template.getAsTemplateDecl())) {
155 if (TTP->isParameterPack())
156 addUnexpanded(TTP);
157 }
158
159#ifndef NDEBUG
160 ContainsIntermediatePacks |=
161 (bool)Template.getAsSubstTemplateTemplateParmPack();
162#endif
163
165 Template, TraverseQualifier);
166 }
167
168 bool
169 TraverseTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc T,
170 bool TraverseQualifier) override {
171 if (TryTraverseSpecializationProducingPacks(T.getTypePtr(),
172 T.getBeginLoc()))
173 return true;
174 return DynamicRecursiveASTVisitor::TraverseTemplateSpecializationTypeLoc(
175 T, TraverseQualifier);
176 }
177
178 bool TraverseTemplateSpecializationType(TemplateSpecializationType *T,
179 bool TraverseQualfier) override {
180 if (TryTraverseSpecializationProducingPacks(T, SourceLocation()))
181 return true;
182 return DynamicRecursiveASTVisitor::TraverseTemplateSpecializationType(T);
183 }
184
185 /// Suppress traversal into Objective-C container literal
186 /// elements that are pack expansions.
187 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) override {
189 return true;
190
191 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
192 ObjCDictionaryElement Element = E->getKeyValueElement(I);
193 if (Element.isPackExpansion())
194 continue;
195
196 TraverseStmt(Element.Key);
197 TraverseStmt(Element.Value);
198 }
199 return true;
200 }
201 //------------------------------------------------------------------------
202 // Pruning the search for unexpanded parameter packs.
203 //------------------------------------------------------------------------
204
205 /// Suppress traversal into statements and expressions that
206 /// do not contain unexpanded parameter packs.
207 bool TraverseStmt(Stmt *S) override {
208 Expr *E = dyn_cast_or_null<Expr>(S);
209 if ((E && E->containsUnexpandedParameterPack()) || InLambdaOrBlock)
211
212 return true;
213 }
214
215 /// Suppress traversal into types that do not contain
216 /// unexpanded parameter packs.
217 bool TraverseType(QualType T, bool TraverseQualifier = true) override {
218 if ((!T.isNull() && T->containsUnexpandedParameterPack()) ||
219 InLambdaOrBlock)
220 return DynamicRecursiveASTVisitor::TraverseType(T, TraverseQualifier);
221
222 return true;
223 }
224
225 /// Suppress traversal into types with location information
226 /// that do not contain unexpanded parameter packs.
227 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
228 if ((!TL.getType().isNull() &&
230 InLambdaOrBlock)
232 TraverseQualifier);
233
234 return true;
235 }
236
237 /// Suppress traversal of parameter packs.
238 bool TraverseDecl(Decl *D) override {
239 // A function parameter pack is a pack expansion, so cannot contain
240 // an unexpanded parameter pack. Likewise for a template parameter
241 // pack that contains any references to other packs.
242 if (D && D->isParameterPack())
243 return true;
244
246 }
247
248 /// Suppress traversal of pack-expanded attributes.
249 bool TraverseAttr(Attr *A) override {
250 if (A->isPackExpansion())
251 return true;
252
254 }
255
256 /// Suppress traversal of pack expansion expressions and types.
257 ///@{
258 bool TraversePackExpansionType(PackExpansionType *T,
259 bool TraverseQualifier) override {
260 return true;
261 }
262 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL,
263 bool TraverseQualifier) override {
264 return true;
265 }
266 bool TraversePackExpansionExpr(PackExpansionExpr *E) override {
267 return true;
268 }
269 bool TraverseCXXFoldExpr(CXXFoldExpr *E) override { return true; }
270 bool TraversePackIndexingExpr(PackIndexingExpr *E) override {
272 }
273 bool TraversePackIndexingType(PackIndexingType *E,
274 bool TraverseQualifier) override {
275 return DynamicRecursiveASTVisitor::TraverseStmt(E->getIndexExpr());
276 }
277 bool TraversePackIndexingTypeLoc(PackIndexingTypeLoc TL,
278 bool TraverseQualifier) override {
280 }
281
282 ///@}
283
284 /// Suppress traversal of using-declaration pack expansion.
285 bool
286 TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) override {
287 if (D->isPackExpansion())
288 return true;
289
290 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingValueDecl(D);
291 }
292
293 /// Suppress traversal of using-declaration pack expansion.
294 bool TraverseUnresolvedUsingTypenameDecl(
295 UnresolvedUsingTypenameDecl *D) override {
296 if (D->isPackExpansion())
297 return true;
298
299 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingTypenameDecl(D);
300 }
301
302 /// Suppress traversal of template argument pack expansions.
303 bool TraverseTemplateArgument(const TemplateArgument &Arg) override {
304 if (Arg.isPackExpansion())
305 return true;
306
308 }
309
310 /// Suppress traversal of template argument pack expansions.
311 bool
312 TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) override {
313 if (ArgLoc.getArgument().isPackExpansion())
314 return true;
315
317 }
318
319 /// Suppress traversal of base specifier pack expansions.
320 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) override {
321 if (Base.isPackExpansion())
322 return true;
323
325 }
326
327 /// Suppress traversal of mem-initializer pack expansions.
328 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
329 if (Init->isPackExpansion())
330 return true;
331
333 }
334
335 /// Note whether we're traversing a lambda containing an unexpanded
336 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
337 /// including all the places where we normally wouldn't look. Within a
338 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
339 /// outside an expression.
340 bool TraverseLambdaExpr(LambdaExpr *Lambda) override {
341 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
342 // even if it's contained within another lambda.
343 if (!Lambda->containsUnexpandedParameterPack())
344 return true;
345
346 SaveAndRestore _(InLambdaOrBlock, true);
347 unsigned OldDepthLimit = DepthLimit;
348
349 if (auto *TPL = Lambda->getTemplateParameterList())
350 DepthLimit = TPL->getDepth();
351
352 DynamicRecursiveASTVisitor::TraverseLambdaExpr(Lambda);
353
354 DepthLimit = OldDepthLimit;
355 return true;
356 }
357
358 /// Analogously for blocks.
359 bool TraverseBlockExpr(BlockExpr *Block) override {
360 if (!Block->containsUnexpandedParameterPack())
361 return true;
362
363 SaveAndRestore _(InLambdaOrBlock, true);
364 DynamicRecursiveASTVisitor::TraverseBlockExpr(Block);
365 return true;
366 }
367
368 /// Suppress traversal within pack expansions in lambda captures.
369 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
370 Expr *Init) override {
371 if (C->isPackExpansion())
372 return true;
373
375 }
376
377 bool TraverseUnresolvedLookupExpr(UnresolvedLookupExpr *E) override {
378 if (E->getNumDecls() == 1) {
379 NamedDecl *ND = *E->decls_begin();
380 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND);
381 TTP && TTP->isParameterPack())
382 addUnexpanded(ND, E->getBeginLoc());
383 }
384 return DynamicRecursiveASTVisitor::TraverseUnresolvedLookupExpr(E);
385 }
386
387 bool TraverseSubstBuiltinTemplatePackType(SubstBuiltinTemplatePackType *T,
388 bool TraverseQualifier) override {
389 addUnexpanded(T);
390 // Do not call into base implementation to supress traversal of the
391 // substituted types.
392 return true;
393 }
394
395#ifndef NDEBUG
396 bool TraverseFunctionParmPackExpr(FunctionParmPackExpr *) override {
397 ContainsIntermediatePacks = true;
398 return true;
399 }
400
401 bool TraverseSubstNonTypeTemplateParmPackExpr(
402 SubstNonTypeTemplateParmPackExpr *) override {
403 ContainsIntermediatePacks = true;
404 return true;
405 }
406
407 bool VisitSubstTemplateTypeParmPackType(
408 SubstTemplateTypeParmPackType *) override {
409 ContainsIntermediatePacks = true;
410 return true;
411 }
412
413 bool VisitSubstTemplateTypeParmPackTypeLoc(
414 SubstTemplateTypeParmPackTypeLoc) override {
415 ContainsIntermediatePacks = true;
416 return true;
417 }
418
419 bool containsIntermediatePacks() const { return ContainsIntermediatePacks; }
420#endif
421};
422}
423
424/// Determine whether it's possible for an unexpanded parameter pack to
425/// be valid in this location. This only happens when we're in a declaration
426/// that is nested within an expression that could be expanded, such as a
427/// lambda-expression within a function call.
428///
429/// This is conservatively correct, but may claim that some unexpanded packs are
430/// permitted when they are not.
432 for (auto *SI : FunctionScopes)
434 return true;
435 return false;
436}
437
438/// Diagnose all of the unexpanded parameter packs in the given
439/// vector.
440bool
444 if (Unexpanded.empty())
445 return false;
446
447 // If we are within a lambda expression and referencing a pack that is not
448 // declared within the lambda itself, that lambda contains an unexpanded
449 // parameter pack, and we are done. Analogously for blocks.
450 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
451 // later.
452 SmallVector<UnexpandedParameterPack, 4> ParamPackReferences;
454 for (auto &Pack : Unexpanded) {
455 auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
456 if (auto *TTPT = dyn_cast<const TemplateTypeParmType *>(Pack.first)) {
457 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
458 return TTPD && TTPD->getTypeForDecl() == TTPT;
459 }
460 return declaresSameEntity(cast<NamedDecl *>(Pack.first), LocalPack);
461 };
462 if (llvm::any_of(CSI->LocalPacks, DeclaresThisPack))
463 ParamPackReferences.push_back(Pack);
464 }
465
466 if (ParamPackReferences.empty()) {
467 // Construct in lambda only references packs declared outside the lambda.
468 // That's OK for now, but the lambda itself is considered to contain an
469 // unexpanded pack in this case, which will require expansion outside the
470 // lambda.
471
472 // We do not permit pack expansion that would duplicate a statement
473 // expression, not even within a lambda.
474 // FIXME: We could probably support this for statement expressions that
475 // do not contain labels.
476 // FIXME: This is insufficient to detect this problem; consider
477 // f( ({ bad: 0; }) + pack ... );
478 bool EnclosingStmtExpr = false;
479 for (unsigned N = FunctionScopes.size(); N; --N) {
481 if (llvm::any_of(
482 Func->CompoundScopes,
483 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
484 EnclosingStmtExpr = true;
485 break;
486 }
487 // Coumpound-statements outside the lambda are OK for now; we'll check
488 // for those when we finish handling the lambda.
489 if (Func == CSI)
490 break;
491 }
492
493 if (!EnclosingStmtExpr) {
494 CSI->ContainsUnexpandedParameterPack = true;
495 return false;
496 }
497 } else {
498 Unexpanded = ParamPackReferences;
499 }
500 }
501
505
506 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
507 IdentifierInfo *Name = nullptr;
508 if (const TemplateTypeParmType *TTP =
509 dyn_cast<const TemplateTypeParmType *>(Unexpanded[I].first))
510 Name = TTP->getIdentifier();
511 else if (NamedDecl *ND = dyn_cast<NamedDecl *>(Unexpanded[I].first))
512 Name = ND->getIdentifier();
513
514 if (Name && NamesKnown.insert(Name).second)
515 Names.push_back(Name);
516
517 if (Unexpanded[I].second.isValid())
518 Locations.push_back(Unexpanded[I].second);
519 }
520
521 auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
522 << (int)UPPC << (int)Names.size();
523 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
524 DB << Names[I];
525
526 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
527 DB << SourceRange(Locations[I]);
528 return true;
529}
530
534 // C++0x [temp.variadic]p5:
535 // An appearance of a name of a parameter pack that is not expanded is
536 // ill-formed.
537 if (!T->getType()->containsUnexpandedParameterPack())
538 return false;
539
541 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
542 T->getTypeLoc());
543 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
544 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
545}
546
549 // C++0x [temp.variadic]p5:
550 // An appearance of a name of a parameter pack that is not expanded is
551 // ill-formed.
553 return false;
554
556 CollectUnexpandedParameterPacksVisitor Visitor(Unexpanded);
557 Visitor.TraverseStmt(E);
558#ifndef NDEBUG
559 // The expression might contain a type/subexpression that has been substituted
560 // but has the expansion held off, e.g. a FunctionParmPackExpr which a larger
561 // CXXFoldExpr would expand. It's only possible when expanding a lambda as a
562 // pattern of a fold expression, so don't fire on an empty result in that
563 // case.
564 bool LambdaReferencingOuterPacks =
565 getEnclosingLambdaOrBlock() && Visitor.containsIntermediatePacks();
566 assert((!Unexpanded.empty() || LambdaReferencingOuterPacks) &&
567 "Unable to find unexpanded parameter packs");
568#endif
569 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
570}
571
574 return false;
575
577 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
578 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
579
580 // We only care about unexpanded references to the RequiresExpr's own
581 // parameter packs.
582 auto Parms = RE->getLocalParameters();
583 llvm::SmallPtrSet<NamedDecl *, 8> ParmSet(llvm::from_range, Parms);
585 for (auto Parm : Unexpanded)
586 if (ParmSet.contains(dyn_cast<NamedDecl *>(Parm.first)))
587 UnexpandedParms.push_back(Parm);
588 if (UnexpandedParms.empty())
589 return false;
590
592 UnexpandedParms);
593}
594
597 // C++0x [temp.variadic]p5:
598 // An appearance of a name of a parameter pack that is not expanded is
599 // ill-formed.
601 return false;
602
604 CollectUnexpandedParameterPacksVisitor(Unexpanded)
605 .TraverseNestedNameSpecifier(SS.getScopeRep());
606 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
608 UPPC, Unexpanded);
609}
610
613 // C++0x [temp.variadic]p5:
614 // An appearance of a name of a parameter pack that is not expanded is
615 // ill-formed.
616 switch (NameInfo.getName().getNameKind()) {
625 return false;
626
630 // FIXME: We shouldn't need this null check!
631 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
632 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
633
635 return false;
636
637 break;
638 }
639
641 CollectUnexpandedParameterPacksVisitor(Unexpanded)
642 .TraverseType(NameInfo.getName().getCXXNameType());
643 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
644 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
645}
646
650
651 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
652 return false;
653
655 CollectUnexpandedParameterPacksVisitor(Unexpanded)
656 .TraverseTemplateName(Template);
657 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
658 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
659}
660
663 if (Arg.getArgument().isNull() ||
665 return false;
666
668 CollectUnexpandedParameterPacksVisitor(Unexpanded)
669 .TraverseTemplateArgumentLoc(Arg);
670 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
671 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
672}
673
676 CollectUnexpandedParameterPacksVisitor(Unexpanded)
677 .TraverseTemplateArgument(Arg);
678}
679
682 CollectUnexpandedParameterPacksVisitor(Unexpanded)
683 .TraverseTemplateArgumentLoc(Arg);
684}
685
688 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
689}
690
694 CollectUnexpandedParameterPacksVisitor(Unexpanded)
695 .TraverseTemplateName(Template);
696}
697
700 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
701}
702
706 CollectUnexpandedParameterPacksVisitor(Unexpanded)
707 .TraverseNestedNameSpecifierLoc(NNS);
708}
709
711 const DeclarationNameInfo &NameInfo,
713 CollectUnexpandedParameterPacksVisitor(Unexpanded)
714 .TraverseDeclarationNameInfo(NameInfo);
715}
716
719 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
720}
721
724 if (Arg.isInvalid())
725 return Arg;
726
727 // We do not allow to reference builtin templates that produce multiple
728 // values, they would not have a well-defined semantics outside template
729 // arguments.
730 auto *T = dyn_cast_or_null<BuiltinTemplateDecl>(
732 if (T && T->isPackProducingBuiltinTemplate())
734 Arg.getNameLoc());
735
736 return Arg;
737}
738
741 SourceLocation EllipsisLoc) {
742 if (Arg.isInvalid())
743 return Arg;
744
745 switch (Arg.getKind()) {
747 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
748 if (Result.isInvalid())
749 return ParsedTemplateArgument();
750
751 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
752 Arg.getNameLoc());
753 }
754
756 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
757 if (Result.isInvalid())
758 return ParsedTemplateArgument();
759
760 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
761 Arg.getNameLoc());
762 }
763
766 SourceRange R(Arg.getNameLoc());
767 if (Arg.getScopeSpec().isValid())
768 R.setBegin(Arg.getScopeSpec().getBeginLoc());
769 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
770 << R;
771 return ParsedTemplateArgument();
772 }
773
774 return Arg.getTemplatePackExpansion(EllipsisLoc);
775 }
776 llvm_unreachable("Unhandled template argument kind?");
777}
778
780 SourceLocation EllipsisLoc) {
781 TypeSourceInfo *TSInfo;
782 GetTypeFromParser(Type, &TSInfo);
783 if (!TSInfo)
784 return true;
785
786 TypeSourceInfo *TSResult =
787 CheckPackExpansion(TSInfo, EllipsisLoc, std::nullopt);
788 if (!TSResult)
789 return true;
790
791 return CreateParsedType(TSResult->getType(), TSResult);
792}
793
795 SourceLocation EllipsisLoc,
796 UnsignedOrNone NumExpansions) {
797 // Create the pack expansion type and source-location information.
799 Pattern->getTypeLoc().getSourceRange(),
800 EllipsisLoc, NumExpansions);
801 if (Result.isNull())
802 return nullptr;
803
804 TypeLocBuilder TLB;
805 TLB.pushFullCopy(Pattern->getTypeLoc());
807 TL.setEllipsisLoc(EllipsisLoc);
808
809 return TLB.getTypeSourceInfo(Context, Result);
810}
811
813 SourceLocation EllipsisLoc,
814 UnsignedOrNone NumExpansions) {
815 // C++11 [temp.variadic]p5:
816 // The pattern of a pack expansion shall name one or more
817 // parameter packs that are not expanded by a nested pack
818 // expansion.
819 //
820 // A pattern containing a deduced type can't occur "naturally" but arises in
821 // the desugaring of an init-capture pack.
822 if (!Pattern->containsUnexpandedParameterPack() &&
823 !Pattern->getContainedDeducedType()) {
824 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
825 << PatternRange;
826 return QualType();
827 }
828
829 return Context.getPackExpansionType(Pattern, NumExpansions,
830 /*ExpectPackInType=*/false);
831}
832
834 return CheckPackExpansion(Pattern, EllipsisLoc, std::nullopt);
835}
836
838 UnsignedOrNone NumExpansions) {
839 if (!Pattern)
840 return ExprError();
841
842 // C++0x [temp.variadic]p5:
843 // The pattern of a pack expansion shall name one or more
844 // parameter packs that are not expanded by a nested pack
845 // expansion.
846 if (!Pattern->containsUnexpandedParameterPack()) {
847 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
848 << Pattern->getSourceRange();
849 return ExprError();
850 }
851
852 // Create the pack expansion expression and source-location information.
853 return new (Context) PackExpansionExpr(Pattern, EllipsisLoc, NumExpansions);
854}
855
857 SourceLocation EllipsisLoc, SourceRange PatternRange,
859 const MultiLevelTemplateArgumentList &TemplateArgs,
860 bool FailOnPackProducingTemplates, bool &ShouldExpand,
861 bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose) {
862 ShouldExpand = true;
863 RetainExpansion = false;
864 IdentifierLoc FirstPack;
865 bool HaveFirstPack = false;
866 UnsignedOrNone NumPartialExpansions = std::nullopt;
867 SourceLocation PartiallySubstitutedPackLoc;
868 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
869
870 for (UnexpandedParameterPack ParmPack : Unexpanded) {
871 // Compute the depth and index for this parameter pack.
872 unsigned Depth = 0, Index = 0;
873 IdentifierInfo *Name;
874 bool IsVarDeclPack = false;
875 FunctionParmPackExpr *BindingPack = nullptr;
876 std::optional<unsigned> NumPrecomputedArguments;
877
878 if (auto *TTP = dyn_cast<const TemplateTypeParmType *>(ParmPack.first)) {
879 Depth = TTP->getDepth();
880 Index = TTP->getIndex();
881 Name = TTP->getIdentifier();
882 } else if (auto *TST = dyn_cast<const TemplateSpecializationType *>(
883 ParmPack.first)) {
884 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
885 // Delay expansion, substitution is required to know the size.
886 ShouldExpand = false;
887 if (!FailOnPackProducingTemplates)
888 continue;
889
890 if (!Diagnose)
891 return true;
892
893 // It is not yet supported in certain contexts.
894 return Diag(PatternRange.getBegin().isValid() ? PatternRange.getBegin()
895 : EllipsisLoc,
896 diag::err_unsupported_builtin_template_pack_expansion)
897 << TST->getTemplateName();
898 } else if (auto *S = dyn_cast<const SubstBuiltinTemplatePackType *>(
899 ParmPack.first)) {
900 Name = nullptr;
901 NumPrecomputedArguments = S->getNumArgs();
902 } else {
903 NamedDecl *ND = cast<NamedDecl *>(ParmPack.first);
904 if (isa<VarDecl>(ND))
905 IsVarDeclPack = true;
906 else if (isa<BindingDecl>(ND)) {
907 // Find the instantiated BindingDecl and check it for a resolved pack.
908 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
909 CurrentInstantiationScope->findInstantiationOf(ND);
910 Decl *B = cast<Decl *>(*Instantiation);
911 Expr *BindingExpr = cast<BindingDecl>(B)->getBinding();
912 BindingPack = cast_if_present<FunctionParmPackExpr>(BindingExpr);
913 if (!BindingPack) {
914 ShouldExpand = false;
915 continue;
916 }
917 } else
918 std::tie(Depth, Index) = getDepthAndIndex(ND);
919
920 Name = ND->getIdentifier();
921 }
922
923 // Determine the size of this argument pack.
924 unsigned NewPackSize, PendingPackExpansionSize = 0;
925 if (IsVarDeclPack) {
926 // Figure out whether we're instantiating to an argument pack or not.
927 //
928 // The instantiation may not exist; this can happen when instantiating an
929 // expansion statement that contains a pack (e.g.
930 // `template for (auto x : {{ts...}})`).
931 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
932 CurrentInstantiationScope->getInstantiationOfIfExists(
933 cast<NamedDecl *>(ParmPack.first));
934 if (Instantiation && isa<DeclArgumentPack *>(*Instantiation)) {
935 // We could expand this function parameter pack.
936 NewPackSize = cast<DeclArgumentPack *>(*Instantiation)->size();
937 } else {
938 // We can't expand this function parameter pack, so we can't expand
939 // the pack expansion.
940 ShouldExpand = false;
941 continue;
942 }
943 } else if (BindingPack) {
944 NewPackSize = BindingPack->getNumExpansions();
945 } else if (NumPrecomputedArguments) {
946 NewPackSize = *NumPrecomputedArguments;
947 } else {
948 // If we don't have a template argument at this depth/index, then we
949 // cannot expand the pack expansion. Make a note of this, but we still
950 // want to check any parameter packs we *do* have arguments for.
951 if (Depth >= TemplateArgs.getNumLevels() ||
952 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
953 ShouldExpand = false;
954 continue;
955 }
956
957 // Determine the size of the argument pack.
959 TemplateArgs(Depth, Index).getPackAsArray();
960 NewPackSize = Pack.size();
961 PendingPackExpansionSize =
962 llvm::count_if(Pack, [](const TemplateArgument &TA) {
963 if (!TA.isPackExpansion())
964 return false;
965
967 return !TA.getAsType()
968 ->castAs<PackExpansionType>()
969 ->getNumExpansions();
970
973 ->getNumExpansions();
974
975 return !TA.getNumTemplateExpansions();
976 });
977 }
978
979 // C++0x [temp.arg.explicit]p9:
980 // Template argument deduction can extend the sequence of template
981 // arguments corresponding to a template parameter pack, even when the
982 // sequence contains explicitly specified template arguments.
983 if (!IsVarDeclPack && CurrentInstantiationScope) {
984 if (NamedDecl *PartialPack =
985 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
986 unsigned PartialDepth, PartialIndex;
987 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
988 if (PartialDepth == Depth && PartialIndex == Index) {
989 RetainExpansion = true;
990 // We don't actually know the new pack size yet.
991 NumPartialExpansions = NewPackSize;
992 PartiallySubstitutedPackLoc = ParmPack.second;
993 continue;
994 }
995 }
996 }
997
998 if (!NumExpansions) {
999 // This is the first pack we've seen for which we have an argument.
1000 // Record it.
1001 NumExpansions = NewPackSize;
1002 FirstPack = IdentifierLoc(ParmPack.second, Name);
1003 HaveFirstPack = true;
1004 continue;
1005 }
1006
1007 if (NewPackSize != *NumExpansions) {
1008 // In some cases, we might be handling packs with unexpanded template
1009 // arguments. For example, this can occur when substituting into a type
1010 // alias declaration that uses its injected template parameters as
1011 // arguments:
1012 //
1013 // template <class... Outer> struct S {
1014 // template <class... Inner> using Alias = S<void(Outer, Inner)...>;
1015 // };
1016 //
1017 // Consider an instantiation attempt like 'S<int>::Alias<Pack...>', where
1018 // Pack comes from another template parameter. 'S<int>' is first
1019 // instantiated, expanding the outer pack 'Outer' to <int>. The alias
1020 // declaration is accordingly substituted, leaving the template arguments
1021 // as unexpanded
1022 // '<Pack...>'.
1023 //
1024 // Since we have no idea of the size of '<Pack...>' until its expansion,
1025 // we shouldn't assume its pack size for validation. However if we are
1026 // certain that there are extra arguments beyond unexpanded packs, in
1027 // which case the pack size is already larger than the previous expansion,
1028 // we can complain that before instantiation.
1029 unsigned LeastNewPackSize = NewPackSize - PendingPackExpansionSize;
1030 if (PendingPackExpansionSize && LeastNewPackSize <= *NumExpansions) {
1031 ShouldExpand = false;
1032 continue;
1033 }
1034 // C++0x [temp.variadic]p5:
1035 // All of the parameter packs expanded by a pack expansion shall have
1036 // the same number of arguments specified.
1037 if (!Diagnose)
1038 ;
1039 else if (HaveFirstPack)
1040 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
1041 << FirstPack.getIdentifierInfo() << Name << *NumExpansions
1042 << (LeastNewPackSize != NewPackSize) << LeastNewPackSize
1043 << SourceRange(FirstPack.getLoc()) << SourceRange(ParmPack.second);
1044 else
1045 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
1046 << Name << *NumExpansions << (LeastNewPackSize != NewPackSize)
1047 << LeastNewPackSize << SourceRange(ParmPack.second);
1048 return true;
1049 }
1050 }
1051
1052 // If we're performing a partial expansion but we also have a full expansion,
1053 // expand to the number of common arguments. For example, given:
1054 //
1055 // template<typename ...T> struct A {
1056 // template<typename ...U> void f(pair<T, U>...);
1057 // };
1058 //
1059 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
1060 // retain an expansion.
1061 if (NumPartialExpansions) {
1062 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
1063 NamedDecl *PartialPack =
1064 CurrentInstantiationScope->getPartiallySubstitutedPack();
1065 if (!Diagnose)
1066 return true;
1067 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
1068 << PartialPack << *NumPartialExpansions << *NumExpansions
1069 << SourceRange(PartiallySubstitutedPackLoc);
1070 return true;
1071 }
1072
1073 NumExpansions = NumPartialExpansions;
1074 }
1075
1076 return false;
1077}
1078
1081 const MultiLevelTemplateArgumentList &TemplateArgs) {
1082 UnsignedOrNone Result = std::nullopt;
1083 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1084 // Compute the depth and index for this parameter pack.
1085 unsigned Depth;
1086 unsigned Index;
1087
1088 if (const TemplateTypeParmType *TTP =
1089 dyn_cast<const TemplateTypeParmType *>(Unexpanded[I].first)) {
1090 Depth = TTP->getDepth();
1091 Index = TTP->getIndex();
1092 } else if (auto *TST = dyn_cast<const TemplateSpecializationType *>(
1093 Unexpanded[I].first)) {
1094 // This is a dependent pack, we are not ready to expand it yet.
1095 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
1096 (void)TST;
1097 return std::nullopt;
1098 } else if (auto *PST = dyn_cast<const SubstBuiltinTemplatePackType *>(
1099 Unexpanded[I].first)) {
1100 assert((!Result || *Result == PST->getNumArgs()) &&
1101 "inconsistent pack sizes");
1102 Result = PST->getNumArgs();
1103 continue;
1104 } else {
1105 NamedDecl *ND = cast<NamedDecl *>(Unexpanded[I].first);
1106 if (isa<VarDecl>(ND)) {
1107 // Function parameter pack or init-capture pack.
1108 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1109
1110 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
1111 CurrentInstantiationScope->findInstantiationOf(
1112 cast<NamedDecl *>(Unexpanded[I].first));
1113 if (isa<Decl *>(*Instantiation))
1114 // The pattern refers to an unexpanded pack. We're not ready to expand
1115 // this pack yet.
1116 return std::nullopt;
1117
1118 unsigned Size = cast<DeclArgumentPack *>(*Instantiation)->size();
1119 assert((!Result || *Result == Size) && "inconsistent pack sizes");
1120 Result = Size;
1121 continue;
1122 }
1123
1124 std::tie(Depth, Index) = getDepthAndIndex(ND);
1125 }
1126 if (Depth >= TemplateArgs.getNumLevels() ||
1127 !TemplateArgs.hasTemplateArgument(Depth, Index))
1128 // The pattern refers to an unknown template argument. We're not ready to
1129 // expand this pack yet.
1130 return std::nullopt;
1131
1132 // Determine the size of the argument pack.
1133 unsigned Size = TemplateArgs(Depth, Index).pack_size();
1134 assert((!Result || *Result == Size) && "inconsistent pack sizes");
1135 Result = Size;
1136 }
1137
1138 return Result;
1139}
1140
1142 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) {
1143 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
1145 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
1146 return getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
1147}
1148
1150 const DeclSpec &DS = D.getDeclSpec();
1151 switch (DS.getTypeSpecType()) {
1153 case TST_typename:
1155 case TST_typeofType:
1156#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
1157#include "clang/Basic/BuiltinTraits.inc"
1158 case TST_atomic: {
1159 QualType T = DS.getRepAsType().get();
1160 if (!T.isNull() && T->containsUnexpandedParameterPack())
1161 return true;
1162 break;
1163 }
1164
1166 case TST_typeofExpr:
1167 case TST_decltype:
1168 case TST_bitint:
1169 if (DS.getRepAsExpr() &&
1171 return true;
1172 break;
1173
1174 case TST_unspecified:
1175 case TST_void:
1176 case TST_char:
1177 case TST_wchar:
1178 case TST_char8:
1179 case TST_char16:
1180 case TST_char32:
1181 case TST_int:
1182 case TST_int128:
1183 case TST_half:
1184 case TST_float:
1185 case TST_double:
1186 case TST_Accum:
1187 case TST_Fract:
1188 case TST_Float16:
1189 case TST_float128:
1190 case TST_ibm128:
1191 case TST_bool:
1192 case TST_decimal32:
1193 case TST_decimal64:
1194 case TST_decimal128:
1195 case TST_enum:
1196 case TST_union:
1197 case TST_struct:
1198 case TST_interface:
1199 case TST_class:
1200 case TST_auto:
1201 case TST_auto_type:
1202 case TST_decltype_auto:
1203 case TST_BFloat16:
1204#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
1205#include "clang/Basic/OpenCLImageTypes.def"
1206#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case TST_##Name:
1207#include "clang/Basic/HLSLIntangibleTypes.def"
1208#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case TST_##Name:
1209#include "clang/Basic/HLSLPackedTypes.def"
1211 case TST_error:
1212 break;
1213 }
1214
1215 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
1216 const DeclaratorChunk &Chunk = D.getTypeObject(I);
1217 switch (Chunk.Kind) {
1223 // These declarator chunks cannot contain any parameter packs.
1224 break;
1225
1227 if (Chunk.Arr.NumElts &&
1229 return true;
1230 break;
1232 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
1233 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
1234 QualType ParamTy = Param->getType();
1235 assert(!ParamTy.isNull() && "Couldn't parse type?");
1236 if (ParamTy->containsUnexpandedParameterPack()) return true;
1237 }
1238
1239 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
1240 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
1241 if (Chunk.Fun.Exceptions[i]
1242 .Ty.get()
1244 return true;
1245 }
1246 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
1248 return true;
1249
1250 if (Chunk.Fun.hasTrailingReturnType()) {
1252 if (!T.isNull() && T->containsUnexpandedParameterPack())
1253 return true;
1254 }
1255 break;
1256
1259 return true;
1260 break;
1261 }
1262 }
1263
1264 if (Expr *TRC = D.getTrailingRequiresClause())
1265 if (TRC->containsUnexpandedParameterPack())
1266 return true;
1267
1268 return false;
1269}
1270
1271namespace {
1272
1273// Callback to only accept typo corrections that refer to parameter packs.
1274class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
1275 public:
1276 bool ValidateCandidate(const TypoCorrection &candidate) override {
1277 NamedDecl *ND = candidate.getCorrectionDecl();
1278 return ND && ND->isParameterPack();
1279 }
1280
1281 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1282 return std::make_unique<ParameterPackValidatorCCC>(*this);
1283 }
1284};
1285
1286}
1287
1289 SourceLocation OpLoc,
1290 IdentifierInfo &Name,
1291 SourceLocation NameLoc,
1292 SourceLocation RParenLoc) {
1293 // C++0x [expr.sizeof]p5:
1294 // The identifier in a sizeof... expression shall name a parameter pack.
1295 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1296 LookupName(R, S);
1297
1298 NamedDecl *ParameterPack = nullptr;
1299 switch (R.getResultKind()) {
1301 ParameterPack = R.getFoundDecl();
1302 break;
1303
1306 ParameterPackValidatorCCC CCC{};
1307 if (TypoCorrection Corrected =
1308 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1310 diagnoseTypo(Corrected,
1311 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1312 PDiag(diag::note_parameter_pack_here));
1313 ParameterPack = Corrected.getCorrectionDecl();
1314 }
1315 break;
1316 }
1319 break;
1320
1323 return ExprError();
1324 }
1325
1326 if (!ParameterPack || !ParameterPack->isParameterPack()) {
1327 Diag(NameLoc, diag::err_expected_name_of_pack) << &Name;
1328 return ExprError();
1329 }
1330
1331 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1332
1333 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1334 RParenLoc);
1335}
1336
1337static bool isParameterPack(Expr *PackExpression) {
1338 if (auto *D = dyn_cast<DeclRefExpr>(PackExpression); D) {
1339 ValueDecl *VD = D->getDecl();
1340 return VD->isParameterPack();
1341 }
1342 return false;
1343}
1344
1346 SourceLocation EllipsisLoc,
1347 SourceLocation LSquareLoc,
1348 Expr *IndexExpr,
1349 SourceLocation RSquareLoc) {
1350 bool isParameterPack = ::isParameterPack(PackExpression);
1351 if (!isParameterPack) {
1352 if (!PackExpression->containsErrors())
1353 Diag(PackExpression->getBeginLoc(), diag::err_expected_name_of_pack)
1354 << PackExpression;
1355 return ExprError();
1356 }
1357 ExprResult Res =
1358 BuildPackIndexingExpr(PackExpression, EllipsisLoc, IndexExpr, RSquareLoc);
1359 if (!Res.isInvalid())
1360 DiagCompat(Res.get()->getBeginLoc(), diag_compat::pack_indexing);
1361 return Res;
1362}
1363
1365 SourceLocation EllipsisLoc,
1366 Expr *IndexExpr,
1367 SourceLocation RSquareLoc,
1368 ArrayRef<Expr *> ExpandedExprs,
1369 bool FullySubstituted) {
1370
1371 std::optional<uint64_t> Index;
1372 if (!IndexExpr->isInstantiationDependent()) {
1373 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1374
1376 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
1377 if (!Res.isUsable() || !Value.isRepresentableByInt64())
1378 return ExprError();
1379 Index = Value.getZExtValue();
1380 IndexExpr = Res.get();
1381 }
1382
1383 if (Index && FullySubstituted) {
1384 if (*Index >= ExpandedExprs.size()) {
1385 Diag(PackExpression->getBeginLoc(), diag::err_pack_index_out_of_bound)
1386 << *Index << PackExpression << ExpandedExprs.size();
1387 return ExprError();
1388 }
1389 }
1390
1391 return PackIndexingExpr::Create(getASTContext(), EllipsisLoc, RSquareLoc,
1392 PackExpression, IndexExpr, Index,
1393 ExpandedExprs, FullySubstituted);
1394}
1395
1397 SourceLocation NameLoc,
1398 Expr *IndexExpr) {
1399 assert(!Pattern.isNull() && IndexExpr);
1400
1401 // C++29 [temp.names]p3:
1402 // The simple-template-name P in a pack-index-template-name shall denote a
1403 // pack.
1404 if (!Pattern.getAsTemplateTemplateParmDecl()) {
1405 Diag(NameLoc, diag::err_expected_name_of_pack) << Pattern;
1406 return TemplateName();
1407 }
1408
1409 bool DenotesPack = Pattern.containsUnexpandedParameterPack();
1410 if (!DenotesPack)
1411 Diag(NameLoc, diag::err_expected_name_of_pack) << Pattern;
1412
1413 TemplateName Name = BuildPackIndexingTemplateName(Pattern, IndexExpr);
1414 if (!Name.isNull() && DenotesPack)
1415 DiagCompat(NameLoc, diag_compat::pack_indexing_template);
1416 return Name;
1417}
1418
1421 bool FullySubstituted,
1422 ArrayRef<TemplateName> Expansions) {
1423 if (!IndexExpr->isInstantiationDependent()) {
1424 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1426 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
1427 if (!Res.isUsable() || !Value.isRepresentableByInt64())
1428 return TemplateName();
1429
1430 IndexExpr = Res.get();
1431 uint64_t V = Value.getZExtValue();
1432 if (FullySubstituted && V >= Expansions.size()) {
1433 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
1434 << V << Pattern << Expansions.size();
1435 return TemplateName();
1436 }
1437 }
1438
1439 return Context.getPackIndexingTemplateName(Pattern, IndexExpr,
1440 FullySubstituted, Expansions);
1441}
1442
1444 TemplateName Name, SourceLocation NameLoc) {
1445
1446 QualType T = Context.getDeducedTemplateSpecializationType(
1448 TypeLocBuilder TLB;
1450 TL.setElaboratedKeywordLoc(SourceLocation());
1451 TL.setQualifierLoc(NestedNameSpecifierLoc());
1452 TL.setNameLoc(NameLoc);
1454}
1455
1457 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
1458 UnsignedOrNone &NumExpansions) const {
1459 const TemplateArgument &Argument = OrigLoc.getArgument();
1460 assert(Argument.isPackExpansion());
1461 switch (Argument.getKind()) {
1463 // FIXME: We shouldn't ever have to worry about missing
1464 // type-source info!
1465 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1466 if (!ExpansionTSInfo)
1467 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1468 Ellipsis);
1469 PackExpansionTypeLoc Expansion =
1470 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1471 Ellipsis = Expansion.getEllipsisLoc();
1472
1473 TypeLoc Pattern = Expansion.getPatternLoc();
1474 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1475
1476 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1477 // TypeSourceInfo.
1478 // FIXME: Find some way to avoid the copy?
1479 TypeLocBuilder TLB;
1480 TLB.pushFullCopy(Pattern);
1481 TypeSourceInfo *PatternTSInfo =
1482 TLB.getTypeSourceInfo(Context, Pattern.getType());
1484 PatternTSInfo);
1485 }
1486
1488 PackExpansionExpr *Expansion
1489 = cast<PackExpansionExpr>(Argument.getAsExpr());
1490 Expr *Pattern = Expansion->getPattern();
1491 Ellipsis = Expansion->getEllipsisLoc();
1492 NumExpansions = Expansion->getNumExpansions();
1493 return TemplateArgumentLoc(
1494 TemplateArgument(Pattern, Argument.isCanonicalExpr()), Pattern);
1495 }
1496
1498 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1499 NumExpansions = Argument.getNumTemplateExpansions();
1500 return TemplateArgumentLoc(
1501 Context, Argument.getPackExpansionPattern(), OrigLoc.getTemplateKWLoc(),
1502 OrigLoc.getTemplateQualifierLoc(), OrigLoc.getTemplateNameLoc());
1503
1511 return TemplateArgumentLoc();
1512 }
1513
1514 llvm_unreachable("Invalid TemplateArgument Kind!");
1515}
1516
1518 assert(Arg.containsUnexpandedParameterPack());
1519
1520 // If this is a substituted pack, grab that pack. If not, we don't know
1521 // the size yet.
1522 // FIXME: We could find a size in more cases by looking for a substituted
1523 // pack anywhere within this argument, but that's not necessary in the common
1524 // case for 'sizeof...(A)' handling.
1525 TemplateArgument Pack;
1526 switch (Arg.getKind()) {
1528 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1529 Pack = Subst->getArgumentPack();
1530 else
1531 return std::nullopt;
1532 break;
1533
1535 if (auto *Subst =
1536 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1537 Pack = Subst->getArgumentPack();
1538 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1539 for (ValueDecl *PD : *Subst)
1540 if (PD->isParameterPack())
1541 return std::nullopt;
1542 return Subst->getNumExpansions();
1543 } else
1544 return std::nullopt;
1545 break;
1546
1550 Pack = Subst->getArgumentPack();
1551 else
1552 return std::nullopt;
1553 break;
1554
1562 return std::nullopt;
1563 }
1564
1565 // Check that no argument in the pack is itself a pack expansion.
1566 for (TemplateArgument Elem : Pack.pack_elements()) {
1567 // There's no point recursing in this case; we would have already
1568 // expanded this pack expansion into the enclosing pack if we could.
1569 if (Elem.isPackExpansion())
1570 return std::nullopt;
1571 // Don't guess the size of unexpanded packs. The pack within a template
1572 // argument may have yet to be of a PackExpansion type before we see the
1573 // ellipsis in the annotation stage.
1574 //
1575 // This doesn't mean we would invalidate the optimization: Arg can be an
1576 // unexpanded pack regardless of Elem's dependence. For instance,
1577 // A TemplateArgument that contains either a SubstTemplateTypeParmPackType
1578 // or SubstNonTypeTemplateParmPackExpr is always considered Unexpanded, but
1579 // the underlying TemplateArgument thereof may not.
1580 if (Elem.containsUnexpandedParameterPack())
1581 return std::nullopt;
1582 }
1583 return Pack.pack_size();
1584}
1585
1586static void CheckFoldOperand(Sema &S, Expr *E) {
1587 if (!E)
1588 return;
1589
1590 E = E->IgnoreImpCasts();
1591 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1592 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1594 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1595 << E->getSourceRange()
1598 ")");
1599 }
1600}
1601
1603 tok::TokenKind Operator,
1604 SourceLocation EllipsisLoc, Expr *RHS,
1605 SourceLocation RParenLoc) {
1606 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1607 // in the parser and reduce down to just cast-expressions here.
1608 CheckFoldOperand(*this, LHS);
1609 CheckFoldOperand(*this, RHS);
1610
1611 // [expr.prim.fold]p3:
1612 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1613 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1614 // an unexpanded parameter pack, but not both.
1615 if (LHS && RHS &&
1618 return Diag(EllipsisLoc,
1620 ? diag::err_fold_expression_packs_both_sides
1621 : diag::err_pack_expansion_without_parameter_packs)
1622 << LHS->getSourceRange() << RHS->getSourceRange();
1623 }
1624
1625 // [expr.prim.fold]p2:
1626 // In a unary fold, the cast-expression shall contain an unexpanded
1627 // parameter pack.
1628 if (!LHS || !RHS) {
1629 Expr *Pack = LHS ? LHS : RHS;
1630 assert(Pack && "fold expression with neither LHS nor RHS");
1631 if (!Pack->containsUnexpandedParameterPack()) {
1632 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1633 << Pack->getSourceRange();
1634 }
1635 }
1636
1637 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1638
1639 // Perform first-phase name lookup now.
1640 UnresolvedLookupExpr *ULE = nullptr;
1641 {
1642 UnresolvedSet<16> Functions;
1643 LookupBinOp(S, EllipsisLoc, Opc, Functions);
1644 if (!Functions.empty()) {
1645 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1648 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1649 DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1650 if (Callee.isInvalid())
1651 return ExprError();
1652 ULE = cast<UnresolvedLookupExpr>(Callee.get());
1653 }
1654 }
1655
1656 return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1657 std::nullopt);
1658}
1659
1661 SourceLocation LParenLoc, Expr *LHS,
1662 BinaryOperatorKind Operator,
1663 SourceLocation EllipsisLoc, Expr *RHS,
1664 SourceLocation RParenLoc,
1665 UnsignedOrNone NumExpansions) {
1666 return new (Context)
1667 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1668 EllipsisLoc, RHS, RParenLoc, NumExpansions);
1669}
1670
1672 BinaryOperatorKind Operator) {
1673 // [temp.variadic]p9:
1674 // If N is zero for a unary fold-expression, the value of the expression is
1675 // && -> true
1676 // || -> false
1677 // , -> void()
1678 // if the operator is not listed [above], the instantiation is ill-formed.
1679 //
1680 // Note that we need to use something like int() here, not merely 0, to
1681 // prevent the result from being a null pointer constant.
1682 QualType ScalarType;
1683 switch (Operator) {
1684 case BO_LOr:
1685 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1686 case BO_LAnd:
1687 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1688 case BO_Comma:
1689 ScalarType = Context.VoidTy;
1690 break;
1691
1692 default:
1693 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1694 << BinaryOperator::getOpcodeStr(Operator);
1695 }
1696
1697 return new (Context) CXXScalarValueInitExpr(
1698 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1699 EllipsisLoc);
1700}
#define V(N, I)
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:109
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2214
StringRef getOpcodeStr() const
Definition Expr.h:4152
Represents a folding of a pack over an operator.
Definition ExprCXX.h:5086
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2201
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
ValueDecl * getDecl()
Definition Expr.h:1362
SourceLocation getLocation() const
Definition Expr.h:1370
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
TST getTypeSpecType() const
Definition DeclSpec.h:525
ParsedType getRepAsType() const
Definition DeclSpec.h:535
Expr * getRepAsExpr() const
Definition DeclSpec.h:543
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:266
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
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:1955
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2453
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2102
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2688
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2449
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 TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
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 TraverseType(QualType T, bool TraverseQualifier=true)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
This represents one expression.
Definition Expr.h:113
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:242
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:224
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3106
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
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:103
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4895
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4933
QualType desugar() const
Definition TypeBase.h:5997
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:526
TemplateParameterList * getTemplateParameterList() const
If this is a generic lambda expression, retrieve the template parameter list associated with it,...
Definition ExprCXX.cpp:1446
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:380
Represents the results of name lookup.
Definition Lookup.h:147
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:181
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition Template.h:129
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
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:391
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition ExprObjC.h:393
PtrTy get() const
Definition Ownership.h:81
decls_iterator decls_begin() const
Definition ExprCXX.h:3236
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3247
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4417
Expr * getPattern()
Retrieve the pattern of the pack expansion.
Definition ExprCXX.h:4446
UnsignedOrNone getNumExpansions() const
Determine the number of expansions that will be produced when this pack expansion is instantiated,...
Definition ExprCXX.h:4457
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that describes this pack expansion.
Definition ExprCXX.h:4453
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2664
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2660
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2676
Expr * getIndexExpr() const
Definition ExprCXX.h:4682
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:1763
Expr * getIndexExpr() const
Definition TypeLoc.h:2343
Represents a parameter to a function.
Definition Decl.h:1820
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:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
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
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13231
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2702
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:9443
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1268
TemplateName BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< TemplateName > Expansions={})
ASTContext & Context
Definition Sema.h:1332
TypeResult ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name, SourceLocation NameLoc)
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern, SourceLocation NameLoc, Expr *IndexExpr)
ExprResult BuildPackIndexingExpr(Expr *PackExpression, SourceLocation EllipsisLoc, Expr *IndexExpr, SourceLocation RSquareLoc, ArrayRef< Expr * > ExpandedExprs={}, bool FullySubstituted=false)
ASTContext & getASTContext() const
Definition Sema.h:935
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:84
UnexpandedParameterPackContext
The context in which an unexpanded parameter pack is being diagnosed.
Definition Sema.h:14577
@ UPPC_Requirement
Definition Sema.h:14645
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.
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 ).
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6508
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:1739
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.
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
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 isNull() const
Determine whether this template name is NULL.
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.
TemplateTemplateParmDecl * getAsTemplateTemplateParmDecl() const
Retrieve the template template parameter that this template name refers to, if any.
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:8417
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8428
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
The base class of the type hierarchy.
Definition TypeBase.h:1879
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2235
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
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:3373
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:3450
A set of unresolved declarations.
bool isPackExpansion() const
Determine whether this is a pack expansion.
Definition DeclCXX.h:4113
bool isPackExpansion() const
Determine whether this is a pack expansion.
Definition DeclCXX.h:4023
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5674
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
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
@ TST_typeof_unqualType
Definition Specifiers.h:88
@ TST_ibm128
Definition Specifiers.h:75
@ TST_decimal64
Definition Specifiers.h:78
@ TST_float
Definition Specifiers.h:72
@ TST_auto_type
Definition Specifiers.h:95
@ TST_auto
Definition Specifiers.h:93
@ TST_typeof_unqualExpr
Definition Specifiers.h:89
@ TST_decimal32
Definition Specifiers.h:77
@ TST_int128
Definition Specifiers.h:65
@ TST_atomic
Definition Specifiers.h:97
@ TST_half
Definition Specifiers.h:67
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename_pack_indexing
Definition Specifiers.h:98
@ TST_char32
Definition Specifiers.h:63
@ TST_struct
Definition Specifiers.h:82
@ TST_typeofType
Definition Specifiers.h:86
@ TST_bitint
Definition Specifiers.h:66
@ TST_wchar
Definition Specifiers.h:60
@ TST_BFloat16
Definition Specifiers.h:71
@ TST_char16
Definition Specifiers.h:62
@ TST_char
Definition Specifiers.h:59
@ TST_unspecified
Definition Specifiers.h:57
@ TST_class
Definition Specifiers.h:83
@ TST_union
Definition Specifiers.h:81
@ TST_Fract
Definition Specifiers.h:70
@ TST_float128
Definition Specifiers.h:74
@ TST_double
Definition Specifiers.h:73
@ TST_Accum
Definition Specifiers.h:69
@ TST_int
Definition Specifiers.h:64
@ TST_bool
Definition Specifiers.h:76
@ TST_typeofExpr
Definition Specifiers.h:87
@ TST_typename
Definition Specifiers.h:85
@ TST_void
Definition Specifiers.h:58
@ TST_unknown_anytype
Definition Specifiers.h:96
@ TST_enum
Definition Specifiers.h:80
@ TST_error
Definition Specifiers.h:108
@ TST_decltype_auto
Definition Specifiers.h:94
@ TST_interface
Definition Specifiers.h:84
@ TST_Float16
Definition Specifiers.h:68
@ TST_char8
Definition Specifiers.h:61
@ TST_decimal128
Definition Specifiers.h:79
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ 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:243
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ExprResult ExprError()
Definition Ownership.h:265
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
Definition Address.h:327
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
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
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1368
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1633
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1487
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1475
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1636
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1450
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1619
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1614
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1491
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1290
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1691
ArrayTypeInfo Arr
Definition DeclSpec.h:1688
FunctionTypeInfo Fun
Definition DeclSpec.h:1689
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
Expr * Value
The value of the dictionary element.
Definition ExprObjC.h:299
bool isPackExpansion() const
Determines whether this dictionary element is a pack expansion.
Definition ExprObjC.h:309
Expr * Key
The key for the dictionary element.
Definition ExprObjC.h:296