blob: c8bc2c3880974baf180df4c16f4b92ce99f11a1b [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
Douglas Gregor1da294a2010-12-15 19:43:21 +000029namespace {
30 /// \brief A class that collects unexpanded parameter packs.
31 class CollectUnexpandedParameterPacksVisitor :
32 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
33 {
34 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
35 inherited;
36
Chris Lattner0e62c1c2011-07-23 10:55:15 +000037 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +000038
Richard Smith2589b9802012-07-25 03:56:55 +000039 bool InLambda;
40
Douglas Gregor1da294a2010-12-15 19:43:21 +000041 public:
42 explicit CollectUnexpandedParameterPacksVisitor(
Chris Lattner0e62c1c2011-07-23 10:55:15 +000043 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
Richard Smith2589b9802012-07-25 03:56:55 +000044 : Unexpanded(Unexpanded), InLambda(false) { }
Douglas Gregor1da294a2010-12-15 19:43:21 +000045
Douglas Gregor15b4ec22010-12-20 23:07:20 +000046 bool shouldWalkTypesOfTypeLocs() const { return false; }
47
Douglas Gregor1da294a2010-12-15 19:43:21 +000048 //------------------------------------------------------------------------
49 // Recording occurrences of (unexpanded) parameter packs.
50 //------------------------------------------------------------------------
51
52 /// \brief Record occurrences of template type parameter packs.
53 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
54 if (TL.getTypePtr()->isParameterPack())
55 Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
56 return true;
57 }
58
59 /// \brief Record occurrences of template type parameter packs
60 /// when we don't have proper source-location information for
61 /// them.
62 ///
63 /// Ideally, this routine would never be used.
64 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
65 if (T->isParameterPack())
66 Unexpanded.push_back(std::make_pair(T, SourceLocation()));
67
68 return true;
69 }
70
Douglas Gregor476e3022011-01-19 21:32:01 +000071 /// \brief Record occurrences of function and non-type template
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000072 /// parameter packs in an expression.
73 bool VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf3010112011-01-07 16:43:16 +000074 if (E->getDecl()->isParameterPack())
75 Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000076
77 return true;
78 }
79
Douglas Gregorf5500772011-01-05 15:48:55 +000080 /// \brief Record occurrences of template template parameter packs.
81 bool TraverseTemplateName(TemplateName Template) {
82 if (TemplateTemplateParmDecl *TTP
83 = dyn_cast_or_null<TemplateTemplateParmDecl>(
84 Template.getAsTemplateDecl()))
85 if (TTP->isParameterPack())
86 Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
87
88 return inherited::TraverseTemplateName(Template);
89 }
Douglas Gregor1da294a2010-12-15 19:43:21 +000090
Ted Kremeneke65b0862012-03-06 20:05:56 +000091 /// \brief Suppress traversal into Objective-C container literal
92 /// elements that are pack expansions.
93 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
94 if (!E->containsUnexpandedParameterPack())
95 return true;
96
97 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
98 ObjCDictionaryElement Element = E->getKeyValueElement(I);
99 if (Element.isPackExpansion())
100 continue;
101
102 TraverseStmt(Element.Key);
103 TraverseStmt(Element.Value);
104 }
105 return true;
106 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000107 //------------------------------------------------------------------------
108 // Pruning the search for unexpanded parameter packs.
109 //------------------------------------------------------------------------
110
111 /// \brief Suppress traversal into statements and expressions that
112 /// do not contain unexpanded parameter packs.
113 bool TraverseStmt(Stmt *S) {
Richard Smith2589b9802012-07-25 03:56:55 +0000114 Expr *E = dyn_cast_or_null<Expr>(S);
115 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
116 return inherited::TraverseStmt(S);
Douglas Gregor1da294a2010-12-15 19:43:21 +0000117
Richard Smith2589b9802012-07-25 03:56:55 +0000118 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000119 }
120
121 /// \brief Suppress traversal into types that do not contain
122 /// unexpanded parameter packs.
123 bool TraverseType(QualType T) {
Richard Smith2589b9802012-07-25 03:56:55 +0000124 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000125 return inherited::TraverseType(T);
126
127 return true;
128 }
129
130 /// \brief Suppress traversel into types with location information
131 /// that do not contain unexpanded parameter packs.
132 bool TraverseTypeLoc(TypeLoc TL) {
Richard Smith2589b9802012-07-25 03:56:55 +0000133 if ((!TL.getType().isNull() &&
134 TL.getType()->containsUnexpandedParameterPack()) ||
135 InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000136 return inherited::TraverseTypeLoc(TL);
137
138 return true;
139 }
140
Douglas Gregora8461bb2010-12-15 21:57:59 +0000141 /// \brief Suppress traversal of non-parameter declarations, since
142 /// they cannot contain unexpanded parameter packs.
143 bool TraverseDecl(Decl *D) {
Richard Smith2589b9802012-07-25 03:56:55 +0000144 if ((D && isa<ParmVarDecl>(D)) || InLambda)
Douglas Gregora8461bb2010-12-15 21:57:59 +0000145 return inherited::TraverseDecl(D);
146
Richard Smith2589b9802012-07-25 03:56:55 +0000147 return true;
Douglas Gregora8461bb2010-12-15 21:57:59 +0000148 }
Douglas Gregoreb29d182011-01-05 17:40:24 +0000149
150 /// \brief Suppress traversal of template argument pack expansions.
151 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
152 if (Arg.isPackExpansion())
153 return true;
154
155 return inherited::TraverseTemplateArgument(Arg);
156 }
157
158 /// \brief Suppress traversal of template argument pack expansions.
159 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
160 if (ArgLoc.getArgument().isPackExpansion())
161 return true;
162
163 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
164 }
Richard Smith2589b9802012-07-25 03:56:55 +0000165
166 /// \brief Note whether we're traversing a lambda containing an unexpanded
167 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
168 /// including all the places where we normally wouldn't look. Within a
169 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
170 /// outside an expression.
171 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
172 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
173 // even if it's contained within another lambda.
174 if (!Lambda->containsUnexpandedParameterPack())
175 return true;
176
177 bool WasInLambda = InLambda;
178 InLambda = true;
179
180 // If any capture names a function parameter pack, that pack is expanded
181 // when the lambda is expanded.
182 for (LambdaExpr::capture_iterator I = Lambda->capture_begin(),
Richard Smithba71c082013-05-16 06:20:58 +0000183 E = Lambda->capture_end();
184 I != E; ++I) {
185 if (I->capturesVariable()) {
186 VarDecl *VD = I->getCapturedVar();
Richard Smith2589b9802012-07-25 03:56:55 +0000187 if (VD->isParameterPack())
188 Unexpanded.push_back(std::make_pair(VD, I->getLocation()));
Richard Smithba71c082013-05-16 06:20:58 +0000189 }
190 }
Richard Smith2589b9802012-07-25 03:56:55 +0000191
192 inherited::TraverseLambdaExpr(Lambda);
193
194 InLambda = WasInLambda;
195 return true;
196 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000197 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000198}
Douglas Gregor1da294a2010-12-15 19:43:21 +0000199
Richard Smith36ee9fb2014-08-11 23:30:23 +0000200/// \brief Determine whether it's possible for an unexpanded parameter pack to
201/// be valid in this location. This only happens when we're in a declaration
202/// that is nested within an expression that could be expanded, such as a
203/// lambda-expression within a function call.
204///
205/// This is conservatively correct, but may claim that some unexpanded packs are
206/// permitted when they are not.
207bool Sema::isUnexpandedParameterPackPermitted() {
208 for (auto *SI : FunctionScopes)
209 if (isa<sema::LambdaScopeInfo>(SI))
210 return true;
211 return false;
212}
213
Douglas Gregor1da294a2010-12-15 19:43:21 +0000214/// \brief Diagnose all of the unexpanded parameter packs in the given
215/// vector.
Richard Smith2589b9802012-07-25 03:56:55 +0000216bool
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000217Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
218 UnexpandedParameterPackContext UPPC,
Bill Wendling8ac06af2012-02-22 09:38:11 +0000219 ArrayRef<UnexpandedParameterPack> Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000220 if (Unexpanded.empty())
Richard Smith2589b9802012-07-25 03:56:55 +0000221 return false;
222
223 // If we are within a lambda expression, that lambda contains an unexpanded
224 // parameter pack, and we are done.
225 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
226 // later.
227 for (unsigned N = FunctionScopes.size(); N; --N) {
228 if (sema::LambdaScopeInfo *LSI =
229 dyn_cast<sema::LambdaScopeInfo>(FunctionScopes[N-1])) {
230 LSI->ContainsUnexpandedParameterPack = true;
231 return false;
232 }
233 }
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000234
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000235 SmallVector<SourceLocation, 4> Locations;
236 SmallVector<IdentifierInfo *, 4> Names;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000237 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
238
239 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000240 IdentifierInfo *Name = nullptr;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000241 if (const TemplateTypeParmType *TTP
242 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000243 Name = TTP->getIdentifier();
Douglas Gregor1da294a2010-12-15 19:43:21 +0000244 else
245 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
246
David Blaikie82e95a32014-11-19 07:49:47 +0000247 if (Name && NamesKnown.insert(Name).second)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000248 Names.push_back(Name);
249
250 if (Unexpanded[I].second.isValid())
251 Locations.push_back(Unexpanded[I].second);
252 }
253
Benjamin Kramer3a8650a2015-03-27 17:23:14 +0000254 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
255 << (int)UPPC << (int)Names.size();
256 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
257 DB << Names[I];
Douglas Gregor1da294a2010-12-15 19:43:21 +0000258
259 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
260 DB << SourceRange(Locations[I]);
Richard Smith2589b9802012-07-25 03:56:55 +0000261 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000262}
263
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000264bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
265 TypeSourceInfo *T,
266 UnexpandedParameterPackContext UPPC) {
267 // C++0x [temp.variadic]p5:
268 // An appearance of a name of a parameter pack that is not expanded is
269 // ill-formed.
270 if (!T->getType()->containsUnexpandedParameterPack())
271 return false;
272
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000273 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000274 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
275 T->getTypeLoc());
276 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000277 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000278}
279
280bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
Douglas Gregorc4356532010-12-16 00:46:58 +0000281 UnexpandedParameterPackContext UPPC) {
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000282 // C++0x [temp.variadic]p5:
283 // An appearance of a name of a parameter pack that is not expanded is
284 // ill-formed.
285 if (!E->containsUnexpandedParameterPack())
286 return false;
287
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000288 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000289 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
290 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000291 return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000292}
Douglas Gregorc4356532010-12-16 00:46:58 +0000293
294bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
295 UnexpandedParameterPackContext UPPC) {
296 // C++0x [temp.variadic]p5:
297 // An appearance of a name of a parameter pack that is not expanded is
298 // ill-formed.
299 if (!SS.getScopeRep() ||
300 !SS.getScopeRep()->containsUnexpandedParameterPack())
301 return false;
302
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000304 CollectUnexpandedParameterPacksVisitor(Unexpanded)
305 .TraverseNestedNameSpecifier(SS.getScopeRep());
306 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000307 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
308 UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000309}
310
311bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
312 UnexpandedParameterPackContext UPPC) {
313 // C++0x [temp.variadic]p5:
314 // An appearance of a name of a parameter pack that is not expanded is
315 // ill-formed.
316 switch (NameInfo.getName().getNameKind()) {
317 case DeclarationName::Identifier:
318 case DeclarationName::ObjCZeroArgSelector:
319 case DeclarationName::ObjCOneArgSelector:
320 case DeclarationName::ObjCMultiArgSelector:
321 case DeclarationName::CXXOperatorName:
322 case DeclarationName::CXXLiteralOperatorName:
323 case DeclarationName::CXXUsingDirective:
324 return false;
325
326 case DeclarationName::CXXConstructorName:
327 case DeclarationName::CXXDestructorName:
328 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor062ecac2010-12-16 17:19:19 +0000329 // FIXME: We shouldn't need this null check!
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000330 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
331 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
332
333 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
Douglas Gregorc4356532010-12-16 00:46:58 +0000334 return false;
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000335
Douglas Gregorc4356532010-12-16 00:46:58 +0000336 break;
337 }
338
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000340 CollectUnexpandedParameterPacksVisitor(Unexpanded)
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000341 .TraverseType(NameInfo.getName().getCXXNameType());
Douglas Gregorc4356532010-12-16 00:46:58 +0000342 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000343 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000344}
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000345
346bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
347 TemplateName Template,
348 UnexpandedParameterPackContext UPPC) {
349
350 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
351 return false;
352
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000353 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000354 CollectUnexpandedParameterPacksVisitor(Unexpanded)
355 .TraverseTemplateName(Template);
356 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000357 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000358}
359
Douglas Gregor14406932011-01-03 20:35:03 +0000360bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
361 UnexpandedParameterPackContext UPPC) {
362 if (Arg.getArgument().isNull() ||
363 !Arg.getArgument().containsUnexpandedParameterPack())
364 return false;
365
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000366 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor14406932011-01-03 20:35:03 +0000367 CollectUnexpandedParameterPacksVisitor(Unexpanded)
368 .TraverseTemplateArgumentLoc(Arg);
369 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000370 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
Douglas Gregor14406932011-01-03 20:35:03 +0000371}
372
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000373void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000374 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000375 CollectUnexpandedParameterPacksVisitor(Unexpanded)
376 .TraverseTemplateArgument(Arg);
377}
378
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000379void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000380 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000381 CollectUnexpandedParameterPacksVisitor(Unexpanded)
382 .TraverseTemplateArgumentLoc(Arg);
383}
384
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000385void Sema::collectUnexpandedParameterPacks(QualType T,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000386 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000387 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
388}
389
Douglas Gregor752a5952011-01-03 22:36:02 +0000390void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor752a5952011-01-03 22:36:02 +0000392 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
393}
394
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000395void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
396 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
397 NestedNameSpecifier *Qualifier = SS.getScopeRep();
398 if (!Qualifier)
399 return;
400
401 NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
402 CollectUnexpandedParameterPacksVisitor(Unexpanded)
403 .TraverseNestedNameSpecifierLoc(QualifierLoc);
404}
405
406void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
407 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
408 CollectUnexpandedParameterPacksVisitor(Unexpanded)
409 .TraverseDeclarationNameInfo(NameInfo);
410}
411
412
Douglas Gregord2fa7662010-12-20 02:24:11 +0000413ParsedTemplateArgument
414Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
415 SourceLocation EllipsisLoc) {
416 if (Arg.isInvalid())
417 return Arg;
418
419 switch (Arg.getKind()) {
420 case ParsedTemplateArgument::Type: {
421 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
422 if (Result.isInvalid())
423 return ParsedTemplateArgument();
424
425 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
426 Arg.getLocation());
427 }
428
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000429 case ParsedTemplateArgument::NonType: {
430 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
431 if (Result.isInvalid())
432 return ParsedTemplateArgument();
433
434 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
435 Arg.getLocation());
436 }
437
Douglas Gregord2fa7662010-12-20 02:24:11 +0000438 case ParsedTemplateArgument::Template:
Douglas Gregoreb29d182011-01-05 17:40:24 +0000439 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
440 SourceRange R(Arg.getLocation());
441 if (Arg.getScopeSpec().isValid())
442 R.setBegin(Arg.getScopeSpec().getBeginLoc());
443 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
444 << R;
445 return ParsedTemplateArgument();
446 }
447
448 return Arg.getTemplatePackExpansion(EllipsisLoc);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000449 }
450 llvm_unreachable("Unhandled template argument kind?");
Douglas Gregord2fa7662010-12-20 02:24:11 +0000451}
452
453TypeResult Sema::ActOnPackExpansion(ParsedType Type,
454 SourceLocation EllipsisLoc) {
455 TypeSourceInfo *TSInfo;
456 GetTypeFromParser(Type, &TSInfo);
457 if (!TSInfo)
458 return true;
459
David Blaikie7a30dc52013-02-21 01:47:18 +0000460 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000461 if (!TSResult)
462 return true;
463
464 return CreateParsedType(TSResult->getType(), TSResult);
465}
466
David Blaikie05785d12013-02-20 22:23:23 +0000467TypeSourceInfo *
468Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
469 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +0000470 // Create the pack expansion type and source-location information.
Douglas Gregor822d0302011-01-12 17:07:58 +0000471 QualType Result = CheckPackExpansion(Pattern->getType(),
472 Pattern->getTypeLoc().getSourceRange(),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000473 EllipsisLoc, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000474 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +0000475 return nullptr;
Eli Friedman7152fbe2013-06-07 20:31:48 +0000476
477 TypeLocBuilder TLB;
478 TLB.pushFullCopy(Pattern->getTypeLoc());
479 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000480 TL.setEllipsisLoc(EllipsisLoc);
Eli Friedman7152fbe2013-06-07 20:31:48 +0000481
482 return TLB.getTypeSourceInfo(Context, Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000483}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000484
David Blaikie05785d12013-02-20 22:23:23 +0000485QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000486 SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000487 Optional<unsigned> NumExpansions) {
Douglas Gregor822d0302011-01-12 17:07:58 +0000488 // C++0x [temp.variadic]p5:
489 // The pattern of a pack expansion shall name one or more
490 // parameter packs that are not expanded by a nested pack
491 // expansion.
492 if (!Pattern->containsUnexpandedParameterPack()) {
493 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
494 << PatternRange;
495 return QualType();
496 }
497
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000498 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000499}
500
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000501ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
David Blaikie7a30dc52013-02-21 01:47:18 +0000502 return CheckPackExpansion(Pattern, EllipsisLoc, None);
Douglas Gregorb8840002011-01-14 21:20:45 +0000503}
504
505ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000506 Optional<unsigned> NumExpansions) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000507 if (!Pattern)
508 return ExprError();
509
510 // C++0x [temp.variadic]p5:
511 // The pattern of a pack expansion shall name one or more
512 // parameter packs that are not expanded by a nested pack
513 // expansion.
514 if (!Pattern->containsUnexpandedParameterPack()) {
515 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
516 << Pattern->getSourceRange();
517 return ExprError();
518 }
519
520 // Create the pack expansion expression and source-location information.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000521 return new (Context)
522 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000523}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000524
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000525/// \brief Retrieve the depth and index of a parameter pack.
526static std::pair<unsigned, unsigned>
527getDepthAndIndex(NamedDecl *ND) {
528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
529 return std::make_pair(TTP->getDepth(), TTP->getIndex());
530
531 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
532 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
533
534 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
535 return std::make_pair(TTP->getDepth(), TTP->getIndex());
536}
537
David Blaikie05785d12013-02-20 22:23:23 +0000538bool Sema::CheckParameterPacksForExpansion(
539 SourceLocation EllipsisLoc, SourceRange PatternRange,
540 ArrayRef<UnexpandedParameterPack> Unexpanded,
541 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
542 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000543 ShouldExpand = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000544 RetainExpansion = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000545 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
546 bool HaveFirstPack = false;
547
David Blaikieb9c168a2011-09-22 02:34:54 +0000548 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
549 end = Unexpanded.end();
550 i != end; ++i) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000551 // Compute the depth and index for this parameter pack.
Ted Kremenek582a0992011-01-23 17:04:59 +0000552 unsigned Depth = 0, Index = 0;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000553 IdentifierInfo *Name;
Douglas Gregorf3010112011-01-07 16:43:16 +0000554 bool IsFunctionParameterPack = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000555
556 if (const TemplateTypeParmType *TTP
David Blaikieb9c168a2011-09-22 02:34:54 +0000557 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000558 Depth = TTP->getDepth();
559 Index = TTP->getIndex();
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000560 Name = TTP->getIdentifier();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000561 } else {
David Blaikieb9c168a2011-09-22 02:34:54 +0000562 NamedDecl *ND = i->first.get<NamedDecl *>();
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000563 if (isa<ParmVarDecl>(ND))
Douglas Gregorf3010112011-01-07 16:43:16 +0000564 IsFunctionParameterPack = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000565 else
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000566 std::tie(Depth, Index) = getDepthAndIndex(ND);
567
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000568 Name = ND->getIdentifier();
569 }
570
Douglas Gregorf3010112011-01-07 16:43:16 +0000571 // Determine the size of this argument pack.
572 unsigned NewPackSize;
573 if (IsFunctionParameterPack) {
574 // Figure out whether we're instantiating to an argument pack or not.
575 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
576
577 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
578 = CurrentInstantiationScope->findInstantiationOf(
David Blaikieb9c168a2011-09-22 02:34:54 +0000579 i->first.get<NamedDecl *>());
Chris Lattner15a776f2011-02-17 19:38:27 +0000580 if (Instantiation->is<DeclArgumentPack *>()) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000581 // We could expand this function parameter pack.
582 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
583 } else {
584 // We can't expand this function parameter pack, so we can't expand
585 // the pack expansion.
586 ShouldExpand = false;
587 continue;
588 }
589 } else {
590 // If we don't have a template argument at this depth/index, then we
591 // cannot expand the pack expansion. Make a note of this, but we still
592 // want to check any parameter packs we *do* have arguments for.
593 if (Depth >= TemplateArgs.getNumLevels() ||
594 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
595 ShouldExpand = false;
596 continue;
597 }
598
599 // Determine the size of the argument pack.
600 NewPackSize = TemplateArgs(Depth, Index).pack_size();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000601 }
602
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000603 // C++0x [temp.arg.explicit]p9:
604 // Template argument deduction can extend the sequence of template
605 // arguments corresponding to a template parameter pack, even when the
606 // sequence contains explicitly specified template arguments.
Olivier Goffarteeba9e42016-05-26 12:55:34 +0000607 if (!IsFunctionParameterPack && CurrentInstantiationScope) {
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000608 if (NamedDecl *PartialPack
609 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
610 unsigned PartialDepth, PartialIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000611 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000612 if (PartialDepth == Depth && PartialIndex == Index)
613 RetainExpansion = true;
614 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000615 }
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000616
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000617 if (!NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000618 // The is the first pack we've seen for which we have an argument.
619 // Record it.
620 NumExpansions = NewPackSize;
621 FirstPack.first = Name;
David Blaikieb9c168a2011-09-22 02:34:54 +0000622 FirstPack.second = i->second;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000623 HaveFirstPack = true;
624 continue;
625 }
626
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000627 if (NewPackSize != *NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000628 // C++0x [temp.variadic]p5:
629 // All of the parameter packs expanded by a pack expansion shall have
630 // the same number of arguments specified.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000631 if (HaveFirstPack)
632 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
633 << FirstPack.first << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000634 << SourceRange(FirstPack.second) << SourceRange(i->second);
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000635 else
636 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
637 << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000638 << SourceRange(i->second);
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000639 return true;
640 }
641 }
Richard Smithc5452ed2016-10-19 22:18:42 +0000642
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000643 return false;
644}
Douglas Gregor27b4c162010-12-23 22:44:42 +0000645
David Blaikie05785d12013-02-20 22:23:23 +0000646Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
Douglas Gregor5cde3862011-01-11 03:14:20 +0000647 const MultiLevelTemplateArgumentList &TemplateArgs) {
648 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000649 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000650 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
651
David Blaikie05785d12013-02-20 22:23:23 +0000652 Optional<unsigned> Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000653 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
654 // Compute the depth and index for this parameter pack.
655 unsigned Depth;
656 unsigned Index;
657
658 if (const TemplateTypeParmType *TTP
659 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
660 Depth = TTP->getDepth();
661 Index = TTP->getIndex();
662 } else {
663 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
664 if (isa<ParmVarDecl>(ND)) {
665 // Function parameter pack.
666 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
667
668 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
669 = CurrentInstantiationScope->findInstantiationOf(
670 Unexpanded[I].first.get<NamedDecl *>());
Richard Smith198223b2012-07-18 01:29:05 +0000671 if (Instantiation->is<Decl*>())
672 // The pattern refers to an unexpanded pack. We're not ready to expand
673 // this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000674 return None;
Richard Smith198223b2012-07-18 01:29:05 +0000675
676 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
677 assert((!Result || *Result == Size) && "inconsistent pack sizes");
678 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000679 continue;
680 }
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000681
682 std::tie(Depth, Index) = getDepthAndIndex(ND);
Douglas Gregor5cde3862011-01-11 03:14:20 +0000683 }
684 if (Depth >= TemplateArgs.getNumLevels() ||
685 !TemplateArgs.hasTemplateArgument(Depth, Index))
Richard Smith198223b2012-07-18 01:29:05 +0000686 // The pattern refers to an unknown template argument. We're not ready to
687 // expand this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000688 return None;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000689
690 // Determine the size of the argument pack.
Richard Smith198223b2012-07-18 01:29:05 +0000691 unsigned Size = TemplateArgs(Depth, Index).pack_size();
692 assert((!Result || *Result == Size) && "inconsistent pack sizes");
693 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000694 }
695
Richard Smith198223b2012-07-18 01:29:05 +0000696 return Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000697}
698
Douglas Gregor27b4c162010-12-23 22:44:42 +0000699bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
700 const DeclSpec &DS = D.getDeclSpec();
701 switch (DS.getTypeSpecType()) {
702 case TST_typename:
Alexis Hunt4a257072011-05-19 05:37:45 +0000703 case TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +0000704 case TST_underlyingType:
705 case TST_atomic: {
Douglas Gregor27b4c162010-12-23 22:44:42 +0000706 QualType T = DS.getRepAsType().get();
707 if (!T.isNull() && T->containsUnexpandedParameterPack())
708 return true;
709 break;
710 }
711
712 case TST_typeofExpr:
713 case TST_decltype:
714 if (DS.getRepAsExpr() &&
715 DS.getRepAsExpr()->containsUnexpandedParameterPack())
716 return true;
717 break;
718
719 case TST_unspecified:
720 case TST_void:
721 case TST_char:
722 case TST_wchar:
723 case TST_char16:
724 case TST_char32:
725 case TST_int:
Richard Smithf016bbc2012-04-04 06:24:32 +0000726 case TST_int128:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000727 case TST_half:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000728 case TST_float:
729 case TST_double:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000730 case TST_float128:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000731 case TST_bool:
732 case TST_decimal32:
733 case TST_decimal64:
734 case TST_decimal128:
735 case TST_enum:
736 case TST_union:
737 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +0000738 case TST_interface:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000739 case TST_class:
740 case TST_auto:
Richard Smithe301ba22015-11-11 02:02:15 +0000741 case TST_auto_type:
Richard Smith74aeef52013-04-26 16:15:35 +0000742 case TST_decltype_auto:
Alexey Bader954ba212016-04-08 13:40:33 +0000743#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +0000744#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +0000745 case TST_unknown_anytype:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000746 case TST_error:
747 break;
748 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000749
Douglas Gregor27b4c162010-12-23 22:44:42 +0000750 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
751 const DeclaratorChunk &Chunk = D.getTypeObject(I);
752 switch (Chunk.Kind) {
753 case DeclaratorChunk::Pointer:
754 case DeclaratorChunk::Reference:
755 case DeclaratorChunk::Paren:
Xiuli Pan9c14e282016-01-09 12:53:17 +0000756 case DeclaratorChunk::Pipe:
Larisse Voufo2e846502014-08-29 21:08:16 +0000757 case DeclaratorChunk::BlockPointer:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000758 // These declarator chunks cannot contain any parameter packs.
759 break;
760
761 case DeclaratorChunk::Array:
Larisse Voufo2e846502014-08-29 21:08:16 +0000762 if (Chunk.Arr.NumElts &&
763 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
764 return true;
765 break;
Douglas Gregor27b4c162010-12-23 22:44:42 +0000766 case DeclaratorChunk::Function:
Larisse Voufo2e846502014-08-29 21:08:16 +0000767 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
768 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
769 QualType ParamTy = Param->getType();
770 assert(!ParamTy.isNull() && "Couldn't parse type?");
771 if (ParamTy->containsUnexpandedParameterPack()) return true;
772 }
773
774 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
Reid Kleckner078aea92016-12-09 17:14:05 +0000775 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
Larisse Voufo2e846502014-08-29 21:08:16 +0000776 if (Chunk.Fun.Exceptions[i]
777 .Ty.get()
778 ->containsUnexpandedParameterPack())
779 return true;
780 }
781 } else if (Chunk.Fun.getExceptionSpecType() == EST_ComputedNoexcept &&
782 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
783 return true;
784
Nico Weber8d26b722014-12-30 02:06:40 +0000785 if (Chunk.Fun.hasTrailingReturnType()) {
786 QualType T = Chunk.Fun.getTrailingReturnType().get();
787 if (!T.isNull() && T->containsUnexpandedParameterPack())
788 return true;
789 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000790 break;
791
Douglas Gregor27b4c162010-12-23 22:44:42 +0000792 case DeclaratorChunk::MemberPointer:
793 if (Chunk.Mem.Scope().getScopeRep() &&
794 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
795 return true;
796 break;
797 }
798 }
799
800 return false;
801}
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000802
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000803namespace {
804
805// Callback to only accept typo corrections that refer to parameter packs.
806class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
807 public:
Craig Toppere14c0f82014-03-12 04:55:44 +0000808 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000809 NamedDecl *ND = candidate.getCorrectionDecl();
810 return ND && ND->isParameterPack();
811 }
812};
813
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000814}
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000815
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000816/// \brief Called when an expression computing the size of a parameter pack
817/// is parsed.
818///
819/// \code
820/// template<typename ...Types> struct count {
821/// static const unsigned value = sizeof...(Types);
822/// };
823/// \endcode
824///
825//
826/// \param OpLoc The location of the "sizeof" keyword.
827/// \param Name The name of the parameter pack whose size will be determined.
828/// \param NameLoc The source location of the name of the parameter pack.
829/// \param RParenLoc The location of the closing parentheses.
830ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
831 SourceLocation OpLoc,
832 IdentifierInfo &Name,
833 SourceLocation NameLoc,
834 SourceLocation RParenLoc) {
835 // C++0x [expr.sizeof]p5:
836 // The identifier in a sizeof... expression shall name a parameter pack.
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000837 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
838 LookupName(R, S);
Craig Topperc3ec1492014-05-26 06:22:03 +0000839
840 NamedDecl *ParameterPack = nullptr;
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000841 switch (R.getResultKind()) {
842 case LookupResult::Found:
843 ParameterPack = R.getFoundDecl();
844 break;
845
846 case LookupResult::NotFound:
847 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000848 if (TypoCorrection Corrected =
849 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
850 llvm::make_unique<ParameterPackValidatorCCC>(),
851 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000852 diagnoseTypo(Corrected,
853 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
854 PDiag(diag::note_parameter_pack_here));
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000855 ParameterPack = Corrected.getCorrectionDecl();
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000856 }
Richard Smithf9b15102013-08-17 00:46:16 +0000857
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000858 case LookupResult::FoundOverloaded:
859 case LookupResult::FoundUnresolvedValue:
860 break;
861
862 case LookupResult::Ambiguous:
863 DiagnoseAmbiguousLookup(R);
864 return ExprError();
865 }
866
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000867 if (!ParameterPack || !ParameterPack->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000868 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
869 << &Name;
870 return ExprError();
871 }
872
Nick Lewycky45b50522013-02-02 00:25:55 +0000873 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
Eli Friedman23b1be92012-03-01 21:32:56 +0000874
Richard Smithd784e682015-09-23 21:41:42 +0000875 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
876 RParenLoc);
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000877}
Eli Friedman94e9eaa2013-06-20 04:11:21 +0000878
879TemplateArgumentLoc
880Sema::getTemplateArgumentPackExpansionPattern(
881 TemplateArgumentLoc OrigLoc,
882 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
883 const TemplateArgument &Argument = OrigLoc.getArgument();
884 assert(Argument.isPackExpansion());
885 switch (Argument.getKind()) {
886 case TemplateArgument::Type: {
887 // FIXME: We shouldn't ever have to worry about missing
888 // type-source info!
889 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
890 if (!ExpansionTSInfo)
891 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
892 Ellipsis);
893 PackExpansionTypeLoc Expansion =
894 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
895 Ellipsis = Expansion.getEllipsisLoc();
896
897 TypeLoc Pattern = Expansion.getPatternLoc();
898 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
899
900 // We need to copy the TypeLoc because TemplateArgumentLocs store a
901 // TypeSourceInfo.
902 // FIXME: Find some way to avoid the copy?
903 TypeLocBuilder TLB;
904 TLB.pushFullCopy(Pattern);
905 TypeSourceInfo *PatternTSInfo =
906 TLB.getTypeSourceInfo(Context, Pattern.getType());
907 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
908 PatternTSInfo);
909 }
910
911 case TemplateArgument::Expression: {
912 PackExpansionExpr *Expansion
913 = cast<PackExpansionExpr>(Argument.getAsExpr());
914 Expr *Pattern = Expansion->getPattern();
915 Ellipsis = Expansion->getEllipsisLoc();
916 NumExpansions = Expansion->getNumExpansions();
917 return TemplateArgumentLoc(Pattern, Pattern);
918 }
919
920 case TemplateArgument::TemplateExpansion:
921 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
922 NumExpansions = Argument.getNumTemplateExpansions();
923 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
924 OrigLoc.getTemplateQualifierLoc(),
925 OrigLoc.getTemplateNameLoc());
926
927 case TemplateArgument::Declaration:
928 case TemplateArgument::NullPtr:
929 case TemplateArgument::Template:
930 case TemplateArgument::Integral:
931 case TemplateArgument::Pack:
932 case TemplateArgument::Null:
933 return TemplateArgumentLoc();
934 }
935
936 llvm_unreachable("Invalid TemplateArgument Kind!");
937}
Richard Smith0f0af192014-11-08 05:07:16 +0000938
Richard Smithc5452ed2016-10-19 22:18:42 +0000939Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
940 assert(Arg.containsUnexpandedParameterPack());
941
942 // If this is a substituted pack, grab that pack. If not, we don't know
943 // the size yet.
944 // FIXME: We could find a size in more cases by looking for a substituted
945 // pack anywhere within this argument, but that's not necessary in the common
946 // case for 'sizeof...(A)' handling.
947 TemplateArgument Pack;
948 switch (Arg.getKind()) {
949 case TemplateArgument::Type:
950 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
951 Pack = Subst->getArgumentPack();
952 else
953 return None;
954 break;
955
956 case TemplateArgument::Expression:
957 if (auto *Subst =
958 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
959 Pack = Subst->getArgumentPack();
960 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
961 for (ParmVarDecl *PD : *Subst)
962 if (PD->isParameterPack())
963 return None;
964 return Subst->getNumExpansions();
965 } else
966 return None;
967 break;
968
969 case TemplateArgument::Template:
970 if (SubstTemplateTemplateParmPackStorage *Subst =
971 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
972 Pack = Subst->getArgumentPack();
973 else
974 return None;
975 break;
976
977 case TemplateArgument::Declaration:
978 case TemplateArgument::NullPtr:
979 case TemplateArgument::TemplateExpansion:
980 case TemplateArgument::Integral:
981 case TemplateArgument::Pack:
982 case TemplateArgument::Null:
983 return None;
984 }
985
986 // Check that no argument in the pack is itself a pack expansion.
987 for (TemplateArgument Elem : Pack.pack_elements()) {
988 // There's no point recursing in this case; we would have already
989 // expanded this pack expansion into the enclosing pack if we could.
990 if (Elem.isPackExpansion())
991 return None;
992 }
993 return Pack.pack_size();
994}
995
Richard Smith0f0af192014-11-08 05:07:16 +0000996static void CheckFoldOperand(Sema &S, Expr *E) {
997 if (!E)
998 return;
999
1000 E = E->IgnoreImpCasts();
Richard Smith66094432016-10-20 00:55:15 +00001001 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1002 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1003 isa<AbstractConditionalOperator>(E)) {
Richard Smith0f0af192014-11-08 05:07:16 +00001004 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1005 << E->getSourceRange()
1006 << FixItHint::CreateInsertion(E->getLocStart(), "(")
1007 << FixItHint::CreateInsertion(E->getLocEnd(), ")");
1008 }
1009}
1010
1011ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1012 tok::TokenKind Operator,
1013 SourceLocation EllipsisLoc, Expr *RHS,
1014 SourceLocation RParenLoc) {
1015 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1016 // in the parser and reduce down to just cast-expressions here.
1017 CheckFoldOperand(*this, LHS);
1018 CheckFoldOperand(*this, RHS);
1019
1020 // [expr.prim.fold]p3:
1021 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1022 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1023 // an unexpanded parameter pack, but not both.
1024 if (LHS && RHS &&
1025 LHS->containsUnexpandedParameterPack() ==
1026 RHS->containsUnexpandedParameterPack()) {
1027 return Diag(EllipsisLoc,
1028 LHS->containsUnexpandedParameterPack()
1029 ? diag::err_fold_expression_packs_both_sides
1030 : diag::err_pack_expansion_without_parameter_packs)
1031 << LHS->getSourceRange() << RHS->getSourceRange();
1032 }
1033
1034 // [expr.prim.fold]p2:
1035 // In a unary fold, the cast-expression shall contain an unexpanded
1036 // parameter pack.
1037 if (!LHS || !RHS) {
1038 Expr *Pack = LHS ? LHS : RHS;
1039 assert(Pack && "fold expression with neither LHS nor RHS");
1040 if (!Pack->containsUnexpandedParameterPack())
1041 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1042 << Pack->getSourceRange();
1043 }
1044
1045 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1046 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
1047}
1048
1049ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1050 BinaryOperatorKind Operator,
1051 SourceLocation EllipsisLoc, Expr *RHS,
1052 SourceLocation RParenLoc) {
1053 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1054 Operator, EllipsisLoc, RHS, RParenLoc);
1055}
1056
1057ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1058 BinaryOperatorKind Operator) {
1059 // [temp.variadic]p9:
1060 // If N is zero for a unary fold-expression, the value of the expression is
Richard Smith0f0af192014-11-08 05:07:16 +00001061 // && -> true
1062 // || -> false
1063 // , -> void()
1064 // if the operator is not listed [above], the instantiation is ill-formed.
1065 //
1066 // Note that we need to use something like int() here, not merely 0, to
1067 // prevent the result from being a null pointer constant.
1068 QualType ScalarType;
1069 switch (Operator) {
Richard Smith0f0af192014-11-08 05:07:16 +00001070 case BO_LOr:
1071 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1072 case BO_LAnd:
1073 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1074 case BO_Comma:
1075 ScalarType = Context.VoidTy;
1076 break;
1077
1078 default:
1079 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1080 << BinaryOperator::getOpcodeStr(Operator);
1081 }
1082
1083 return new (Context) CXXScalarValueInitExpr(
1084 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1085 EllipsisLoc);
1086}