]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaTemplateVariadic.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaTemplateVariadic.cpp
1 //===------- 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"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/RecursiveASTVisitor.h"
16 #include "clang/AST/TypeLoc.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/SemaInternal.h"
21 #include "clang/Sema/Template.h"
22
23 using namespace clang;
24
25 //----------------------------------------------------------------------------
26 // Visitor that collects unexpanded parameter packs
27 //----------------------------------------------------------------------------
28
29 namespace {
30   /// A class that collects unexpanded parameter packs.
31   class CollectUnexpandedParameterPacksVisitor :
32     public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
33   {
34     typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
35       inherited;
36
37     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
38
39     bool InLambda = false;
40     unsigned DepthLimit = (unsigned)-1;
41
42     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     }
61
62   public:
63     explicit CollectUnexpandedParameterPacksVisitor(
64         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
65         : Unexpanded(Unexpanded) {}
66
67     bool shouldWalkTypesOfTypeLocs() const { return false; }
68
69     //------------------------------------------------------------------------
70     // Recording occurrences of (unexpanded) parameter packs.
71     //------------------------------------------------------------------------
72
73     /// Record occurrences of template type parameter packs.
74     bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
75       if (TL.getTypePtr()->isParameterPack())
76         addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
77       return true;
78     }
79
80     /// Record occurrences of template type parameter packs
81     /// 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())
87         addUnexpanded(T);
88
89       return true;
90     }
91
92     /// Record occurrences of function and non-type template
93     /// parameter packs in an expression.
94     bool VisitDeclRefExpr(DeclRefExpr *E) {
95       if (E->getDecl()->isParameterPack())
96         addUnexpanded(E->getDecl(), E->getLocation());
97
98       return true;
99     }
100
101     /// Record occurrences of template template parameter packs.
102     bool TraverseTemplateName(TemplateName Template) {
103       if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
104               Template.getAsTemplateDecl())) {
105         if (TTP->isParameterPack())
106           addUnexpanded(TTP);
107       }
108
109       return inherited::TraverseTemplateName(Template);
110     }
111
112     /// Suppress traversal into Objective-C container literal
113     /// 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     }
128     //------------------------------------------------------------------------
129     // Pruning the search for unexpanded parameter packs.
130     //------------------------------------------------------------------------
131
132     /// Suppress traversal into statements and expressions that
133     /// do not contain unexpanded parameter packs.
134     bool TraverseStmt(Stmt *S) {
135       Expr *E = dyn_cast_or_null<Expr>(S);
136       if ((E && E->containsUnexpandedParameterPack()) || InLambda)
137         return inherited::TraverseStmt(S);
138
139       return true;
140     }
141
142     /// Suppress traversal into types that do not contain
143     /// unexpanded parameter packs.
144     bool TraverseType(QualType T) {
145       if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
146         return inherited::TraverseType(T);
147
148       return true;
149     }
150
151     /// Suppress traversal into types with location information
152     /// that do not contain unexpanded parameter packs.
153     bool TraverseTypeLoc(TypeLoc TL) {
154       if ((!TL.getType().isNull() &&
155            TL.getType()->containsUnexpandedParameterPack()) ||
156           InLambda)
157         return inherited::TraverseTypeLoc(TL);
158
159       return true;
160     }
161
162     /// Suppress traversal of parameter packs.
163     bool TraverseDecl(Decl *D) {
164       // A function parameter pack is a pack expansion, so cannot contain
165       // an unexpanded parameter pack. Likewise for a template parameter
166       // pack that contains any references to other packs.
167       if (D && D->isParameterPack())
168         return true;
169
170       return inherited::TraverseDecl(D);
171     }
172
173     /// Suppress traversal of pack-expanded attributes.
174     bool TraverseAttr(Attr *A) {
175       if (A->isPackExpansion())
176         return true;
177
178       return inherited::TraverseAttr(A);
179     }
180
181     /// Suppress traversal of pack expansion expressions and types.
182     ///@{
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
190     /// Suppress traversal of using-declaration pack expansion.
191     bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
192       if (D->isPackExpansion())
193         return true;
194
195       return inherited::TraverseUnresolvedUsingValueDecl(D);
196     }
197
198     /// Suppress traversal of using-declaration pack expansion.
199     bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
200       if (D->isPackExpansion())
201         return true;
202
203       return inherited::TraverseUnresolvedUsingTypenameDecl(D);
204     }
205
206     /// Suppress traversal of template argument pack expansions.
207     bool TraverseTemplateArgument(const TemplateArgument &Arg) {
208       if (Arg.isPackExpansion())
209         return true;
210
211       return inherited::TraverseTemplateArgument(Arg);
212     }
213
214     /// Suppress traversal of template argument pack expansions.
215     bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
216       if (ArgLoc.getArgument().isPackExpansion())
217         return true;
218
219       return inherited::TraverseTemplateArgumentLoc(ArgLoc);
220     }
221
222     /// Suppress traversal of base specifier pack expansions.
223     bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
224       if (Base.isPackExpansion())
225         return true;
226
227       return inherited::TraverseCXXBaseSpecifier(Base);
228     }
229
230     /// Suppress traversal of mem-initializer pack expansions.
231     bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
232       if (Init->isPackExpansion())
233         return true;
234
235       return inherited::TraverseConstructorInitializer(Init);
236     }
237
238     /// Note whether we're traversing a lambda containing an unexpanded
239     /// 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;
250       unsigned OldDepthLimit = DepthLimit;
251
252       InLambda = true;
253       if (auto *TPL = Lambda->getTemplateParameterList())
254         DepthLimit = TPL->getDepth();
255
256       inherited::TraverseLambdaExpr(Lambda);
257
258       InLambda = WasInLambda;
259       DepthLimit = OldDepthLimit;
260       return true;
261     }
262
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;
268
269       return inherited::TraverseLambdaCapture(Lambda, C, Init);
270     }
271   };
272 }
273
274 /// Determine whether it's possible for an unexpanded parameter pack to
275 /// 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.
281 bool Sema::isUnexpandedParameterPackPermitted() {
282   for (auto *SI : FunctionScopes)
283     if (isa<sema::LambdaScopeInfo>(SI))
284       return true;
285   return false;
286 }
287
288 /// Diagnose all of the unexpanded parameter packs in the given
289 /// vector.
290 bool
291 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
292                                        UnexpandedParameterPackContext UPPC,
293                                  ArrayRef<UnexpandedParameterPack> Unexpanded) {
294   if (Unexpanded.empty())
295     return false;
296
297   // 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
299   // parameter pack, and we are done.
300   // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
301   // later.
302   SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
303   for (unsigned N = FunctionScopes.size(); N; --N) {
304     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)) {
316       if (N == FunctionScopes.size()) {
317         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)
321             LambdaParamPackReferences.push_back(Param);
322         }
323       }
324
325       // 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;
331         break;
332       }
333
334       LSI->ContainsUnexpandedParameterPack = true;
335       return false;
336     }
337   }
338
339   SmallVector<SourceLocation, 4> Locations;
340   SmallVector<IdentifierInfo *, 4> Names;
341   llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
342
343   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
344     IdentifierInfo *Name = nullptr;
345     if (const TemplateTypeParmType *TTP
346           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
347       Name = TTP->getIdentifier();
348     else
349       Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
350
351     if (Name && NamesKnown.insert(Name).second)
352       Names.push_back(Name);
353
354     if (Unexpanded[I].second.isValid())
355       Locations.push_back(Unexpanded[I].second);
356   }
357
358   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];
362
363   for (unsigned I = 0, N = Locations.size(); I != N; ++I)
364     DB << SourceRange(Locations[I]);
365   return true;
366 }
367
368 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
369                                            TypeSourceInfo *T,
370                                          UnexpandedParameterPackContext UPPC) {
371   // C++0x [temp.variadic]p5:
372   //   An appearance of a name of a parameter pack that is not expanded is
373   //   ill-formed.
374   if (!T->getType()->containsUnexpandedParameterPack())
375     return false;
376
377   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
378   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
379                                                               T->getTypeLoc());
380   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
381   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
382 }
383
384 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
385                                         UnexpandedParameterPackContext UPPC) {
386   // C++0x [temp.variadic]p5:
387   //   An appearance of a name of a parameter pack that is not expanded is
388   //   ill-formed.
389   if (!E->containsUnexpandedParameterPack())
390     return false;
391
392   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
393   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
394   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
395   return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
396 }
397
398 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
399                                         UnexpandedParameterPackContext UPPC) {
400   // C++0x [temp.variadic]p5:
401   //   An appearance of a name of a parameter pack that is not expanded is
402   //   ill-formed.
403   if (!SS.getScopeRep() ||
404       !SS.getScopeRep()->containsUnexpandedParameterPack())
405     return false;
406
407   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
408   CollectUnexpandedParameterPacksVisitor(Unexpanded)
409     .TraverseNestedNameSpecifier(SS.getScopeRep());
410   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
411   return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
412                                           UPPC, Unexpanded);
413 }
414
415 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
416                                          UnexpandedParameterPackContext UPPC) {
417   // C++0x [temp.variadic]p5:
418   //   An appearance of a name of a parameter pack that is not expanded is
419   //   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:
428   case DeclarationName::CXXDeductionGuideName:
429     return false;
430
431   case DeclarationName::CXXConstructorName:
432   case DeclarationName::CXXDestructorName:
433   case DeclarationName::CXXConversionFunctionName:
434     // FIXME: We shouldn't need this null check!
435     if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
436       return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
437
438     if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
439       return false;
440
441     break;
442   }
443
444   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
445   CollectUnexpandedParameterPacksVisitor(Unexpanded)
446     .TraverseType(NameInfo.getName().getCXXNameType());
447   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
448   return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
449 }
450
451 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
452                                            TemplateName Template,
453                                        UnexpandedParameterPackContext UPPC) {
454
455   if (Template.isNull() || !Template.containsUnexpandedParameterPack())
456     return false;
457
458   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
459   CollectUnexpandedParameterPacksVisitor(Unexpanded)
460     .TraverseTemplateName(Template);
461   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
462   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
463 }
464
465 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
466                                          UnexpandedParameterPackContext UPPC) {
467   if (Arg.getArgument().isNull() ||
468       !Arg.getArgument().containsUnexpandedParameterPack())
469     return false;
470
471   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
472   CollectUnexpandedParameterPacksVisitor(Unexpanded)
473     .TraverseTemplateArgumentLoc(Arg);
474   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
475   return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
476 }
477
478 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
479                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
480   CollectUnexpandedParameterPacksVisitor(Unexpanded)
481     .TraverseTemplateArgument(Arg);
482 }
483
484 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
485                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
486   CollectUnexpandedParameterPacksVisitor(Unexpanded)
487     .TraverseTemplateArgumentLoc(Arg);
488 }
489
490 void Sema::collectUnexpandedParameterPacks(QualType T,
491                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
492   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
493 }
494
495 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
496                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
497   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
498 }
499
500 void Sema::collectUnexpandedParameterPacks(
501     NestedNameSpecifierLoc NNS,
502     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
503   CollectUnexpandedParameterPacksVisitor(Unexpanded)
504       .TraverseNestedNameSpecifierLoc(NNS);
505 }
506
507 void Sema::collectUnexpandedParameterPacks(
508     const DeclarationNameInfo &NameInfo,
509     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
510   CollectUnexpandedParameterPacksVisitor(Unexpanded)
511     .TraverseDeclarationNameInfo(NameInfo);
512 }
513
514
515 ParsedTemplateArgument
516 Sema::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
527     return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
528                                   Arg.getLocation());
529   }
530
531   case ParsedTemplateArgument::NonType: {
532     ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
533     if (Result.isInvalid())
534       return ParsedTemplateArgument();
535
536     return ParsedTemplateArgument(Arg.getKind(), Result.get(),
537                                   Arg.getLocation());
538   }
539
540   case ParsedTemplateArgument::Template:
541     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     }
549
550     return Arg.getTemplatePackExpansion(EllipsisLoc);
551   }
552   llvm_unreachable("Unhandled template argument kind?");
553 }
554
555 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
556                                     SourceLocation EllipsisLoc) {
557   TypeSourceInfo *TSInfo;
558   GetTypeFromParser(Type, &TSInfo);
559   if (!TSInfo)
560     return true;
561
562   TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
563   if (!TSResult)
564     return true;
565
566   return CreateParsedType(TSResult->getType(), TSResult);
567 }
568
569 TypeSourceInfo *
570 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
571                          Optional<unsigned> NumExpansions) {
572   // Create the pack expansion type and source-location information.
573   QualType Result = CheckPackExpansion(Pattern->getType(),
574                                        Pattern->getTypeLoc().getSourceRange(),
575                                        EllipsisLoc, NumExpansions);
576   if (Result.isNull())
577     return nullptr;
578
579   TypeLocBuilder TLB;
580   TLB.pushFullCopy(Pattern->getTypeLoc());
581   PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
582   TL.setEllipsisLoc(EllipsisLoc);
583
584   return TLB.getTypeSourceInfo(Context, Result);
585 }
586
587 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
588                                   SourceLocation EllipsisLoc,
589                                   Optional<unsigned> NumExpansions) {
590   // 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
600   return Context.getPackExpansionType(Pattern, NumExpansions);
601 }
602
603 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
604   return CheckPackExpansion(Pattern, EllipsisLoc, None);
605 }
606
607 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
608                                     Optional<unsigned> NumExpansions) {
609   if (!Pattern)
610     return ExprError();
611
612   // 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   }
621
622   // Create the pack expansion expression and source-location information.
623   return new (Context)
624     PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
625 }
626
627 bool Sema::CheckParameterPacksForExpansion(
628     SourceLocation EllipsisLoc, SourceRange PatternRange,
629     ArrayRef<UnexpandedParameterPack> Unexpanded,
630     const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
631     bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
632   ShouldExpand = true;
633   RetainExpansion = false;
634   std::pair<IdentifierInfo *, SourceLocation> FirstPack;
635   bool HaveFirstPack = false;
636   Optional<unsigned> NumPartialExpansions;
637   SourceLocation PartiallySubstitutedPackLoc;
638
639   for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
640                                                  end = Unexpanded.end();
641                                                   i != end; ++i) {
642     // Compute the depth and index for this parameter pack.
643     unsigned Depth = 0, Index = 0;
644     IdentifierInfo *Name;
645     bool IsFunctionParameterPack = false;
646
647     if (const TemplateTypeParmType *TTP
648         = i->first.dyn_cast<const TemplateTypeParmType *>()) {
649       Depth = TTP->getDepth();
650       Index = TTP->getIndex();
651       Name = TTP->getIdentifier();
652     } else {
653       NamedDecl *ND = i->first.get<NamedDecl *>();
654       if (isa<ParmVarDecl>(ND))
655         IsFunctionParameterPack = true;
656       else
657         std::tie(Depth, Index) = getDepthAndIndex(ND);
658
659       Name = ND->getIdentifier();
660     }
661
662     // Determine the size of this argument pack.
663     unsigned NewPackSize;
664     if (IsFunctionParameterPack) {
665       // Figure out whether we're instantiating to an argument pack or not.
666       typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
667
668       llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
669         = CurrentInstantiationScope->findInstantiationOf(
670                                         i->first.get<NamedDecl *>());
671       if (Instantiation->is<DeclArgumentPack *>()) {
672         // 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 {
681       // 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
683       // 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       }
689
690       // Determine the size of the argument pack.
691       NewPackSize = TemplateArgs(Depth, Index).pack_size();
692     }
693
694     // C++0x [temp.arg.explicit]p9:
695     //   Template argument deduction can extend the sequence of template
696     //   arguments corresponding to a template parameter pack, even when the
697     //   sequence contains explicitly specified template arguments.
698     if (!IsFunctionParameterPack && CurrentInstantiationScope) {
699       if (NamedDecl *PartialPack
700                     = CurrentInstantiationScope->getPartiallySubstitutedPack()){
701         unsigned PartialDepth, PartialIndex;
702         std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
703         if (PartialDepth == Depth && PartialIndex == Index) {
704           RetainExpansion = true;
705           // We don't actually know the new pack size yet.
706           NumPartialExpansions = NewPackSize;
707           PartiallySubstitutedPackLoc = i->second;
708           continue;
709         }
710       }
711     }
712
713     if (!NumExpansions) {
714       // The is the first pack we've seen for which we have an argument.
715       // Record it.
716       NumExpansions = NewPackSize;
717       FirstPack.first = Name;
718       FirstPack.second = i->second;
719       HaveFirstPack = true;
720       continue;
721     }
722
723     if (NewPackSize != *NumExpansions) {
724       // C++0x [temp.variadic]p5:
725       //   All of the parameter packs expanded by a pack expansion shall have
726       //   the same number of arguments specified.
727       if (HaveFirstPack)
728         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
729           << FirstPack.first << Name << *NumExpansions << NewPackSize
730           << SourceRange(FirstPack.second) << SourceRange(i->second);
731       else
732         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
733           << Name << *NumExpansions << NewPackSize
734           << SourceRange(i->second);
735       return true;
736     }
737   }
738
739   // 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
761   return false;
762 }
763
764 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
765                           const MultiLevelTemplateArgumentList &TemplateArgs) {
766   QualType Pattern = cast<PackExpansionType>(T)->getPattern();
767   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
768   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
769
770   Optional<unsigned> Result;
771   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;
775
776     if (const TemplateTypeParmType *TTP
777           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
778       Depth = TTP->getDepth();
779       Index = TTP->getIndex();
780     } else {
781       NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
782       if (isa<ParmVarDecl>(ND)) {
783         // Function parameter pack.
784         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
785
786         llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
787           = CurrentInstantiationScope->findInstantiationOf(
788                                         Unexpanded[I].first.get<NamedDecl *>());
789         if (Instantiation->is<Decl*>())
790           // The pattern refers to an unexpanded pack. We're not ready to expand
791           // this pack yet.
792           return None;
793
794         unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
795         assert((!Result || *Result == Size) && "inconsistent pack sizes");
796         Result = Size;
797         continue;
798       }
799
800       std::tie(Depth, Index) = getDepthAndIndex(ND);
801     }
802     if (Depth >= TemplateArgs.getNumLevels() ||
803         !TemplateArgs.hasTemplateArgument(Depth, Index))
804       // The pattern refers to an unknown template argument. We're not ready to
805       // expand this pack yet.
806       return None;
807
808     // Determine the size of the argument pack.
809     unsigned Size = TemplateArgs(Depth, Index).pack_size();
810     assert((!Result || *Result == Size) && "inconsistent pack sizes");
811     Result = Size;
812   }
813
814   return Result;
815 }
816
817 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
818   const DeclSpec &DS = D.getDeclSpec();
819   switch (DS.getTypeSpecType()) {
820   case TST_typename:
821   case TST_typeofType:
822   case TST_underlyingType:
823   case TST_atomic: {
824     QualType T = DS.getRepAsType().get();
825     if (!T.isNull() && T->containsUnexpandedParameterPack())
826       return true;
827     break;
828   }
829
830   case TST_typeofExpr:
831   case TST_decltype:
832     if (DS.getRepAsExpr() &&
833         DS.getRepAsExpr()->containsUnexpandedParameterPack())
834       return true;
835     break;
836
837   case TST_unspecified:
838   case TST_void:
839   case TST_char:
840   case TST_wchar:
841   case TST_char8:
842   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:
849   case TST_Accum:
850   case TST_Fract:
851   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:
866 #include "clang/Basic/OpenCLImageTypes.def"
867   case TST_unknown_anytype:
868   case TST_error:
869     break;
870   }
871
872   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:
878     case DeclaratorChunk::Pipe:
879     case DeclaratorChunk::BlockPointer:
880       // These declarator chunks cannot contain any parameter packs.
881       break;
882
883     case DeclaratorChunk::Array:
884       if (Chunk.Arr.NumElts &&
885           Chunk.Arr.NumElts->containsUnexpandedParameterPack())
886         return true;
887       break;
888     case DeclaratorChunk::Function:
889       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) {
897         for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
898           if (Chunk.Fun.Exceptions[i]
899                   .Ty.get()
900                   ->containsUnexpandedParameterPack())
901             return true;
902         }
903       } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
904                  Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
905         return true;
906
907       if (Chunk.Fun.hasTrailingReturnType()) {
908         QualType T = Chunk.Fun.getTrailingReturnType().get();
909         if (!T.isNull() && T->containsUnexpandedParameterPack())
910           return true;
911       }
912       break;
913
914     case DeclaratorChunk::MemberPointer:
915       if (Chunk.Mem.Scope().getScopeRep() &&
916           Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
917         return true;
918       break;
919     }
920   }
921
922   return false;
923 }
924
925 namespace {
926
927 // Callback to only accept typo corrections that refer to parameter packs.
928 class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
929  public:
930   bool ValidateCandidate(const TypoCorrection &candidate) override {
931     NamedDecl *ND = candidate.getCorrectionDecl();
932     return ND && ND->isParameterPack();
933   }
934 };
935
936 }
937
938 /// Called when an expression computing the size of a parameter pack
939 /// 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.
952 ExprResult 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.
959   LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
960   LookupName(R, S);
961
962   NamedDecl *ParameterPack = nullptr;
963   switch (R.getResultKind()) {
964   case LookupResult::Found:
965     ParameterPack = R.getFoundDecl();
966     break;
967
968   case LookupResult::NotFound:
969   case LookupResult::NotFoundInCurrentInstantiation:
970     if (TypoCorrection Corrected =
971             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
972                         llvm::make_unique<ParameterPackValidatorCCC>(),
973                         CTK_ErrorRecovery)) {
974       diagnoseTypo(Corrected,
975                    PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
976                    PDiag(diag::note_parameter_pack_here));
977       ParameterPack = Corrected.getCorrectionDecl();
978     }
979     break;
980
981   case LookupResult::FoundOverloaded:
982   case LookupResult::FoundUnresolvedValue:
983     break;
984
985   case LookupResult::Ambiguous:
986     DiagnoseAmbiguousLookup(R);
987     return ExprError();
988   }
989
990   if (!ParameterPack || !ParameterPack->isParameterPack()) {
991     Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
992       << &Name;
993     return ExprError();
994   }
995
996   MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
997
998   return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
999                                 RParenLoc);
1000 }
1001
1002 TemplateArgumentLoc
1003 Sema::getTemplateArgumentPackExpansionPattern(
1004       TemplateArgumentLoc OrigLoc,
1005       SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1006   const TemplateArgument &Argument = OrigLoc.getArgument();
1007   assert(Argument.isPackExpansion());
1008   switch (Argument.getKind()) {
1009   case TemplateArgument::Type: {
1010     // FIXME: We shouldn't ever have to worry about missing
1011     // type-source info!
1012     TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1013     if (!ExpansionTSInfo)
1014       ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1015                                                          Ellipsis);
1016     PackExpansionTypeLoc Expansion =
1017         ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1018     Ellipsis = Expansion.getEllipsisLoc();
1019
1020     TypeLoc Pattern = Expansion.getPatternLoc();
1021     NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1022
1023     // We need to copy the TypeLoc because TemplateArgumentLocs store a
1024     // TypeSourceInfo.
1025     // FIXME: Find some way to avoid the copy?
1026     TypeLocBuilder TLB;
1027     TLB.pushFullCopy(Pattern);
1028     TypeSourceInfo *PatternTSInfo =
1029         TLB.getTypeSourceInfo(Context, Pattern.getType());
1030     return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1031                                PatternTSInfo);
1032   }
1033
1034   case TemplateArgument::Expression: {
1035     PackExpansionExpr *Expansion
1036       = cast<PackExpansionExpr>(Argument.getAsExpr());
1037     Expr *Pattern = Expansion->getPattern();
1038     Ellipsis = Expansion->getEllipsisLoc();
1039     NumExpansions = Expansion->getNumExpansions();
1040     return TemplateArgumentLoc(Pattern, Pattern);
1041   }
1042
1043   case TemplateArgument::TemplateExpansion:
1044     Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1045     NumExpansions = Argument.getNumTemplateExpansions();
1046     return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1047                                OrigLoc.getTemplateQualifierLoc(),
1048                                OrigLoc.getTemplateNameLoc());
1049
1050   case TemplateArgument::Declaration:
1051   case TemplateArgument::NullPtr:
1052   case TemplateArgument::Template:
1053   case TemplateArgument::Integral:
1054   case TemplateArgument::Pack:
1055   case TemplateArgument::Null:
1056     return TemplateArgumentLoc();
1057   }
1058
1059   llvm_unreachable("Invalid TemplateArgument Kind!");
1060 }
1061
1062 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1063   assert(Arg.containsUnexpandedParameterPack());
1064
1065   // If this is a substituted pack, grab that pack. If not, we don't know
1066   // the size yet.
1067   // FIXME: We could find a size in more cases by looking for a substituted
1068   // pack anywhere within this argument, but that's not necessary in the common
1069   // case for 'sizeof...(A)' handling.
1070   TemplateArgument Pack;
1071   switch (Arg.getKind()) {
1072   case TemplateArgument::Type:
1073     if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1074       Pack = Subst->getArgumentPack();
1075     else
1076       return None;
1077     break;
1078
1079   case TemplateArgument::Expression:
1080     if (auto *Subst =
1081             dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1082       Pack = Subst->getArgumentPack();
1083     else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1084       for (ParmVarDecl *PD : *Subst)
1085         if (PD->isParameterPack())
1086           return None;
1087       return Subst->getNumExpansions();
1088     } else
1089       return None;
1090     break;
1091
1092   case TemplateArgument::Template:
1093     if (SubstTemplateTemplateParmPackStorage *Subst =
1094             Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1095       Pack = Subst->getArgumentPack();
1096     else
1097       return None;
1098     break;
1099
1100   case TemplateArgument::Declaration:
1101   case TemplateArgument::NullPtr:
1102   case TemplateArgument::TemplateExpansion:
1103   case TemplateArgument::Integral:
1104   case TemplateArgument::Pack:
1105   case TemplateArgument::Null:
1106     return None;
1107   }
1108
1109   // Check that no argument in the pack is itself a pack expansion.
1110   for (TemplateArgument Elem : Pack.pack_elements()) {
1111     // There's no point recursing in this case; we would have already
1112     // expanded this pack expansion into the enclosing pack if we could.
1113     if (Elem.isPackExpansion())
1114       return None;
1115   }
1116   return Pack.pack_size();
1117 }
1118
1119 static void CheckFoldOperand(Sema &S, Expr *E) {
1120   if (!E)
1121     return;
1122
1123   E = E->IgnoreImpCasts();
1124   auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1125   if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1126       isa<AbstractConditionalOperator>(E)) {
1127     S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1128         << E->getSourceRange()
1129         << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1130         << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1131   }
1132 }
1133
1134 ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1135                                   tok::TokenKind Operator,
1136                                   SourceLocation EllipsisLoc, Expr *RHS,
1137                                   SourceLocation RParenLoc) {
1138   // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1139   // in the parser and reduce down to just cast-expressions here.
1140   CheckFoldOperand(*this, LHS);
1141   CheckFoldOperand(*this, RHS);
1142
1143   auto DiscardOperands = [&] {
1144     CorrectDelayedTyposInExpr(LHS);
1145     CorrectDelayedTyposInExpr(RHS);
1146   };
1147
1148   // [expr.prim.fold]p3:
1149   //   In a binary fold, op1 and op2 shall be the same fold-operator, and
1150   //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
1151   //   an unexpanded parameter pack, but not both.
1152   if (LHS && RHS &&
1153       LHS->containsUnexpandedParameterPack() ==
1154           RHS->containsUnexpandedParameterPack()) {
1155     DiscardOperands();
1156     return Diag(EllipsisLoc,
1157                 LHS->containsUnexpandedParameterPack()
1158                     ? diag::err_fold_expression_packs_both_sides
1159                     : diag::err_pack_expansion_without_parameter_packs)
1160         << LHS->getSourceRange() << RHS->getSourceRange();
1161   }
1162
1163   // [expr.prim.fold]p2:
1164   //   In a unary fold, the cast-expression shall contain an unexpanded
1165   //   parameter pack.
1166   if (!LHS || !RHS) {
1167     Expr *Pack = LHS ? LHS : RHS;
1168     assert(Pack && "fold expression with neither LHS nor RHS");
1169     DiscardOperands();
1170     if (!Pack->containsUnexpandedParameterPack())
1171       return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1172              << Pack->getSourceRange();
1173   }
1174
1175   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1176   return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc);
1177 }
1178
1179 ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1180                                   BinaryOperatorKind Operator,
1181                                   SourceLocation EllipsisLoc, Expr *RHS,
1182                                   SourceLocation RParenLoc) {
1183   return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1184                                    Operator, EllipsisLoc, RHS, RParenLoc);
1185 }
1186
1187 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1188                                        BinaryOperatorKind Operator) {
1189   // [temp.variadic]p9:
1190   //   If N is zero for a unary fold-expression, the value of the expression is
1191   //       &&  ->  true
1192   //       ||  ->  false
1193   //       ,   ->  void()
1194   //   if the operator is not listed [above], the instantiation is ill-formed.
1195   //
1196   // Note that we need to use something like int() here, not merely 0, to
1197   // prevent the result from being a null pointer constant.
1198   QualType ScalarType;
1199   switch (Operator) {
1200   case BO_LOr:
1201     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1202   case BO_LAnd:
1203     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1204   case BO_Comma:
1205     ScalarType = Context.VoidTy;
1206     break;
1207
1208   default:
1209     return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1210         << BinaryOperator::getOpcodeStr(Operator);
1211   }
1212
1213   return new (Context) CXXScalarValueInitExpr(
1214       ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1215       EllipsisLoc);
1216 }