Coverage Report

Created: 2022-01-18 06:27

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