Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaTemplateVariadic.cpp
Line
Count
Source (jump to first uncovered line)
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
//===----------------------------------------------------------------------===/
10
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"
21
22
using namespace clang;
23
24
//----------------------------------------------------------------------------
25
// Visitor that collects unexpanded parameter packs
26
//----------------------------------------------------------------------------
27
28
namespace {
29
  /// A class that collects unexpanded parameter packs.
30
  class CollectUnexpandedParameterPacksVisitor :
31
    public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
32
  {
33
    typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34
      inherited;
35
36
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
37
38
    bool InLambda = false;
39
    unsigned DepthLimit = (unsigned)-1;
40
41
48.1k
    void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42
48.1k
      if (auto *VD = dyn_cast<VarDecl>(ND)) {
43
7.46k
        // For now, the only problematic case is a generic lambda's templated
44
7.46k
        // call operator, so we don't need to look for all the other ways we
45
7.46k
        // could have reached a dependent parameter pack.
46
7.46k
        auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
47
7.46k
        auto *FTD = FD ? 
FD->getDescribedFunctionTemplate()7.45k
:
nullptr4
;
48
7.46k
        if (FTD && 
FTD->getTemplateParameters()->getDepth() >= DepthLimit7.37k
)
49
0
          return;
50
40.6k
      } else if (getDepthAndIndex(ND).first >= DepthLimit)
51
0
        return;
52
48.1k
53
48.1k
      Unexpanded.push_back({ND, Loc});
54
48.1k
    }
55
    void addUnexpanded(const TemplateTypeParmType *T,
56
272k
                       SourceLocation Loc = SourceLocation()) {
57
272k
      if (T->getDepth() < DepthLimit)
58
272k
        Unexpanded.push_back({T, Loc});
59
272k
    }
60
61
  public:
62
    explicit CollectUnexpandedParameterPacksVisitor(
63
        SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64
311k
        : Unexpanded(Unexpanded) {}
65
66
235k
    bool shouldWalkTypesOfTypeLocs() const { return false; }
67
68
    //------------------------------------------------------------------------
69
    // Recording occurrences of (unexpanded) parameter packs.
70
    //------------------------------------------------------------------------
71
72
    /// Record occurrences of template type parameter packs.
73
184k
    bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74
184k
      if (TL.getTypePtr()->isParameterPack())
75
184k
        addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76
184k
      return true;
77
184k
    }
78
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
88.5k
    bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85
88.5k
      if (T->isParameterPack())
86
88.5k
        addUnexpanded(T);
87
88.5k
88
88.5k
      return true;
89
88.5k
    }
90
91
    /// Record occurrences of function and non-type template
92
    /// parameter packs in an expression.
93
48.1k
    bool VisitDeclRefExpr(DeclRefExpr *E) {
94
48.1k
      if (E->getDecl()->isParameterPack())
95
48.0k
        addUnexpanded(E->getDecl(), E->getLocation());
96
48.1k
97
48.1k
      return true;
98
48.1k
    }
99
100
    /// Record occurrences of template template parameter packs.
101
8.73k
    bool TraverseTemplateName(TemplateName Template) {
102
8.73k
      if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
103
2.31k
              Template.getAsTemplateDecl())) {
104
2.31k
        if (TTP->isParameterPack())
105
61
          addUnexpanded(TTP);
106
2.31k
      }
107
8.73k
108
8.73k
      return inherited::TraverseTemplateName(Template);
109
8.73k
    }
110
111
    /// Suppress traversal into Objective-C container literal
112
    /// elements that are pack expansions.
113
1
    bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
114
1
      if (!E->containsUnexpandedParameterPack())
115
0
        return true;
116
1
117
2
      
for (unsigned I = 0, N = E->getNumElements(); 1
I != N;
++I1
) {
118
1
        ObjCDictionaryElement Element = E->getKeyValueElement(I);
119
1
        if (Element.isPackExpansion())
120
0
          continue;
121
1
122
1
        TraverseStmt(Element.Key);
123
1
        TraverseStmt(Element.Value);
124
1
      }
125
1
      return true;
126
1
    }
127
    //------------------------------------------------------------------------
128
    // Pruning the search for unexpanded parameter packs.
129
    //------------------------------------------------------------------------
130
131
    /// Suppress traversal into statements and expressions that
132
    /// do not contain unexpanded parameter packs.
133
127k
    bool TraverseStmt(Stmt *S) {
134
127k
      Expr *E = dyn_cast_or_null<Expr>(S);
135
127k
      if ((E && 
E->containsUnexpandedParameterPack()127k
) ||
InLambda13.9k
)
136
113k
        return inherited::TraverseStmt(S);
137
13.6k
138
13.6k
      return true;
139
13.6k
    }
140
141
    /// Suppress traversal into types that do not contain
142
    /// unexpanded parameter packs.
143
152k
    bool TraverseType(QualType T) {
144
152k
      if ((!T.isNull() && 
T->containsUnexpandedParameterPack()152k
) ||
InLambda1.16k
)
145
150k
        return inherited::TraverseType(T);
146
1.13k
147
1.13k
      return true;
148
1.13k
    }
149
150
    /// Suppress traversal into types with location information
151
    /// that do not contain unexpanded parameter packs.
152
248k
    bool TraverseTypeLoc(TypeLoc TL) {
153
248k
      if ((!TL.getType().isNull() &&
154
248k
           TL.getType()->containsUnexpandedParameterPack()) ||
155
248k
          
InLambda12.8k
)
156
235k
        return inherited::TraverseTypeLoc(TL);
157
12.7k
158
12.7k
      return true;
159
12.7k
    }
160
161
    /// Suppress traversal of parameter packs.
162
172
    bool TraverseDecl(Decl *D) {
163
172
      // A function parameter pack is a pack expansion, so cannot contain
164
172
      // an unexpanded parameter pack. Likewise for a template parameter
165
172
      // pack that contains any references to other packs.
166
172
      if (D && 
D->isParameterPack()171
)
167
14
        return true;
168
158
169
158
      return inherited::TraverseDecl(D);
170
158
    }
