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 //----------------------------------------------------------------------------
29 /// \brief Retrieve the depth and index of a parameter pack.
30 static std::pair<unsigned, unsigned>
31 getDepthAndIndex(NamedDecl *ND) {
32 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
33 return std::make_pair(TTP->getDepth(), TTP->getIndex());
35 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
36 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
38 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
39 return std::make_pair(TTP->getDepth(), TTP->getIndex());
43 /// \brief A class that collects unexpanded parameter packs.
44 class CollectUnexpandedParameterPacksVisitor :
45 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
47 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
50 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
52 bool InLambda = false;
53 unsigned DepthLimit = (unsigned)-1;
55 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
56 if (auto *PVD = dyn_cast<ParmVarDecl>(ND)) {
57 // For now, the only problematic case is a generic lambda's templated
58 // call operator, so we don't need to look for all the other ways we
59 // could have reached a dependent parameter pack.
60 auto *FD = dyn_cast<FunctionDecl>(PVD->getDeclContext());
61 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
62 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
64 } else if (getDepthAndIndex(ND).first >= DepthLimit)
67 Unexpanded.push_back({ND, Loc});
69 void addUnexpanded(const TemplateTypeParmType *T,
70 SourceLocation Loc = SourceLocation()) {
71 if (T->getDepth() < DepthLimit)
72 Unexpanded.push_back({T, Loc});
76 explicit CollectUnexpandedParameterPacksVisitor(
77 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
78 : Unexpanded(Unexpanded) {}
80 bool shouldWalkTypesOfTypeLocs() const { return false; }
82 //------------------------------------------------------------------------
83 // Recording occurrences of (unexpanded) parameter packs.
84 //------------------------------------------------------------------------
86 /// \brief Record occurrences of template type parameter packs.
87 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
88 if (TL.getTypePtr()->isParameterPack())
89 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
93 /// \brief Record occurrences of template type parameter packs
94 /// when we don't have proper source-location information for
97 /// Ideally, this routine would never be used.
98 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
99 if (T->isParameterPack())
105 /// \brief Record occurrences of function and non-type template
106 /// parameter packs in an expression.
107 bool VisitDeclRefExpr(DeclRefExpr *E) {
108 if (E->getDecl()->isParameterPack())
109 addUnexpanded(E->getDecl(), E->getLocation());
114 /// \brief Record occurrences of template template parameter packs.
115 bool TraverseTemplateName(TemplateName Template) {
116 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
117 Template.getAsTemplateDecl())) {
118 if (TTP->isParameterPack())
122 return inherited::TraverseTemplateName(Template);
125 /// \brief Suppress traversal into Objective-C container literal
126 /// elements that are pack expansions.
127 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
128 if (!E->containsUnexpandedParameterPack())
131 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
132 ObjCDictionaryElement Element = E->getKeyValueElement(I);
133 if (Element.isPackExpansion())
136 TraverseStmt(Element.Key);
137 TraverseStmt(Element.Value);
141 //------------------------------------------------------------------------
142 // Pruning the search for unexpanded parameter packs.
143 //------------------------------------------------------------------------
145 /// \brief Suppress traversal into statements and expressions that
146 /// do not contain unexpanded parameter packs.
147 bool TraverseStmt(Stmt *S) {
148 Expr *E = dyn_cast_or_null<Expr>(S);
149 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
150 return inherited::TraverseStmt(S);
155 /// \brief Suppress traversal into types that do not contain
156 /// unexpanded parameter packs.
157 bool TraverseType(QualType T) {
158 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
159 return inherited::TraverseType(T);
164 /// \brief Suppress traversal into types with location information
165 /// that do not contain unexpanded parameter packs.
166 bool TraverseTypeLoc(TypeLoc TL) {
167 if ((!TL.getType().isNull() &&
168 TL.getType()->containsUnexpandedParameterPack()) ||
170 return inherited::TraverseTypeLoc(TL);
175 /// \brief Suppress traversal of parameter packs.
176 bool TraverseDecl(Decl *D) {
177 // A function parameter pack is a pack expansion, so cannot contain
178 // an unexpanded parameter pack. Likewise for a template parameter
179 // pack that contains any references to other packs.
180 if (D->isParameterPack())
183 return inherited::TraverseDecl(D);
186 /// \brief Suppress traversal of pack-expanded attributes.
187 bool TraverseAttr(Attr *A) {
188 if (A->isPackExpansion())
191 return inherited::TraverseAttr(A);
194 /// \brief Suppress traversal of pack expansion expressions and types.
196 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
197 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
198 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
199 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
203 /// \brief Suppress traversal of using-declaration pack expansion.
204 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
205 if (D->isPackExpansion())
208 return inherited::TraverseUnresolvedUsingValueDecl(D);
211 /// \brief Suppress traversal of using-declaration pack expansion.
212 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
213 if (D->isPackExpansion())
216 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
219 /// \brief Suppress traversal of template argument pack expansions.
220 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
221 if (Arg.isPackExpansion())
224 return inherited::TraverseTemplateArgument(Arg);
227 /// \brief Suppress traversal of template argument pack expansions.
228 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
229 if (ArgLoc.getArgument().isPackExpansion())
232 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
235 /// \brief Suppress traversal of base specifier pack expansions.
236 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
237 if (Base.isPackExpansion())
240 return inherited::TraverseCXXBaseSpecifier(Base);
243 /// \brief Suppress traversal of mem-initializer pack expansions.
244 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
245 if (Init->isPackExpansion())
248 return inherited::TraverseConstructorInitializer(Init);
251 /// \brief Note whether we're traversing a lambda containing an unexpanded
252 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
253 /// including all the places where we normally wouldn't look. Within a
254 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
255 /// outside an expression.
256 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
257 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
258 // even if it's contained within another lambda.
259 if (!Lambda->containsUnexpandedParameterPack())
262 bool WasInLambda = InLambda;
263 unsigned OldDepthLimit = DepthLimit;
266 if (auto *TPL = Lambda->getTemplateParameterList())
267 DepthLimit = TPL->getDepth();
269 inherited::TraverseLambdaExpr(Lambda);
271 InLambda = WasInLambda;
272 DepthLimit = OldDepthLimit;
276 /// Suppress traversal within pack expansions in lambda captures.
277 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
279 if (C->isPackExpansion())
282 return inherited::TraverseLambdaCapture(Lambda, C, Init);
287 /// \brief Determine whether it's possible for an unexpanded parameter pack to
288 /// be valid in this location. This only happens when we're in a declaration
289 /// that is nested within an expression that could be expanded, such as a
290 /// lambda-expression within a function call.
292 /// This is conservatively correct, but may claim that some unexpanded packs are
293 /// permitted when they are not.
294 bool Sema::isUnexpandedParameterPackPermitted() {
295 for (auto *SI : FunctionScopes)
296 if (isa<sema::LambdaScopeInfo>(SI))
301 /// \brief Diagnose all of the unexpanded parameter packs in the given
304 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
305 UnexpandedParameterPackContext UPPC,
306 ArrayRef<UnexpandedParameterPack> Unexpanded) {
307 if (Unexpanded.empty())
310 // If we are within a lambda expression and referencing a pack that is not
311 // a parameter of the lambda itself, that lambda contains an unexpanded
312 // parameter pack, and we are done.
313 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
315 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
316 for (unsigned N = FunctionScopes.size(); N; --N) {
317 if (sema::LambdaScopeInfo *LSI =
318 dyn_cast<sema::LambdaScopeInfo>(FunctionScopes[N-1])) {
319 if (N == FunctionScopes.size()) {
320 for (auto &Param : Unexpanded) {
321 auto *PD = dyn_cast_or_null<ParmVarDecl>(
322 Param.first.dyn_cast<NamedDecl *>());
323 if (PD && PD->getDeclContext() == LSI->CallOperator)
324 LambdaParamPackReferences.push_back(Param);
328 // If we have references to a parameter pack of the innermost enclosing
329 // lambda, only diagnose those ones. We don't know whether any other
330 // unexpanded parameters referenced herein are actually unexpanded;
331 // they might be expanded at an outer level.
332 if (!LambdaParamPackReferences.empty()) {
333 Unexpanded = LambdaParamPackReferences;
337 LSI->ContainsUnexpandedParameterPack = true;
342 SmallVector<SourceLocation, 4> Locations;
343 SmallVector<IdentifierInfo *, 4> Names;
344 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
346 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
347 IdentifierInfo *Name = nullptr;
348 if (const TemplateTypeParmType *TTP
349 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
350 Name = TTP->getIdentifier();
352 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
354 if (Name && NamesKnown.insert(Name).second)
355 Names.push_back(Name);
357 if (Unexpanded[I].second.isValid())
358 Locations.push_back(Unexpanded[I].second);
361 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
362 << (int)UPPC << (int)Names.size();
363 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
366 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
367 DB << SourceRange(Locations[I]);
371 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
373 UnexpandedParameterPackContext UPPC) {
374 // C++0x [temp.variadic]p5:
375 // An appearance of a name of a parameter pack that is not expanded is
377 if (!T->getType()->containsUnexpandedParameterPack())
380 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
381 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
383 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
384 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
387 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
388 UnexpandedParameterPackContext UPPC) {
389 // C++0x [temp.variadic]p5:
390 // An appearance of a name of a parameter pack that is not expanded is
392 if (!E->containsUnexpandedParameterPack())
395 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
396 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
397 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
398 return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
401 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
402 UnexpandedParameterPackContext UPPC) {
403 // C++0x [temp.variadic]p5:
404 // An appearance of a name of a parameter pack that is not expanded is
406 if (!SS.getScopeRep() ||
407 !SS.getScopeRep()->containsUnexpandedParameterPack())
410 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
411 CollectUnexpandedParameterPacksVisitor(Unexpanded)
412 .TraverseNestedNameSpecifier(SS.getScopeRep());
413 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
414 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
418 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
419 UnexpandedParameterPackContext UPPC) {
420 // C++0x [temp.variadic]p5:
421 // An appearance of a name of a parameter pack that is not expanded is
423 switch (NameInfo.getName().getNameKind()) {
424 case DeclarationName::Identifier:
425 case DeclarationName::ObjCZeroArgSelector:
426 case DeclarationName::ObjCOneArgSelector:
427 case DeclarationName::ObjCMultiArgSelector:
428 case DeclarationName::CXXOperatorName:
429 case DeclarationName::CXXLiteralOperatorName:
430 case DeclarationName::CXXUsingDirective:
431 case DeclarationName::CXXDeductionGuideName:
434 case DeclarationName::CXXConstructorName:
435 case DeclarationName::CXXDestructorName:
436 case DeclarationName::CXXConversionFunctionName:
437 // FIXME: We shouldn't need this null check!
438 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
439 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
441 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
447 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
448 CollectUnexpandedParameterPacksVisitor(Unexpanded)
449 .TraverseType(NameInfo.getName().getCXXNameType());
450 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
451 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
454 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
455 TemplateName Template,
456 UnexpandedParameterPackContext UPPC) {
458 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
461 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
462 CollectUnexpandedParameterPacksVisitor(Unexpanded)
463 .TraverseTemplateName(Template);
464 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
465 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
468 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
469 UnexpandedParameterPackContext UPPC) {
470 if (Arg.getArgument().isNull() ||
471 !Arg.getArgument().containsUnexpandedParameterPack())
474 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
475 CollectUnexpandedParameterPacksVisitor(Unexpanded)
476 .TraverseTemplateArgumentLoc(Arg);
477 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
478 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
481 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
482 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
483 CollectUnexpandedParameterPacksVisitor(Unexpanded)
484 .TraverseTemplateArgument(Arg);
487 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
488 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
489 CollectUnexpandedParameterPacksVisitor(Unexpanded)
490 .TraverseTemplateArgumentLoc(Arg);
493 void Sema::collectUnexpandedParameterPacks(QualType T,
494 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
495 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
498 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
499 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
500 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
503 void Sema::collectUnexpandedParameterPacks(
504 NestedNameSpecifierLoc NNS,
505 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
506 CollectUnexpandedParameterPacksVisitor(Unexpanded)
507 .TraverseNestedNameSpecifierLoc(NNS);
510 void Sema::collectUnexpandedParameterPacks(
511 const DeclarationNameInfo &NameInfo,
512 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
513 CollectUnexpandedParameterPacksVisitor(Unexpanded)
514 .TraverseDeclarationNameInfo(NameInfo);
518 ParsedTemplateArgument
519 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
520 SourceLocation EllipsisLoc) {
524 switch (Arg.getKind()) {
525 case ParsedTemplateArgument::Type: {
526 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
527 if (Result.isInvalid())
528 return ParsedTemplateArgument();
530 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
534 case ParsedTemplateArgument::NonType: {
535 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
536 if (Result.isInvalid())
537 return ParsedTemplateArgument();
539 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
543 case ParsedTemplateArgument::Template:
544 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
545 SourceRange R(Arg.getLocation());
546 if (Arg.getScopeSpec().isValid())
547 R.setBegin(Arg.getScopeSpec().getBeginLoc());
548 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
550 return ParsedTemplateArgument();
553 return Arg.getTemplatePackExpansion(EllipsisLoc);
555 llvm_unreachable("Unhandled template argument kind?");
558 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
559 SourceLocation EllipsisLoc) {
560 TypeSourceInfo *TSInfo;
561 GetTypeFromParser(Type, &TSInfo);
565 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
569 return CreateParsedType(TSResult->getType(), TSResult);
573 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
574 Optional<unsigned> NumExpansions) {
575 // Create the pack expansion type and source-location information.
576 QualType Result = CheckPackExpansion(Pattern->getType(),
577 Pattern->getTypeLoc().getSourceRange(),
578 EllipsisLoc, NumExpansions);
583 TLB.pushFullCopy(Pattern->getTypeLoc());
584 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
585 TL.setEllipsisLoc(EllipsisLoc);
587 return TLB.getTypeSourceInfo(Context, Result);
590 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
591 SourceLocation EllipsisLoc,
592 Optional<unsigned> NumExpansions) {
593 // C++0x [temp.variadic]p5:
594 // The pattern of a pack expansion shall name one or more
595 // parameter packs that are not expanded by a nested pack
597 if (!Pattern->containsUnexpandedParameterPack()) {
598 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
603 return Context.getPackExpansionType(Pattern, NumExpansions);
606 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
607 return CheckPackExpansion(Pattern, EllipsisLoc, None);
610 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
611 Optional<unsigned> NumExpansions) {
615 // C++0x [temp.variadic]p5:
616 // The pattern of a pack expansion shall name one or more
617 // parameter packs that are not expanded by a nested pack
619 if (!Pattern->containsUnexpandedParameterPack()) {
620 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
621 << Pattern->getSourceRange();
625 // Create the pack expansion expression and source-location information.
627 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
630 bool Sema::CheckParameterPacksForExpansion(
631 SourceLocation EllipsisLoc, SourceRange PatternRange,
632 ArrayRef<UnexpandedParameterPack> Unexpanded,
633 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
634 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
636 RetainExpansion = false;
637 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
638 bool HaveFirstPack = false;
640 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
641 end = Unexpanded.end();
643 // Compute the depth and index for this parameter pack.
644 unsigned Depth = 0, Index = 0;
645 IdentifierInfo *Name;
646 bool IsFunctionParameterPack = false;
648 if (const TemplateTypeParmType *TTP
649 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
650 Depth = TTP->getDepth();
651 Index = TTP->getIndex();
652 Name = TTP->getIdentifier();
654 NamedDecl *ND = i->first.get<NamedDecl *>();
655 if (isa<ParmVarDecl>(ND))
656 IsFunctionParameterPack = true;
658 std::tie(Depth, Index) = getDepthAndIndex(ND);
660 Name = ND->getIdentifier();
663 // Determine the size of this argument pack.
664 unsigned NewPackSize;
665 if (IsFunctionParameterPack) {
666 // Figure out whether we're instantiating to an argument pack or not.
667 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
669 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
670 = CurrentInstantiationScope->findInstantiationOf(
671 i->first.get<NamedDecl *>());
672 if (Instantiation->is<DeclArgumentPack *>()) {
673 // We could expand this function parameter pack.
674 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
676 // We can't expand this function parameter pack, so we can't expand
677 // the pack expansion.
678 ShouldExpand = false;
682 // If we don't have a template argument at this depth/index, then we
683 // cannot expand the pack expansion. Make a note of this, but we still
684 // want to check any parameter packs we *do* have arguments for.
685 if (Depth >= TemplateArgs.getNumLevels() ||
686 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
687 ShouldExpand = false;
691 // Determine the size of the argument pack.
692 NewPackSize = TemplateArgs(Depth, Index).pack_size();
695 // C++0x [temp.arg.explicit]p9:
696 // Template argument deduction can extend the sequence of template
697 // arguments corresponding to a template parameter pack, even when the
698 // sequence contains explicitly specified template arguments.
699 if (!IsFunctionParameterPack && CurrentInstantiationScope) {
700 if (NamedDecl *PartialPack
701 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
702 unsigned PartialDepth, PartialIndex;
703 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
704 if (PartialDepth == Depth && PartialIndex == Index)
705 RetainExpansion = true;
709 if (!NumExpansions) {
710 // The is the first pack we've seen for which we have an argument.
712 NumExpansions = NewPackSize;
713 FirstPack.first = Name;
714 FirstPack.second = i->second;
715 HaveFirstPack = true;
719 if (NewPackSize != *NumExpansions) {
720 // C++0x [temp.variadic]p5:
721 // All of the parameter packs expanded by a pack expansion shall have
722 // the same number of arguments specified.
724 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
725 << FirstPack.first << Name << *NumExpansions << NewPackSize
726 << SourceRange(FirstPack.second) << SourceRange(i->second);
728 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
729 << Name << *NumExpansions << NewPackSize
730 << SourceRange(i->second);
738 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
739 const MultiLevelTemplateArgumentList &TemplateArgs) {
740 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
741 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
742 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
744 Optional<unsigned> Result;
745 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
746 // Compute the depth and index for this parameter pack.
750 if (const TemplateTypeParmType *TTP
751 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
752 Depth = TTP->getDepth();
753 Index = TTP->getIndex();
755 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
756 if (isa<ParmVarDecl>(ND)) {
757 // Function parameter pack.
758 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
760 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
761 = CurrentInstantiationScope->findInstantiationOf(
762 Unexpanded[I].first.get<NamedDecl *>());
763 if (Instantiation->is<Decl*>())
764 // The pattern refers to an unexpanded pack. We're not ready to expand
768 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
769 assert((!Result || *Result == Size) && "inconsistent pack sizes");
774 std::tie(Depth, Index) = getDepthAndIndex(ND);
776 if (Depth >= TemplateArgs.getNumLevels() ||
777 !TemplateArgs.hasTemplateArgument(Depth, Index))
778 // The pattern refers to an unknown template argument. We're not ready to
779 // expand this pack yet.
782 // Determine the size of the argument pack.
783 unsigned Size = TemplateArgs(Depth, Index).pack_size();
784 assert((!Result || *Result == Size) && "inconsistent pack sizes");
791 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
792 const DeclSpec &DS = D.getDeclSpec();
793 switch (DS.getTypeSpecType()) {
796 case TST_underlyingType:
798 QualType T = DS.getRepAsType().get();
799 if (!T.isNull() && T->containsUnexpandedParameterPack())
806 if (DS.getRepAsExpr() &&
807 DS.getRepAsExpr()->containsUnexpandedParameterPack())
811 case TST_unspecified:
835 case TST_decltype_auto:
836 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
837 #include "clang/Basic/OpenCLImageTypes.def"
838 case TST_unknown_anytype:
843 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
844 const DeclaratorChunk &Chunk = D.getTypeObject(I);
845 switch (Chunk.Kind) {
846 case DeclaratorChunk::Pointer:
847 case DeclaratorChunk::Reference:
848 case DeclaratorChunk::Paren:
849 case DeclaratorChunk::Pipe:
850 case DeclaratorChunk::BlockPointer:
851 // These declarator chunks cannot contain any parameter packs.
854 case DeclaratorChunk::Array:
855 if (Chunk.Arr.NumElts &&
856 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
859 case DeclaratorChunk::Function:
860 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
861 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
862 QualType ParamTy = Param->getType();
863 assert(!ParamTy.isNull() && "Couldn't parse type?");
864 if (ParamTy->containsUnexpandedParameterPack()) return true;
867 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
868 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
869 if (Chunk.Fun.Exceptions[i]
871 ->containsUnexpandedParameterPack())
874 } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
875 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
878 if (Chunk.Fun.hasTrailingReturnType()) {
879 QualType T = Chunk.Fun.getTrailingReturnType().get();
880 if (!T.isNull() && T->containsUnexpandedParameterPack())
885 case DeclaratorChunk::MemberPointer:
886 if (Chunk.Mem.Scope().getScopeRep() &&
887 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
898 // Callback to only accept typo corrections that refer to parameter packs.
899 class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
901 bool ValidateCandidate(const TypoCorrection &candidate) override {
902 NamedDecl *ND = candidate.getCorrectionDecl();
903 return ND && ND->isParameterPack();
909 /// \brief Called when an expression computing the size of a parameter pack
913 /// template<typename ...Types> struct count {
914 /// static const unsigned value = sizeof...(Types);
919 /// \param OpLoc The location of the "sizeof" keyword.
920 /// \param Name The name of the parameter pack whose size will be determined.
921 /// \param NameLoc The source location of the name of the parameter pack.
922 /// \param RParenLoc The location of the closing parentheses.
923 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
924 SourceLocation OpLoc,
925 IdentifierInfo &Name,
926 SourceLocation NameLoc,
927 SourceLocation RParenLoc) {
928 // C++0x [expr.sizeof]p5:
929 // The identifier in a sizeof... expression shall name a parameter pack.
930 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
933 NamedDecl *ParameterPack = nullptr;
934 switch (R.getResultKind()) {
935 case LookupResult::Found:
936 ParameterPack = R.getFoundDecl();
939 case LookupResult::NotFound:
940 case LookupResult::NotFoundInCurrentInstantiation:
941 if (TypoCorrection Corrected =
942 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
943 llvm::make_unique<ParameterPackValidatorCCC>(),
944 CTK_ErrorRecovery)) {
945 diagnoseTypo(Corrected,
946 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
947 PDiag(diag::note_parameter_pack_here));
948 ParameterPack = Corrected.getCorrectionDecl();
951 case LookupResult::FoundOverloaded:
952 case LookupResult::FoundUnresolvedValue:
955 case LookupResult::Ambiguous:
956 DiagnoseAmbiguousLookup(R);
960 if (!ParameterPack || !ParameterPack->isParameterPack()) {
961 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
966 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
968 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
973 Sema::getTemplateArgumentPackExpansionPattern(
974 TemplateArgumentLoc OrigLoc,
975 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
976 const TemplateArgument &Argument = OrigLoc.getArgument();
977 assert(Argument.isPackExpansion());
978 switch (Argument.getKind()) {
979 case TemplateArgument::Type: {
980 // FIXME: We shouldn't ever have to worry about missing
982 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
983 if (!ExpansionTSInfo)
984 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
986 PackExpansionTypeLoc Expansion =
987 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
988 Ellipsis = Expansion.getEllipsisLoc();
990 TypeLoc Pattern = Expansion.getPatternLoc();
991 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
993 // We need to copy the TypeLoc because TemplateArgumentLocs store a
995 // FIXME: Find some way to avoid the copy?
997 TLB.pushFullCopy(Pattern);
998 TypeSourceInfo *PatternTSInfo =
999 TLB.getTypeSourceInfo(Context, Pattern.getType());
1000 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1004 case TemplateArgument::Expression: {
1005 PackExpansionExpr *Expansion
1006 = cast<PackExpansionExpr>(Argument.getAsExpr());
1007 Expr *Pattern = Expansion->getPattern();
1008 Ellipsis = Expansion->getEllipsisLoc();
1009 NumExpansions = Expansion->getNumExpansions();
1010 return TemplateArgumentLoc(Pattern, Pattern);
1013 case TemplateArgument::TemplateExpansion:
1014 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1015 NumExpansions = Argument.getNumTemplateExpansions();
1016 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1017 OrigLoc.getTemplateQualifierLoc(),
1018 OrigLoc.getTemplateNameLoc());
1020 case TemplateArgument::Declaration:
1021 case TemplateArgument::NullPtr:
1022 case TemplateArgument::Template:
1023 case TemplateArgument::Integral:
1024 case TemplateArgument::Pack:
1025 case TemplateArgument::Null:
1026 return TemplateArgumentLoc();
1029 llvm_unreachable("Invalid TemplateArgument Kind!");
1032 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1033 assert(Arg.containsUnexpandedParameterPack());
1035 // If this is a substituted pack, grab that pack. If not, we don't know
1037 // FIXME: We could find a size in more cases by looking for a substituted
1038 // pack anywhere within this argument, but that's not necessary in the common
1039 // case for 'sizeof...(A)' handling.
1040 TemplateArgument Pack;
1041 switch (Arg.getKind()) {
1042 case TemplateArgument::Type:
1043 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1044 Pack = Subst->getArgumentPack();
1049 case TemplateArgument::Expression:
1051 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1052 Pack = Subst->getArgumentPack();
1053 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1054 for (ParmVarDecl *PD : *Subst)
1055 if (PD->isParameterPack())
1057 return Subst->getNumExpansions();
1062 case TemplateArgument::Template:
1063 if (SubstTemplateTemplateParmPackStorage *Subst =
1064 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1065 Pack = Subst->getArgumentPack();
1070 case TemplateArgument::Declaration:
1071 case TemplateArgument::NullPtr:
1072 case TemplateArgument::TemplateExpansion:
1073 case TemplateArgument::Integral:
1074 case TemplateArgument::Pack:
1075 case TemplateArgument::Null:
1079 // Check that no argument in the pack is itself a pack expansion.
1080 for (TemplateArgument Elem : Pack.pack_elements()) {
1081 // There's no point recursing in this case; we would have already
1082 // expanded this pack expansion into the enclosing pack if we could.
1083 if (Elem.isPackExpansion())
1086 return Pack.pack_size();
1089 static void CheckFoldOperand(Sema &S, Expr *E) {
1093 E = E->IgnoreImpCasts();
1094 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1095 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1096 isa<AbstractConditionalOperator>(E)) {
1097 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1098 << E->getSourceRange()
1099 << FixItHint::CreateInsertion(E->getLocStart(), "(")
1100 << FixItHint::CreateInsertion(E->getLocEnd(), ")");
1104 ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1105 tok::TokenKind Operator,
1106 SourceLocation EllipsisLoc, Expr *RHS,
1107 SourceLocation RParenLoc) {
1108 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1109 // in the parser and reduce down to just cast-expressions here.
1110 CheckFoldOperand(*this, LHS);
1111 CheckFoldOperand(*this, RHS);
1113 auto DiscardOperands = [&] {
1114 CorrectDelayedTyposInExpr(LHS);
1115 CorrectDelayedTyposInExpr(RHS);
1118 // [expr.prim.fold]p3:
1119 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1120 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1121 // an unexpanded parameter pack, but not both.
1123 LHS->containsUnexpandedParameterPack() ==
1124 RHS->containsUnexpandedParameterPack()) {
1126 return Diag(EllipsisLoc,
1127 LHS->containsUnexpandedParameterPack()
1128 ? diag::err_fold_expression_packs_both_sides
1129 : diag::err_pack_expansion_without_parameter_packs)
1130 << LHS->getSourceRange() << RHS->getSourceRange();
1133 // [expr.prim.fold]p2:
1134 // In a unary fold, the cast-expression shall contain an unexpanded
1137 Expr *Pack = LHS ? LHS : RHS;
1138 assert(Pack && "fold expression with neither LHS nor RHS");
1140 if (!Pack->containsUnexpandedParameterPack())
1141 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1142 << Pack->getSourceRange();
1145 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1146 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
1149 ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1150 BinaryOperatorKind Operator,
1151 SourceLocation EllipsisLoc, Expr *RHS,
1152 SourceLocation RParenLoc) {
1153 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1154 Operator, EllipsisLoc, RHS, RParenLoc);
1157 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1158 BinaryOperatorKind Operator) {
1159 // [temp.variadic]p9:
1160 // If N is zero for a unary fold-expression, the value of the expression is
1164 // if the operator is not listed [above], the instantiation is ill-formed.
1166 // Note that we need to use something like int() here, not merely 0, to
1167 // prevent the result from being a null pointer constant.
1168 QualType ScalarType;
1171 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1173 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1175 ScalarType = Context.VoidTy;
1179 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1180 << BinaryOperator::getOpcodeStr(Operator);
1183 return new (Context) CXXScalarValueInitExpr(
1184 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),