blob: 7aa0e317df0f592c7f9f01b8bc48ccc5ee45c235 [file] [log] [blame]
Douglas Gregorb55fdf82010-12-15 17:38:57 +00001//===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements semantic analysis for C++0x variadic templates.
10//===----------------------------------------------------------------------===/
11
12#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000013#include "TypeLocBuilder.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/AST/Expr.h"
15#include "clang/AST/RecursiveASTVisitor.h"
16#include "clang/AST/TypeLoc.h"
Douglas Gregor820ba7b2011-01-04 17:33:58 +000017#include "clang/Sema/Lookup.h"
Douglas Gregord2fa7662010-12-20 02:24:11 +000018#include "clang/Sema/ParsedTemplate.h"
Richard Smith2589b9802012-07-25 03:56:55 +000019#include "clang/Sema/ScopeInfo.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000020#include "clang/Sema/SemaInternal.h"
Douglas Gregor840bd6c2010-12-20 22:05:00 +000021#include "clang/Sema/Template.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000022
23using namespace clang;
24
Douglas Gregor1da294a2010-12-15 19:43:21 +000025//----------------------------------------------------------------------------
26// Visitor that collects unexpanded parameter packs
27//----------------------------------------------------------------------------
28
Richard Smith78a07ba2017-08-15 19:11:21 +000029/// \brief Retrieve the depth and index of a parameter pack.
30static std::pair<unsigned, unsigned>
31getDepthAndIndex(NamedDecl *ND) {
32 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
33 return std::make_pair(TTP->getDepth(), TTP->getIndex());
34
35 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
36 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
37
38 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
39 return std::make_pair(TTP->getDepth(), TTP->getIndex());
40}
41
Douglas Gregor1da294a2010-12-15 19:43:21 +000042namespace {
43 /// \brief A class that collects unexpanded parameter packs.
44 class CollectUnexpandedParameterPacksVisitor :
45 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
46 {
47 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
48 inherited;
49
Chris Lattner0e62c1c2011-07-23 10:55:15 +000050 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +000051
Richard Smith78a07ba2017-08-15 19:11:21 +000052 bool InLambda = false;
53 unsigned DepthLimit = (unsigned)-1;
Richard Smith2589b9802012-07-25 03:56:55 +000054
Richard Smith78a07ba2017-08-15 19:11:21 +000055 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)
63 return;
64 } else if (getDepthAndIndex(ND).first >= DepthLimit)
65 return;
66
67 Unexpanded.push_back({ND, Loc});
68 }
69 void addUnexpanded(const TemplateTypeParmType *T,
70 SourceLocation Loc = SourceLocation()) {
71 if (T->getDepth() < DepthLimit)
72 Unexpanded.push_back({T, Loc});
73 }
74
Douglas Gregor1da294a2010-12-15 19:43:21 +000075 public:
76 explicit CollectUnexpandedParameterPacksVisitor(
Richard Smith78a07ba2017-08-15 19:11:21 +000077 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
78 : Unexpanded(Unexpanded) {}
Douglas Gregor1da294a2010-12-15 19:43:21 +000079
Douglas Gregor15b4ec22010-12-20 23:07:20 +000080 bool shouldWalkTypesOfTypeLocs() const { return false; }
Richard Smith78a07ba2017-08-15 19:11:21 +000081
Douglas Gregor1da294a2010-12-15 19:43:21 +000082 //------------------------------------------------------------------------
83 // Recording occurrences of (unexpanded) parameter packs.
84 //------------------------------------------------------------------------
85
86 /// \brief Record occurrences of template type parameter packs.
87 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
88 if (TL.getTypePtr()->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000089 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
Douglas Gregor1da294a2010-12-15 19:43:21 +000090 return true;
91 }
92
93 /// \brief Record occurrences of template type parameter packs
94 /// when we don't have proper source-location information for
95 /// them.
96 ///
97 /// Ideally, this routine would never be used.
98 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
99 if (T->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000100 addUnexpanded(T);
Douglas Gregor1da294a2010-12-15 19:43:21 +0000101
102 return true;
103 }
104
Douglas Gregor476e3022011-01-19 21:32:01 +0000105 /// \brief Record occurrences of function and non-type template
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000106 /// parameter packs in an expression.
107 bool VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000108 if (E->getDecl()->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000109 addUnexpanded(E->getDecl(), E->getLocation());
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000110
111 return true;
112 }
113
Douglas Gregorf5500772011-01-05 15:48:55 +0000114 /// \brief Record occurrences of template template parameter packs.
115 bool TraverseTemplateName(TemplateName Template) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000116 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
117 Template.getAsTemplateDecl())) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000118 if (TTP->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000119 addUnexpanded(TTP);
120 }
Douglas Gregorf5500772011-01-05 15:48:55 +0000121
122 return inherited::TraverseTemplateName(Template);
123 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000124
Ted Kremeneke65b0862012-03-06 20:05:56 +0000125 /// \brief Suppress traversal into Objective-C container literal
126 /// elements that are pack expansions.
127 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
128 if (!E->containsUnexpandedParameterPack())
129 return true;
130
131 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
132 ObjCDictionaryElement Element = E->getKeyValueElement(I);
133 if (Element.isPackExpansion())
134 continue;
135
136 TraverseStmt(Element.Key);
137 TraverseStmt(Element.Value);
138 }
139 return true;
140 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000141 //------------------------------------------------------------------------
142 // Pruning the search for unexpanded parameter packs.
143 //------------------------------------------------------------------------
144
145 /// \brief Suppress traversal into statements and expressions that
146 /// do not contain unexpanded parameter packs.
147 bool TraverseStmt(Stmt *S) {
Richard Smith2589b9802012-07-25 03:56:55 +0000148 Expr *E = dyn_cast_or_null<Expr>(S);
149 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
150 return inherited::TraverseStmt(S);
Douglas Gregor1da294a2010-12-15 19:43:21 +0000151
Richard Smith2589b9802012-07-25 03:56:55 +0000152 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000153 }
154
155 /// \brief Suppress traversal into types that do not contain
156 /// unexpanded parameter packs.
157 bool TraverseType(QualType T) {
Richard Smith2589b9802012-07-25 03:56:55 +0000158 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000159 return inherited::TraverseType(T);
160
161 return true;
162 }
163
Richard Smithf26d5512017-08-15 22:58:45 +0000164 /// \brief Suppress traversal into types with location information
Douglas Gregor1da294a2010-12-15 19:43:21 +0000165 /// that do not contain unexpanded parameter packs.
166 bool TraverseTypeLoc(TypeLoc TL) {
Richard Smith2589b9802012-07-25 03:56:55 +0000167 if ((!TL.getType().isNull() &&
168 TL.getType()->containsUnexpandedParameterPack()) ||
169 InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000170 return inherited::TraverseTypeLoc(TL);
171
172 return true;
173 }
174
Richard Smithf26d5512017-08-15 22:58:45 +0000175 /// \brief Suppress traversal of parameter packs.
Douglas Gregora8461bb2010-12-15 21:57:59 +0000176 bool TraverseDecl(Decl *D) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000177 // A function parameter pack is a pack expansion, so cannot contain
Richard Smithf26d5512017-08-15 22:58:45 +0000178 // an unexpanded parameter pack. Likewise for a template parameter
179 // pack that contains any references to other packs.
180 if (D->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000181 return true;
182
Richard Smithf26d5512017-08-15 22:58:45 +0000183 return inherited::TraverseDecl(D);
184 }
Douglas Gregora8461bb2010-12-15 21:57:59 +0000185
Richard Smithf26d5512017-08-15 22:58:45 +0000186 /// \brief Suppress traversal of pack-expanded attributes.
187 bool TraverseAttr(Attr *A) {
188 if (A->isPackExpansion())
189 return true;
190
191 return inherited::TraverseAttr(A);
192 }
193
194 /// \brief Suppress traversal of pack expansion expressions and types.
195 ///@{
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; }
200
201 ///@}
202
203 /// \brief Suppress traversal of using-declaration pack expansion.
204 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
205 if (D->isPackExpansion())
206 return true;
207
208 return inherited::TraverseUnresolvedUsingValueDecl(D);
209 }
210
211 /// \brief Suppress traversal of using-declaration pack expansion.
212 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
213 if (D->isPackExpansion())
214 return true;
215
216 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
Douglas Gregora8461bb2010-12-15 21:57:59 +0000217 }
Douglas Gregoreb29d182011-01-05 17:40:24 +0000218
219 /// \brief Suppress traversal of template argument pack expansions.
220 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
221 if (Arg.isPackExpansion())
222 return true;
223
224 return inherited::TraverseTemplateArgument(Arg);
225 }
226
227 /// \brief Suppress traversal of template argument pack expansions.
228 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
229 if (ArgLoc.getArgument().isPackExpansion())
230 return true;
231
232 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
233 }
Richard Smith2589b9802012-07-25 03:56:55 +0000234
Richard Smithf26d5512017-08-15 22:58:45 +0000235 /// \brief Suppress traversal of base specifier pack expansions.
236 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
237 if (Base.isPackExpansion())
238 return true;
239
240 return inherited::TraverseCXXBaseSpecifier(Base);
241 }
242
243 /// \brief Suppress traversal of mem-initializer pack expansions.
244 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
245 if (Init->isPackExpansion())
246 return true;
247
248 return inherited::TraverseConstructorInitializer(Init);
249 }
250
Richard Smith2589b9802012-07-25 03:56:55 +0000251 /// \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())
260 return true;
261
262 bool WasInLambda = InLambda;
Richard Smith78a07ba2017-08-15 19:11:21 +0000263 unsigned OldDepthLimit = DepthLimit;
Richard Smith2589b9802012-07-25 03:56:55 +0000264
Richard Smith78a07ba2017-08-15 19:11:21 +0000265 InLambda = true;
266 if (auto *TPL = Lambda->getTemplateParameterList())
267 DepthLimit = TPL->getDepth();
Richard Smith2589b9802012-07-25 03:56:55 +0000268
269 inherited::TraverseLambdaExpr(Lambda);
270
271 InLambda = WasInLambda;
Richard Smith78a07ba2017-08-15 19:11:21 +0000272 DepthLimit = OldDepthLimit;
Richard Smith2589b9802012-07-25 03:56:55 +0000273 return true;
274 }
Richard Smith78a07ba2017-08-15 19:11:21 +0000275
276 /// Suppress traversal within pack expansions in lambda captures.
277 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
278 Expr *Init) {
279 if (C->isPackExpansion())
280 return true;
Richard Smithf26d5512017-08-15 22:58:45 +0000281
Richard Smith78a07ba2017-08-15 19:11:21 +0000282 return inherited::TraverseLambdaCapture(Lambda, C, Init);
283 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000284 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000285}
Douglas Gregor1da294a2010-12-15 19:43:21 +0000286
Richard Smith36ee9fb2014-08-11 23:30:23 +0000287/// \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.
291///
292/// This is conservatively correct, but may claim that some unexpanded packs are
293/// permitted when they are not.
294bool Sema::isUnexpandedParameterPackPermitted() {
295 for (auto *SI : FunctionScopes)
296 if (isa<sema::LambdaScopeInfo>(SI))
297 return true;
298 return false;
299}
300
Douglas Gregor1da294a2010-12-15 19:43:21 +0000301/// \brief Diagnose all of the unexpanded parameter packs in the given
302/// vector.
Richard Smith2589b9802012-07-25 03:56:55 +0000303bool
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000304Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
305 UnexpandedParameterPackContext UPPC,
Bill Wendling8ac06af2012-02-22 09:38:11 +0000306 ArrayRef<UnexpandedParameterPack> Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000307 if (Unexpanded.empty())
Richard Smith2589b9802012-07-25 03:56:55 +0000308 return false;
309
Richard Smith78a07ba2017-08-15 19:11:21 +0000310 // 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
Richard Smith2589b9802012-07-25 03:56:55 +0000312 // parameter pack, and we are done.
313 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
314 // later.
Richard Smithf26d5512017-08-15 22:58:45 +0000315 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
Richard Smith2589b9802012-07-25 03:56:55 +0000316 for (unsigned N = FunctionScopes.size(); N; --N) {
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000317 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
318 // We do not permit pack expansion that would duplicate a statement
319 // expression, not even within a lambda.
320 // FIXME: We could probably support this for statement expressions that do
321 // not contain labels, and for pack expansions that expand both the stmt
322 // expr and the enclosing lambda.
323 if (std::any_of(
324 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
325 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; }))
326 break;
327
328 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Func)) {
Richard Smithf26d5512017-08-15 22:58:45 +0000329 if (N == FunctionScopes.size()) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000330 for (auto &Param : Unexpanded) {
331 auto *PD = dyn_cast_or_null<ParmVarDecl>(
332 Param.first.dyn_cast<NamedDecl *>());
333 if (PD && PD->getDeclContext() == LSI->CallOperator)
Richard Smithf26d5512017-08-15 22:58:45 +0000334 LambdaParamPackReferences.push_back(Param);
Richard Smith78a07ba2017-08-15 19:11:21 +0000335 }
336 }
337
Richard Smithf26d5512017-08-15 22:58:45 +0000338 // If we have references to a parameter pack of the innermost enclosing
339 // lambda, only diagnose those ones. We don't know whether any other
340 // unexpanded parameters referenced herein are actually unexpanded;
341 // they might be expanded at an outer level.
342 if (!LambdaParamPackReferences.empty()) {
343 Unexpanded = LambdaParamPackReferences;
Richard Smith78a07ba2017-08-15 19:11:21 +0000344 break;
345 }
346
Richard Smith2589b9802012-07-25 03:56:55 +0000347 LSI->ContainsUnexpandedParameterPack = true;
348 return false;
349 }
350 }
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000351
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<SourceLocation, 4> Locations;
353 SmallVector<IdentifierInfo *, 4> Names;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000354 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
355
356 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000357 IdentifierInfo *Name = nullptr;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000358 if (const TemplateTypeParmType *TTP
359 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000360 Name = TTP->getIdentifier();
Douglas Gregor1da294a2010-12-15 19:43:21 +0000361 else
362 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
363
David Blaikie82e95a32014-11-19 07:49:47 +0000364 if (Name && NamesKnown.insert(Name).second)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000365 Names.push_back(Name);
366
367 if (Unexpanded[I].second.isValid())
368 Locations.push_back(Unexpanded[I].second);
369 }
370
Benjamin Kramer3a8650a2015-03-27 17:23:14 +0000371 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
372 << (int)UPPC << (int)Names.size();
373 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
374 DB << Names[I];
Douglas Gregor1da294a2010-12-15 19:43:21 +0000375
376 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
377 DB << SourceRange(Locations[I]);
Richard Smith2589b9802012-07-25 03:56:55 +0000378 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000379}
380
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000381bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
382 TypeSourceInfo *T,
383 UnexpandedParameterPackContext UPPC) {
384 // C++0x [temp.variadic]p5:
385 // An appearance of a name of a parameter pack that is not expanded is
386 // ill-formed.
387 if (!T->getType()->containsUnexpandedParameterPack())
388 return false;
389
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000390 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000391 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
392 T->getTypeLoc());
393 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000394 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000395}
396
397bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
Douglas Gregorc4356532010-12-16 00:46:58 +0000398 UnexpandedParameterPackContext UPPC) {
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000399 // C++0x [temp.variadic]p5:
400 // An appearance of a name of a parameter pack that is not expanded is
401 // ill-formed.
402 if (!E->containsUnexpandedParameterPack())
403 return false;
404
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000405 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000406 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
407 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000408 return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000409}
Douglas Gregorc4356532010-12-16 00:46:58 +0000410
411bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
412 UnexpandedParameterPackContext UPPC) {
413 // C++0x [temp.variadic]p5:
414 // An appearance of a name of a parameter pack that is not expanded is
415 // ill-formed.
416 if (!SS.getScopeRep() ||
417 !SS.getScopeRep()->containsUnexpandedParameterPack())
418 return false;
419
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000420 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000421 CollectUnexpandedParameterPacksVisitor(Unexpanded)
422 .TraverseNestedNameSpecifier(SS.getScopeRep());
423 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000424 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
425 UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000426}
427
428bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
429 UnexpandedParameterPackContext UPPC) {
430 // C++0x [temp.variadic]p5:
431 // An appearance of a name of a parameter pack that is not expanded is
432 // ill-formed.
433 switch (NameInfo.getName().getNameKind()) {
434 case DeclarationName::Identifier:
435 case DeclarationName::ObjCZeroArgSelector:
436 case DeclarationName::ObjCOneArgSelector:
437 case DeclarationName::ObjCMultiArgSelector:
438 case DeclarationName::CXXOperatorName:
439 case DeclarationName::CXXLiteralOperatorName:
440 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +0000441 case DeclarationName::CXXDeductionGuideName:
Douglas Gregorc4356532010-12-16 00:46:58 +0000442 return false;
443
444 case DeclarationName::CXXConstructorName:
445 case DeclarationName::CXXDestructorName:
446 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor062ecac2010-12-16 17:19:19 +0000447 // FIXME: We shouldn't need this null check!
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000448 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
449 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
450
451 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
Douglas Gregorc4356532010-12-16 00:46:58 +0000452 return false;
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000453
Douglas Gregorc4356532010-12-16 00:46:58 +0000454 break;
455 }
456
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000458 CollectUnexpandedParameterPacksVisitor(Unexpanded)
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000459 .TraverseType(NameInfo.getName().getCXXNameType());
Douglas Gregorc4356532010-12-16 00:46:58 +0000460 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000461 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000462}
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000463
464bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
465 TemplateName Template,
466 UnexpandedParameterPackContext UPPC) {
467
468 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
469 return false;
470
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000472 CollectUnexpandedParameterPacksVisitor(Unexpanded)
473 .TraverseTemplateName(Template);
474 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000475 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000476}
477
Douglas Gregor14406932011-01-03 20:35:03 +0000478bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
479 UnexpandedParameterPackContext UPPC) {
480 if (Arg.getArgument().isNull() ||
481 !Arg.getArgument().containsUnexpandedParameterPack())
482 return false;
483
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor14406932011-01-03 20:35:03 +0000485 CollectUnexpandedParameterPacksVisitor(Unexpanded)
486 .TraverseTemplateArgumentLoc(Arg);
487 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000488 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
Douglas Gregor14406932011-01-03 20:35:03 +0000489}
490
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000491void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000493 CollectUnexpandedParameterPacksVisitor(Unexpanded)
494 .TraverseTemplateArgument(Arg);
495}
496
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000497void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000499 CollectUnexpandedParameterPacksVisitor(Unexpanded)
500 .TraverseTemplateArgumentLoc(Arg);
501}
502
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000503void Sema::collectUnexpandedParameterPacks(QualType T,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000505 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
506}
507
Douglas Gregor752a5952011-01-03 22:36:02 +0000508void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000509 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor752a5952011-01-03 22:36:02 +0000510 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
Richard Smith22a250c2016-12-19 04:08:53 +0000511}
512
Richard Smith151c4562016-12-20 21:35:28 +0000513void Sema::collectUnexpandedParameterPacks(
514 NestedNameSpecifierLoc NNS,
515 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516 CollectUnexpandedParameterPacksVisitor(Unexpanded)
517 .TraverseNestedNameSpecifierLoc(NNS);
518}
519
520void Sema::collectUnexpandedParameterPacks(
521 const DeclarationNameInfo &NameInfo,
522 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000523 CollectUnexpandedParameterPacksVisitor(Unexpanded)
524 .TraverseDeclarationNameInfo(NameInfo);
525}
526
527
Douglas Gregord2fa7662010-12-20 02:24:11 +0000528ParsedTemplateArgument
529Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
530 SourceLocation EllipsisLoc) {
531 if (Arg.isInvalid())
532 return Arg;
533
534 switch (Arg.getKind()) {
535 case ParsedTemplateArgument::Type: {
536 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
537 if (Result.isInvalid())
538 return ParsedTemplateArgument();
539
540 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
541 Arg.getLocation());
542 }
543
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000544 case ParsedTemplateArgument::NonType: {
545 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
546 if (Result.isInvalid())
547 return ParsedTemplateArgument();
548
549 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
550 Arg.getLocation());
551 }
552
Douglas Gregord2fa7662010-12-20 02:24:11 +0000553 case ParsedTemplateArgument::Template:
Douglas Gregoreb29d182011-01-05 17:40:24 +0000554 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
555 SourceRange R(Arg.getLocation());
556 if (Arg.getScopeSpec().isValid())
557 R.setBegin(Arg.getScopeSpec().getBeginLoc());
558 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
559 << R;
560 return ParsedTemplateArgument();
561 }
562
563 return Arg.getTemplatePackExpansion(EllipsisLoc);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000564 }
565 llvm_unreachable("Unhandled template argument kind?");
Douglas Gregord2fa7662010-12-20 02:24:11 +0000566}
567
568TypeResult Sema::ActOnPackExpansion(ParsedType Type,
569 SourceLocation EllipsisLoc) {
570 TypeSourceInfo *TSInfo;
571 GetTypeFromParser(Type, &TSInfo);
572 if (!TSInfo)
573 return true;
574
David Blaikie7a30dc52013-02-21 01:47:18 +0000575 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000576 if (!TSResult)
577 return true;
578
579 return CreateParsedType(TSResult->getType(), TSResult);
580}
581
David Blaikie05785d12013-02-20 22:23:23 +0000582TypeSourceInfo *
583Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
584 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +0000585 // Create the pack expansion type and source-location information.
Douglas Gregor822d0302011-01-12 17:07:58 +0000586 QualType Result = CheckPackExpansion(Pattern->getType(),
587 Pattern->getTypeLoc().getSourceRange(),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000588 EllipsisLoc, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000589 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +0000590 return nullptr;
Eli Friedman7152fbe2013-06-07 20:31:48 +0000591
592 TypeLocBuilder TLB;
593 TLB.pushFullCopy(Pattern->getTypeLoc());
594 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000595 TL.setEllipsisLoc(EllipsisLoc);
Eli Friedman7152fbe2013-06-07 20:31:48 +0000596
597 return TLB.getTypeSourceInfo(Context, Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000598}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000599
David Blaikie05785d12013-02-20 22:23:23 +0000600QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000601 SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000602 Optional<unsigned> NumExpansions) {
Douglas Gregor822d0302011-01-12 17:07:58 +0000603 // C++0x [temp.variadic]p5:
604 // The pattern of a pack expansion shall name one or more
605 // parameter packs that are not expanded by a nested pack
606 // expansion.
607 if (!Pattern->containsUnexpandedParameterPack()) {
608 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
609 << PatternRange;
610 return QualType();
611 }
612
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000613 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000614}
615
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000616ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
David Blaikie7a30dc52013-02-21 01:47:18 +0000617 return CheckPackExpansion(Pattern, EllipsisLoc, None);
Douglas Gregorb8840002011-01-14 21:20:45 +0000618}
619
620ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000621 Optional<unsigned> NumExpansions) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000622 if (!Pattern)
623 return ExprError();
624
625 // C++0x [temp.variadic]p5:
626 // The pattern of a pack expansion shall name one or more
627 // parameter packs that are not expanded by a nested pack
628 // expansion.
629 if (!Pattern->containsUnexpandedParameterPack()) {
630 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
631 << Pattern->getSourceRange();
632 return ExprError();
633 }
634
635 // Create the pack expansion expression and source-location information.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000636 return new (Context)
637 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000638}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000639
David Blaikie05785d12013-02-20 22:23:23 +0000640bool Sema::CheckParameterPacksForExpansion(
641 SourceLocation EllipsisLoc, SourceRange PatternRange,
642 ArrayRef<UnexpandedParameterPack> Unexpanded,
643 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
644 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000645 ShouldExpand = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000646 RetainExpansion = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000647 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
648 bool HaveFirstPack = false;
649
David Blaikieb9c168a2011-09-22 02:34:54 +0000650 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
651 end = Unexpanded.end();
652 i != end; ++i) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000653 // Compute the depth and index for this parameter pack.
Ted Kremenek582a0992011-01-23 17:04:59 +0000654 unsigned Depth = 0, Index = 0;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000655 IdentifierInfo *Name;
Douglas Gregorf3010112011-01-07 16:43:16 +0000656 bool IsFunctionParameterPack = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000657
658 if (const TemplateTypeParmType *TTP
David Blaikieb9c168a2011-09-22 02:34:54 +0000659 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000660 Depth = TTP->getDepth();
661 Index = TTP->getIndex();
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000662 Name = TTP->getIdentifier();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000663 } else {
David Blaikieb9c168a2011-09-22 02:34:54 +0000664 NamedDecl *ND = i->first.get<NamedDecl *>();
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000665 if (isa<ParmVarDecl>(ND))
Douglas Gregorf3010112011-01-07 16:43:16 +0000666 IsFunctionParameterPack = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000667 else
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000668 std::tie(Depth, Index) = getDepthAndIndex(ND);
669
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000670 Name = ND->getIdentifier();
671 }
672
Douglas Gregorf3010112011-01-07 16:43:16 +0000673 // Determine the size of this argument pack.
674 unsigned NewPackSize;
675 if (IsFunctionParameterPack) {
676 // Figure out whether we're instantiating to an argument pack or not.
677 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
678
679 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
680 = CurrentInstantiationScope->findInstantiationOf(
David Blaikieb9c168a2011-09-22 02:34:54 +0000681 i->first.get<NamedDecl *>());
Chris Lattner15a776f2011-02-17 19:38:27 +0000682 if (Instantiation->is<DeclArgumentPack *>()) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000683 // We could expand this function parameter pack.
684 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
685 } else {
686 // We can't expand this function parameter pack, so we can't expand
687 // the pack expansion.
688 ShouldExpand = false;
689 continue;
690 }
691 } else {
692 // If we don't have a template argument at this depth/index, then we
693 // cannot expand the pack expansion. Make a note of this, but we still
694 // want to check any parameter packs we *do* have arguments for.
695 if (Depth >= TemplateArgs.getNumLevels() ||
696 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
697 ShouldExpand = false;
698 continue;
699 }
700
701 // Determine the size of the argument pack.
702 NewPackSize = TemplateArgs(Depth, Index).pack_size();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000703 }
704
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000705 // C++0x [temp.arg.explicit]p9:
706 // Template argument deduction can extend the sequence of template
707 // arguments corresponding to a template parameter pack, even when the
708 // sequence contains explicitly specified template arguments.
Olivier Goffarteeba9e42016-05-26 12:55:34 +0000709 if (!IsFunctionParameterPack && CurrentInstantiationScope) {
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000710 if (NamedDecl *PartialPack
711 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
712 unsigned PartialDepth, PartialIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000713 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000714 if (PartialDepth == Depth && PartialIndex == Index)
715 RetainExpansion = true;
716 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000717 }
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000718
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000719 if (!NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000720 // The is the first pack we've seen for which we have an argument.
721 // Record it.
722 NumExpansions = NewPackSize;
723 FirstPack.first = Name;
David Blaikieb9c168a2011-09-22 02:34:54 +0000724 FirstPack.second = i->second;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000725 HaveFirstPack = true;
726 continue;
727 }
728
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000729 if (NewPackSize != *NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000730 // C++0x [temp.variadic]p5:
731 // All of the parameter packs expanded by a pack expansion shall have
732 // the same number of arguments specified.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000733 if (HaveFirstPack)
734 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
735 << FirstPack.first << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000736 << SourceRange(FirstPack.second) << SourceRange(i->second);
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000737 else
738 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
739 << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000740 << SourceRange(i->second);
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000741 return true;
742 }
743 }
Richard Smithc5452ed2016-10-19 22:18:42 +0000744
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000745 return false;
746}
Douglas Gregor27b4c162010-12-23 22:44:42 +0000747
David Blaikie05785d12013-02-20 22:23:23 +0000748Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
Douglas Gregor5cde3862011-01-11 03:14:20 +0000749 const MultiLevelTemplateArgumentList &TemplateArgs) {
750 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000751 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000752 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
753
David Blaikie05785d12013-02-20 22:23:23 +0000754 Optional<unsigned> Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000755 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
756 // Compute the depth and index for this parameter pack.
757 unsigned Depth;
758 unsigned Index;
759
760 if (const TemplateTypeParmType *TTP
761 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
762 Depth = TTP->getDepth();
763 Index = TTP->getIndex();
764 } else {
765 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
766 if (isa<ParmVarDecl>(ND)) {
767 // Function parameter pack.
768 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
769
770 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
771 = CurrentInstantiationScope->findInstantiationOf(
772 Unexpanded[I].first.get<NamedDecl *>());
Richard Smith198223b2012-07-18 01:29:05 +0000773 if (Instantiation->is<Decl*>())
774 // The pattern refers to an unexpanded pack. We're not ready to expand
775 // this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000776 return None;
Richard Smith198223b2012-07-18 01:29:05 +0000777
778 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
779 assert((!Result || *Result == Size) && "inconsistent pack sizes");
780 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000781 continue;
782 }
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000783
784 std::tie(Depth, Index) = getDepthAndIndex(ND);
Douglas Gregor5cde3862011-01-11 03:14:20 +0000785 }
786 if (Depth >= TemplateArgs.getNumLevels() ||
787 !TemplateArgs.hasTemplateArgument(Depth, Index))
Richard Smith198223b2012-07-18 01:29:05 +0000788 // The pattern refers to an unknown template argument. We're not ready to
789 // expand this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000790 return None;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000791
792 // Determine the size of the argument pack.
Richard Smith198223b2012-07-18 01:29:05 +0000793 unsigned Size = TemplateArgs(Depth, Index).pack_size();
794 assert((!Result || *Result == Size) && "inconsistent pack sizes");
795 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000796 }
797
Richard Smith198223b2012-07-18 01:29:05 +0000798 return Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000799}
800
Douglas Gregor27b4c162010-12-23 22:44:42 +0000801bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
802 const DeclSpec &DS = D.getDeclSpec();
803 switch (DS.getTypeSpecType()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000804 case TST_typename:
805 case TST_typeofType:
806 case TST_underlyingType:
807 case TST_atomic: {
Douglas Gregor27b4c162010-12-23 22:44:42 +0000808 QualType T = DS.getRepAsType().get();
809 if (!T.isNull() && T->containsUnexpandedParameterPack())
810 return true;
811 break;
812 }
813
Faisal Vali090da2d2018-01-01 18:23:28 +0000814 case TST_typeofExpr:
815 case TST_decltype:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000816 if (DS.getRepAsExpr() &&
817 DS.getRepAsExpr()->containsUnexpandedParameterPack())
818 return true;
819 break;
820
Faisal Vali090da2d2018-01-01 18:23:28 +0000821 case TST_unspecified:
822 case TST_void:
823 case TST_char:
824 case TST_wchar:
825 case TST_char16:
826 case TST_char32:
827 case TST_int:
828 case TST_int128:
829 case TST_half:
830 case TST_float:
831 case TST_double:
832 case TST_Float16:
833 case TST_float128:
834 case TST_bool:
835 case TST_decimal32:
836 case TST_decimal64:
837 case TST_decimal128:
838 case TST_enum:
839 case TST_union:
840 case TST_struct:
841 case TST_interface:
842 case TST_class:
843 case TST_auto:
844 case TST_auto_type:
845 case TST_decltype_auto:
846#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +0000847#include "clang/Basic/OpenCLImageTypes.def"
Faisal Vali090da2d2018-01-01 18:23:28 +0000848 case TST_unknown_anytype:
849 case TST_error:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000850 break;
851 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000852
Douglas Gregor27b4c162010-12-23 22:44:42 +0000853 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
854 const DeclaratorChunk &Chunk = D.getTypeObject(I);
855 switch (Chunk.Kind) {
856 case DeclaratorChunk::Pointer:
857 case DeclaratorChunk::Reference:
858 case DeclaratorChunk::Paren:
Xiuli Pan9c14e282016-01-09 12:53:17 +0000859 case DeclaratorChunk::Pipe:
Larisse Voufo2e846502014-08-29 21:08:16 +0000860 case DeclaratorChunk::BlockPointer:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000861 // These declarator chunks cannot contain any parameter packs.
862 break;
863
864 case DeclaratorChunk::Array:
Larisse Voufo2e846502014-08-29 21:08:16 +0000865 if (Chunk.Arr.NumElts &&
866 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
867 return true;
868 break;
Douglas Gregor27b4c162010-12-23 22:44:42 +0000869 case DeclaratorChunk::Function:
Larisse Voufo2e846502014-08-29 21:08:16 +0000870 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
871 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
872 QualType ParamTy = Param->getType();
873 assert(!ParamTy.isNull() && "Couldn't parse type?");
874 if (ParamTy->containsUnexpandedParameterPack()) return true;
875 }
876
877 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
Reid Kleckner078aea92016-12-09 17:14:05 +0000878 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
Larisse Voufo2e846502014-08-29 21:08:16 +0000879 if (Chunk.Fun.Exceptions[i]
880 .Ty.get()
881 ->containsUnexpandedParameterPack())
882 return true;
883 }
884 } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
885 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
886 return true;
887
Nico Weber8d26b722014-12-30 02:06:40 +0000888 if (Chunk.Fun.hasTrailingReturnType()) {
889 QualType T = Chunk.Fun.getTrailingReturnType().get();
890 if (!T.isNull() && T->containsUnexpandedParameterPack())
891 return true;
892 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000893 break;
894
Douglas Gregor27b4c162010-12-23 22:44:42 +0000895 case DeclaratorChunk::MemberPointer:
896 if (Chunk.Mem.Scope().getScopeRep() &&
897 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
898 return true;
899 break;
900 }
901 }
902
903 return false;
904}
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000905
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000906namespace {
907
908// Callback to only accept typo corrections that refer to parameter packs.
909class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
910 public:
Craig Toppere14c0f82014-03-12 04:55:44 +0000911 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000912 NamedDecl *ND = candidate.getCorrectionDecl();
913 return ND && ND->isParameterPack();
914 }
915};
916
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000917}
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000918
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000919/// \brief Called when an expression computing the size of a parameter pack
920/// is parsed.
921///
922/// \code
923/// template<typename ...Types> struct count {
924/// static const unsigned value = sizeof...(Types);
925/// };
926/// \endcode
927///
928//
929/// \param OpLoc The location of the "sizeof" keyword.
930/// \param Name The name of the parameter pack whose size will be determined.
931/// \param NameLoc The source location of the name of the parameter pack.
932/// \param RParenLoc The location of the closing parentheses.
933ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
934 SourceLocation OpLoc,
935 IdentifierInfo &Name,
936 SourceLocation NameLoc,
937 SourceLocation RParenLoc) {
938 // C++0x [expr.sizeof]p5:
939 // The identifier in a sizeof... expression shall name a parameter pack.
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000940 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
941 LookupName(R, S);
Craig Topperc3ec1492014-05-26 06:22:03 +0000942
943 NamedDecl *ParameterPack = nullptr;
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000944 switch (R.getResultKind()) {
945 case LookupResult::Found:
946 ParameterPack = R.getFoundDecl();
947 break;
948
949 case LookupResult::NotFound:
950 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000951 if (TypoCorrection Corrected =
952 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
953 llvm::make_unique<ParameterPackValidatorCCC>(),
954 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000955 diagnoseTypo(Corrected,
956 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
957 PDiag(diag::note_parameter_pack_here));
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000958 ParameterPack = Corrected.getCorrectionDecl();
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000959 }
Richard Smithf9b15102013-08-17 00:46:16 +0000960
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000961 case LookupResult::FoundOverloaded:
962 case LookupResult::FoundUnresolvedValue:
963 break;
964
965 case LookupResult::Ambiguous:
966 DiagnoseAmbiguousLookup(R);
967 return ExprError();
968 }
969
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000970 if (!ParameterPack || !ParameterPack->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000971 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
972 << &Name;
973 return ExprError();
974 }
975
Nick Lewycky45b50522013-02-02 00:25:55 +0000976 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
Eli Friedman23b1be92012-03-01 21:32:56 +0000977
Richard Smithd784e682015-09-23 21:41:42 +0000978 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
979 RParenLoc);
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000980}
Eli Friedman94e9eaa2013-06-20 04:11:21 +0000981
982TemplateArgumentLoc
983Sema::getTemplateArgumentPackExpansionPattern(
984 TemplateArgumentLoc OrigLoc,
985 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
986 const TemplateArgument &Argument = OrigLoc.getArgument();
987 assert(Argument.isPackExpansion());
988 switch (Argument.getKind()) {
989 case TemplateArgument::Type: {
990 // FIXME: We shouldn't ever have to worry about missing
991 // type-source info!
992 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
993 if (!ExpansionTSInfo)
994 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
995 Ellipsis);
996 PackExpansionTypeLoc Expansion =
997 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
998 Ellipsis = Expansion.getEllipsisLoc();
999
1000 TypeLoc Pattern = Expansion.getPatternLoc();
1001 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1002
1003 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1004 // TypeSourceInfo.
1005 // FIXME: Find some way to avoid the copy?
1006 TypeLocBuilder TLB;
1007 TLB.pushFullCopy(Pattern);
1008 TypeSourceInfo *PatternTSInfo =
1009 TLB.getTypeSourceInfo(Context, Pattern.getType());
1010 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1011 PatternTSInfo);
1012 }
1013
1014 case TemplateArgument::Expression: {
1015 PackExpansionExpr *Expansion
1016 = cast<PackExpansionExpr>(Argument.getAsExpr());
1017 Expr *Pattern = Expansion->getPattern();
1018 Ellipsis = Expansion->getEllipsisLoc();
1019 NumExpansions = Expansion->getNumExpansions();
1020 return TemplateArgumentLoc(Pattern, Pattern);
1021 }
1022
1023 case TemplateArgument::TemplateExpansion:
1024 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1025 NumExpansions = Argument.getNumTemplateExpansions();
1026 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1027 OrigLoc.getTemplateQualifierLoc(),
1028 OrigLoc.getTemplateNameLoc());
1029
1030 case TemplateArgument::Declaration:
1031 case TemplateArgument::NullPtr:
1032 case TemplateArgument::Template:
1033 case TemplateArgument::Integral:
1034 case TemplateArgument::Pack:
1035 case TemplateArgument::Null:
1036 return TemplateArgumentLoc();
1037 }
1038
1039 llvm_unreachable("Invalid TemplateArgument Kind!");
1040}
Richard Smith0f0af192014-11-08 05:07:16 +00001041
Richard Smithc5452ed2016-10-19 22:18:42 +00001042Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1043 assert(Arg.containsUnexpandedParameterPack());
1044
1045 // If this is a substituted pack, grab that pack. If not, we don't know
1046 // the size yet.
1047 // FIXME: We could find a size in more cases by looking for a substituted
1048 // pack anywhere within this argument, but that's not necessary in the common
1049 // case for 'sizeof...(A)' handling.
1050 TemplateArgument Pack;
1051 switch (Arg.getKind()) {
1052 case TemplateArgument::Type:
1053 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1054 Pack = Subst->getArgumentPack();
1055 else
1056 return None;
1057 break;
1058
1059 case TemplateArgument::Expression:
1060 if (auto *Subst =
1061 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1062 Pack = Subst->getArgumentPack();
1063 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1064 for (ParmVarDecl *PD : *Subst)
1065 if (PD->isParameterPack())
1066 return None;
1067 return Subst->getNumExpansions();
1068 } else
1069 return None;
1070 break;
1071
1072 case TemplateArgument::Template:
1073 if (SubstTemplateTemplateParmPackStorage *Subst =
1074 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1075 Pack = Subst->getArgumentPack();
1076 else
1077 return None;
1078 break;
1079
1080 case TemplateArgument::Declaration:
1081 case TemplateArgument::NullPtr:
1082 case TemplateArgument::TemplateExpansion:
1083 case TemplateArgument::Integral:
1084 case TemplateArgument::Pack:
1085 case TemplateArgument::Null:
1086 return None;
1087 }
1088
1089 // Check that no argument in the pack is itself a pack expansion.
1090 for (TemplateArgument Elem : Pack.pack_elements()) {
1091 // There's no point recursing in this case; we would have already
1092 // expanded this pack expansion into the enclosing pack if we could.
1093 if (Elem.isPackExpansion())
1094 return None;
1095 }
1096 return Pack.pack_size();
1097}
1098
Richard Smith0f0af192014-11-08 05:07:16 +00001099static void CheckFoldOperand(Sema &S, Expr *E) {
1100 if (!E)
1101 return;
1102
1103 E = E->IgnoreImpCasts();
Richard Smith66094432016-10-20 00:55:15 +00001104 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1105 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1106 isa<AbstractConditionalOperator>(E)) {
Richard Smith0f0af192014-11-08 05:07:16 +00001107 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1108 << E->getSourceRange()
1109 << FixItHint::CreateInsertion(E->getLocStart(), "(")
1110 << FixItHint::CreateInsertion(E->getLocEnd(), ")");
1111 }
1112}
1113
1114ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1115 tok::TokenKind Operator,
1116 SourceLocation EllipsisLoc, Expr *RHS,
1117 SourceLocation RParenLoc) {
1118 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1119 // in the parser and reduce down to just cast-expressions here.
1120 CheckFoldOperand(*this, LHS);
1121 CheckFoldOperand(*this, RHS);
1122
Richard Smith90e043d2017-02-15 19:57:10 +00001123 auto DiscardOperands = [&] {
1124 CorrectDelayedTyposInExpr(LHS);
1125 CorrectDelayedTyposInExpr(RHS);
1126 };
1127
Richard Smith0f0af192014-11-08 05:07:16 +00001128 // [expr.prim.fold]p3:
1129 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1130 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1131 // an unexpanded parameter pack, but not both.
1132 if (LHS && RHS &&
1133 LHS->containsUnexpandedParameterPack() ==
1134 RHS->containsUnexpandedParameterPack()) {
Richard Smith90e043d2017-02-15 19:57:10 +00001135 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001136 return Diag(EllipsisLoc,
1137 LHS->containsUnexpandedParameterPack()
1138 ? diag::err_fold_expression_packs_both_sides
1139 : diag::err_pack_expansion_without_parameter_packs)
1140 << LHS->getSourceRange() << RHS->getSourceRange();
1141 }
1142
1143 // [expr.prim.fold]p2:
1144 // In a unary fold, the cast-expression shall contain an unexpanded
1145 // parameter pack.
1146 if (!LHS || !RHS) {
1147 Expr *Pack = LHS ? LHS : RHS;
1148 assert(Pack && "fold expression with neither LHS nor RHS");
Richard Smith90e043d2017-02-15 19:57:10 +00001149 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001150 if (!Pack->containsUnexpandedParameterPack())
1151 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1152 << Pack->getSourceRange();
1153 }
1154
1155 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1156 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
1157}
1158
1159ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1160 BinaryOperatorKind Operator,
1161 SourceLocation EllipsisLoc, Expr *RHS,
1162 SourceLocation RParenLoc) {
1163 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1164 Operator, EllipsisLoc, RHS, RParenLoc);
1165}
1166
1167ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1168 BinaryOperatorKind Operator) {
1169 // [temp.variadic]p9:
1170 // If N is zero for a unary fold-expression, the value of the expression is
Richard Smith0f0af192014-11-08 05:07:16 +00001171 // && -> true
1172 // || -> false
1173 // , -> void()
1174 // if the operator is not listed [above], the instantiation is ill-formed.
1175 //
1176 // Note that we need to use something like int() here, not merely 0, to
1177 // prevent the result from being a null pointer constant.
1178 QualType ScalarType;
1179 switch (Operator) {
Richard Smith0f0af192014-11-08 05:07:16 +00001180 case BO_LOr:
1181 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1182 case BO_LAnd:
1183 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1184 case BO_Comma:
1185 ScalarType = Context.VoidTy;
1186 break;
1187
1188 default:
1189 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1190 << BinaryOperator::getOpcodeStr(Operator);
1191 }
1192
1193 return new (Context) CXXScalarValueInitExpr(
1194 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1195 EllipsisLoc);
1196}