171
172
    /// Suppress traversal of pack-expanded attributes.
173
6
    bool TraverseAttr(Attr *A) {
174
6
      if (A->isPackExpansion())
175
4
        return true;
176
2
177
2
      return inherited::TraverseAttr(A);
178
2
    }
179
180
    /// Suppress traversal of pack expansion expressions and types.
181
    ///@{
182
0
    bool TraversePackExpansionType(PackExpansionType *T) { return true; }
183
0
    bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
184
10
    bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
185
2
    bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
186
187
    ///@}
188
189
    /// Suppress traversal of using-declaration pack expansion.
190
3
    bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
191
3
      if (D->isPackExpansion())
192
2
        return true;
193
1
194
1
      return inherited::TraverseUnresolvedUsingValueDecl(D);
195
1
    }
196
197
    /// Suppress traversal of using-declaration pack expansion.
198
3
    bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
199
3
      if (D->isPackExpansion())
200
2
        return true;
201
1
202
1
      return inherited::TraverseUnresolvedUsingTypenameDecl(D);
203
1
    }
204
205
    /// Suppress traversal of template argument pack expansions.
206
60.0k
    bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207
60.0k
      if (Arg.isPackExpansion())
208
8
        return true;
209
60.0k
210
60.0k
      return inherited::TraverseTemplateArgument(Arg);
211
60.0k
    }
212
213
    /// Suppress traversal of template argument pack expansions.
214
166k
    bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215
166k
      if (ArgLoc.getArgument().isPackExpansion())
216
633
        return true;
217
166k
218
166k
      return inherited::TraverseTemplateArgumentLoc(ArgLoc);
219
166k
    }
220
221
    /// Suppress traversal of base specifier pack expansions.
222
13
    bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
223
13
      if (Base.isPackExpansion())
224
10
        return true;
225
3
226
3
      return inherited::TraverseCXXBaseSpecifier(Base);
227
3
    }
228
229
    /// Suppress traversal of mem-initializer pack expansions.
230
6
    bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
231
6
      if (Init->isPackExpansion())
232
4
        return true;
233
2
234
2
      return inherited::TraverseConstructorInitializer(Init);
235
2
    }
236
237
    /// Note whether we're traversing a lambda containing an unexpanded
238
    /// parameter pack. In this case, the unexpanded pack can occur anywhere,
239
    /// including all the places where we normally wouldn't look. Within a
240
    /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
241
    /// outside an expression.
242
90
    bool TraverseLambdaExpr(LambdaExpr *Lambda) {
243
90
      // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
244
90
      // even if it's contained within another lambda.
245
90
      if (!Lambda->containsUnexpandedParameterPack())
246
7
        return true;
247
83
248
83
      bool WasInLambda = InLambda;
249
83
      unsigned OldDepthLimit = DepthLimit;
250
83
251
83
      InLambda = true;
252
83
      if (auto *TPL = Lambda->getTemplateParameterList())
253
4
        DepthLimit = TPL->getDepth();
254
83
255
83
      inherited::TraverseLambdaExpr(Lambda);
256
83
257
83
      InLambda = WasInLambda;
258
83
      DepthLimit = OldDepthLimit;
259
83
      return true;
260
83
    }
261
262
    /// Suppress traversal within pack expansions in lambda captures.
263
    bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
264
44
                               Expr *Init) {
265
44
      if (C->isPackExpansion())
266
6
        return true;
267
38
268
38
      return inherited::TraverseLambdaCapture(Lambda, C, Init);
269
38
    }
270
  };
271
}
272
273
/// Determine whether it's possible for an unexpanded parameter pack to
274
/// be valid in this location. This only happens when we're in a declaration
275
/// that is nested within an expression that could be expanded, such as a
276
/// lambda-expression within a function call.
277
///
278
/// This is conservatively correct, but may claim that some unexpanded packs are
279
/// permitted when they are not.
280
38
bool Sema::isUnexpandedParameterPackPermitted() {
281
38
  for (auto *SI : FunctionScopes)
282
4
    if (isa<sema::LambdaScopeInfo>(SI))
283
2
      return true;
284
38
  
return false36
;
285
38
}
286
287
/// Diagnose all of the unexpanded parameter packs in the given
288
/// vector.
289
bool
290
Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
291
                                       UnexpandedParameterPackContext UPPC,
292
241
                                 ArrayRef<UnexpandedParameterPack> Unexpanded) {
293
241
  if (Unexpanded.empty())
294
0
    return false;
295
241
296
241
  // If we are within a lambda expression and referencing a pack that is not
297
241
  // a parameter of the lambda itself, that lambda contains an unexpanded
298
241
  // parameter pack, and we are done.
299
241
  // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
300
241
  // later.
301
241
  SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
302
352
  for (unsigned N = FunctionScopes.size(); N; 
--N111
) {
303
174
    sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
304
174
    // We do not permit pack expansion that would duplicate a statement
305
174
    // expression, not even within a lambda.
306
174
    // FIXME: We could probably support this for statement expressions that do
307
174
    // not contain labels, and for pack expansions that expand both the stmt
308
174
    // expr and the enclosing lambda.
309
174
    if (std::any_of(
310
174
            Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
311
174
            [](sema::CompoundScopeInfo &CSI) 
{ return CSI.IsStmtExpr; }172
))
312
2
      break;
313
172
314
172
    if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Func)) {
315
61
      if (N == FunctionScopes.size()) {
316
61
        for (auto &Pack : Unexpanded) {
317
61
          auto *VD = dyn_cast_or_null<VarDecl>(
318
61
              Pack.first.dyn_cast<NamedDecl *>());
319
61
          if (VD && 
VD->getDeclContext() == LSI->CallOperator20
)
320
11
            LambdaParamPackReferences.push_back(Pack);
321
61
        }
322
58
      }
323
61
324
61
      // If we have references to a parameter pack of the innermost enclosing
325
61
      // lambda, only diagnose those ones. We don't know whether any other
326
61
      // unexpanded parameters referenced herein are actually unexpanded;
327
61
      // they might be expanded at an outer level.
328
61
      if (!LambdaParamPackReferences.empty()) {
329
11
        Unexpanded = LambdaParamPackReferences;
330
11
        break;
331
11
      }
332
50
333
50
      LSI->ContainsUnexpandedParameterPack = true;
334
50
      return false;
335
50
    }
