1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements semantic analysis for C++0x variadic templates.
10 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/Sema.h"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/RecursiveASTVisitor.h"
16 #include "clang/AST/TypeLoc.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/SemaInternal.h"
21 #include "clang/Sema/Template.h"
23 using namespace clang;
25 //----------------------------------------------------------------------------
26 // Visitor that collects unexpanded parameter packs
27 //----------------------------------------------------------------------------
30 /// A class that collects unexpanded parameter packs.
31 class CollectUnexpandedParameterPacksVisitor :
32 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
37 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
39 bool InLambda = false;
40 unsigned DepthLimit = (unsigned)-1;
42 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
43 if (auto *PVD = dyn_cast<ParmVarDecl>(ND)) {
44 // For now, the only problematic case is a generic lambda's templated
45 // call operator, so we don't need to look for all the other ways we
46 // could have reached a dependent parameter pack.
47 auto *FD = dyn_cast<FunctionDecl>(PVD->getDeclContext());
48 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
49 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
51 } else if (getDepthAndIndex(ND).first >= DepthLimit)
54 Unexpanded.push_back({ND, Loc});
56 void addUnexpanded(const TemplateTypeParmType *T,
57 SourceLocation Loc = SourceLocation()) {
58 if (T->getDepth() < DepthLimit)
59 Unexpanded.push_back({T, Loc});
63 explicit CollectUnexpandedParameterPacksVisitor(
64 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
65 : Unexpanded(Unexpanded) {}
67 bool shouldWalkTypesOfTypeLocs() const { return false; }
69 //------------------------------------------------------------------------
70 // Recording occurrences of (unexpanded) parameter packs.
71 //------------------------------------------------------------------------
73 /// Record occurrences of template type parameter packs.
74 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
75 if (TL.getTypePtr()->isParameterPack())
76 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
80 /// Record occurrences of template type parameter packs
81 /// when we don't have proper source-location information for
84 /// Ideally, this routine would never be used.
85 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
86 if (T->isParameterPack())
92 /// Record occurrences of function and non-type template
93 /// parameter packs in an expression.
94 bool VisitDeclRefExpr(DeclRefExpr *E) {
95 if (E->getDecl()->isParameterPack())
96 addUnexpanded(E->getDecl(), E->getLocation());
101 /// Record occurrences of template template parameter packs.
102 bool TraverseTemplateName(TemplateName Template) {
103 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
104 Template.getAsTemplateDecl())) {
105 if (TTP->isParameterPack())
109 return inherited::TraverseTemplateName(Template);
112 /// Suppress traversal into Objective-C container literal
113 /// elements that are pack expansions.
114 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
115 if (!E->containsUnexpandedParameterPack())
118 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
119 ObjCDictionaryElement Element = E->getKeyValueElement(I);
120 if (Element.isPackExpansion())
123 TraverseStmt(Element.Key);
124 TraverseStmt(Element.Value);
128 //------------------------------------------------------------------------
129 // Pruning the search for unexpanded parameter packs.
130 //------------------------------------------------------------------------
132 /// Suppress traversal into statements and expressions that
133 /// do not contain unexpanded parameter packs.
134 bool TraverseStmt(Stmt *S) {
135 Expr *E = dyn_cast_or_null<Expr>(S);
136 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
137 return inherited::TraverseStmt(S);
142 /// Suppress traversal into types that do not contain
143 /// unexpanded parameter packs.
144 bool TraverseType(QualType T) {
145 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
146 return inherited::TraverseType(T);
151 /// Suppress traversal into types with location information
152 /// that do not contain unexpanded parameter packs.
153 bool TraverseTypeLoc(TypeLoc TL) {
154 if ((!TL.getType().isNull() &&
155 TL.getType()->containsUnexpandedParameterPack()) ||
157 return inherited::TraverseTypeLoc(TL);
162 /// Suppress traversal of parameter packs.
163 bool TraverseDecl(Decl *D) {
164 // A function parameter pack is a pack expansion, so cannot contain
165 // an unexpanded parameter pack. Likewise for a template parameter
166 // pack that contains any references to other packs.
167 if (D->isParameterPack())
170 return inherited::TraverseDecl(D);
173 /// Suppress traversal of pack-expanded attributes.
174 bool TraverseAttr(Attr *A) {
175 if (A->isPackExpansion())
178 return inherited::TraverseAttr(A);
181 /// Suppress traversal of pack expansion expressions and types.
183 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
184 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
185 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
186 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
190 /// Suppress traversal of using-declaration pack expansion.
191 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
192 if (D->isPackExpansion())
195 return inherited::TraverseUnresolvedUsingValueDecl(D);
198 /// Suppress traversal of using-declaration pack expansion.
199 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
200 if (D->isPackExpansion())
203 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
206 /// Suppress traversal of template argument pack expansions.
207 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
208 if (Arg.isPackExpansion())
211 return inherited::TraverseTemplateArgument(Arg);
214 /// Suppress traversal of template argument pack expansions.
215 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
216 if (ArgLoc.getArgument().isPackExpansion())
219 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
222 /// Suppress traversal of base specifier pack expansions.
223 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
224 if (Base.isPackExpansion())
227 return inherited::TraverseCXXBaseSpecifier(Base);
230 /// Suppress traversal of mem-initializer pack expansions.
231 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
232 if (Init->isPackExpansion())
235 return inherited::TraverseConstructorInitializer(Init);
238 /// Note whether we're traversing a lambda containing an unexpanded
239 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
240 /// including all the places where we normally wouldn't look. Within a
241 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
242 /// outside an expression.
243 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
244 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
245 // even if it's contained within another lambda.
246 if (!Lambda->containsUnexpandedParameterPack())
249 bool WasInLambda = InLambda;
250 unsigned OldDepthLimit = DepthLimit;
253 if (auto *TPL = Lambda->getTemplateParameterList())
254 DepthLimit = TPL->getDepth();
256 inherited::TraverseLambdaExpr(Lambda);
258 InLambda = WasInLambda;
259 DepthLimit = OldDepthLimit;
263 /// Suppress traversal within pack expansions in lambda captures.
264 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
266 if (C->isPackExpansion())
269 return inherited::TraverseLambdaCapture(Lambda, C, Init);
274 /// Determine whether it's possible for an unexpanded parameter pack to
275 /// be valid in this location. This only happens when we're in a declaration
276 /// that is nested within an expression that could be expanded, such as a
277 /// lambda-expression within a function call.
279 /// This is conservatively correct, but may claim that some unexpanded packs are
280 /// permitted when they are not.
281 bool Sema::isUnexpandedParameterPackPermitted() {
282 for (auto *SI : FunctionScopes)
283 if (isa<sema::LambdaScopeInfo>(SI))
288 /// Diagnose all of the unexpanded parameter packs in the given
291 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
292 UnexpandedParameterPackContext UPPC,
293 ArrayRef<UnexpandedParameterPack> Unexpanded) {
294 if (Unexpanded.empty())
297 // If we are within a lambda expression and referencing a pack that is not
298 // a parameter of the lambda itself, that lambda contains an unexpanded
299 // parameter pack, and we are done.
300 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
302 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
303 for (unsigned N = FunctionScopes.size(); N; --N) {
304 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
305 // We do not permit pack expansion that would duplicate a statement
306 // expression, not even within a lambda.
307 // FIXME: We could probably support this for statement expressions that do
308 // not contain labels, and for pack expansions that expand both the stmt
309 // expr and the enclosing lambda.
311 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
312 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; }))
315 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Func)) {
316 if (N == FunctionScopes.size()) {
317 for (auto &Param : Unexpanded) {
318 auto *PD = dyn_cast_or_null<ParmVarDecl>(
319 Param.first.dyn_cast<NamedDecl *>());
320 if (PD && PD->getDeclContext() == LSI->CallOperator)
321 LambdaParamPackReferences.push_back(Param);
325 // If we have references to a parameter pack of the innermost enclosing
326 // lambda, only diagnose those ones. We don't know whether any other
327 // unexpanded parameters referenced herein are actually unexpanded;
328 // they might be expanded at an outer level.
329 if (!LambdaParamPackReferences.empty()) {
330 Unexpanded = LambdaParamPackReferences;
334 LSI->ContainsUnexpandedParameterPack = true;
339 SmallVector<SourceLocation, 4> Locations;
340 SmallVector<IdentifierInfo *, 4> Names;
341 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
343 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
344 IdentifierInfo *Name = nullptr;
345 if (const TemplateTypeParmType *TTP
346 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
347 Name = TTP->getIdentifier();
349 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
351 if (Name && NamesKnown.insert(Name).second)
352 Names.push_back(Name);
354 if (Unexpanded[I].second.isValid())
355 Locations.push_back(Unexpanded[I].second);
358 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
359 << (int)UPPC << (int)Names.size();
360 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
363 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
364 DB << SourceRange(Locations[I]);
368 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
370 UnexpandedParameterPackContext UPPC) {
371 // C++0x [temp.variadic]p5:
372 // An appearance of a name of a parameter pack that is not expanded is
374 if (!T->getType()->containsUnexpandedParameterPack())
377 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
378 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
380 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
381 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
384 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
385 UnexpandedParameterPackContext UPPC) {
386 // C++0x [temp.variadic]p5:
387 // An appearance of a name of a parameter pack that is not expanded is
389 if (!E->containsUnexpandedParameterPack())
392 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
393 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
394 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
395 return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
398 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
399 UnexpandedParameterPackContext UPPC) {
400 // C++0x [temp.variadic]p5:
401 // An appearance of a name of a parameter pack that is not expanded is
403 if (!SS.getScopeRep() ||
404 !SS.getScopeRep()->containsUnexpandedParameterPack())
407 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
408 CollectUnexpandedParameterPacksVisitor(Unexpanded)
409 .TraverseNestedNameSpecifier(SS.getScopeRep());
410 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
411 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
415 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
416 UnexpandedParameterPackContext UPPC) {
417 // C++0x [temp.variadic]p5:
418 // An appearance of a name of a parameter pack that is not expanded is
420 switch (NameInfo.getName().getNameKind()) {
421 case DeclarationName::Identifier:
422 case DeclarationName::ObjCZeroArgSelector:
423 case DeclarationName::ObjCOneArgSelector:
424 case DeclarationName::ObjCMultiArgSelector:
425 case DeclarationName::CXXOperatorName:
426 case DeclarationName::CXXLiteralOperatorName:
427 case DeclarationName::CXXUsingDirective:
428 case DeclarationName::CXXDeductionGuideName:
431 case DeclarationName::CXXConstructorName:
432 case DeclarationName::CXXDestructorName:
433 case DeclarationName::CXXConversionFunctionName:
434 // FIXME: We shouldn't need this null check!
435 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
436 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
438 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
444 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
445 CollectUnexpandedParameterPacksVisitor(Unexpanded)
446 .TraverseType(NameInfo.getName().getCXXNameType());
447 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
448 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
451 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
452 TemplateName Template,
453 UnexpandedParameterPackContext UPPC) {
455 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
458 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
459 CollectUnexpandedParameterPacksVisitor(Unexpanded)
460 .TraverseTemplateName(Template);
461 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
462 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
465 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
466 UnexpandedParameterPackContext UPPC) {
467 if (Arg.getArgument().isNull() ||
468 !Arg.getArgument().containsUnexpandedParameterPack())
471 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
472 CollectUnexpandedParameterPacksVisitor(Unexpanded)
473 .TraverseTemplateArgumentLoc(Arg);
474 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
475 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
478 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
479 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
480 CollectUnexpandedParameterPacksVisitor(Unexpanded)
481 .TraverseTemplateArgument(Arg);
484 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
485 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
486 CollectUnexpandedParameterPacksVisitor(Unexpanded)
487 .TraverseTemplateArgumentLoc(Arg);
490 void Sema::collectUnexpandedParameterPacks(QualType T,
491 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
492 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
495 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
496 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
497 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
500 void Sema::collectUnexpandedParameterPacks(
501 NestedNameSpecifierLoc NNS,
502 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
503 CollectUnexpandedParameterPacksVisitor(Unexpanded)
504 .TraverseNestedNameSpecifierLoc(NNS);
507 void Sema::collectUnexpandedParameterPacks(
508 const DeclarationNameInfo &NameInfo,
509 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
510 CollectUnexpandedParameterPacksVisitor(Unexpanded)
511 .TraverseDeclarationNameInfo(NameInfo);
515 ParsedTemplateArgument
516 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
517 SourceLocation EllipsisLoc) {
521 switch (Arg.getKind()) {
522 case ParsedTemplateArgument::Type: {
523 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
524 if (Result.isInvalid())
525 return ParsedTemplateArgument();
527 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
531 case ParsedTemplateArgument::NonType: {
532 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
533 if (Result.isInvalid())
534 return ParsedTemplateArgument();
536 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
540 case ParsedTemplateArgument::Template:
541 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
542 SourceRange R(Arg.getLocation());
543 if (Arg.getScopeSpec().isValid())
544 R.setBegin(Arg.getScopeSpec().getBeginLoc());
545 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
547 return ParsedTemplateArgument();
550 return Arg.getTemplatePackExpansion(EllipsisLoc);
552 llvm_unreachable("Unhandled template argument kind?");
555 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
556 SourceLocation EllipsisLoc) {
557 TypeSourceInfo *TSInfo;
558 GetTypeFromParser(Type, &TSInfo);
562 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
566 return CreateParsedType(TSResult->getType(), TSResult);
570 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
571 Optional<unsigned> NumExpansions) {
572 // Create the pack expansion type and source-location information.
573 QualType Result = CheckPackExpansion(Pattern->getType(),
574 Pattern->getTypeLoc().getSourceRange(),
575 EllipsisLoc, NumExpansions);
580 TLB.pushFullCopy(Pattern->getTypeLoc());
581 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
582 TL.setEllipsisLoc(EllipsisLoc);
584 return TLB.getTypeSourceInfo(Context, Result);
587 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
588 SourceLocation EllipsisLoc,
589 Optional<unsigned> NumExpansions) {
590 // C++0x [temp.variadic]p5:
591 // The pattern of a pack expansion shall name one or more
592 // parameter packs that are not expanded by a nested pack
594 if (!Pattern->containsUnexpandedParameterPack()) {
595 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
600 return Context.getPackExpansionType(Pattern, NumExpansions);
603 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
604 return CheckPackExpansion(Pattern, EllipsisLoc, None);
607 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
608 Optional<unsigned> NumExpansions) {
612 // C++0x [temp.variadic]p5:
613 // The pattern of a pack expansion shall name one or more
614 // parameter packs that are not expanded by a nested pack
616 if (!Pattern->containsUnexpandedParameterPack()) {
617 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
618 << Pattern->getSourceRange();
622 // Create the pack expansion expression and source-location information.
624 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
627 bool Sema::CheckParameterPacksForExpansion(
628 SourceLocation EllipsisLoc, SourceRange PatternRange,
629 ArrayRef<UnexpandedParameterPack> Unexpanded,
630 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
631 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
633 RetainExpansion = false;
634 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
635 bool HaveFirstPack = false;
636 Optional<unsigned> NumPartialExpansions;
637 SourceLocation PartiallySubstitutedPackLoc;
639 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
640 end = Unexpanded.end();
642 // Compute the depth and index for this parameter pack.
643 unsigned Depth = 0, Index = 0;
644 IdentifierInfo *Name;
645 bool IsFunctionParameterPack = false;
647 if (const TemplateTypeParmType *TTP
648 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
649 Depth = TTP->getDepth();
650 Index = TTP->getIndex();
651 Name = TTP->getIdentifier();
653 NamedDecl *ND = i->first.get<NamedDecl *>();
654 if (isa<ParmVarDecl>(ND))
655 IsFunctionParameterPack = true;
657 std::tie(Depth, Index) = getDepthAndIndex(ND);
659 Name = ND->getIdentifier();
662 // Determine the size of this argument pack.
663 unsigned NewPackSize;
664 if (IsFunctionParameterPack) {
665 // Figure out whether we're instantiating to an argument pack or not.
666 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
668 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
669 = CurrentInstantiationScope->findInstantiationOf(
670 i->first.get<NamedDecl *>());
671 if (Instantiation->is<DeclArgumentPack *>()) {
672 // We could expand this function parameter pack.
673 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
675 // We can't expand this function parameter pack, so we can't expand
676 // the pack expansion.
677 ShouldExpand = false;
681 // If we don't have a template argument at this depth/index, then we
682 // cannot expand the pack expansion. Make a note of this, but we still
683 // want to check any parameter packs we *do* have arguments for.
684 if (Depth >= TemplateArgs.getNumLevels() ||
685 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
686 ShouldExpand = false;
690 // Determine the size of the argument pack.
691 NewPackSize = TemplateArgs(Depth, Index).pack_size();
694 // C++0x [temp.arg.explicit]p9:
695 // Template argument deduction can extend the sequence of template
696 // arguments corresponding to a template parameter pack, even when the
697 // sequence contains explicitly specified template arguments.
698 if (!IsFunctionParameterPack && CurrentInstantiationScope) {
699 if (NamedDecl *PartialPack
700 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
701 unsigned PartialDepth, PartialIndex;
702 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
703 if (PartialDepth == Depth && PartialIndex == Index) {
704 RetainExpansion = true;
705 // We don't actually know the new pack size yet.
706 NumPartialExpansions = NewPackSize;
707 PartiallySubstitutedPackLoc = i->second;
713 if (!NumExpansions) {
714 // The is the first pack we've seen for which we have an argument.
716 NumExpansions = NewPackSize;
717 FirstPack.first = Name;
718 FirstPack.second = i->second;
719 HaveFirstPack = true;
723 if (NewPackSize != *NumExpansions) {
724 // C++0x [temp.variadic]p5:
725 // All of the parameter packs expanded by a pack expansion shall have
726 // the same number of arguments specified.
728 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
729 << FirstPack.first << Name << *NumExpansions << NewPackSize
730 << SourceRange(FirstPack.second) << SourceRange(i->second);
732 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
733 << Name << *NumExpansions << NewPackSize
734 << SourceRange(i->second);
739 // If we're performing a partial expansion but we also have a full expansion,
740 // expand to the number of common arguments. For example, given:
742 // template<typename ...T> struct A {
743 // template<typename ...U> void f(pair<T, U>...);
746 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
747 // retain an expansion.
748 if (NumPartialExpansions) {
749 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
750 NamedDecl *PartialPack =
751 CurrentInstantiationScope->getPartiallySubstitutedPack();
752 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
753 << PartialPack << *NumPartialExpansions << *NumExpansions
754 << SourceRange(PartiallySubstitutedPackLoc);
758 NumExpansions = NumPartialExpansions;
764 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
765 const MultiLevelTemplateArgumentList &TemplateArgs) {
766 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
767 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
768 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
770 Optional<unsigned> Result;
771 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
772 // Compute the depth and index for this parameter pack.
776 if (const TemplateTypeParmType *TTP
777 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
778 Depth = TTP->getDepth();
779 Index = TTP->getIndex();
781 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
782 if (isa<ParmVarDecl>(ND)) {
783 // Function parameter pack.
784 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
786 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
787 = CurrentInstantiationScope->findInstantiationOf(
788 Unexpanded[I].first.get<NamedDecl *>());
789 if (Instantiation->is<Decl*>())
790 // The pattern refers to an unexpanded pack. We're not ready to expand
794 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
795 assert((!Result || *Result == Size) && "inconsistent pack sizes");
800 std::tie(Depth, Index) = getDepthAndIndex(ND);
802 if (Depth >= TemplateArgs.getNumLevels() ||
803 !TemplateArgs.hasTemplateArgument(Depth, Index))
804 // The pattern refers to an unknown template argument. We're not ready to
805 // expand this pack yet.
808 // Determine the size of the argument pack.
809 unsigned Size = TemplateArgs(Depth, Index).pack_size();
810 assert((!Result || *Result == Size) && "inconsistent pack sizes");
817 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
818 const DeclSpec &DS = D.getDeclSpec();
819 switch (DS.getTypeSpecType()) {
822 case TST_underlyingType:
824 QualType T = DS.getRepAsType().get();
825 if (!T.isNull() && T->containsUnexpandedParameterPack())
832 if (DS.getRepAsExpr() &&
833 DS.getRepAsExpr()->containsUnexpandedParameterPack())
837 case TST_unspecified:
864 case TST_decltype_auto:
865 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
866 #include "clang/Basic/OpenCLImageTypes.def"
867 case TST_unknown_anytype:
872 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
873 const DeclaratorChunk &Chunk = D.getTypeObject(I);
874 switch (Chunk.Kind) {
875 case DeclaratorChunk::Pointer:
876 case DeclaratorChunk::Reference:
877 case DeclaratorChunk::Paren:
878 case DeclaratorChunk::Pipe:
879 case DeclaratorChunk::BlockPointer:
880 // These declarator chunks cannot contain any parameter packs.
883 case DeclaratorChunk::Array:
884 if (Chunk.Arr.NumElts &&
885 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
888 case DeclaratorChunk::Function:
889 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
890 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
891 QualType ParamTy = Param->getType();
892 assert(!ParamTy.isNull() && "Couldn't parse type?");
893 if (ParamTy->containsUnexpandedParameterPack()) return true;
896 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
897 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
898 if (Chunk.Fun.Exceptions[i]
900 ->containsUnexpandedParameterPack())
903 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
904 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
907 if (Chunk.Fun.hasTrailingReturnType()) {
908 QualType T = Chunk.Fun.getTrailingReturnType().get();
909 if (!T.isNull() && T->containsUnexpandedParameterPack())
914 case DeclaratorChunk::MemberPointer:
915 if (Chunk.Mem.Scope().getScopeRep() &&
916 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
927 // Callback to only accept typo corrections that refer to parameter packs.
928 class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
930 bool ValidateCandidate(const TypoCorrection &candidate) override {
931 NamedDecl *ND = candidate.getCorrectionDecl();
932 return ND && ND->isParameterPack();
938 /// Called when an expression computing the size of a parameter pack
942 /// template<typename ...Types> struct count {
943 /// static const unsigned value = sizeof...(Types);
948 /// \param OpLoc The location of the "sizeof" keyword.
949 /// \param Name The name of the parameter pack whose size will be determined.
950 /// \param NameLoc The source location of the name of the parameter pack.
951 /// \param RParenLoc The location of the closing parentheses.
952 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
953 SourceLocation OpLoc,
954 IdentifierInfo &Name,
955 SourceLocation NameLoc,
956 SourceLocation RParenLoc) {
957 // C++0x [expr.sizeof]p5:
958 // The identifier in a sizeof... expression shall name a parameter pack.
959 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
962 NamedDecl *ParameterPack = nullptr;
963 switch (R.getResultKind()) {
964 case LookupResult::Found:
965 ParameterPack = R.getFoundDecl();
968 case LookupResult::NotFound:
969 case LookupResult::NotFoundInCurrentInstantiation:
970 if (TypoCorrection Corrected =
971 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
972 llvm::make_unique<ParameterPackValidatorCCC>(),
973 CTK_ErrorRecovery)) {
974 diagnoseTypo(Corrected,
975 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
976 PDiag(diag::note_parameter_pack_here));
977 ParameterPack = Corrected.getCorrectionDecl();
980 case LookupResult::FoundOverloaded:
981 case LookupResult::FoundUnresolvedValue:
984 case LookupResult::Ambiguous:
985 DiagnoseAmbiguousLookup(R);
989 if (!ParameterPack || !ParameterPack->isParameterPack()) {
990 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
995 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
997 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1002 Sema::getTemplateArgumentPackExpansionPattern(
1003 TemplateArgumentLoc OrigLoc,
1004 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1005 const TemplateArgument &Argument = OrigLoc.getArgument();
1006 assert(Argument.isPackExpansion());
1007 switch (Argument.getKind()) {
1008 case TemplateArgument::Type: {
1009 // FIXME: We shouldn't ever have to worry about missing
1010 // type-source info!
1011 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1012 if (!ExpansionTSInfo)
1013 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1015 PackExpansionTypeLoc Expansion =
1016 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1017 Ellipsis = Expansion.getEllipsisLoc();
1019 TypeLoc Pattern = Expansion.getPatternLoc();
1020 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1022 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1024 // FIXME: Find some way to avoid the copy?
1026 TLB.pushFullCopy(Pattern);
1027 TypeSourceInfo *PatternTSInfo =
1028 TLB.getTypeSourceInfo(Context, Pattern.getType());
1029 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1033 case TemplateArgument::Expression: {
1034 PackExpansionExpr *Expansion
1035 = cast<PackExpansionExpr>(Argument.getAsExpr());
1036 Expr *Pattern = Expansion->getPattern();
1037 Ellipsis = Expansion->getEllipsisLoc();
1038 NumExpansions = Expansion->getNumExpansions();
1039 return TemplateArgumentLoc(Pattern, Pattern);
1042 case TemplateArgument::TemplateExpansion:
1043 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1044 NumExpansions = Argument.getNumTemplateExpansions();
1045 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1046 OrigLoc.getTemplateQualifierLoc(),
1047 OrigLoc.getTemplateNameLoc());
1049 case TemplateArgument::Declaration:
1050 case TemplateArgument::NullPtr:
1051 case TemplateArgument::Template:
1052 case TemplateArgument::Integral:
1053 case TemplateArgument::Pack:
1054 case TemplateArgument::Null:
1055 return TemplateArgumentLoc();
1058 llvm_unreachable("Invalid TemplateArgument Kind!");
1061 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1062 assert(Arg.containsUnexpandedParameterPack());
1064 // If this is a substituted pack, grab that pack. If not, we don't know
1066 // FIXME: We could find a size in more cases by looking for a substituted
1067 // pack anywhere within this argument, but that's not necessary in the common
1068 // case for 'sizeof...(A)' handling.
1069 TemplateArgument Pack;
1070 switch (Arg.getKind()) {
1071 case TemplateArgument::Type:
1072 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1073 Pack = Subst->getArgumentPack();
1078 case TemplateArgument::Expression:
1080 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1081 Pack = Subst->getArgumentPack();
1082 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1083 for (ParmVarDecl *PD : *Subst)
1084 if (PD->isParameterPack())
1086 return Subst->getNumExpansions();
1091 case TemplateArgument::Template:
1092 if (SubstTemplateTemplateParmPackStorage *Subst =
1093 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1094 Pack = Subst->getArgumentPack();
1099 case TemplateArgument::Declaration:
1100 case TemplateArgument::NullPtr:
1101 case TemplateArgument::TemplateExpansion:
1102 case TemplateArgument::Integral:
1103 case TemplateArgument::Pack:
1104 case TemplateArgument::Null:
1108 // Check that no argument in the pack is itself a pack expansion.
1109 for (TemplateArgument Elem : Pack.pack_elements()) {
1110 // There's no point recursing in this case; we would have already
1111 // expanded this pack expansion into the enclosing pack if we could.
1112 if (Elem.isPackExpansion())
1115 return Pack.pack_size();
1118 static void CheckFoldOperand(Sema &S, Expr *E) {
1122 E = E->IgnoreImpCasts();
1123 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1124 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1125 isa<AbstractConditionalOperator>(E)) {
1126 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1127 << E->getSourceRange()
1128 << FixItHint::CreateInsertion(E->getLocStart(), "(")
1129 << FixItHint::CreateInsertion(E->getLocEnd(), ")");
1133 ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1134 tok::TokenKind Operator,
1135 SourceLocation EllipsisLoc, Expr *RHS,
1136 SourceLocation RParenLoc) {
1137 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1138 // in the parser and reduce down to just cast-expressions here.
1139 CheckFoldOperand(*this, LHS);
1140 CheckFoldOperand(*this, RHS);
1142 auto DiscardOperands = [&] {
1143 CorrectDelayedTyposInExpr(LHS);
1144 CorrectDelayedTyposInExpr(RHS);
1147 // [expr.prim.fold]p3:
1148 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1149 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1150 // an unexpanded parameter pack, but not both.
1152 LHS->containsUnexpandedParameterPack() ==
1153 RHS->containsUnexpandedParameterPack()) {
1155 return Diag(EllipsisLoc,
1156 LHS->containsUnexpandedParameterPack()
1157 ? diag::err_fold_expression_packs_both_sides
1158 : diag::err_pack_expansion_without_parameter_packs)
1159 << LHS->getSourceRange() << RHS->getSourceRange();
1162 // [expr.prim.fold]p2:
1163 // In a unary fold, the cast-expression shall contain an unexpanded
1166 Expr *Pack = LHS ? LHS : RHS;
1167 assert(Pack && "fold expression with neither LHS nor RHS");
1169 if (!Pack->containsUnexpandedParameterPack())
1170 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1171 << Pack->getSourceRange();
1174 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1175 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
1178 ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1179 BinaryOperatorKind Operator,
1180 SourceLocation EllipsisLoc, Expr *RHS,
1181 SourceLocation RParenLoc) {
1182 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1183 Operator, EllipsisLoc, RHS, RParenLoc);
1186 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1187 BinaryOperatorKind Operator) {
1188 // [temp.variadic]p9:
1189 // If N is zero for a unary fold-expression, the value of the expression is
1193 // if the operator is not listed [above], the instantiation is ill-formed.
1195 // Note that we need to use something like int() here, not merely 0, to
1196 // prevent the result from being a null pointer constant.
1197 QualType ScalarType;
1200 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1202 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1204 ScalarType = Context.VoidTy;
1208 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1209 << BinaryOperator::getOpcodeStr(Operator);
1212 return new (Context) CXXScalarValueInitExpr(
1213 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),