Coverage Report

Created: 2022-05-14 11:35

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