336
172
  }
337
241
338
241
  SmallVector<SourceLocation, 4> Locations;
339
191
  SmallVector<IdentifierInfo *, 4> Names;
340
191
  llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
341
191
342
393
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I202
) {
343
202
    IdentifierInfo *Name = nullptr;
344
202
    if (const TemplateTypeParmType *TTP
345
137
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
346
137
      Name = TTP->getIdentifier();
347
65
    else
348
65
      Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
349
202
350
202
    if (Name && NamesKnown.insert(Name).second)
351
198
      Names.push_back(Name);
352
202
353
202
    if (Unexpanded[I].second.isValid())
354
189
      Locations.push_back(Unexpanded[I].second);
355
202
  }
356
191
357
191
  DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
358
191
                         << (int)UPPC << (int)Names.size();
359
388
  for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; 
++I197
)
360
197
    DB << Names[I];
361
191
362
380
  for (unsigned I = 0, N = Locations.size(); I != N; 
++I189
)
363
189
    DB << SourceRange(Locations[I]);
364
191
  return true;
365
241
}
366
367
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
368
                                           TypeSourceInfo *T,
369
12.1M
                                         UnexpandedParameterPackContext UPPC) {
370
12.1M
  // C++0x [temp.variadic]p5:
371
12.1M
  //   An appearance of a name of a parameter pack that is not expanded is
372
12.1M
  //   ill-formed.
373
12.1M
  if (!T->getType()->containsUnexpandedParameterPack())
374
12.1M
    return false;
375
91
376
91
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
377
91
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
378
91
                                                              T->getTypeLoc());
379
91
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
380
91
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
381
91
}
382
383
bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
384
17.1M
                                        UnexpandedParameterPackContext UPPC) {
385
17.1M
  // C++0x [temp.variadic]p5:
386
17.1M
  //   An appearance of a name of a parameter pack that is not expanded is
387
17.1M
  //   ill-formed.
388
17.1M
  if (!E->containsUnexpandedParameterPack())
389
17.1M
    return false;
390
139
391
139
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
392
139
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
393
139
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
394
139
  return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
395
139
}
396
397
bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
398
442k
                                        UnexpandedParameterPackContext UPPC) {
399
442k
  // C++0x [temp.variadic]p5:
400
442k
  //   An appearance of a name of a parameter pack that is not expanded is
401
442k
  //   ill-formed.
402
442k
  if (!SS.getScopeRep() ||
403
442k
      
!SS.getScopeRep()->containsUnexpandedParameterPack()412k
)
404
442k
    return false;
405
8
406
8
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
407
8
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
408
8
    .TraverseNestedNameSpecifier(SS.getScopeRep());
409
8
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
410
8
  return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
411
8
                                          UPPC, Unexpanded);
412
8
}
413
414
bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
415
10.1M
                                         UnexpandedParameterPackContext UPPC) {
416
10.1M
  // C++0x [temp.variadic]p5:
417
10.1M
  //   An appearance of a name of a parameter pack that is not expanded is
418
10.1M
  //   ill-formed.
419
10.1M
  switch (NameInfo.getName().getNameKind()) {
420
10.1M
  case DeclarationName::Identifier:
421
9.73M
  case DeclarationName::ObjCZeroArgSelector:
422
9.73M
  case DeclarationName::ObjCOneArgSelector:
423
9.73M
  case DeclarationName::ObjCMultiArgSelector:
424
9.73M
  case DeclarationName::CXXOperatorName:
425
9.73M
  case DeclarationName::CXXLiteralOperatorName:
426
9.73M
  case DeclarationName::CXXUsingDirective:
427
9.73M
  case DeclarationName::CXXDeductionGuideName:
428
9.73M
    return false;
429
9.73M
430
9.73M
  case DeclarationName::CXXConstructorName:
431
388k
  case DeclarationName::CXXDestructorName:
432
388k
  case DeclarationName::CXXConversionFunctionName:
433
388k
    // FIXME: We shouldn't need this null check!
434
388k
    if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
435
72.4k
      return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
436
315k
437
315k
    if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
438
315k
      return false;
439
0
440
0
    break;
441
0
  }
442
0
443
0
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
444
0
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
445
0
    .TraverseType(NameInfo.getName().getCXXNameType());
446
0
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
447
0
  return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
448
0
}
449
450
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
451
                                           TemplateName Template,
452
171
                                       UnexpandedParameterPackContext UPPC) {
453
171
454
171
  if (Template.isNull() || !Template.containsUnexpandedParameterPack())
455
170
    return false;
456
1
457
1
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
458
1
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
459
1
    .TraverseTemplateName(Template);
460
1
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
461
1
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
462
1
}
463
464
bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
465
467k
                                         UnexpandedParameterPackContext UPPC) {
466
467k
  if (Arg.getArgument().isNull() ||
467
467k
      !Arg.getArgument().containsUnexpandedParameterPack())
468
467k
    return false;
469
1
470
1
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
471
1
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
472
1
    .TraverseTemplateArgumentLoc(Arg);
473
1
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
474
1
  return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
475
1
}
476
477
void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
478
59.4k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
479
59.4k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
480
59.4k
    .TraverseTemplateArgument(Arg);
481
59.4k
}
482
483
void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
484
140k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
485
140k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
486
140k
    .TraverseTemplateArgumentLoc(Arg);
