blob: 6f9dddf5c05ec919fa10279decc068c027134408 [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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// A class that collects unexpanded parameter packs.
Douglas Gregor1da294a2010-12-15 19:43:21 +000031 class CollectUnexpandedParameterPacksVisitor :
Fangrui Song6907ce22018-07-30 19:24:48 +000032 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
Douglas Gregor1da294a2010-12-15 19:43:21 +000033 {
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 Smith78a07ba2017-08-15 19:11:21 +000039 bool InLambda = false;
40 unsigned DepthLimit = (unsigned)-1;
Richard Smith2589b9802012-07-25 03:56:55 +000041
Richard Smith78a07ba2017-08-15 19:11:21 +000042 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
43 if (auto *PVD = dyn_cast<ParmVarDecl>(ND)) {
44 // For now, the only problematic case is a generic lambda's templated
45 // call operator, so we don't need to look for all the other ways we
46 // could have reached a dependent parameter pack.
47 auto *FD = dyn_cast<FunctionDecl>(PVD->getDeclContext());
48 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
49 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
50 return;
51 } else if (getDepthAndIndex(ND).first >= DepthLimit)
52 return;
53
54 Unexpanded.push_back({ND, Loc});
55 }
56 void addUnexpanded(const TemplateTypeParmType *T,
57 SourceLocation Loc = SourceLocation()) {
58 if (T->getDepth() < DepthLimit)
59 Unexpanded.push_back({T, Loc});
60 }
Fangrui Song6907ce22018-07-30 19:24:48 +000061
Douglas Gregor1da294a2010-12-15 19:43:21 +000062 public:
63 explicit CollectUnexpandedParameterPacksVisitor(
Richard Smith78a07ba2017-08-15 19:11:21 +000064 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
65 : Unexpanded(Unexpanded) {}
Douglas Gregor1da294a2010-12-15 19:43:21 +000066
Douglas Gregor15b4ec22010-12-20 23:07:20 +000067 bool shouldWalkTypesOfTypeLocs() const { return false; }
Richard Smith78a07ba2017-08-15 19:11:21 +000068
Douglas Gregor1da294a2010-12-15 19:43:21 +000069 //------------------------------------------------------------------------
70 // Recording occurrences of (unexpanded) parameter packs.
71 //------------------------------------------------------------------------
72
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073 /// Record occurrences of template type parameter packs.
Douglas Gregor1da294a2010-12-15 19:43:21 +000074 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
75 if (TL.getTypePtr()->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000076 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
Douglas Gregor1da294a2010-12-15 19:43:21 +000077 return true;
78 }
79
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Record occurrences of template type parameter packs
Douglas Gregor1da294a2010-12-15 19:43:21 +000081 /// when we don't have proper source-location information for
82 /// them.
83 ///
84 /// Ideally, this routine would never be used.
85 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
86 if (T->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000087 addUnexpanded(T);
Douglas Gregor1da294a2010-12-15 19:43:21 +000088
89 return true;
90 }
91
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Record occurrences of function and non-type template
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000093 /// parameter packs in an expression.
94 bool VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf3010112011-01-07 16:43:16 +000095 if (E->getDecl()->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000096 addUnexpanded(E->getDecl(), E->getLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +000097
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000098 return true;
99 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000101 /// Record occurrences of template template parameter packs.
Douglas Gregorf5500772011-01-05 15:48:55 +0000102 bool TraverseTemplateName(TemplateName Template) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000103 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
104 Template.getAsTemplateDecl())) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000105 if (TTP->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000106 addUnexpanded(TTP);
107 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000108
Douglas Gregorf5500772011-01-05 15:48:55 +0000109 return inherited::TraverseTemplateName(Template);
110 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112 /// Suppress traversal into Objective-C container literal
Ted Kremeneke65b0862012-03-06 20:05:56 +0000113 /// elements that are pack expansions.
114 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
115 if (!E->containsUnexpandedParameterPack())
116 return true;
117
118 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
119 ObjCDictionaryElement Element = E->getKeyValueElement(I);
120 if (Element.isPackExpansion())
121 continue;
122
123 TraverseStmt(Element.Key);
124 TraverseStmt(Element.Value);
125 }
126 return true;
127 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000128 //------------------------------------------------------------------------
129 // Pruning the search for unexpanded parameter packs.
130 //------------------------------------------------------------------------
131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132 /// Suppress traversal into statements and expressions that
Douglas Gregor1da294a2010-12-15 19:43:21 +0000133 /// do not contain unexpanded parameter packs.
Fangrui Song6907ce22018-07-30 19:24:48 +0000134 bool TraverseStmt(Stmt *S) {
Richard Smith2589b9802012-07-25 03:56:55 +0000135 Expr *E = dyn_cast_or_null<Expr>(S);
136 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
137 return inherited::TraverseStmt(S);
Douglas Gregor1da294a2010-12-15 19:43:21 +0000138
Richard Smith2589b9802012-07-25 03:56:55 +0000139 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000140 }
141
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000142 /// Suppress traversal into types that do not contain
Douglas Gregor1da294a2010-12-15 19:43:21 +0000143 /// unexpanded parameter packs.
144 bool TraverseType(QualType T) {
Richard Smith2589b9802012-07-25 03:56:55 +0000145 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000146 return inherited::TraverseType(T);
147
148 return true;
149 }
150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000151 /// Suppress traversal into types with location information
Douglas Gregor1da294a2010-12-15 19:43:21 +0000152 /// that do not contain unexpanded parameter packs.
153 bool TraverseTypeLoc(TypeLoc TL) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000154 if ((!TL.getType().isNull() &&
Richard Smith2589b9802012-07-25 03:56:55 +0000155 TL.getType()->containsUnexpandedParameterPack()) ||
156 InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000157 return inherited::TraverseTypeLoc(TL);
158
159 return true;
160 }
161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000162 /// Suppress traversal of parameter packs.
Fangrui Song6907ce22018-07-30 19:24:48 +0000163 bool TraverseDecl(Decl *D) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000164 // A function parameter pack is a pack expansion, so cannot contain
Richard Smithf26d5512017-08-15 22:58:45 +0000165 // an unexpanded parameter pack. Likewise for a template parameter
166 // pack that contains any references to other packs.
167 if (D->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000168 return true;
169
Richard Smithf26d5512017-08-15 22:58:45 +0000170 return inherited::TraverseDecl(D);
171 }
Douglas Gregora8461bb2010-12-15 21:57:59 +0000172
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000173 /// Suppress traversal of pack-expanded attributes.
Richard Smithf26d5512017-08-15 22:58:45 +0000174 bool TraverseAttr(Attr *A) {
175 if (A->isPackExpansion())
176 return true;
177
178 return inherited::TraverseAttr(A);
179 }
180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000181 /// Suppress traversal of pack expansion expressions and types.
Richard Smithf26d5512017-08-15 22:58:45 +0000182 ///@{
183 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
184 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
185 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
186 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
187
188 ///@}
189
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000190 /// Suppress traversal of using-declaration pack expansion.
Richard Smithf26d5512017-08-15 22:58:45 +0000191 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
192 if (D->isPackExpansion())
193 return true;
194
195 return inherited::TraverseUnresolvedUsingValueDecl(D);
196 }
197
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000198 /// Suppress traversal of using-declaration pack expansion.
Richard Smithf26d5512017-08-15 22:58:45 +0000199 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
200 if (D->isPackExpansion())
201 return true;
202
203 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
Douglas Gregora8461bb2010-12-15 21:57:59 +0000204 }
Douglas Gregoreb29d182011-01-05 17:40:24 +0000205
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000206 /// Suppress traversal of template argument pack expansions.
Douglas Gregoreb29d182011-01-05 17:40:24 +0000207 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
208 if (Arg.isPackExpansion())
209 return true;
210
211 return inherited::TraverseTemplateArgument(Arg);
212 }
213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// Suppress traversal of template argument pack expansions.
Douglas Gregoreb29d182011-01-05 17:40:24 +0000215 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
216 if (ArgLoc.getArgument().isPackExpansion())
217 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000218
Douglas Gregoreb29d182011-01-05 17:40:24 +0000219 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
220 }
Richard Smith2589b9802012-07-25 03:56:55 +0000221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000222 /// Suppress traversal of base specifier pack expansions.
Richard Smithf26d5512017-08-15 22:58:45 +0000223 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
224 if (Base.isPackExpansion())
225 return true;
226
227 return inherited::TraverseCXXBaseSpecifier(Base);
228 }
229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000230 /// Suppress traversal of mem-initializer pack expansions.
Richard Smithf26d5512017-08-15 22:58:45 +0000231 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
232 if (Init->isPackExpansion())
233 return true;
234
235 return inherited::TraverseConstructorInitializer(Init);
236 }
237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000238 /// Note whether we're traversing a lambda containing an unexpanded
Richard Smith2589b9802012-07-25 03:56:55 +0000239 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
240 /// including all the places where we normally wouldn't look. Within a
241 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
242 /// outside an expression.
243 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
244 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
245 // even if it's contained within another lambda.
246 if (!Lambda->containsUnexpandedParameterPack())
247 return true;
248
249 bool WasInLambda = InLambda;
Richard Smith78a07ba2017-08-15 19:11:21 +0000250 unsigned OldDepthLimit = DepthLimit;
Richard Smith2589b9802012-07-25 03:56:55 +0000251
Richard Smith78a07ba2017-08-15 19:11:21 +0000252 InLambda = true;
253 if (auto *TPL = Lambda->getTemplateParameterList())
254 DepthLimit = TPL->getDepth();
Richard Smith2589b9802012-07-25 03:56:55 +0000255
256 inherited::TraverseLambdaExpr(Lambda);
257
258 InLambda = WasInLambda;
Richard Smith78a07ba2017-08-15 19:11:21 +0000259 DepthLimit = OldDepthLimit;
Richard Smith2589b9802012-07-25 03:56:55 +0000260 return true;
261 }
Richard Smith78a07ba2017-08-15 19:11:21 +0000262
263 /// Suppress traversal within pack expansions in lambda captures.
264 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
265 Expr *Init) {
266 if (C->isPackExpansion())
267 return true;
Richard Smithf26d5512017-08-15 22:58:45 +0000268
Richard Smith78a07ba2017-08-15 19:11:21 +0000269 return inherited::TraverseLambdaCapture(Lambda, C, Init);
270 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000271 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000272}
Douglas Gregor1da294a2010-12-15 19:43:21 +0000273
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000274/// Determine whether it's possible for an unexpanded parameter pack to
Richard Smith36ee9fb2014-08-11 23:30:23 +0000275/// be valid in this location. This only happens when we're in a declaration
276/// that is nested within an expression that could be expanded, such as a
277/// lambda-expression within a function call.
278///
279/// This is conservatively correct, but may claim that some unexpanded packs are
280/// permitted when they are not.
281bool Sema::isUnexpandedParameterPackPermitted() {
282 for (auto *SI : FunctionScopes)
283 if (isa<sema::LambdaScopeInfo>(SI))
284 return true;
285 return false;
286}
287
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000288/// Diagnose all of the unexpanded parameter packs in the given
Douglas Gregor1da294a2010-12-15 19:43:21 +0000289/// vector.
Richard Smith2589b9802012-07-25 03:56:55 +0000290bool
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000291Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
292 UnexpandedParameterPackContext UPPC,
Bill Wendling8ac06af2012-02-22 09:38:11 +0000293 ArrayRef<UnexpandedParameterPack> Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000294 if (Unexpanded.empty())
Richard Smith2589b9802012-07-25 03:56:55 +0000295 return false;
296
Richard Smith78a07ba2017-08-15 19:11:21 +0000297 // If we are within a lambda expression and referencing a pack that is not
298 // a parameter of the lambda itself, that lambda contains an unexpanded
Richard Smith2589b9802012-07-25 03:56:55 +0000299 // parameter pack, and we are done.
300 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
301 // later.
Richard Smithf26d5512017-08-15 22:58:45 +0000302 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
Richard Smith2589b9802012-07-25 03:56:55 +0000303 for (unsigned N = FunctionScopes.size(); N; --N) {
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000304 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
305 // We do not permit pack expansion that would duplicate a statement
306 // expression, not even within a lambda.
307 // FIXME: We could probably support this for statement expressions that do
308 // not contain labels, and for pack expansions that expand both the stmt
309 // expr and the enclosing lambda.
310 if (std::any_of(
311 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
312 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; }))
313 break;
314
315 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Func)) {
Richard Smithf26d5512017-08-15 22:58:45 +0000316 if (N == FunctionScopes.size()) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000317 for (auto &Param : Unexpanded) {
318 auto *PD = dyn_cast_or_null<ParmVarDecl>(
319 Param.first.dyn_cast<NamedDecl *>());
320 if (PD && PD->getDeclContext() == LSI->CallOperator)
Richard Smithf26d5512017-08-15 22:58:45 +0000321 LambdaParamPackReferences.push_back(Param);
Richard Smith78a07ba2017-08-15 19:11:21 +0000322 }
323 }
324
Richard Smithf26d5512017-08-15 22:58:45 +0000325 // If we have references to a parameter pack of the innermost enclosing
326 // lambda, only diagnose those ones. We don't know whether any other
327 // unexpanded parameters referenced herein are actually unexpanded;
328 // they might be expanded at an outer level.
329 if (!LambdaParamPackReferences.empty()) {
330 Unexpanded = LambdaParamPackReferences;
Richard Smith78a07ba2017-08-15 19:11:21 +0000331 break;
332 }
333
Richard Smith2589b9802012-07-25 03:56:55 +0000334 LSI->ContainsUnexpandedParameterPack = true;
335 return false;
336 }
337 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000338
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 SmallVector<SourceLocation, 4> Locations;
340 SmallVector<IdentifierInfo *, 4> Names;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000341 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
342
343 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000344 IdentifierInfo *Name = nullptr;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000345 if (const TemplateTypeParmType *TTP
346 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000347 Name = TTP->getIdentifier();
Douglas Gregor1da294a2010-12-15 19:43:21 +0000348 else
349 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
350
David Blaikie82e95a32014-11-19 07:49:47 +0000351 if (Name && NamesKnown.insert(Name).second)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000352 Names.push_back(Name);
353
354 if (Unexpanded[I].second.isValid())
355 Locations.push_back(Unexpanded[I].second);
356 }
357
Benjamin Kramer3a8650a2015-03-27 17:23:14 +0000358 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
359 << (int)UPPC << (int)Names.size();
360 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
361 DB << Names[I];
Douglas Gregor1da294a2010-12-15 19:43:21 +0000362
363 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
364 DB << SourceRange(Locations[I]);
Richard Smith2589b9802012-07-25 03:56:55 +0000365 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000366}
367
Fangrui Song6907ce22018-07-30 19:24:48 +0000368bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000369 TypeSourceInfo *T,
370 UnexpandedParameterPackContext UPPC) {
371 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000372 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000373 // ill-formed.
374 if (!T->getType()->containsUnexpandedParameterPack())
375 return false;
376
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000377 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000378 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
379 T->getTypeLoc());
380 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000381 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000382}
383
384bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
Douglas Gregorc4356532010-12-16 00:46:58 +0000385 UnexpandedParameterPackContext UPPC) {
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000386 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000387 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000388 // ill-formed.
389 if (!E->containsUnexpandedParameterPack())
390 return false;
391
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000392 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000393 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
394 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000395 return DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000396}
Douglas Gregorc4356532010-12-16 00:46:58 +0000397
398bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
399 UnexpandedParameterPackContext UPPC) {
400 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000401 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorc4356532010-12-16 00:46:58 +0000402 // ill-formed.
Fangrui Song6907ce22018-07-30 19:24:48 +0000403 if (!SS.getScopeRep() ||
Douglas Gregorc4356532010-12-16 00:46:58 +0000404 !SS.getScopeRep()->containsUnexpandedParameterPack())
405 return false;
406
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000407 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000408 CollectUnexpandedParameterPacksVisitor(Unexpanded)
409 .TraverseNestedNameSpecifier(SS.getScopeRep());
410 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000411 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
412 UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000413}
414
415bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
416 UnexpandedParameterPackContext UPPC) {
417 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000418 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorc4356532010-12-16 00:46:58 +0000419 // ill-formed.
420 switch (NameInfo.getName().getNameKind()) {
421 case DeclarationName::Identifier:
422 case DeclarationName::ObjCZeroArgSelector:
423 case DeclarationName::ObjCOneArgSelector:
424 case DeclarationName::ObjCMultiArgSelector:
425 case DeclarationName::CXXOperatorName:
426 case DeclarationName::CXXLiteralOperatorName:
427 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +0000428 case DeclarationName::CXXDeductionGuideName:
Douglas Gregorc4356532010-12-16 00:46:58 +0000429 return false;
430
431 case DeclarationName::CXXConstructorName:
432 case DeclarationName::CXXDestructorName:
433 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor062ecac2010-12-16 17:19:19 +0000434 // FIXME: We shouldn't need this null check!
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000435 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
436 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
437
438 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
Douglas Gregorc4356532010-12-16 00:46:58 +0000439 return false;
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000440
Douglas Gregorc4356532010-12-16 00:46:58 +0000441 break;
442 }
443
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000444 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000445 CollectUnexpandedParameterPacksVisitor(Unexpanded)
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000446 .TraverseType(NameInfo.getName().getCXXNameType());
Douglas Gregorc4356532010-12-16 00:46:58 +0000447 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000448 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000449}
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000450
451bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
452 TemplateName Template,
453 UnexpandedParameterPackContext UPPC) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000454
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000455 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
456 return false;
457
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000458 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000459 CollectUnexpandedParameterPacksVisitor(Unexpanded)
460 .TraverseTemplateName(Template);
461 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000462 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000463}
464
Douglas Gregor14406932011-01-03 20:35:03 +0000465bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
466 UnexpandedParameterPackContext UPPC) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000467 if (Arg.getArgument().isNull() ||
Douglas Gregor14406932011-01-03 20:35:03 +0000468 !Arg.getArgument().containsUnexpandedParameterPack())
469 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000470
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor14406932011-01-03 20:35:03 +0000472 CollectUnexpandedParameterPacksVisitor(Unexpanded)
473 .TraverseTemplateArgumentLoc(Arg);
474 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000475 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
Douglas Gregor14406932011-01-03 20:35:03 +0000476}
477
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000478void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000480 CollectUnexpandedParameterPacksVisitor(Unexpanded)
481 .TraverseTemplateArgument(Arg);
482}
483
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000484void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000485 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000486 CollectUnexpandedParameterPacksVisitor(Unexpanded)
487 .TraverseTemplateArgumentLoc(Arg);
488}
489
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000490void Sema::collectUnexpandedParameterPacks(QualType T,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000492 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
493}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000494
Douglas Gregor752a5952011-01-03 22:36:02 +0000495void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000497 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
Richard Smith22a250c2016-12-19 04:08:53 +0000498}
499
Richard Smith151c4562016-12-20 21:35:28 +0000500void Sema::collectUnexpandedParameterPacks(
501 NestedNameSpecifierLoc NNS,
502 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
503 CollectUnexpandedParameterPacksVisitor(Unexpanded)
504 .TraverseNestedNameSpecifierLoc(NNS);
505}
506
507void Sema::collectUnexpandedParameterPacks(
508 const DeclarationNameInfo &NameInfo,
509 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000510 CollectUnexpandedParameterPacksVisitor(Unexpanded)
511 .TraverseDeclarationNameInfo(NameInfo);
512}
513
514
Fangrui Song6907ce22018-07-30 19:24:48 +0000515ParsedTemplateArgument
Douglas Gregord2fa7662010-12-20 02:24:11 +0000516Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
517 SourceLocation EllipsisLoc) {
518 if (Arg.isInvalid())
519 return Arg;
520
521 switch (Arg.getKind()) {
522 case ParsedTemplateArgument::Type: {
523 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
524 if (Result.isInvalid())
525 return ParsedTemplateArgument();
526
Fangrui Song6907ce22018-07-30 19:24:48 +0000527 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
Douglas Gregord2fa7662010-12-20 02:24:11 +0000528 Arg.getLocation());
529 }
530
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000531 case ParsedTemplateArgument::NonType: {
532 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
533 if (Result.isInvalid())
534 return ParsedTemplateArgument();
Fangrui Song6907ce22018-07-30 19:24:48 +0000535
536 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000537 Arg.getLocation());
538 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000539
Douglas Gregord2fa7662010-12-20 02:24:11 +0000540 case ParsedTemplateArgument::Template:
Douglas Gregoreb29d182011-01-05 17:40:24 +0000541 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
542 SourceRange R(Arg.getLocation());
543 if (Arg.getScopeSpec().isValid())
544 R.setBegin(Arg.getScopeSpec().getBeginLoc());
545 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
546 << R;
547 return ParsedTemplateArgument();
548 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000549
Douglas Gregoreb29d182011-01-05 17:40:24 +0000550 return Arg.getTemplatePackExpansion(EllipsisLoc);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000551 }
552 llvm_unreachable("Unhandled template argument kind?");
Douglas Gregord2fa7662010-12-20 02:24:11 +0000553}
554
Fangrui Song6907ce22018-07-30 19:24:48 +0000555TypeResult Sema::ActOnPackExpansion(ParsedType Type,
Douglas Gregord2fa7662010-12-20 02:24:11 +0000556 SourceLocation EllipsisLoc) {
557 TypeSourceInfo *TSInfo;
558 GetTypeFromParser(Type, &TSInfo);
559 if (!TSInfo)
560 return true;
561
David Blaikie7a30dc52013-02-21 01:47:18 +0000562 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000563 if (!TSResult)
564 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000565
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000566 return CreateParsedType(TSResult->getType(), TSResult);
567}
568
David Blaikie05785d12013-02-20 22:23:23 +0000569TypeSourceInfo *
570Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
571 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +0000572 // Create the pack expansion type and source-location information.
Fangrui Song6907ce22018-07-30 19:24:48 +0000573 QualType Result = CheckPackExpansion(Pattern->getType(),
Douglas Gregor822d0302011-01-12 17:07:58 +0000574 Pattern->getTypeLoc().getSourceRange(),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000575 EllipsisLoc, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000576 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +0000577 return nullptr;
Eli Friedman7152fbe2013-06-07 20:31:48 +0000578
579 TypeLocBuilder TLB;
580 TLB.pushFullCopy(Pattern->getTypeLoc());
581 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000582 TL.setEllipsisLoc(EllipsisLoc);
Eli Friedman7152fbe2013-06-07 20:31:48 +0000583
584 return TLB.getTypeSourceInfo(Context, Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000585}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000586
David Blaikie05785d12013-02-20 22:23:23 +0000587QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000588 SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000589 Optional<unsigned> NumExpansions) {
Douglas Gregor822d0302011-01-12 17:07:58 +0000590 // C++0x [temp.variadic]p5:
591 // The pattern of a pack expansion shall name one or more
592 // parameter packs that are not expanded by a nested pack
593 // expansion.
594 if (!Pattern->containsUnexpandedParameterPack()) {
595 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
596 << PatternRange;
597 return QualType();
598 }
599
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000600 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000601}
602
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000603ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
David Blaikie7a30dc52013-02-21 01:47:18 +0000604 return CheckPackExpansion(Pattern, EllipsisLoc, None);
Douglas Gregorb8840002011-01-14 21:20:45 +0000605}
606
607ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000608 Optional<unsigned> NumExpansions) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000609 if (!Pattern)
610 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000611
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000612 // C++0x [temp.variadic]p5:
613 // The pattern of a pack expansion shall name one or more
614 // parameter packs that are not expanded by a nested pack
615 // expansion.
616 if (!Pattern->containsUnexpandedParameterPack()) {
617 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
618 << Pattern->getSourceRange();
619 return ExprError();
620 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000621
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000622 // Create the pack expansion expression and source-location information.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000623 return new (Context)
624 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000625}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000626
David Blaikie05785d12013-02-20 22:23:23 +0000627bool Sema::CheckParameterPacksForExpansion(
628 SourceLocation EllipsisLoc, SourceRange PatternRange,
629 ArrayRef<UnexpandedParameterPack> Unexpanded,
630 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
631 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000632 ShouldExpand = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000633 RetainExpansion = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000634 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
635 bool HaveFirstPack = false;
Richard Smith4a8f3512018-07-19 19:00:37 +0000636 Optional<unsigned> NumPartialExpansions;
637 SourceLocation PartiallySubstitutedPackLoc;
638
David Blaikieb9c168a2011-09-22 02:34:54 +0000639 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
640 end = Unexpanded.end();
641 i != end; ++i) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000642 // Compute the depth and index for this parameter pack.
Ted Kremenek582a0992011-01-23 17:04:59 +0000643 unsigned Depth = 0, Index = 0;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000644 IdentifierInfo *Name;
Douglas Gregorf3010112011-01-07 16:43:16 +0000645 bool IsFunctionParameterPack = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000646
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000647 if (const TemplateTypeParmType *TTP
David Blaikieb9c168a2011-09-22 02:34:54 +0000648 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000649 Depth = TTP->getDepth();
650 Index = TTP->getIndex();
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000651 Name = TTP->getIdentifier();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000652 } else {
David Blaikieb9c168a2011-09-22 02:34:54 +0000653 NamedDecl *ND = i->first.get<NamedDecl *>();
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000654 if (isa<ParmVarDecl>(ND))
Douglas Gregorf3010112011-01-07 16:43:16 +0000655 IsFunctionParameterPack = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000656 else
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000657 std::tie(Depth, Index) = getDepthAndIndex(ND);
658
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000659 Name = ND->getIdentifier();
660 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000661
Douglas Gregorf3010112011-01-07 16:43:16 +0000662 // Determine the size of this argument pack.
Fangrui Song6907ce22018-07-30 19:24:48 +0000663 unsigned NewPackSize;
Douglas Gregorf3010112011-01-07 16:43:16 +0000664 if (IsFunctionParameterPack) {
665 // Figure out whether we're instantiating to an argument pack or not.
666 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
Fangrui Song6907ce22018-07-30 19:24:48 +0000667
Douglas Gregorf3010112011-01-07 16:43:16 +0000668 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
669 = CurrentInstantiationScope->findInstantiationOf(
David Blaikieb9c168a2011-09-22 02:34:54 +0000670 i->first.get<NamedDecl *>());
Chris Lattner15a776f2011-02-17 19:38:27 +0000671 if (Instantiation->is<DeclArgumentPack *>()) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000672 // We could expand this function parameter pack.
673 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
674 } else {
675 // We can't expand this function parameter pack, so we can't expand
676 // the pack expansion.
677 ShouldExpand = false;
678 continue;
679 }
680 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000681 // If we don't have a template argument at this depth/index, then we
682 // cannot expand the pack expansion. Make a note of this, but we still
Douglas Gregorf3010112011-01-07 16:43:16 +0000683 // want to check any parameter packs we *do* have arguments for.
684 if (Depth >= TemplateArgs.getNumLevels() ||
685 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
686 ShouldExpand = false;
687 continue;
688 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000689
Douglas Gregorf3010112011-01-07 16:43:16 +0000690 // Determine the size of the argument pack.
691 NewPackSize = TemplateArgs(Depth, Index).pack_size();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000692 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000693
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000694 // C++0x [temp.arg.explicit]p9:
Fangrui Song6907ce22018-07-30 19:24:48 +0000695 // Template argument deduction can extend the sequence of template
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000696 // arguments corresponding to a template parameter pack, even when the
697 // sequence contains explicitly specified template arguments.
Olivier Goffarteeba9e42016-05-26 12:55:34 +0000698 if (!IsFunctionParameterPack && CurrentInstantiationScope) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000699 if (NamedDecl *PartialPack
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000700 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
701 unsigned PartialDepth, PartialIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000702 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
Richard Smith4a8f3512018-07-19 19:00:37 +0000703 if (PartialDepth == Depth && PartialIndex == Index) {
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000704 RetainExpansion = true;
Richard Smith4a8f3512018-07-19 19:00:37 +0000705 // We don't actually know the new pack size yet.
706 NumPartialExpansions = NewPackSize;
707 PartiallySubstitutedPackLoc = i->second;
708 continue;
709 }
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000710 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000711 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000712
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000713 if (!NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000714 // The is the first pack we've seen for which we have an argument.
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000715 // Record it.
716 NumExpansions = NewPackSize;
717 FirstPack.first = Name;
David Blaikieb9c168a2011-09-22 02:34:54 +0000718 FirstPack.second = i->second;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000719 HaveFirstPack = true;
720 continue;
721 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000722
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000723 if (NewPackSize != *NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000724 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000725 // All of the parameter packs expanded by a pack expansion shall have
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000726 // the same number of arguments specified.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000727 if (HaveFirstPack)
728 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
729 << FirstPack.first << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000730 << SourceRange(FirstPack.second) << SourceRange(i->second);
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000731 else
732 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
733 << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000734 << SourceRange(i->second);
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000735 return true;
736 }
737 }
Richard Smithc5452ed2016-10-19 22:18:42 +0000738
Richard Smith4a8f3512018-07-19 19:00:37 +0000739 // If we're performing a partial expansion but we also have a full expansion,
740 // expand to the number of common arguments. For example, given:
741 //
742 // template<typename ...T> struct A {
743 // template<typename ...U> void f(pair<T, U>...);
744 // };
745 //
746 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
747 // retain an expansion.
748 if (NumPartialExpansions) {
749 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
750 NamedDecl *PartialPack =
751 CurrentInstantiationScope->getPartiallySubstitutedPack();
752 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
753 << PartialPack << *NumPartialExpansions << *NumExpansions
754 << SourceRange(PartiallySubstitutedPackLoc);
755 return true;
756 }
757
758 NumExpansions = NumPartialExpansions;
759 }
760
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000761 return false;
762}
Douglas Gregor27b4c162010-12-23 22:44:42 +0000763
David Blaikie05785d12013-02-20 22:23:23 +0000764Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
Douglas Gregor5cde3862011-01-11 03:14:20 +0000765 const MultiLevelTemplateArgumentList &TemplateArgs) {
766 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000767 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000768 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
769
David Blaikie05785d12013-02-20 22:23:23 +0000770 Optional<unsigned> Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000771 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
772 // Compute the depth and index for this parameter pack.
773 unsigned Depth;
774 unsigned Index;
Fangrui Song6907ce22018-07-30 19:24:48 +0000775
Douglas Gregor5cde3862011-01-11 03:14:20 +0000776 if (const TemplateTypeParmType *TTP
777 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
778 Depth = TTP->getDepth();
779 Index = TTP->getIndex();
Fangrui Song6907ce22018-07-30 19:24:48 +0000780 } else {
Douglas Gregor5cde3862011-01-11 03:14:20 +0000781 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
782 if (isa<ParmVarDecl>(ND)) {
783 // Function parameter pack.
784 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
Fangrui Song6907ce22018-07-30 19:24:48 +0000785
Douglas Gregor5cde3862011-01-11 03:14:20 +0000786 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
787 = CurrentInstantiationScope->findInstantiationOf(
788 Unexpanded[I].first.get<NamedDecl *>());
Richard Smith198223b2012-07-18 01:29:05 +0000789 if (Instantiation->is<Decl*>())
790 // The pattern refers to an unexpanded pack. We're not ready to expand
791 // this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000792 return None;
Richard Smith198223b2012-07-18 01:29:05 +0000793
794 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
795 assert((!Result || *Result == Size) && "inconsistent pack sizes");
796 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000797 continue;
798 }
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000799
800 std::tie(Depth, Index) = getDepthAndIndex(ND);
Douglas Gregor5cde3862011-01-11 03:14:20 +0000801 }
802 if (Depth >= TemplateArgs.getNumLevels() ||
803 !TemplateArgs.hasTemplateArgument(Depth, Index))
Richard Smith198223b2012-07-18 01:29:05 +0000804 // The pattern refers to an unknown template argument. We're not ready to
805 // expand this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000806 return None;
Fangrui Song6907ce22018-07-30 19:24:48 +0000807
Douglas Gregor5cde3862011-01-11 03:14:20 +0000808 // Determine the size of the argument pack.
Richard Smith198223b2012-07-18 01:29:05 +0000809 unsigned Size = TemplateArgs(Depth, Index).pack_size();
810 assert((!Result || *Result == Size) && "inconsistent pack sizes");
811 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000812 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000813
Richard Smith198223b2012-07-18 01:29:05 +0000814 return Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000815}
816
Douglas Gregor27b4c162010-12-23 22:44:42 +0000817bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
818 const DeclSpec &DS = D.getDeclSpec();
819 switch (DS.getTypeSpecType()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000820 case TST_typename:
821 case TST_typeofType:
822 case TST_underlyingType:
823 case TST_atomic: {
Douglas Gregor27b4c162010-12-23 22:44:42 +0000824 QualType T = DS.getRepAsType().get();
825 if (!T.isNull() && T->containsUnexpandedParameterPack())
826 return true;
827 break;
828 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000829
Faisal Vali090da2d2018-01-01 18:23:28 +0000830 case TST_typeofExpr:
831 case TST_decltype:
Fangrui Song6907ce22018-07-30 19:24:48 +0000832 if (DS.getRepAsExpr() &&
Douglas Gregor27b4c162010-12-23 22:44:42 +0000833 DS.getRepAsExpr()->containsUnexpandedParameterPack())
834 return true;
835 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000836
Faisal Vali090da2d2018-01-01 18:23:28 +0000837 case TST_unspecified:
838 case TST_void:
839 case TST_char:
840 case TST_wchar:
Richard Smith3a8244d2018-05-01 05:02:45 +0000841 case TST_char8:
Faisal Vali090da2d2018-01-01 18:23:28 +0000842 case TST_char16:
843 case TST_char32:
844 case TST_int:
845 case TST_int128:
846 case TST_half:
847 case TST_float:
848 case TST_double:
Leonard Chanf921d852018-06-04 16:07:52 +0000849 case TST_Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000850 case TST_Fract:
Faisal Vali090da2d2018-01-01 18:23:28 +0000851 case TST_Float16:
852 case TST_float128:
853 case TST_bool:
854 case TST_decimal32:
855 case TST_decimal64:
856 case TST_decimal128:
857 case TST_enum:
858 case TST_union:
859 case TST_struct:
860 case TST_interface:
861 case TST_class:
862 case TST_auto:
863 case TST_auto_type:
864 case TST_decltype_auto:
865#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +0000866#include "clang/Basic/OpenCLImageTypes.def"
Faisal Vali090da2d2018-01-01 18:23:28 +0000867 case TST_unknown_anytype:
868 case TST_error:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000869 break;
870 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000871
Douglas Gregor27b4c162010-12-23 22:44:42 +0000872 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
873 const DeclaratorChunk &Chunk = D.getTypeObject(I);
874 switch (Chunk.Kind) {
875 case DeclaratorChunk::Pointer:
876 case DeclaratorChunk::Reference:
877 case DeclaratorChunk::Paren:
Xiuli Pan9c14e282016-01-09 12:53:17 +0000878 case DeclaratorChunk::Pipe:
Larisse Voufo2e846502014-08-29 21:08:16 +0000879 case DeclaratorChunk::BlockPointer:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000880 // These declarator chunks cannot contain any parameter packs.
881 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000882
Douglas Gregor27b4c162010-12-23 22:44:42 +0000883 case DeclaratorChunk::Array:
Larisse Voufo2e846502014-08-29 21:08:16 +0000884 if (Chunk.Arr.NumElts &&
885 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
886 return true;
887 break;
Douglas Gregor27b4c162010-12-23 22:44:42 +0000888 case DeclaratorChunk::Function:
Larisse Voufo2e846502014-08-29 21:08:16 +0000889 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
890 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
891 QualType ParamTy = Param->getType();
892 assert(!ParamTy.isNull() && "Couldn't parse type?");
893 if (ParamTy->containsUnexpandedParameterPack()) return true;
894 }
895
896 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
Reid Kleckner078aea92016-12-09 17:14:05 +0000897 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
Larisse Voufo2e846502014-08-29 21:08:16 +0000898 if (Chunk.Fun.Exceptions[i]
899 .Ty.get()
900 ->containsUnexpandedParameterPack())
901 return true;
902 }
Richard Smitheaf11ad2018-05-03 03:58:32 +0000903 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
Larisse Voufo2e846502014-08-29 21:08:16 +0000904 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
905 return true;
906
Nico Weber8d26b722014-12-30 02:06:40 +0000907 if (Chunk.Fun.hasTrailingReturnType()) {
908 QualType T = Chunk.Fun.getTrailingReturnType().get();
Fangrui Song99337e22018-07-20 08:19:20 +0000909 if (!T.isNull() && T->containsUnexpandedParameterPack())
910 return true;
Nico Weber8d26b722014-12-30 02:06:40 +0000911 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000912 break;
913
Douglas Gregor27b4c162010-12-23 22:44:42 +0000914 case DeclaratorChunk::MemberPointer:
915 if (Chunk.Mem.Scope().getScopeRep() &&
916 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
917 return true;
918 break;
919 }
920 }
Fangrui Song99337e22018-07-20 08:19:20 +0000921
Douglas Gregor27b4c162010-12-23 22:44:42 +0000922 return false;
923}
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000924
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000925namespace {
926
927// Callback to only accept typo corrections that refer to parameter packs.
928class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
929 public:
Craig Toppere14c0f82014-03-12 04:55:44 +0000930 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000931 NamedDecl *ND = candidate.getCorrectionDecl();
932 return ND && ND->isParameterPack();
933 }
934};
935
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000936}
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000937
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000938/// Called when an expression computing the size of a parameter pack
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000939/// is parsed.
940///
941/// \code
942/// template<typename ...Types> struct count {
943/// static const unsigned value = sizeof...(Types);
944/// };
945/// \endcode
946///
947//
948/// \param OpLoc The location of the "sizeof" keyword.
949/// \param Name The name of the parameter pack whose size will be determined.
950/// \param NameLoc The source location of the name of the parameter pack.
951/// \param RParenLoc The location of the closing parentheses.
952ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
953 SourceLocation OpLoc,
954 IdentifierInfo &Name,
955 SourceLocation NameLoc,
956 SourceLocation RParenLoc) {
957 // C++0x [expr.sizeof]p5:
958 // The identifier in a sizeof... expression shall name a parameter pack.
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000959 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
960 LookupName(R, S);
Craig Topperc3ec1492014-05-26 06:22:03 +0000961
962 NamedDecl *ParameterPack = nullptr;
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000963 switch (R.getResultKind()) {
964 case LookupResult::Found:
965 ParameterPack = R.getFoundDecl();
966 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000967
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000968 case LookupResult::NotFound:
969 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000970 if (TypoCorrection Corrected =
971 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
972 llvm::make_unique<ParameterPackValidatorCCC>(),
973 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000974 diagnoseTypo(Corrected,
975 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
976 PDiag(diag::note_parameter_pack_here));
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000977 ParameterPack = Corrected.getCorrectionDecl();
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000978 }
Richard Smithf9b15102013-08-17 00:46:16 +0000979
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000980 case LookupResult::FoundOverloaded:
981 case LookupResult::FoundUnresolvedValue:
982 break;
Fangrui Song99337e22018-07-20 08:19:20 +0000983
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000984 case LookupResult::Ambiguous:
985 DiagnoseAmbiguousLookup(R);
986 return ExprError();
987 }
Fangrui Song99337e22018-07-20 08:19:20 +0000988
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000989 if (!ParameterPack || !ParameterPack->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000990 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
991 << &Name;
992 return ExprError();
993 }
994
Nick Lewycky45b50522013-02-02 00:25:55 +0000995 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
Eli Friedman23b1be92012-03-01 21:32:56 +0000996
Richard Smithd784e682015-09-23 21:41:42 +0000997 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
998 RParenLoc);
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000999}
Eli Friedman94e9eaa2013-06-20 04:11:21 +00001000
1001TemplateArgumentLoc
1002Sema::getTemplateArgumentPackExpansionPattern(
1003 TemplateArgumentLoc OrigLoc,
1004 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1005 const TemplateArgument &Argument = OrigLoc.getArgument();
1006 assert(Argument.isPackExpansion());
1007 switch (Argument.getKind()) {
1008 case TemplateArgument::Type: {
1009 // FIXME: We shouldn't ever have to worry about missing
1010 // type-source info!
1011 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1012 if (!ExpansionTSInfo)
1013 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1014 Ellipsis);
1015 PackExpansionTypeLoc Expansion =
1016 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1017 Ellipsis = Expansion.getEllipsisLoc();
1018
1019 TypeLoc Pattern = Expansion.getPatternLoc();
1020 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1021
1022 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1023 // TypeSourceInfo.
1024 // FIXME: Find some way to avoid the copy?
1025 TypeLocBuilder TLB;
1026 TLB.pushFullCopy(Pattern);
1027 TypeSourceInfo *PatternTSInfo =
1028 TLB.getTypeSourceInfo(Context, Pattern.getType());
1029 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1030 PatternTSInfo);
1031 }
1032
1033 case TemplateArgument::Expression: {
1034 PackExpansionExpr *Expansion
1035 = cast<PackExpansionExpr>(Argument.getAsExpr());
1036 Expr *Pattern = Expansion->getPattern();
1037 Ellipsis = Expansion->getEllipsisLoc();
1038 NumExpansions = Expansion->getNumExpansions();
1039 return TemplateArgumentLoc(Pattern, Pattern);
1040 }
1041
1042 case TemplateArgument::TemplateExpansion:
1043 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1044 NumExpansions = Argument.getNumTemplateExpansions();
1045 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1046 OrigLoc.getTemplateQualifierLoc(),
1047 OrigLoc.getTemplateNameLoc());
1048
1049 case TemplateArgument::Declaration:
1050 case TemplateArgument::NullPtr:
1051 case TemplateArgument::Template:
1052 case TemplateArgument::Integral:
1053 case TemplateArgument::Pack:
1054 case TemplateArgument::Null:
1055 return TemplateArgumentLoc();
1056 }
1057
1058 llvm_unreachable("Invalid TemplateArgument Kind!");
1059}
Richard Smith0f0af192014-11-08 05:07:16 +00001060
Richard Smithc5452ed2016-10-19 22:18:42 +00001061Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1062 assert(Arg.containsUnexpandedParameterPack());
1063
1064 // If this is a substituted pack, grab that pack. If not, we don't know
1065 // the size yet.
1066 // FIXME: We could find a size in more cases by looking for a substituted
1067 // pack anywhere within this argument, but that's not necessary in the common
1068 // case for 'sizeof...(A)' handling.
1069 TemplateArgument Pack;
1070 switch (Arg.getKind()) {
1071 case TemplateArgument::Type:
1072 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1073 Pack = Subst->getArgumentPack();
1074 else
1075 return None;
1076 break;
1077
1078 case TemplateArgument::Expression:
1079 if (auto *Subst =
1080 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1081 Pack = Subst->getArgumentPack();
1082 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1083 for (ParmVarDecl *PD : *Subst)
1084 if (PD->isParameterPack())
1085 return None;
1086 return Subst->getNumExpansions();
1087 } else
1088 return None;
1089 break;
1090
1091 case TemplateArgument::Template:
1092 if (SubstTemplateTemplateParmPackStorage *Subst =
1093 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1094 Pack = Subst->getArgumentPack();
1095 else
1096 return None;
1097 break;
1098
1099 case TemplateArgument::Declaration:
1100 case TemplateArgument::NullPtr:
1101 case TemplateArgument::TemplateExpansion:
1102 case TemplateArgument::Integral:
1103 case TemplateArgument::Pack:
1104 case TemplateArgument::Null:
1105 return None;
1106 }
1107
1108 // Check that no argument in the pack is itself a pack expansion.
1109 for (TemplateArgument Elem : Pack.pack_elements()) {
1110 // There's no point recursing in this case; we would have already
1111 // expanded this pack expansion into the enclosing pack if we could.
1112 if (Elem.isPackExpansion())
1113 return None;
1114 }
1115 return Pack.pack_size();
1116}
1117
Richard Smith0f0af192014-11-08 05:07:16 +00001118static void CheckFoldOperand(Sema &S, Expr *E) {
1119 if (!E)
1120 return;
1121
1122 E = E->IgnoreImpCasts();
Richard Smith66094432016-10-20 00:55:15 +00001123 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1124 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1125 isa<AbstractConditionalOperator>(E)) {
Richard Smith0f0af192014-11-08 05:07:16 +00001126 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1127 << E->getSourceRange()
1128 << FixItHint::CreateInsertion(E->getLocStart(), "(")
1129 << FixItHint::CreateInsertion(E->getLocEnd(), ")");
1130 }
1131}
1132
1133ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1134 tok::TokenKind Operator,
1135 SourceLocation EllipsisLoc, Expr *RHS,
1136 SourceLocation RParenLoc) {
1137 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1138 // in the parser and reduce down to just cast-expressions here.
1139 CheckFoldOperand(*this, LHS);
1140 CheckFoldOperand(*this, RHS);
1141
Richard Smith90e043d2017-02-15 19:57:10 +00001142 auto DiscardOperands = [&] {
1143 CorrectDelayedTyposInExpr(LHS);
1144 CorrectDelayedTyposInExpr(RHS);
1145 };
1146
Richard Smith0f0af192014-11-08 05:07:16 +00001147 // [expr.prim.fold]p3:
1148 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1149 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1150 // an unexpanded parameter pack, but not both.
1151 if (LHS && RHS &&
1152 LHS->containsUnexpandedParameterPack() ==
1153 RHS->containsUnexpandedParameterPack()) {
Richard Smith90e043d2017-02-15 19:57:10 +00001154 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001155 return Diag(EllipsisLoc,
1156 LHS->containsUnexpandedParameterPack()
1157 ? diag::err_fold_expression_packs_both_sides
1158 : diag::err_pack_expansion_without_parameter_packs)
1159 << LHS->getSourceRange() << RHS->getSourceRange();
1160 }
1161
1162 // [expr.prim.fold]p2:
1163 // In a unary fold, the cast-expression shall contain an unexpanded
1164 // parameter pack.
1165 if (!LHS || !RHS) {
1166 Expr *Pack = LHS ? LHS : RHS;
1167 assert(Pack && "fold expression with neither LHS nor RHS");
Richard Smith90e043d2017-02-15 19:57:10 +00001168 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001169 if (!Pack->containsUnexpandedParameterPack())
1170 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1171 << Pack->getSourceRange();
1172 }
1173
1174 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1175 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
1176}
1177
1178ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1179 BinaryOperatorKind Operator,
1180 SourceLocation EllipsisLoc, Expr *RHS,
1181 SourceLocation RParenLoc) {
1182 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1183 Operator, EllipsisLoc, RHS, RParenLoc);
1184}
1185
1186ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1187 BinaryOperatorKind Operator) {
1188 // [temp.variadic]p9:
1189 // If N is zero for a unary fold-expression, the value of the expression is
Richard Smith0f0af192014-11-08 05:07:16 +00001190 // && -> true
1191 // || -> false
1192 // , -> void()
1193 // if the operator is not listed [above], the instantiation is ill-formed.
1194 //
1195 // Note that we need to use something like int() here, not merely 0, to
1196 // prevent the result from being a null pointer constant.
1197 QualType ScalarType;
1198 switch (Operator) {
Richard Smith0f0af192014-11-08 05:07:16 +00001199 case BO_LOr:
1200 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1201 case BO_LAnd:
1202 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1203 case BO_Comma:
1204 ScalarType = Context.VoidTy;
1205 break;
1206
1207 default:
1208 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1209 << BinaryOperator::getOpcodeStr(Operator);
1210 }
1211
1212 return new (Context) CXXScalarValueInitExpr(
1213 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1214 EllipsisLoc);
1215}