[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaTemplateVariadic.cpp
blob69e0c70bbec537f8e05559d81c77a8af430f176d
1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
7 //
8 // This file implements semantic analysis for C++0x variadic templates.
9 //===----------------------------------------------------------------------===/
11 #include "clang/Sema/Sema.h"
12 #include "TypeLocBuilder.h"
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/RecursiveASTVisitor.h"
15 #include "clang/AST/TypeLoc.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/ParsedTemplate.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Sema/SemaInternal.h"
20 #include "clang/Sema/Template.h"
22 using namespace clang;
24 //----------------------------------------------------------------------------
25 // Visitor that collects unexpanded parameter packs
26 //----------------------------------------------------------------------------
28 namespace {
29 /// A class that collects unexpanded parameter packs.
30 class CollectUnexpandedParameterPacksVisitor :
31 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
33 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34 inherited;
36 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
38 bool InLambda = false;
39 unsigned DepthLimit = (unsigned)-1;
41 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42 if (auto *VD = dyn_cast<VarDecl>(ND)) {
43 // For now, the only problematic case is a generic lambda's templated
44 // call operator, so we don't need to look for all the other ways we
45 // could have reached a dependent parameter pack.
46 auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
47 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
48 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
49 return;
50 } else if (getDepthAndIndex(ND).first >= DepthLimit)
51 return;
53 Unexpanded.push_back({ND, Loc});
55 void addUnexpanded(const TemplateTypeParmType *T,
56 SourceLocation Loc = SourceLocation()) {
57 if (T->getDepth() < DepthLimit)
58 Unexpanded.push_back({T, Loc});
61 public:
62 explicit CollectUnexpandedParameterPacksVisitor(
63 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64 : Unexpanded(Unexpanded) {}
66 bool shouldWalkTypesOfTypeLocs() const { return false; }
68 //------------------------------------------------------------------------
69 // Recording occurrences of (unexpanded) parameter packs.
70 //------------------------------------------------------------------------
72 /// Record occurrences of template type parameter packs.
73 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74 if (TL.getTypePtr()->isParameterPack())
75 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76 return true;
79 /// Record occurrences of template type parameter packs
80 /// when we don't have proper source-location information for
81 /// them.
82 ///
83 /// Ideally, this routine would never be used.
84 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85 if (T->isParameterPack())
86 addUnexpanded(T);
88 return true;
91 bool
92 VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL) {
93 Unexpanded.push_back({TL.getTypePtr(), TL.getNameLoc()});
94 return true;
97 bool VisitSubstTemplateTypeParmPackType(SubstTemplateTypeParmPackType *T) {
98 Unexpanded.push_back({T, SourceLocation()});
99 return true;
102 bool
103 VisitSubstNonTypeTemplateParmPackExpr(SubstNonTypeTemplateParmPackExpr *E) {
104 Unexpanded.push_back({E, E->getParameterPackLocation()});
105 return true;
108 /// Record occurrences of function and non-type template
109 /// parameter packs in an expression.
110 bool VisitDeclRefExpr(DeclRefExpr *E) {
111 if (E->getDecl()->isParameterPack())
112 addUnexpanded(E->getDecl(), E->getLocation());
114 return true;
117 /// Record occurrences of template template parameter packs.
118 bool TraverseTemplateName(TemplateName Template) {
119 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
120 Template.getAsTemplateDecl())) {
121 if (TTP->isParameterPack())
122 addUnexpanded(TTP);
125 return inherited::TraverseTemplateName(Template);
128 /// Suppress traversal into Objective-C container literal
129 /// elements that are pack expansions.
130 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
131 if (!E->containsUnexpandedParameterPack())
132 return true;
134 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
135 ObjCDictionaryElement Element = E->getKeyValueElement(I);
136 if (Element.isPackExpansion())
137 continue;
139 TraverseStmt(Element.Key);
140 TraverseStmt(Element.Value);
142 return true;
144 //------------------------------------------------------------------------
145 // Pruning the search for unexpanded parameter packs.
146 //------------------------------------------------------------------------
148 /// Suppress traversal into statements and expressions that
149 /// do not contain unexpanded parameter packs.
150 bool TraverseStmt(Stmt *S) {
151 Expr *E = dyn_cast_or_null<Expr>(S);
152 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
153 return inherited::TraverseStmt(S);
155 return true;
158 /// Suppress traversal into types that do not contain
159 /// unexpanded parameter packs.
160 bool TraverseType(QualType T) {
161 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
162 return inherited::TraverseType(T);
164 return true;
167 /// Suppress traversal into types with location information
168 /// that do not contain unexpanded parameter packs.
169 bool TraverseTypeLoc(TypeLoc TL) {
170 if ((!TL.getType().isNull() &&
171 TL.getType()->containsUnexpandedParameterPack()) ||
172 InLambda)
173 return inherited::TraverseTypeLoc(TL);
175 return true;
178 /// Suppress traversal of parameter packs.
179 bool TraverseDecl(Decl *D) {
180 // A function parameter pack is a pack expansion, so cannot contain
181 // an unexpanded parameter pack. Likewise for a template parameter
182 // pack that contains any references to other packs.
183 if (D && D->isParameterPack())
184 return true;
186 return inherited::TraverseDecl(D);
189 /// Suppress traversal of pack-expanded attributes.
190 bool TraverseAttr(Attr *A) {
191 if (A->isPackExpansion())
192 return true;
194 return inherited::TraverseAttr(A);
197 /// Suppress traversal of pack expansion expressions and types.
198 ///@{
199 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
200 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
201 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
202 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
204 ///@}
206 /// Suppress traversal of using-declaration pack expansion.
207 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
208 if (D->isPackExpansion())
209 return true;
211 return inherited::TraverseUnresolvedUsingValueDecl(D);
214 /// Suppress traversal of using-declaration pack expansion.
215 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
216 if (D->isPackExpansion())
217 return true;
219 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
222 /// Suppress traversal of template argument pack expansions.
223 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
224 if (Arg.isPackExpansion())
225 return true;
227 return inherited::TraverseTemplateArgument(Arg);
230 /// Suppress traversal of template argument pack expansions.
231 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
232 if (ArgLoc.getArgument().isPackExpansion())
233 return true;
235 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
238 /// Suppress traversal of base specifier pack expansions.
239 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
240 if (Base.isPackExpansion())
241 return true;
243 return inherited::TraverseCXXBaseSpecifier(Base);
246 /// Suppress traversal of mem-initializer pack expansions.
247 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
248 if (Init->isPackExpansion())
249 return true;
251 return inherited::TraverseConstructorInitializer(Init);
254 /// Note whether we're traversing a lambda containing an unexpanded
255 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
256 /// including all the places where we normally wouldn't look. Within a
257 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
258 /// outside an expression.
259 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
260 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
261 // even if it's contained within another lambda.
262 if (!Lambda->containsUnexpandedParameterPack())
263 return true;
265 bool WasInLambda = InLambda;
266 unsigned OldDepthLimit = DepthLimit;
268 InLambda = true;
269 if (auto *TPL = Lambda->getTemplateParameterList())
270 DepthLimit = TPL->getDepth();
272 inherited::TraverseLambdaExpr(Lambda);
274 InLambda = WasInLambda;
275 DepthLimit = OldDepthLimit;
276 return true;
279 /// Suppress traversal within pack expansions in lambda captures.
280 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
281 Expr *Init) {
282 if (C->isPackExpansion())
283 return true;
285 return inherited::TraverseLambdaCapture(Lambda, C, Init);
290 /// Determine whether it's possible for an unexpanded parameter pack to
291 /// be valid in this location. This only happens when we're in a declaration
292 /// that is nested within an expression that could be expanded, such as a
293 /// lambda-expression within a function call.
295 /// This is conservatively correct, but may claim that some unexpanded packs are
296 /// permitted when they are not.
297 bool Sema::isUnexpandedParameterPackPermitted() {
298 for (auto *SI : FunctionScopes)
299 if (isa<sema::LambdaScopeInfo>(SI))
300 return true;
301 return false;
304 /// Diagnose all of the unexpanded parameter packs in the given
305 /// vector.
306 bool
307 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
308 UnexpandedParameterPackContext UPPC,
309 ArrayRef<UnexpandedParameterPack> Unexpanded) {
310 if (Unexpanded.empty())
311 return false;
313 // If we are within a lambda expression and referencing a pack that is not
314 // declared within the lambda itself, that lambda contains an unexpanded
315 // parameter pack, and we are done.
316 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
317 // later.
318 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
319 if (auto *LSI = getEnclosingLambda()) {
320 for (auto &Pack : Unexpanded) {
321 auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
322 if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
323 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
324 return TTPD && TTPD->getTypeForDecl() == TTPT;
326 return declaresSameEntity(Pack.first.get<const NamedDecl *>(),
327 LocalPack);
329 if (llvm::any_of(LSI->LocalPacks, DeclaresThisPack))
330 LambdaParamPackReferences.push_back(Pack);
333 if (LambdaParamPackReferences.empty()) {
334 // Construct in lambda only references packs declared outside the lambda.
335 // That's OK for now, but the lambda itself is considered to contain an
336 // unexpanded pack in this case, which will require expansion outside the
337 // lambda.
339 // We do not permit pack expansion that would duplicate a statement
340 // expression, not even within a lambda.
341 // FIXME: We could probably support this for statement expressions that
342 // do not contain labels.
343 // FIXME: This is insufficient to detect this problem; consider
344 // f( ({ bad: 0; }) + pack ... );
345 bool EnclosingStmtExpr = false;
346 for (unsigned N = FunctionScopes.size(); N; --N) {
347 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
348 if (llvm::any_of(
349 Func->CompoundScopes,
350 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
351 EnclosingStmtExpr = true;
352 break;
354 // Coumpound-statements outside the lambda are OK for now; we'll check
355 // for those when we finish handling the lambda.
356 if (Func == LSI)
357 break;
360 if (!EnclosingStmtExpr) {
361 LSI->ContainsUnexpandedParameterPack = true;
362 return false;
364 } else {
365 Unexpanded = LambdaParamPackReferences;
369 SmallVector<SourceLocation, 4> Locations;
370 SmallVector<IdentifierInfo *, 4> Names;
371 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
373 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
374 IdentifierInfo *Name = nullptr;
375 if (const TemplateTypeParmType *TTP
376 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
377 Name = TTP->getIdentifier();
378 else
379 Name = Unexpanded[I].first.get<const NamedDecl *>()->getIdentifier();
381 if (Name && NamesKnown.insert(Name).second)
382 Names.push_back(Name);
384 if (Unexpanded[I].second.isValid())
385 Locations.push_back(Unexpanded[I].second);
388 auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
389 << (int)UPPC << (int)Names.size();
390 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
391 DB << Names[I];
393 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
394 DB << SourceRange(Locations[I]);
395 return true;
398 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
399 TypeSourceInfo *T,
400 UnexpandedParameterPackContext UPPC) {
401 // C++0x [temp.variadic]p5:
402 // An appearance of a name of a parameter pack that is not expanded is
403 // ill-formed.
404 if (!T->getType()->containsUnexpandedParameterPack())
405 return false;
407 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
408 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
409 T->getTypeLoc());
410 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
411 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
414 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
415 UnexpandedParameterPackContext UPPC) {
416 // C++0x [temp.variadic]p5:
417 // An appearance of a name of a parameter pack that is not expanded is
418 // ill-formed.
419 if (!E->containsUnexpandedParameterPack())
420 return false;
422 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
423 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
424 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
425 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
428 bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
429 if (!RE->containsUnexpandedParameterPack())
430 return false;
432 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
433 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
434 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
436 // We only care about unexpanded references to the RequiresExpr's own
437 // parameter packs.
438 auto Parms = RE->getLocalParameters();
439 llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end());
440 SmallVector<UnexpandedParameterPack, 2> UnexpandedParms;
441 for (auto Parm : Unexpanded)
442 if (ParmSet.contains(Parm.first.dyn_cast<const NamedDecl *>()))
443 UnexpandedParms.push_back(Parm);
444 if (UnexpandedParms.empty())
445 return false;
447 return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
448 UnexpandedParms);
451 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
452 UnexpandedParameterPackContext UPPC) {
453 // C++0x [temp.variadic]p5:
454 // An appearance of a name of a parameter pack that is not expanded is
455 // ill-formed.
456 if (!SS.getScopeRep() ||
457 !SS.getScopeRep()->containsUnexpandedParameterPack())
458 return false;
460 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
461 CollectUnexpandedParameterPacksVisitor(Unexpanded)
462 .TraverseNestedNameSpecifier(SS.getScopeRep());
463 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
464 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
465 UPPC, Unexpanded);
468 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
469 UnexpandedParameterPackContext UPPC) {
470 // C++0x [temp.variadic]p5:
471 // An appearance of a name of a parameter pack that is not expanded is
472 // ill-formed.
473 switch (NameInfo.getName().getNameKind()) {
474 case DeclarationName::Identifier:
475 case DeclarationName::ObjCZeroArgSelector:
476 case DeclarationName::ObjCOneArgSelector:
477 case DeclarationName::ObjCMultiArgSelector:
478 case DeclarationName::CXXOperatorName:
479 case DeclarationName::CXXLiteralOperatorName:
480 case DeclarationName::CXXUsingDirective:
481 case DeclarationName::CXXDeductionGuideName:
482 return false;
484 case DeclarationName::CXXConstructorName:
485 case DeclarationName::CXXDestructorName:
486 case DeclarationName::CXXConversionFunctionName:
487 // FIXME: We shouldn't need this null check!
488 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
489 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
491 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
492 return false;
494 break;
497 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
498 CollectUnexpandedParameterPacksVisitor(Unexpanded)
499 .TraverseType(NameInfo.getName().getCXXNameType());
500 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
501 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
504 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
505 TemplateName Template,
506 UnexpandedParameterPackContext UPPC) {
508 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
509 return false;
511 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
512 CollectUnexpandedParameterPacksVisitor(Unexpanded)
513 .TraverseTemplateName(Template);
514 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
515 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
518 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
519 UnexpandedParameterPackContext UPPC) {
520 if (Arg.getArgument().isNull() ||
521 !Arg.getArgument().containsUnexpandedParameterPack())
522 return false;
524 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
525 CollectUnexpandedParameterPacksVisitor(Unexpanded)
526 .TraverseTemplateArgumentLoc(Arg);
527 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
528 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
531 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
532 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
533 CollectUnexpandedParameterPacksVisitor(Unexpanded)
534 .TraverseTemplateArgument(Arg);
537 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
538 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
539 CollectUnexpandedParameterPacksVisitor(Unexpanded)
540 .TraverseTemplateArgumentLoc(Arg);
543 void Sema::collectUnexpandedParameterPacks(QualType T,
544 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
545 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
548 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
549 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
550 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
553 void Sema::collectUnexpandedParameterPacks(
554 NestedNameSpecifierLoc NNS,
555 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
556 CollectUnexpandedParameterPacksVisitor(Unexpanded)
557 .TraverseNestedNameSpecifierLoc(NNS);
560 void Sema::collectUnexpandedParameterPacks(
561 const DeclarationNameInfo &NameInfo,
562 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
563 CollectUnexpandedParameterPacksVisitor(Unexpanded)
564 .TraverseDeclarationNameInfo(NameInfo);
568 ParsedTemplateArgument
569 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
570 SourceLocation EllipsisLoc) {
571 if (Arg.isInvalid())
572 return Arg;
574 switch (Arg.getKind()) {
575 case ParsedTemplateArgument::Type: {
576 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
577 if (Result.isInvalid())
578 return ParsedTemplateArgument();
580 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
581 Arg.getLocation());
584 case ParsedTemplateArgument::NonType: {
585 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
586 if (Result.isInvalid())
587 return ParsedTemplateArgument();
589 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
590 Arg.getLocation());
593 case ParsedTemplateArgument::Template:
594 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
595 SourceRange R(Arg.getLocation());
596 if (Arg.getScopeSpec().isValid())
597 R.setBegin(Arg.getScopeSpec().getBeginLoc());
598 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
599 << R;
600 return ParsedTemplateArgument();
603 return Arg.getTemplatePackExpansion(EllipsisLoc);
605 llvm_unreachable("Unhandled template argument kind?");
608 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
609 SourceLocation EllipsisLoc) {
610 TypeSourceInfo *TSInfo;
611 GetTypeFromParser(Type, &TSInfo);
612 if (!TSInfo)
613 return true;
615 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
616 if (!TSResult)
617 return true;
619 return CreateParsedType(TSResult->getType(), TSResult);
622 TypeSourceInfo *
623 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
624 Optional<unsigned> NumExpansions) {
625 // Create the pack expansion type and source-location information.
626 QualType Result = CheckPackExpansion(Pattern->getType(),
627 Pattern->getTypeLoc().getSourceRange(),
628 EllipsisLoc, NumExpansions);
629 if (Result.isNull())
630 return nullptr;
632 TypeLocBuilder TLB;
633 TLB.pushFullCopy(Pattern->getTypeLoc());
634 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
635 TL.setEllipsisLoc(EllipsisLoc);
637 return TLB.getTypeSourceInfo(Context, Result);
640 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
641 SourceLocation EllipsisLoc,
642 Optional<unsigned> NumExpansions) {
643 // C++11 [temp.variadic]p5:
644 // The pattern of a pack expansion shall name one or more
645 // parameter packs that are not expanded by a nested pack
646 // expansion.
648 // A pattern containing a deduced type can't occur "naturally" but arises in
649 // the desugaring of an init-capture pack.
650 if (!Pattern->containsUnexpandedParameterPack() &&
651 !Pattern->getContainedDeducedType()) {
652 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
653 << PatternRange;
654 return QualType();
657 return Context.getPackExpansionType(Pattern, NumExpansions,
658 /*ExpectPackInType=*/false);
661 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
662 return CheckPackExpansion(Pattern, EllipsisLoc, None);
665 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
666 Optional<unsigned> NumExpansions) {
667 if (!Pattern)
668 return ExprError();
670 // C++0x [temp.variadic]p5:
671 // The pattern of a pack expansion shall name one or more
672 // parameter packs that are not expanded by a nested pack
673 // expansion.
674 if (!Pattern->containsUnexpandedParameterPack()) {
675 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
676 << Pattern->getSourceRange();
677 CorrectDelayedTyposInExpr(Pattern);
678 return ExprError();
681 // Create the pack expansion expression and source-location information.
682 return new (Context)
683 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
686 bool Sema::CheckParameterPacksForExpansion(
687 SourceLocation EllipsisLoc, SourceRange PatternRange,
688 ArrayRef<UnexpandedParameterPack> Unexpanded,
689 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
690 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
691 ShouldExpand = true;
692 RetainExpansion = false;
693 std::pair<const IdentifierInfo *, SourceLocation> FirstPack;
694 Optional<std::pair<unsigned, SourceLocation>> PartialExpansion;
695 Optional<unsigned> CurNumExpansions;
697 for (auto [P, Loc] : Unexpanded) {
698 // Compute the depth and index for this parameter pack.
699 Optional<std::pair<unsigned, unsigned>> Pos;
700 unsigned NewPackSize;
701 const auto *ND = P.dyn_cast<const NamedDecl *>();
702 if (ND && isa<VarDecl>(ND)) {
703 const auto *DAP =
704 CurrentInstantiationScope->findInstantiationOf(ND)
705 ->dyn_cast<LocalInstantiationScope::DeclArgumentPack *>();
706 if (!DAP) {
707 // We can't expand this function parameter pack, so we can't expand
708 // the pack expansion.
709 ShouldExpand = false;
710 continue;
712 NewPackSize = DAP->size();
713 } else if (ND) {
714 Pos = getDepthAndIndex(ND);
715 } else if (const auto *TTP = P.dyn_cast<const TemplateTypeParmType *>()) {
716 Pos = {TTP->getDepth(), TTP->getIndex()};
717 ND = TTP->getDecl();
718 // FIXME: We either should have some fallback for canonical TTP, or
719 // never have canonical TTP here.
720 } else if (const auto *STP =
721 P.dyn_cast<const SubstTemplateTypeParmPackType *>()) {
722 NewPackSize = STP->getNumArgs();
723 ND = STP->getReplacedParameter()->getDecl();
724 } else {
725 const auto *SEP = P.get<const SubstNonTypeTemplateParmPackExpr *>();
726 NewPackSize = SEP->getArgumentPack().pack_size();
727 ND = SEP->getParameterPack();
730 if (Pos) {
731 // If we don't have a template argument at this depth/index, then we
732 // cannot expand the pack expansion. Make a note of this, but we still
733 // want to check any parameter packs we *do* have arguments for.
734 if (Pos->first >= TemplateArgs.getNumLevels() ||
735 !TemplateArgs.hasTemplateArgument(Pos->first, Pos->second)) {
736 ShouldExpand = false;
737 continue;
739 // Determine the size of the argument pack.
740 NewPackSize = TemplateArgs(Pos->first, Pos->second).pack_size();
741 // C++0x [temp.arg.explicit]p9:
742 // Template argument deduction can extend the sequence of template
743 // arguments corresponding to a template parameter pack, even when the
744 // sequence contains explicitly specified template arguments.
745 if (CurrentInstantiationScope)
746 if (const NamedDecl *PartialPack =
747 CurrentInstantiationScope->getPartiallySubstitutedPack();
748 PartialPack && getDepthAndIndex(PartialPack) == *Pos) {
749 RetainExpansion = true;
750 // We don't actually know the new pack size yet.
751 PartialExpansion = {NewPackSize, Loc};
752 continue;
756 // FIXME: Workaround for Canonical TTP.
757 const IdentifierInfo *Name = ND ? ND->getIdentifier() : nullptr;
758 if (!CurNumExpansions) {
759 // The is the first pack we've seen for which we have an argument.
760 // Record it.
761 CurNumExpansions = NewPackSize;
762 FirstPack = {Name, Loc};
763 } else if (NewPackSize != *CurNumExpansions) {
764 // C++0x [temp.variadic]p5:
765 // All of the parameter packs expanded by a pack expansion shall have
766 // the same number of arguments specified.
767 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
768 << FirstPack.first << Name << *CurNumExpansions << NewPackSize
769 << SourceRange(FirstPack.second) << SourceRange(Loc);
770 return true;
774 if (NumExpansions && CurNumExpansions &&
775 *NumExpansions != *CurNumExpansions) {
776 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
777 << FirstPack.first << *CurNumExpansions << *NumExpansions
778 << SourceRange(FirstPack.second);
779 return true;
782 // If we're performing a partial expansion but we also have a full expansion,
783 // expand to the number of common arguments. For example, given:
785 // template<typename ...T> struct A {
786 // template<typename ...U> void f(pair<T, U>...);
787 // };
789 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
790 // retain an expansion.
791 if (PartialExpansion) {
792 if (CurNumExpansions && *CurNumExpansions < PartialExpansion->first) {
793 NamedDecl *PartialPack =
794 CurrentInstantiationScope->getPartiallySubstitutedPack();
795 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
796 << PartialPack << PartialExpansion->first << *CurNumExpansions
797 << SourceRange(PartialExpansion->second);
798 return true;
800 NumExpansions = PartialExpansion->first;
801 } else {
802 NumExpansions = CurNumExpansions;
805 return false;
808 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
809 const MultiLevelTemplateArgumentList &TemplateArgs) {
810 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
811 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
812 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
814 Optional<unsigned> Result;
815 auto setResultSz = [&Result](unsigned Size) {
816 assert((!Result || *Result == Size) && "inconsistent pack sizes");
817 Result = Size;
819 auto setResultPos = [&](const std::pair<unsigned, unsigned> &Pos) -> bool {
820 unsigned Depth = Pos.first, Index = Pos.second;
821 if (Depth >= TemplateArgs.getNumLevels() ||
822 !TemplateArgs.hasTemplateArgument(Depth, Index))
823 // The pattern refers to an unknown template argument. We're not ready to
824 // expand this pack yet.
825 return true;
826 // Determine the size of the argument pack.
827 setResultSz(TemplateArgs(Depth, Index).pack_size());
828 return false;
831 for (auto [I, _] : Unexpanded) {
832 if (const auto *TTP = I.dyn_cast<const TemplateTypeParmType *>()) {
833 if (setResultPos({TTP->getDepth(), TTP->getIndex()}))
834 return None;
835 } else if (const auto *STP =
836 I.dyn_cast<const SubstTemplateTypeParmPackType *>()) {
837 setResultSz(STP->getNumArgs());
838 } else if (const auto *SEP =
839 I.dyn_cast<const SubstNonTypeTemplateParmPackExpr *>()) {
840 setResultSz(SEP->getArgumentPack().pack_size());
841 } else {
842 const auto *ND = I.get<const NamedDecl *>();
843 // Function parameter pack or init-capture pack.
844 if (isa<VarDecl>(ND)) {
845 const auto *DAP =
846 CurrentInstantiationScope->findInstantiationOf(ND)
847 ->dyn_cast<LocalInstantiationScope::DeclArgumentPack *>();
848 if (!DAP)
849 // The pattern refers to an unexpanded pack. We're not ready to expand
850 // this pack yet.
851 return None;
852 setResultSz(DAP->size());
853 } else if (setResultPos(getDepthAndIndex(ND))) {
854 return None;
859 return Result;
862 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
863 const DeclSpec &DS = D.getDeclSpec();
864 switch (DS.getTypeSpecType()) {
865 case TST_typename:
866 case TST_typeofType:
867 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
868 #include "clang/Basic/TransformTypeTraits.def"
869 case TST_atomic: {
870 QualType T = DS.getRepAsType().get();
871 if (!T.isNull() && T->containsUnexpandedParameterPack())
872 return true;
873 break;
876 case TST_typeofExpr:
877 case TST_decltype:
878 case TST_bitint:
879 if (DS.getRepAsExpr() &&
880 DS.getRepAsExpr()->containsUnexpandedParameterPack())
881 return true;
882 break;
884 case TST_unspecified:
885 case TST_void:
886 case TST_char:
887 case TST_wchar:
888 case TST_char8:
889 case TST_char16:
890 case TST_char32:
891 case TST_int:
892 case TST_int128:
893 case TST_half:
894 case TST_float:
895 case TST_double:
896 case TST_Accum:
897 case TST_Fract:
898 case TST_Float16:
899 case TST_float128:
900 case TST_ibm128:
901 case TST_bool:
902 case TST_decimal32:
903 case TST_decimal64:
904 case TST_decimal128:
905 case TST_enum:
906 case TST_union:
907 case TST_struct:
908 case TST_interface:
909 case TST_class:
910 case TST_auto:
911 case TST_auto_type:
912 case TST_decltype_auto:
913 case TST_BFloat16:
914 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
915 #include "clang/Basic/OpenCLImageTypes.def"
916 case TST_unknown_anytype:
917 case TST_error:
918 break;
921 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
922 const DeclaratorChunk &Chunk = D.getTypeObject(I);
923 switch (Chunk.Kind) {
924 case DeclaratorChunk::Pointer:
925 case DeclaratorChunk::Reference:
926 case DeclaratorChunk::Paren:
927 case DeclaratorChunk::Pipe:
928 case DeclaratorChunk::BlockPointer:
929 // These declarator chunks cannot contain any parameter packs.
930 break;
932 case DeclaratorChunk::Array:
933 if (Chunk.Arr.NumElts &&
934 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
935 return true;
936 break;
937 case DeclaratorChunk::Function:
938 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
939 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
940 QualType ParamTy = Param->getType();
941 assert(!ParamTy.isNull() && "Couldn't parse type?");
942 if (ParamTy->containsUnexpandedParameterPack()) return true;
945 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
946 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
947 if (Chunk.Fun.Exceptions[i]
948 .Ty.get()
949 ->containsUnexpandedParameterPack())
950 return true;
952 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
953 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
954 return true;
956 if (Chunk.Fun.hasTrailingReturnType()) {
957 QualType T = Chunk.Fun.getTrailingReturnType().get();
958 if (!T.isNull() && T->containsUnexpandedParameterPack())
959 return true;
961 break;
963 case DeclaratorChunk::MemberPointer:
964 if (Chunk.Mem.Scope().getScopeRep() &&
965 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
966 return true;
967 break;
971 if (Expr *TRC = D.getTrailingRequiresClause())
972 if (TRC->containsUnexpandedParameterPack())
973 return true;
975 return false;
978 namespace {
980 // Callback to only accept typo corrections that refer to parameter packs.
981 class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
982 public:
983 bool ValidateCandidate(const TypoCorrection &candidate) override {
984 NamedDecl *ND = candidate.getCorrectionDecl();
985 return ND && ND->isParameterPack();
988 std::unique_ptr<CorrectionCandidateCallback> clone() override {
989 return std::make_unique<ParameterPackValidatorCCC>(*this);
995 /// Called when an expression computing the size of a parameter pack
996 /// is parsed.
998 /// \code
999 /// template<typename ...Types> struct count {
1000 /// static const unsigned value = sizeof...(Types);
1001 /// };
1002 /// \endcode
1005 /// \param OpLoc The location of the "sizeof" keyword.
1006 /// \param Name The name of the parameter pack whose size will be determined.
1007 /// \param NameLoc The source location of the name of the parameter pack.
1008 /// \param RParenLoc The location of the closing parentheses.
1009 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
1010 SourceLocation OpLoc,
1011 IdentifierInfo &Name,
1012 SourceLocation NameLoc,
1013 SourceLocation RParenLoc) {
1014 // C++0x [expr.sizeof]p5:
1015 // The identifier in a sizeof... expression shall name a parameter pack.
1016 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1017 LookupName(R, S);
1019 NamedDecl *ParameterPack = nullptr;
1020 switch (R.getResultKind()) {
1021 case LookupResult::Found:
1022 ParameterPack = R.getFoundDecl();
1023 break;
1025 case LookupResult::NotFound:
1026 case LookupResult::NotFoundInCurrentInstantiation: {
1027 ParameterPackValidatorCCC CCC{};
1028 if (TypoCorrection Corrected =
1029 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1030 CCC, CTK_ErrorRecovery)) {
1031 diagnoseTypo(Corrected,
1032 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1033 PDiag(diag::note_parameter_pack_here));
1034 ParameterPack = Corrected.getCorrectionDecl();
1036 break;
1038 case LookupResult::FoundOverloaded:
1039 case LookupResult::FoundUnresolvedValue:
1040 break;
1042 case LookupResult::Ambiguous:
1043 DiagnoseAmbiguousLookup(R);
1044 return ExprError();
1047 if (!ParameterPack || !ParameterPack->isParameterPack()) {
1048 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1049 << &Name;
1050 return ExprError();
1053 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1055 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1056 RParenLoc);
1059 TemplateArgumentLoc
1060 Sema::getTemplateArgumentPackExpansionPattern(
1061 TemplateArgumentLoc OrigLoc,
1062 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1063 const TemplateArgument &Argument = OrigLoc.getArgument();
1064 assert(Argument.isPackExpansion());
1065 switch (Argument.getKind()) {
1066 case TemplateArgument::Type: {
1067 // FIXME: We shouldn't ever have to worry about missing
1068 // type-source info!
1069 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1070 if (!ExpansionTSInfo)
1071 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1072 Ellipsis);
1073 PackExpansionTypeLoc Expansion =
1074 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1075 Ellipsis = Expansion.getEllipsisLoc();
1077 TypeLoc Pattern = Expansion.getPatternLoc();
1078 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1080 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1081 // TypeSourceInfo.
1082 // FIXME: Find some way to avoid the copy?
1083 TypeLocBuilder TLB;
1084 TLB.pushFullCopy(Pattern);
1085 TypeSourceInfo *PatternTSInfo =
1086 TLB.getTypeSourceInfo(Context, Pattern.getType());
1087 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1088 PatternTSInfo);
1091 case TemplateArgument::Expression: {
1092 PackExpansionExpr *Expansion
1093 = cast<PackExpansionExpr>(Argument.getAsExpr());
1094 Expr *Pattern = Expansion->getPattern();
1095 Ellipsis = Expansion->getEllipsisLoc();
1096 NumExpansions = Expansion->getNumExpansions();
1097 return TemplateArgumentLoc(Pattern, Pattern);
1100 case TemplateArgument::TemplateExpansion:
1101 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1102 NumExpansions = Argument.getNumTemplateExpansions();
1103 return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(),
1104 OrigLoc.getTemplateQualifierLoc(),
1105 OrigLoc.getTemplateNameLoc());
1107 case TemplateArgument::Declaration:
1108 case TemplateArgument::NullPtr:
1109 case TemplateArgument::Template:
1110 case TemplateArgument::Integral:
1111 case TemplateArgument::Pack:
1112 case TemplateArgument::Null:
1113 return TemplateArgumentLoc();
1116 llvm_unreachable("Invalid TemplateArgument Kind!");
1119 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1120 assert(Arg.containsUnexpandedParameterPack());
1122 // If this is a substituted pack, grab that pack. If not, we don't know
1123 // the size yet.
1124 // FIXME: We could find a size in more cases by looking for a substituted
1125 // pack anywhere within this argument, but that's not necessary in the common
1126 // case for 'sizeof...(A)' handling.
1127 TemplateArgument Pack;
1128 switch (Arg.getKind()) {
1129 case TemplateArgument::Type:
1130 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1131 Pack = Subst->getArgumentPack();
1132 else
1133 return None;
1134 break;
1136 case TemplateArgument::Expression:
1137 if (auto *Subst =
1138 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1139 Pack = Subst->getArgumentPack();
1140 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1141 for (VarDecl *PD : *Subst)
1142 if (PD->isParameterPack())
1143 return None;
1144 return Subst->getNumExpansions();
1145 } else
1146 return None;
1147 break;
1149 case TemplateArgument::Template:
1150 if (SubstTemplateTemplateParmPackStorage *Subst =
1151 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1152 Pack = Subst->getArgumentPack();
1153 else
1154 return None;
1155 break;
1157 case TemplateArgument::Declaration:
1158 case TemplateArgument::NullPtr:
1159 case TemplateArgument::TemplateExpansion:
1160 case TemplateArgument::Integral:
1161 case TemplateArgument::Pack:
1162 case TemplateArgument::Null:
1163 return None;
1166 // Check that no argument in the pack is itself a pack expansion.
1167 for (TemplateArgument Elem : Pack.pack_elements()) {
1168 // There's no point recursing in this case; we would have already
1169 // expanded this pack expansion into the enclosing pack if we could.
1170 if (Elem.isPackExpansion())
1171 return None;
1173 return Pack.pack_size();
1176 static void CheckFoldOperand(Sema &S, Expr *E) {
1177 if (!E)
1178 return;
1180 E = E->IgnoreImpCasts();
1181 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1182 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1183 isa<AbstractConditionalOperator>(E)) {
1184 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1185 << E->getSourceRange()
1186 << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1187 << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1191 ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1192 tok::TokenKind Operator,
1193 SourceLocation EllipsisLoc, Expr *RHS,
1194 SourceLocation RParenLoc) {
1195 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1196 // in the parser and reduce down to just cast-expressions here.
1197 CheckFoldOperand(*this, LHS);
1198 CheckFoldOperand(*this, RHS);
1200 auto DiscardOperands = [&] {
1201 CorrectDelayedTyposInExpr(LHS);
1202 CorrectDelayedTyposInExpr(RHS);
1205 // [expr.prim.fold]p3:
1206 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1207 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1208 // an unexpanded parameter pack, but not both.
1209 if (LHS && RHS &&
1210 LHS->containsUnexpandedParameterPack() ==
1211 RHS->containsUnexpandedParameterPack()) {
1212 DiscardOperands();
1213 return Diag(EllipsisLoc,
1214 LHS->containsUnexpandedParameterPack()
1215 ? diag::err_fold_expression_packs_both_sides
1216 : diag::err_pack_expansion_without_parameter_packs)
1217 << LHS->getSourceRange() << RHS->getSourceRange();
1220 // [expr.prim.fold]p2:
1221 // In a unary fold, the cast-expression shall contain an unexpanded
1222 // parameter pack.
1223 if (!LHS || !RHS) {
1224 Expr *Pack = LHS ? LHS : RHS;
1225 assert(Pack && "fold expression with neither LHS nor RHS");
1226 DiscardOperands();
1227 if (!Pack->containsUnexpandedParameterPack())
1228 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1229 << Pack->getSourceRange();
1232 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1234 // Perform first-phase name lookup now.
1235 UnresolvedLookupExpr *ULE = nullptr;
1237 UnresolvedSet<16> Functions;
1238 LookupBinOp(S, EllipsisLoc, Opc, Functions);
1239 if (!Functions.empty()) {
1240 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1241 BinaryOperator::getOverloadedOperator(Opc));
1242 ExprResult Callee = CreateUnresolvedLookupExpr(
1243 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1244 DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1245 if (Callee.isInvalid())
1246 return ExprError();
1247 ULE = cast<UnresolvedLookupExpr>(Callee.get());
1251 return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1252 None);
1255 ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1256 SourceLocation LParenLoc, Expr *LHS,
1257 BinaryOperatorKind Operator,
1258 SourceLocation EllipsisLoc, Expr *RHS,
1259 SourceLocation RParenLoc,
1260 Optional<unsigned> NumExpansions) {
1261 return new (Context)
1262 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1263 EllipsisLoc, RHS, RParenLoc, NumExpansions);
1266 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1267 BinaryOperatorKind Operator) {
1268 // [temp.variadic]p9:
1269 // If N is zero for a unary fold-expression, the value of the expression is
1270 // && -> true
1271 // || -> false
1272 // , -> void()
1273 // if the operator is not listed [above], the instantiation is ill-formed.
1275 // Note that we need to use something like int() here, not merely 0, to
1276 // prevent the result from being a null pointer constant.
1277 QualType ScalarType;
1278 switch (Operator) {
1279 case BO_LOr:
1280 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1281 case BO_LAnd:
1282 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1283 case BO_Comma:
1284 ScalarType = Context.VoidTy;
1285 break;
1287 default:
1288 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1289 << BinaryOperator::getOpcodeStr(Operator);
1292 return new (Context) CXXScalarValueInitExpr(
1293 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1294 EllipsisLoc);