487
140k
}
488
489
void Sema::collectUnexpandedParameterPacks(QualType T,
490
947
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
491
947
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
492
947
}
493
494
void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
495
65.4k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
496
65.4k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
497
65.4k
}
498
499
void Sema::collectUnexpandedParameterPacks(
500
    NestedNameSpecifierLoc NNS,
501
40
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
502
40
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
503
40
      .TraverseNestedNameSpecifierLoc(NNS);
504
40
}
505
506
void Sema::collectUnexpandedParameterPacks(
507
    const DeclarationNameInfo &NameInfo,
508
40
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
509
40
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
510
40
    .TraverseDeclarationNameInfo(NameInfo);
511
40
}
512
513
514
ParsedTemplateArgument
515
Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
516
97.7k
                         SourceLocation EllipsisLoc) {
517
97.7k
  if (Arg.isInvalid())
518
11
    return Arg;
519
97.7k
520
97.7k
  switch (Arg.getKind()) {
521
97.7k
  case ParsedTemplateArgument::Type: {
522
80.2k
    TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
523
80.2k
    if (Result.isInvalid())
524
2
      return ParsedTemplateArgument();
525
80.2k
526
80.2k
    return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
527
80.2k
                                  Arg.getLocation());
528
80.2k
  }
529
80.2k
530
80.2k
  case ParsedTemplateArgument::NonType: {
531
17.4k
    ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
532
17.4k
    if (Result.isInvalid())
533
0
      return ParsedTemplateArgument();
534
17.4k
535
17.4k
    return ParsedTemplateArgument(Arg.getKind(), Result.get(),
536
17.4k
                                  Arg.getLocation());
537
17.4k
  }
538
17.4k
539
17.4k
  case ParsedTemplateArgument::Template:
540
22
    if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
541
0
      SourceRange R(Arg.getLocation());
542
0
      if (Arg.getScopeSpec().isValid())
543
0
        R.setBegin(Arg.getScopeSpec().getBeginLoc());
544
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
545
0
        << R;
546
0
      return ParsedTemplateArgument();
547
0
    }
548
22
549
22
    return Arg.getTemplatePackExpansion(EllipsisLoc);
550
0
  }
551
0
  llvm_unreachable("Unhandled template argument kind?");
552
0
}
553
554
TypeResult Sema::ActOnPackExpansion(ParsedType Type,
555
82.6k
                                    SourceLocation EllipsisLoc) {
556
82.6k
  TypeSourceInfo *TSInfo;
557
82.6k
  GetTypeFromParser(Type, &TSInfo);
558
82.6k
  if (!TSInfo)
559
0
    return true;
560
82.6k
561
82.6k
  TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
562
82.6k
  if (!TSResult)
563
2
    return true;
564
82.6k
565
82.6k
  return CreateParsedType(TSResult->getType(), TSResult);
566
82.6k
}
567
568
TypeSourceInfo *
569
Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
570
156k
                         Optional<unsigned> NumExpansions) {
571
156k
  // Create the pack expansion type and source-location information.
572
156k
  QualType Result = CheckPackExpansion(Pattern->getType(),
573
156k
                                       Pattern->getTypeLoc().getSourceRange(),
574
156k
                                       EllipsisLoc, NumExpansions);
575
156k
  if (Result.isNull())
576
2
    return nullptr;
577
156k
578
156k
  TypeLocBuilder TLB;
579
156k
  TLB.pushFullCopy(Pattern->getTypeLoc());
580
156k
  PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
581
156k
  TL.setEllipsisLoc(EllipsisLoc);
582
156k
583
156k
  return TLB.getTypeSourceInfo(Context, Result);
584
156k
}
585
586
QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
587
                                  SourceLocation EllipsisLoc,
588
156k
                                  Optional<unsigned> NumExpansions) {
589
156k
  // C++11 [temp.variadic]p5:
590
156k
  //   The pattern of a pack expansion shall name one or more
591
156k
  //   parameter packs that are not expanded by a nested pack
592
156k
  //   expansion.
593
156k
  //
594
156k
  // A pattern containing a deduced type can't occur "naturally" but arises in
595
156k
  // the desugaring of an init-capture pack.
596
156k
  if (!Pattern->containsUnexpandedParameterPack() &&
597
156k
      
!Pattern->getContainedDeducedType()5
) {
598
2
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
599
2
      << PatternRange;
600
2
    return QualType();
601
2
  }
602
156k
603
156k
  return Context.getPackExpansionType(Pattern, NumExpansions);
604
156k
}
605
606
61.8k
ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
607
61.8k
  return CheckPackExpansion(Pattern, EllipsisLoc, None);
608
61.8k
}
609
610
ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
611
89.9k
                                    Optional<unsigned> NumExpansions) {
612
89.9k
  if (!Pattern)
613
7
    return ExprError();
614
89.9k
615
89.9k
  // C++0x [temp.variadic]p5:
616
89.9k
  //   The pattern of a pack expansion shall name one or more
617
89.9k
  //   parameter packs that are not expanded by a nested pack
618
89.9k
  //   expansion.
619
89.9k
  if (!Pattern->containsUnexpandedParameterPack()) {
620
12
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
621
12
    << Pattern->getSourceRange();
622
12
    CorrectDelayedTyposInExpr(Pattern);
623
12
    return ExprError();
624
12
  }
625
89.9k
626
89.9k
  // Create the pack expansion expression and source-location information.
627
89.9k
  return new (Context)
628
89.9k
    PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
629
89.9k
}
630
631
bool Sema::CheckParameterPacksForExpansion(
632
    SourceLocation EllipsisLoc, SourceRange PatternRange,
633
    ArrayRef<UnexpandedParameterPack> Unexpanded,
634
    const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
635
252k
    bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
636
252k
  ShouldExpand = true;
637
252k
  RetainExpansion = false;
638
252k
  std::pair<IdentifierInfo *, SourceLocation> FirstPack;
639
252k
  bool HaveFirstPack = false;
640
252k
  Optional<unsigned> NumPartialExpansions;
641
252k
  SourceLocation PartiallySubstitutedPackLoc;
642
252k
643
252k
  for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
644
252k
                                                 end = Unexpanded.end();
645
516k
                                                  i != end; 
++i263k
) {
646
263k
    // Compute the depth and index for this parameter pack.
647
263k
    unsigned Depth = 0, Index = 0;
648
263k
    IdentifierInfo *Name;
649
263k
    bool IsVarDeclPack = false;
650
263k
651
263k
    if (const TemplateTypeParmType *TTP
652
169k
        = i->first.dyn_cast<const TemplateTypeParmType *>()) {
653
169k
      Depth = TTP->getDepth();
654
169k
      Index = TTP->getIndex();
655
169k
      Name = TTP->getIdentifier();
656
169k
    } else {
657
93.5k
      NamedDecl *ND = i->first.get<NamedDecl *>();
658
93.5k
      if (isa<VarDecl>(ND))
659
7.57k
        IsVarDeclPack = true;
660
85.9k
      else
661
85.9k
        std::tie(Depth, Index) = getDepthAndIndex(ND);
662
93.5k
663
93.5k
      Name = ND->getIdentifier();
664
93.5k
    }
665
263k
666
263k
    // Determine the size of this argument pack.
667
263k
    unsigned NewPackSize;
668
263k
    if (IsVarDeclPack) {
669
7.57k
      // Figure out whether we're instantiating to an argument pack or not.
670
7.57k
      typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
671
7.57k
672
7.57k
      llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
673
7.57k
        = CurrentInstantiationScope->findInstantiationOf(
674
7.57k
                                        i->first.get<NamedDecl *>());
675
7.57k
      if (Instantiation->is<DeclArgumentPack *>()) {
676
7.32k
        // We could expand this function parameter pack.
677
7.32k
        NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
678
7.32k
      } else {
679
256
        // We can't expand this function parameter pack, so we can't expand
680
256
        // the pack expansion.
681
256
        ShouldExpand = false;
682
256
        continue;
683
256
      }
684
255k
    } else {
685
255k
      // If we don't have a template argument at this depth/index, then we
686
255k
      // cannot expand the pack expansion. Make a note of this, but we still
687
255k
      // want to check any parameter packs we *do* have arguments for.
688
255k
      if (Depth >= TemplateArgs.getNumLevels() ||
689
255k
          
!TemplateArgs.hasTemplateArgument(Depth, Index)187k
) {
690
87.1k
        ShouldExpand = false;
691
87.1k
        continue;
692
87.1k
      }
693
168k
694
168k
      // Determine the size of the argument pack.
695
168k
      NewPackSize = TemplateArgs(Depth, Index).pack_size();
696
168k
    }
697
263k
698
263k
    // C++0x [temp.arg.explicit]p9:
699
263k
    //   Template argument deduction can extend the sequence of template
700
263k
    //   arguments corresponding to a template parameter pack, even when the
701
263k
    //   sequence contains explicitly specified template arguments.
702
263k
    
if (176k
!IsVarDeclPack176k
&&
CurrentInstantiationScope168k
) {
703
168k
      if (NamedDecl *PartialPack
704
523
                    = CurrentInstantiationScope->getPartiallySubstitutedPack()){
705
523
        unsigned PartialDepth, PartialIndex;
706
523
        std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
707
523
        if (PartialDepth == Depth && PartialIndex == Index) {
708
523
          RetainExpansion = true;
709
523
          // We don't actually know the new pack size yet.
710
523
          NumPartialExpansions = NewPackSize;
711
523
          PartiallySubstitutedPackLoc = i->second;
712
523
          continue;
713
523
        }
714
175k
      }
715
168k
    }
716
175k
717
175k
    if (!NumExpansions) {
718
166k
      // The is the first pack we've seen for which we have an argument.
719
166k
      // Record it.
720
166k
      NumExpansions = NewPackSize;
721
166k
      FirstPack.first = Name;
722
166k
      FirstPack.second = i->second;
723
166k
      HaveFirstPack = true;
724
166k
      continue;
725
166k
    }
726
9.51k
727
9.51k
    if (NewPackSize != *NumExpansions) {
728
26
      // C++0x [temp.variadic]p5:
729
26
      //   All of the parameter packs expanded by a pack expansion shall have
730
26
      //   the same number of arguments specified.
731
26
      if (HaveFirstPack)
732
14
        Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
733
14
          << FirstPack.first << Name << *NumExpansions << NewPackSize
734
14
          << SourceRange(FirstPack.second) << SourceRange(i->second);
735
12
      else
736
12
        Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
737
12
          << Name << *NumExpansions << NewPackSize
738
12
          << SourceRange(i->second);
739
26
      return true;
740
26
    }
741
9.51k
  }
742
252k
743
252k
  // If we're performing a partial expansion but we also have a full expansion,
744
252k
  // expand to the number of common arguments. For example, given:
745
252k
  //
746
252k
  //   template<typename ...T> struct A {
747
252k
  //     template<typename ...U> void f(pair<T, U>...);
748
252k
  //   };
749
252k
  //
750
252k
  // ... a call to 'A<int, int>().f<int>' should expand the pack once and
751
252k
  // retain an expansion.
752
252k
  
if (252k
NumPartialExpansions252k
) {
753
523
    if (NumExpansions && 
*NumExpansions < *NumPartialExpansions7
) {
754
1
      NamedDecl *PartialPack =
755
1
          CurrentInstantiationScope->getPartiallySubstitutedPack();
756
1
      Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
757
1
        << PartialPack << *NumPartialExpansions << *NumExpansions
758
1
        << SourceRange(PartiallySubstitutedPackLoc);
759
1
      return true;
760
1
    }
761
522
762
522
    NumExpansions = NumPartialExpansions;
763
522
  }
764
252k
765
252k
  
return false252k
;
766
252k
}
767
768
Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
769
45.0k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
770
45.0k
  QualType Pattern = cast<PackExpansionType>(T)->getPattern();
771
45.0k
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
772
45.0k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
773
45.0k
774
45.0k
  Optional<unsigned> Result;
775
65.4k
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I20.3k
) {
776
45.1k
    // Compute the depth and index for this parameter pack.
777
45.1k
    unsigned Depth;
778
45.1k
    unsigned Index;
779
45.1k
780
45.1k
    if (const TemplateTypeParmType *TTP
781
45.0k
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
782
45.0k
      Depth = TTP->getDepth();
783
45.0k
      Index = TTP->getIndex();
784
45.0k
    } else {
785
41
      NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
786
41
      if (isa<VarDecl>(ND)) {
787
0
        // Function parameter pack or init-capture pack.
788
0
        typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
789
0
790
0
        llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
791
0
          = CurrentInstantiationScope->findInstantiationOf(
792
0
                                        Unexpanded[I].first.get<NamedDecl *>());
793
0
        if (Instantiation->is<Decl*>())
794
0
          // The pattern refers to an unexpanded pack. We're not ready to expand
795
0
          // this pack yet.
796
0
          return None;
797
0
798
0
        unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
799
0
        assert((!Result || *Result == Size) && "inconsistent pack sizes");
800
0
        Result = Size;
801
0
        continue;
802
0
      }
803
41
804
41
      std::tie(Depth, Index) = getDepthAndIndex(ND);
805
41
    }
806
45.1k
    if (Depth >= TemplateArgs.getNumLevels() ||
807
45.1k
        
!TemplateArgs.hasTemplateArgument(Depth, Index)20.3k
)
808
24.7k
      // The pattern refers to an unknown template argument. We're not ready to
809
24.7k
      // expand this pack yet.
810
24.7k
      return None;
811
20.3k
812
20.3k
    // Determine the size of the argument pack.
813
20.3k
    unsigned Size = TemplateArgs(Depth, Index).pack_size();
814
20.3k
    assert((!Result || *Result == Size) && "inconsistent pack sizes");
815
20.3k
    Result = Size;
816
20.3k
  }
817
45.0k
818
45.0k
  
return Result20.2k
;
819
45.0k
}
820
821
38.5k
bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
822
38.5k
  const DeclSpec &DS = D.getDeclSpec();
823
38.5k
  switch (DS.getTypeSpecType()) {
824
38.5k
  case TST_typename:
825
38.4k
  case TST_typeofType:
826
38.4k
  case TST_underlyingType:
827
38.4k
  case TST_atomic: {
828
38.4k
    QualType T = DS.getRepAsType().get();
829
38.4k
    if (!T.isNull() && T->containsUnexpandedParameterPack())
830
38.4k
      return true;
831
10
    break;
832
10
  }
833
10
834
20
  case TST_typeofExpr:
835
20
  case TST_decltype:
836
20
    if (DS.getRepAsExpr() &&
837
20
        DS.getRepAsExpr()->containsUnexpandedParameterPack())
838
20
      return true;
839
0
    break;
840
0
841
80
  case TST_unspecified:
842
80
  case TST_void:
843
80
  case TST_char:
844
80
  case TST_wchar:
845
80
  case TST_char8:
846
80
  case TST_char16:
847
80
  case TST_char32:
848
80
  case TST_int:
849
80
  case TST_int128:
850
80
  case TST_half:
851
80
  case TST_float:
852
80
  case TST_double:
853
80
  case TST_Accum:
854
80
  case TST_Fract:
855
80
  case TST_Float16:
856
80
  case TST_float128:
857
80
  case TST_bool:
858
80
  case TST_decimal32:
859
80
  case TST_decimal64:
860
80
  case TST_decimal128:
861
80
  case TST_enum:
862
80
  case TST_union:
863
80
  case TST_struct:
864
80
  case TST_interface:
865
80
  case TST_class:
866
80
  case TST_auto:
867
80
  case TST_auto_type:
868
80
  case TST_decltype_auto:
869
960
#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
870
960
#include 
"clang/Basic/OpenCLImageTypes.def"80
871
960
  case TST_unknown_anytype:
872
80
  case TST_error:
873
80
    break;
874
90
  }
875
90
876
116
  
for (unsigned I = 0, N = D.getNumTypeObjects(); 90
I != N;
++I26
) {
877
26
    const DeclaratorChunk &Chunk = D.getTypeObject(I);
878
26
    switch (Chunk.Kind) {
879
26
    case DeclaratorChunk::Pointer:
880
0
    case DeclaratorChunk::Reference:
881
0
    case DeclaratorChunk::Paren:
882
0
    case DeclaratorChunk::Pipe:
883
0
    case DeclaratorChunk::BlockPointer:
884
0
      // These declarator chunks cannot contain any parameter packs.
885
0
      break;
886
0
887
20
    case DeclaratorChunk::Array:
888
20
      if (Chunk.Arr.NumElts &&
889
20
          
Chunk.Arr.NumElts->containsUnexpandedParameterPack()0
)
890
0
        return true;
891
20
      break;
892
20
    case DeclaratorChunk::Function:
893
10
      for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; 
++i4
) {
894
4
        ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
895
4
        QualType ParamTy = Param->getType();
896
4
        assert(!ParamTy.isNull() && "Couldn't parse type?");
897
4
        if (ParamTy->containsUnexpandedParameterPack()) 
return true0
;
898
4
      }
899
6
900
6
      if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
901
0
        for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
902
0
          if (Chunk.Fun.Exceptions[i]
903
0
                  .Ty.get()
904
0
                  ->containsUnexpandedParameterPack())
905
0
            return true;
906
0
        }
907
6
      } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
908
6
                 
Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack()0
)
909
0
        return true;
910
6
911
6
      if (Chunk.Fun.hasTrailingReturnType()) {
912
6
        QualType T = Chunk.Fun.getTrailingReturnType().get();
913
6
        if (!T.isNull() && 
T->containsUnexpandedParameterPack()0
)
914
0
          return true;
915
6
      }
916
6
      break;
917
6
918
6
    case DeclaratorChunk::MemberPointer:
919
0
      if (Chunk.Mem.Scope().getScopeRep() &&
920
0
          Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
921
0
        return true;
922
0
      break;
923
26
    }
924
26
  }
925
90
926
90
  return false;
927
90
}
928
929
namespace {
930
931
// Callback to only accept typo corrections that refer to parameter packs.
932
class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
933
 public:
934
4
  bool ValidateCandidate(const TypoCorrection &candidate) override {
935
4
    NamedDecl *ND = candidate.getCorrectionDecl();
936
4
    return ND && ND->isParameterPack();
937
4
  }
938
939
2
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
940
2
    return llvm::make_unique<ParameterPackValidatorCCC>(*this);
941
2
  }
942
};
943
944
}
945
946
/// Called when an expression computing the size of a parameter pack
947
/// is parsed.
948
///
949
/// \code
950
/// template<typename ...Types> struct count {
951
///   static const unsigned value = sizeof...(Types);
952
/// };
953
/// \endcode
954
///
955
//
956
/// \param OpLoc The location of the "sizeof" keyword.
957
/// \param Name The name of the parameter pack whose size will be determined.
958
/// \param NameLoc The source location of the name of the parameter pack.
959
/// \param RParenLoc The location of the closing parentheses.
960
ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
961
                                              SourceLocation OpLoc,
962
                                              IdentifierInfo &Name,
963
                                              SourceLocation NameLoc,
964
36.6k
                                              SourceLocation RParenLoc) {
965
36.6k
  // C++0x [expr.sizeof]p5:
966
36.6k
  //   The identifier in a sizeof... expression shall name a parameter pack.
967
36.6k
  LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
968
36.6k
  LookupName(R, S);
969
36.6k
970
36.6k
  NamedDecl *ParameterPack = nullptr;
971
36.6k
  switch (R.getResultKind()) {
972
36.6k
  case LookupResult::Found:
973
36.6k
    ParameterPack = R.getFoundDecl();
974
36.6k
    break;
975
36.6k
976
36.6k
  case LookupResult::NotFound:
977
3
  case LookupResult::NotFoundInCurrentInstantiation: {
978
3
    ParameterPackValidatorCCC CCC{};
979
3
    if (TypoCorrection Corrected =
980
2
            CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
981
2
                        CCC, CTK_ErrorRecovery)) {
982
2
      diagnoseTypo(Corrected,
983
2
                   PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
984
2
                   PDiag(diag::note_parameter_pack_here));
985
2
      ParameterPack = Corrected.getCorrectionDecl();
986
2
    }
987
3
    break;
988
3
  }
989
3
  case LookupResult::FoundOverloaded:
990
0
  case LookupResult::FoundUnresolvedValue:
991
0
    break;
992
0
993
0
  case LookupResult::Ambiguous:
994
0
    DiagnoseAmbiguousLookup(R);
995
0
    return ExprError();
996
36.6k
  }
997
36.6k
998
36.6k
  if (!ParameterPack || 
!ParameterPack->isParameterPack()36.6k
) {
999
2
    Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1000
2
      << &Name;
1001
2
    return ExprError();
1002
2
  }
1003
36.6k
1004
36.6k
  MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1005
36.6k
1006
36.6k
  return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1007
36.6k
                                RParenLoc);
1008
36.6k
}
1009
1010
TemplateArgumentLoc
1011
Sema::getTemplateArgumentPackExpansionPattern(
1012
      TemplateArgumentLoc OrigLoc,
1013
181k
      SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1014
181k
  const TemplateArgument &Argument = OrigLoc.getArgument();
1015
181k
  assert(Argument.isPackExpansion());
1016
181k
  switch (Argument.getKind()) {
1017
181k
  case TemplateArgument::Type: {
1018
143k
    // FIXME: We shouldn't ever have to worry about missing
1019
143k
    // type-source info!
1020
143k
    TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1021
143k
    if (!ExpansionTSInfo)
1022
0
      ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1023
0
                                                         Ellipsis);
1024
143k
    PackExpansionTypeLoc Expansion =
1025
143k
        ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1026
143k
    Ellipsis = Expansion.getEllipsisLoc();
1027
143k
1028
143k
    TypeLoc Pattern = Expansion.getPatternLoc();
1029
143k
    NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1030
143k
1031
143k
    // We need to copy the TypeLoc because TemplateArgumentLocs store a
1032
143k
    // TypeSourceInfo.
1033
143k
    // FIXME: Find some way to avoid the copy?
1034
143k
    TypeLocBuilder TLB;
1035
143k
    TLB.pushFullCopy(Pattern);
1036
143k
    TypeSourceInfo *PatternTSInfo =
1037
143k
        TLB.getTypeSourceInfo(Context, Pattern.getType());
1038
143k
    return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1039
143k
                               PatternTSInfo);
1040
181k
  }
1041
181k
1042
181k
  case TemplateArgument::Expression: {
1043
37.9k
    PackExpansionExpr *Expansion
1044
37.9k
      = cast<PackExpansionExpr>(Argument.getAsExpr());
1045
37.9k
    Expr *Pattern = Expansion->getPattern();
1046
37.9k
    Ellipsis = Expansion->getEllipsisLoc();
1047
37.9k
    NumExpansions = Expansion->getNumExpansions();
1048
37.9k
    return TemplateArgumentLoc(Pattern, Pattern);
1049
181k
  }
1050
181k
1051
181k
  case TemplateArgument::TemplateExpansion:
1052
28
    Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1053
28
    NumExpansions = Argument.getNumTemplateExpansions();
1054
28
    return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1055
28
                               OrigLoc.getTemplateQualifierLoc(),
1056
28
                               OrigLoc.getTemplateNameLoc());
1057
181k
1058
181k
  case TemplateArgument::Declaration:
1059
0
  case TemplateArgument::NullPtr:
1060
0
  case TemplateArgument::Template:
1061
0
  case TemplateArgument::Integral:
1062
0
  case TemplateArgument::Pack:
1063
0
  case TemplateArgument::Null:
1064
0
    return TemplateArgumentLoc();
1065
0
  }
1066
0
1067
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
1068
0
}
1069
1070
41.3k
Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1071
41.3k
  assert(Arg.containsUnexpandedParameterPack());
1072
41.3k
1073
41.3k
  // If this is a substituted pack, grab that pack. If not, we don't know
1074
41.3k
  // the size yet.
1075
41.3k
  // FIXME: We could find a size in more cases by looking for a substituted
1076
41.3k
  // pack anywhere within this argument, but that's not necessary in the common
1077
41.3k
  // case for 'sizeof...(A)' handling.
1078
41.3k
  TemplateArgument Pack;
1079
41.3k
  switch (Arg.getKind()) {
1080
41.3k
  case TemplateArgument::Type:
1081
41.2k
    if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1082
41.2k
      Pack = Subst->getArgumentPack();
1083
0
    else
1084
0
      return None;
1085
41.2k
    break;
1086
41.2k
1087
41.2k
  case TemplateArgument::Expression:
1088
97
    if (auto *Subst =
1089
20
            dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1090
20
      Pack = Subst->getArgumentPack();
1091
77
    else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1092
77
      for (VarDecl *PD : *Subst)
1093
443
        if (PD->isParameterPack())
1094
1
          return None;
1095
77
      
return Subst->getNumExpansions()76
;
1096
0
    } else
1097
0
      return None;
1098
20
    break;
1099
20
1100
20
  case TemplateArgument::Template:
1101
4
    if (SubstTemplateTemplateParmPackStorage *Subst =
1102
4
            Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1103
4
      Pack = Subst->getArgumentPack();
1104
0
    else
1105
0
      return None;
1106
4
    break;
1107
4
1108
4
  case TemplateArgument::Declaration:
1109
0
  case TemplateArgument::NullPtr:
1110
0
  case TemplateArgument::TemplateExpansion:
1111
0
  case TemplateArgument::Integral:
1112
0
  case TemplateArgument::Pack:
1113
0
  case TemplateArgument::Null:
1114
0
    return None;
1115
41.2k
  }
1116
41.2k
1117
41.2k
  // Check that no argument in the pack is itself a pack expansion.
1118
95.5k
  
for (TemplateArgument Elem : Pack.pack_elements())41.2k
{
1119
95.5k
    // There's no point recursing in this case; we would have already
1120
95.5k
    // expanded this pack expansion into the enclosing pack if we could.
1121
95.5k
    if (Elem.isPackExpansion())
1122
316
      return None;
1123
95.5k
  }
1124
41.2k
  
return Pack.pack_size()40.9k
;
1125
41.2k
}
1126
1127
230
static void CheckFoldOperand(Sema &S, Expr *E) {
1128
230
  if (!E)
1129
69
    return;
1130
161
1131
161
  E = E->IgnoreImpCasts();
1132
161
  auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1133
161
  if ((OCE && 
OCE->isInfixBinaryOp()5
) ||
isa<BinaryOperator>(E)158
||
1134
161
      
isa<AbstractConditionalOperator>(E)155
) {
1135
6
    S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1136
6
        << E->getSourceRange()
1137
6
        << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1138
6
        << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1139
6
  }
1140
161
}
1141
1142
ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1143
                                  tok::TokenKind Operator,
1144
                                  SourceLocation EllipsisLoc, Expr *RHS,
1145
115
                                  SourceLocation RParenLoc) {
1146
115
  // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1147
115
  // in the parser and reduce down to just cast-expressions here.
1148
115
  CheckFoldOperand(*this, LHS);
1149
115
  CheckFoldOperand(*this, RHS);
1150
115
1151
115
  auto DiscardOperands = [&] {
1152
72
    CorrectDelayedTyposInExpr(LHS);
1153
72
    CorrectDelayedTyposInExpr(RHS);
1154
72
  };
1155
115
1156
115
  // [expr.prim.fold]p3:
1157
115
  //   In a binary fold, op1 and op2 shall be the same fold-operator, and
1158
115
  //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
1159
115
  //   an unexpanded parameter pack, but not both.
1160
115
  if (LHS && 
RHS104
&&
1161
115
      LHS->containsUnexpandedParameterPack() ==
1162
46
          RHS->containsUnexpandedParameterPack()) {
1163
3
    DiscardOperands();
1164
3
    return Diag(EllipsisLoc,
1165
3
                LHS->containsUnexpandedParameterPack()
1166
3
                    ? 
diag::err_fold_expression_packs_both_sides1
1167
3
                    : 
diag::err_pack_expansion_without_parameter_packs2
)
1168
3
        << LHS->getSourceRange() << RHS->getSourceRange();
1169
3
  }
1170
112
1171
112
  // [expr.prim.fold]p2:
1172
112
  //   In a unary fold, the cast-expression shall contain an unexpanded
1173
112
  //   parameter pack.
1174
112
  if (!LHS || 
!RHS101
) {
1175
69
    Expr *Pack = LHS ? 
LHS58
:
RHS11
;
1176
69
    assert(Pack && "fold expression with neither LHS nor RHS");
1177
69
    DiscardOperands();
1178
69
    if (!Pack->containsUnexpandedParameterPack())
1179
4
      return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1180
4
             << Pack->getSourceRange();
1181
108
  }
1182
108
1183
108
  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1184
108
  return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1185
108
                          None);
1186
108
}
1187
1188
ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1189
                                  BinaryOperatorKind Operator,
1190
                                  SourceLocation EllipsisLoc, Expr *RHS,
1191
                                  SourceLocation RParenLoc,
1192
151
                                  Optional<unsigned> NumExpansions) {
1193
151
  return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1194
151
                                   Operator, EllipsisLoc, RHS, RParenLoc,
1195
151
                                   NumExpansions);
1196
151
}
1197
1198
ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1199
27
                                       BinaryOperatorKind Operator) {
1200
27
  // [temp.variadic]p9:
1201
27
  //   If N is zero for a unary fold-expression, the value of the expression is
1202
27
  //       &&  ->  true
1203
27
  //       ||  ->  false
1204
27
  //       ,   ->  void()
1205
27
  //   if the operator is not listed [above], the instantiation is ill-formed.
1206
27
  //
1207
27
  // Note that we need to use something like int() here, not merely 0, to
1208
27
  // prevent the result from being a null pointer constant.
1209
27
  QualType ScalarType;
1210
27
  switch (Operator) {
1211
27
  case BO_LOr:
1212
4
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1213
27
  case BO_LAnd:
1214
2
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1215
27
  case BO_Comma:
1216
5
    ScalarType = Context.VoidTy;
1217
5
    break;
1218
27
1219
27
  default:
1220
16
    return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1221
16
        << BinaryOperator::getOpcodeStr(Operator);
1222
5
  }
1223
5
1224
5
  return new (Context) CXXScalarValueInitExpr(
1225
5
      ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1226
5
      EllipsisLoc);
1227
5
}