Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaLambda.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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
//
9
//  This file implements semantic analysis for C++ lambda expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
#include "clang/Sema/DeclSpec.h"
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTLambda.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/Basic/TargetInfo.h"
17
#include "clang/Sema/Initialization.h"
18
#include "clang/Sema/Lookup.h"
19
#include "clang/Sema/Scope.h"
20
#include "clang/Sema/ScopeInfo.h"
21
#include "clang/Sema/SemaInternal.h"
22
#include "clang/Sema/SemaLambda.h"
23
#include "clang/Sema/Template.h"
24
#include "llvm/ADT/STLExtras.h"
25
#include <optional>
26
using namespace clang;
27
using namespace sema;
28
29
/// Examines the FunctionScopeInfo stack to determine the nearest
30
/// enclosing lambda (to the current lambda) that is 'capture-ready' for
31
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
32
/// If successful, returns the index into Sema's FunctionScopeInfo stack
33
/// of the capture-ready lambda's LambdaScopeInfo.
34
///
35
/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
36
/// lambda - is on top) to determine the index of the nearest enclosing/outer
37
/// lambda that is ready to capture the \p VarToCapture being referenced in
38
/// the current lambda.
39
/// As we climb down the stack, we want the index of the first such lambda -
40
/// that is the lambda with the highest index that is 'capture-ready'.
41
///
42
/// A lambda 'L' is capture-ready for 'V' (var or this) if:
43
///  - its enclosing context is non-dependent
44
///  - and if the chain of lambdas between L and the lambda in which
45
///    V is potentially used (i.e. the lambda at the top of the scope info
46
///    stack), can all capture or have already captured V.
47
/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
48
///
49
/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
50
/// for whether it is 'capture-capable' (see
51
/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
52
/// capture.
53
///
54
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
55
///  LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
56
///  is at the top of the stack and has the highest index.
57
/// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
58
///
59
/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
60
/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
61
/// lambda which is capture-ready.  If the return value evaluates to 'false'
62
/// then no lambda is capture-ready for \p VarToCapture.
63
64
static inline std::optional<unsigned>
65
getStackIndexOfNearestEnclosingCaptureReadyLambda(
66
    ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
67
0
    ValueDecl *VarToCapture) {
68
  // Label failure to capture.
69
0
  const std::optional<unsigned> NoLambdaIsCaptureReady;
70
71
  // Ignore all inner captured regions.
72
0
  unsigned CurScopeIndex = FunctionScopes.size() - 1;
73
0
  while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
74
0
                                  FunctionScopes[CurScopeIndex]))
75
0
    --CurScopeIndex;
76
0
  assert(
77
0
      isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
78
0
      "The function on the top of sema's function-info stack must be a lambda");
79
80
  // If VarToCapture is null, we are attempting to capture 'this'.
81
0
  const bool IsCapturingThis = !VarToCapture;
82
0
  const bool IsCapturingVariable = !IsCapturingThis;
83
84
  // Start with the current lambda at the top of the stack (highest index).
85
0
  DeclContext *EnclosingDC =
86
0
      cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
87
88
0
  do {
89
0
    const clang::sema::LambdaScopeInfo *LSI =
90
0
        cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
91
    // IF we have climbed down to an intervening enclosing lambda that contains
92
    // the variable declaration - it obviously can/must not capture the
93
    // variable.
94
    // Since its enclosing DC is dependent, all the lambdas between it and the
95
    // innermost nested lambda are dependent (otherwise we wouldn't have
96
    // arrived here) - so we don't yet have a lambda that can capture the
97
    // variable.
98
0
    if (IsCapturingVariable &&
99
0
        VarToCapture->getDeclContext()->Equals(EnclosingDC))
100
0
      return NoLambdaIsCaptureReady;
101
102
    // For an enclosing lambda to be capture ready for an entity, all
103
    // intervening lambda's have to be able to capture that entity. If even
104
    // one of the intervening lambda's is not capable of capturing the entity
105
    // then no enclosing lambda can ever capture that entity.
106
    // For e.g.
107
    // const int x = 10;
108
    // [=](auto a) {    #1
109
    //   [](auto b) {   #2 <-- an intervening lambda that can never capture 'x'
110
    //    [=](auto c) { #3
111
    //       f(x, c);  <-- can not lead to x's speculative capture by #1 or #2
112
    //    }; }; };
113
    // If they do not have a default implicit capture, check to see
114
    // if the entity has already been explicitly captured.
115
    // If even a single dependent enclosing lambda lacks the capability
116
    // to ever capture this variable, there is no further enclosing
117
    // non-dependent lambda that can capture this variable.
118
0
    if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
119
0
      if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
120
0
        return NoLambdaIsCaptureReady;
121
0
      if (IsCapturingThis && !LSI->isCXXThisCaptured())
122
0
        return NoLambdaIsCaptureReady;
123
0
    }
124
0
    EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
125
126
0
    assert(CurScopeIndex);
127
0
    --CurScopeIndex;
128
0
  } while (!EnclosingDC->isTranslationUnit() &&
129
0
           EnclosingDC->isDependentContext() &&
130
0
           isLambdaCallOperator(EnclosingDC));
131
132
0
  assert(CurScopeIndex < (FunctionScopes.size() - 1));
133
  // If the enclosingDC is not dependent, then the immediately nested lambda
134
  // (one index above) is capture-ready.
135
0
  if (!EnclosingDC->isDependentContext())
136
0
    return CurScopeIndex + 1;
137
0
  return NoLambdaIsCaptureReady;
138
0
}
139
140
/// Examines the FunctionScopeInfo stack to determine the nearest
141
/// enclosing lambda (to the current lambda) that is 'capture-capable' for
142
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
143
/// If successful, returns the index into Sema's FunctionScopeInfo stack
144
/// of the capture-capable lambda's LambdaScopeInfo.
145
///
146
/// Given the current stack of lambdas being processed by Sema and
147
/// the variable of interest, to identify the nearest enclosing lambda (to the
148
/// current lambda at the top of the stack) that can truly capture
149
/// a variable, it has to have the following two properties:
150
///  a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
151
///     - climb down the stack (i.e. starting from the innermost and examining
152
///       each outer lambda step by step) checking if each enclosing
153
///       lambda can either implicitly or explicitly capture the variable.
154
///       Record the first such lambda that is enclosed in a non-dependent
155
///       context. If no such lambda currently exists return failure.
156
///  b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
157
///  capture the variable by checking all its enclosing lambdas:
158
///     - check if all outer lambdas enclosing the 'capture-ready' lambda
159
///       identified above in 'a' can also capture the variable (this is done
160
///       via tryCaptureVariable for variables and CheckCXXThisCapture for
161
///       'this' by passing in the index of the Lambda identified in step 'a')
162
///
163
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
164
/// LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
165
/// is at the top of the stack.
166
///
167
/// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
168
///
169
///
170
/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
171
/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
172
/// lambda which is capture-capable.  If the return value evaluates to 'false'
173
/// then no lambda is capture-capable for \p VarToCapture.
174
175
std::optional<unsigned>
176
clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
177
    ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
178
0
    ValueDecl *VarToCapture, Sema &S) {
179
180
0
  const std::optional<unsigned> NoLambdaIsCaptureCapable;
181
182
0
  const std::optional<unsigned> OptionalStackIndex =
183
0
      getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
184
0
                                                        VarToCapture);
185
0
  if (!OptionalStackIndex)
186
0
    return NoLambdaIsCaptureCapable;
187
188
0
  const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
189
0
  assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
190
0
          S.getCurGenericLambda()) &&
191
0
         "The capture ready lambda for a potential capture can only be the "
192
0
         "current lambda if it is a generic lambda");
193
194
0
  const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
195
0
      cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
196
197
  // If VarToCapture is null, we are attempting to capture 'this'
198
0
  const bool IsCapturingThis = !VarToCapture;
199
0
  const bool IsCapturingVariable = !IsCapturingThis;
200
201
0
  if (IsCapturingVariable) {
202
    // Check if the capture-ready lambda can truly capture the variable, by
203
    // checking whether all enclosing lambdas of the capture-ready lambda allow
204
    // the capture - i.e. make sure it is capture-capable.
205
0
    QualType CaptureType, DeclRefType;
206
0
    const bool CanCaptureVariable =
207
0
        !S.tryCaptureVariable(VarToCapture,
208
0
                              /*ExprVarIsUsedInLoc*/ SourceLocation(),
209
0
                              clang::Sema::TryCapture_Implicit,
210
0
                              /*EllipsisLoc*/ SourceLocation(),
211
0
                              /*BuildAndDiagnose*/ false, CaptureType,
212
0
                              DeclRefType, &IndexOfCaptureReadyLambda);
213
0
    if (!CanCaptureVariable)
214
0
      return NoLambdaIsCaptureCapable;
215
0
  } else {
216
    // Check if the capture-ready lambda can truly capture 'this' by checking
217
    // whether all enclosing lambdas of the capture-ready lambda can capture
218
    // 'this'.
219
0
    const bool CanCaptureThis =
220
0
        !S.CheckCXXThisCapture(
221
0
             CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
222
0
             /*Explicit*/ false, /*BuildAndDiagnose*/ false,
223
0
             &IndexOfCaptureReadyLambda);
224
0
    if (!CanCaptureThis)
225
0
      return NoLambdaIsCaptureCapable;
226
0
  }
227
0
  return IndexOfCaptureReadyLambda;
228
0
}
229
230
static inline TemplateParameterList *
231
0
getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
232
0
  if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
233
0
    LSI->GLTemplateParameterList = TemplateParameterList::Create(
234
0
        SemaRef.Context,
235
0
        /*Template kw loc*/ SourceLocation(),
236
0
        /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
237
0
        LSI->TemplateParams,
238
0
        /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
239
0
        LSI->RequiresClause.get());
240
0
  }
241
0
  return LSI->GLTemplateParameterList;
242
0
}
243
244
CXXRecordDecl *
245
Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
246
                              unsigned LambdaDependencyKind,
247
0
                              LambdaCaptureDefault CaptureDefault) {
248
0
  DeclContext *DC = CurContext;
249
0
  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
250
0
    DC = DC->getParent();
251
252
0
  bool IsGenericLambda =
253
0
      Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this);
254
  // Start constructing the lambda class.
255
0
  CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
256
0
      Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
257
0
      IsGenericLambda, CaptureDefault);
258
0
  DC->addDecl(Class);
259
260
0
  return Class;
261
0
}
262
263
/// Determine whether the given context is or is enclosed in an inline
264
/// function.
265
4
static bool isInInlineFunction(const DeclContext *DC) {
266
4
  while (!DC->isFileContext()) {
267
0
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
268
0
      if (FD->isInlined())
269
0
        return true;
270
271
0
    DC = DC->getLexicalParent();
272
0
  }
273
274
4
  return false;
275
4
}
276
277
std::tuple<MangleNumberingContext *, Decl *>
278
4
Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
279
  // Compute the context for allocating mangling numbers in the current
280
  // expression, if the ABI requires them.
281
4
  Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
282
283
4
  enum ContextKind {
284
4
    Normal,
285
4
    DefaultArgument,
286
4
    DataMember,
287
4
    InlineVariable,
288
4
    TemplatedVariable,
289
4
    Concept
290
4
  } Kind = Normal;
291
292
4
  bool IsInNonspecializedTemplate =
293
4
      inTemplateInstantiation() || CurContext->isDependentContext();
294
295
  // Default arguments of member function parameters that appear in a class
296
  // definition, as well as the initializers of data members, receive special
297
  // treatment. Identify them.
298
4
  if (ManglingContextDecl) {
299
0
    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
300
0
      if (const DeclContext *LexicalDC
301
0
          = Param->getDeclContext()->getLexicalParent())
302
0
        if (LexicalDC->isRecord())
303
0
          Kind = DefaultArgument;
304
0
    } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
305
0
      if (Var->getMostRecentDecl()->isInline())
306
0
        Kind = InlineVariable;
307
0
      else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
308
0
        Kind = TemplatedVariable;
309
0
      else if (Var->getDescribedVarTemplate())
310
0
        Kind = TemplatedVariable;
311
0
      else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
312
0
        if (!VTS->isExplicitSpecialization())
313
0
          Kind = TemplatedVariable;
314
0
      }
315
0
    } else if (isa<FieldDecl>(ManglingContextDecl)) {
316
0
      Kind = DataMember;
317
0
    } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
318
0
      Kind = Concept;
319
0
    }
320
0
  }
321
322
  // Itanium ABI [5.1.7]:
323
  //   In the following contexts [...] the one-definition rule requires closure
324
  //   types in different translation units to "correspond":
325
4
  switch (Kind) {
326
4
  case Normal: {
327
    //  -- the bodies of inline or templated functions
328
4
    if ((IsInNonspecializedTemplate &&
329
4
         !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
330
4
        isInInlineFunction(CurContext)) {
331
0
      while (auto *CD = dyn_cast<CapturedDecl>(DC))
332
0
        DC = CD->getParent();
333
0
      return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
334
0
    }
335
336
4
    return std::make_tuple(nullptr, nullptr);
337
4
  }
338
339
0
  case Concept:
340
    // Concept definitions aren't code generated and thus aren't mangled,
341
    // however the ManglingContextDecl is important for the purposes of
342
    // re-forming the template argument list of the lambda for constraint
343
    // evaluation.
344
0
  case DataMember:
345
    //  -- default member initializers
346
0
  case DefaultArgument:
347
    //  -- default arguments appearing in class definitions
348
0
  case InlineVariable:
349
0
  case TemplatedVariable:
350
    //  -- the initializers of inline or templated variables
351
0
    return std::make_tuple(
352
0
        &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
353
0
                                          ManglingContextDecl),
354
0
        ManglingContextDecl);
355
4
  }
356
357
0
  llvm_unreachable("unexpected context");
358
0
}
359
360
static QualType
361
buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class,
362
                               TemplateParameterList *TemplateParams,
363
0
                               TypeSourceInfo *MethodTypeInfo) {
364
0
  assert(MethodTypeInfo && "expected a non null type");
365
366
0
  QualType MethodType = MethodTypeInfo->getType();
367
  // If a lambda appears in a dependent context or is a generic lambda (has
368
  // template parameters) and has an 'auto' return type, deduce it to a
369
  // dependent type.
370
0
  if (Class->isDependentContext() || TemplateParams) {
371
0
    const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
372
0
    QualType Result = FPT->getReturnType();
373
0
    if (Result->isUndeducedType()) {
374
0
      Result = S.SubstAutoTypeDependent(Result);
375
0
      MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
376
0
                                             FPT->getExtProtoInfo());
377
0
    }
378
0
  }
379
0
  return MethodType;
380
0
}
381
382
// [C++2b] [expr.prim.lambda.closure] p4
383
//  Given a lambda with a lambda-capture, the type of the explicit object
384
//  parameter, if any, of the lambda's function call operator (possibly
385
//  instantiated from a function call operator template) shall be either:
386
//  - the closure type,
387
//  - class type derived from the closure type, or
388
//  - a reference to a possibly cv-qualified such type.
389
void Sema::DiagnoseInvalidExplicitObjectParameterInLambda(
390
0
    CXXMethodDecl *Method) {
391
0
  if (!isLambdaCallWithExplicitObjectParameter(Method))
392
0
    return;
393
0
  CXXRecordDecl *RD = Method->getParent();
394
0
  if (Method->getType()->isDependentType())
395
0
    return;
396
0
  if (RD->isCapturelessLambda())
397
0
    return;
398
0
  QualType ExplicitObjectParameterType = Method->getParamDecl(0)
399
0
                                             ->getType()
400
0
                                             .getNonReferenceType()
401
0
                                             .getUnqualifiedType()
402
0
                                             .getDesugaredType(getASTContext());
403
0
  QualType LambdaType = getASTContext().getRecordType(RD);
404
0
  if (LambdaType == ExplicitObjectParameterType)
405
0
    return;
406
0
  if (IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType))
407
0
    return;
408
0
  Diag(Method->getParamDecl(0)->getLocation(),
409
0
       diag::err_invalid_explicit_object_type_in_lambda)
410
0
      << ExplicitObjectParameterType;
411
0
}
412
413
void Sema::handleLambdaNumbering(
414
    CXXRecordDecl *Class, CXXMethodDecl *Method,
415
0
    std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
416
0
  if (NumberingOverride) {
417
0
    Class->setLambdaNumbering(*NumberingOverride);
418
0
    return;
419
0
  }
420
421
0
  ContextRAII ManglingContext(*this, Class->getDeclContext());
422
423
0
  auto getMangleNumberingContext =
424
0
      [this](CXXRecordDecl *Class,
425
0
             Decl *ManglingContextDecl) -> MangleNumberingContext * {
426
    // Get mangle numbering context if there's any extra decl context.
427
0
    if (ManglingContextDecl)
428
0
      return &Context.getManglingNumberContext(
429
0
          ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
430
    // Otherwise, from that lambda's decl context.
431
0
    auto DC = Class->getDeclContext();
432
0
    while (auto *CD = dyn_cast<CapturedDecl>(DC))
433
0
      DC = CD->getParent();
434
0
    return &Context.getManglingNumberContext(DC);
435
0
  };
436
437
0
  CXXRecordDecl::LambdaNumbering Numbering;
438
0
  MangleNumberingContext *MCtx;
439
0
  std::tie(MCtx, Numbering.ContextDecl) =
440
0
      getCurrentMangleNumberContext(Class->getDeclContext());
441
0
  if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
442
0
                getLangOpts().SYCLIsHost)) {
443
    // Force lambda numbering in CUDA/HIP as we need to name lambdas following
444
    // ODR. Both device- and host-compilation need to have a consistent naming
445
    // on kernel functions. As lambdas are potential part of these `__global__`
446
    // function names, they needs numbering following ODR.
447
    // Also force for SYCL, since we need this for the
448
    // __builtin_sycl_unique_stable_name implementation, which depends on lambda
449
    // mangling.
450
0
    MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
451
0
    assert(MCtx && "Retrieving mangle numbering context failed!");
452
0
    Numbering.HasKnownInternalLinkage = true;
453
0
  }
454
0
  if (MCtx) {
455
0
    Numbering.IndexInContext = MCtx->getNextLambdaIndex();
456
0
    Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
457
0
    Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
458
0
    Class->setLambdaNumbering(Numbering);
459
460
0
    if (auto *Source =
461
0
            dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
462
0
      Source->AssignedLambdaNumbering(Class);
463
0
  }
464
0
}
465
466
static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI,
467
                                       CXXMethodDecl *CallOperator,
468
0
                                       bool ExplicitResultType) {
469
0
  if (ExplicitResultType) {
470
0
    LSI->HasImplicitReturnType = false;
471
0
    LSI->ReturnType = CallOperator->getReturnType();
472
0
    if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
473
0
      S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
474
0
                            diag::err_lambda_incomplete_result);
475
0
  } else {
476
0
    LSI->HasImplicitReturnType = true;
477
0
  }
478
0
}
479
480
void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
481
                            SourceRange IntroducerRange,
482
                            LambdaCaptureDefault CaptureDefault,
483
                            SourceLocation CaptureDefaultLoc,
484
0
                            bool ExplicitParams, bool Mutable) {
485
0
  LSI->CallOperator = CallOperator;
486
0
  CXXRecordDecl *LambdaClass = CallOperator->getParent();
487
0
  LSI->Lambda = LambdaClass;
488
0
  if (CaptureDefault == LCD_ByCopy)
489
0
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
490
0
  else if (CaptureDefault == LCD_ByRef)
491
0
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
492
0
  LSI->CaptureDefaultLoc = CaptureDefaultLoc;
493
0
  LSI->IntroducerRange = IntroducerRange;
494
0
  LSI->ExplicitParams = ExplicitParams;
495
0
  LSI->Mutable = Mutable;
496
0
}
497
498
0
void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
499
0
  LSI->finishedExplicitCaptures();
500
0
}
501
502
void Sema::ActOnLambdaExplicitTemplateParameterList(
503
    LambdaIntroducer &Intro, SourceLocation LAngleLoc,
504
    ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
505
0
    ExprResult RequiresClause) {
506
0
  LambdaScopeInfo *LSI = getCurLambda();
507
0
  assert(LSI && "Expected a lambda scope");
508
0
  assert(LSI->NumExplicitTemplateParams == 0 &&
509
0
         "Already acted on explicit template parameters");
510
0
  assert(LSI->TemplateParams.empty() &&
511
0
         "Explicit template parameters should come "
512
0
         "before invented (auto) ones");
513
0
  assert(!TParams.empty() &&
514
0
         "No template parameters to act on");
515
0
  LSI->TemplateParams.append(TParams.begin(), TParams.end());
516
0
  LSI->NumExplicitTemplateParams = TParams.size();
517
0
  LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
518
0
  LSI->RequiresClause = RequiresClause;
519
0
}
520
521
/// If this expression is an enumerator-like expression of some type
522
/// T, return the type T; otherwise, return null.
523
///
524
/// Pointer comparisons on the result here should always work because
525
/// it's derived from either the parent of an EnumConstantDecl
526
/// (i.e. the definition) or the declaration returned by
527
/// EnumType::getDecl() (i.e. the definition).
528
0
static EnumDecl *findEnumForBlockReturn(Expr *E) {
529
  // An expression is an enumerator-like expression of type T if,
530
  // ignoring parens and parens-like expressions:
531
0
  E = E->IgnoreParens();
532
533
  //  - it is an enumerator whose enum type is T or
534
0
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
535
0
    if (EnumConstantDecl *D
536
0
          = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
537
0
      return cast<EnumDecl>(D->getDeclContext());
538
0
    }
539
0
    return nullptr;
540
0
  }
541
542
  //  - it is a comma expression whose RHS is an enumerator-like
543
  //    expression of type T or
544
0
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
545
0
    if (BO->getOpcode() == BO_Comma)
546
0
      return findEnumForBlockReturn(BO->getRHS());
547
0
    return nullptr;
548
0
  }
549
550
  //  - it is a statement-expression whose value expression is an
551
  //    enumerator-like expression of type T or
552
0
  if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
553
0
    if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
554
0
      return findEnumForBlockReturn(last);
555
0
    return nullptr;
556
0
  }
557
558
  //   - it is a ternary conditional operator (not the GNU ?:
559
  //     extension) whose second and third operands are
560
  //     enumerator-like expressions of type T or
561
0
  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
562
0
    if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
563
0
      if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
564
0
        return ED;
565
0
    return nullptr;
566
0
  }
567
568
  // (implicitly:)
569
  //   - it is an implicit integral conversion applied to an
570
  //     enumerator-like expression of type T or
571
0
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
572
    // We can sometimes see integral conversions in valid
573
    // enumerator-like expressions.
574
0
    if (ICE->getCastKind() == CK_IntegralCast)
575
0
      return findEnumForBlockReturn(ICE->getSubExpr());
576
577
    // Otherwise, just rely on the type.
578
0
  }
579
580
  //   - it is an expression of that formal enum type.
581
0
  if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
582
0
    return ET->getDecl();
583
0
  }
584
585
  // Otherwise, nope.
586
0
  return nullptr;
587
0
}
588
589
/// Attempt to find a type T for which the returned expression of the
590
/// given statement is an enumerator-like expression of that type.
591
0
static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
592
0
  if (Expr *retValue = ret->getRetValue())
593
0
    return findEnumForBlockReturn(retValue);
594
0
  return nullptr;
595
0
}
596
597
/// Attempt to find a common type T for which all of the returned
598
/// expressions in a block are enumerator-like expressions of that
599
/// type.
600
0
static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
601
0
  ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
602
603
  // Try to find one for the first return.
604
0
  EnumDecl *ED = findEnumForBlockReturn(*i);
605
0
  if (!ED) return nullptr;
606
607
  // Check that the rest of the returns have the same enum.
608
0
  for (++i; i != e; ++i) {
609
0
    if (findEnumForBlockReturn(*i) != ED)
610
0
      return nullptr;
611
0
  }
612
613
  // Never infer an anonymous enum type.
614
0
  if (!ED->hasNameForLinkage()) return nullptr;
615
616
0
  return ED;
617
0
}
618
619
/// Adjust the given return statements so that they formally return
620
/// the given type.  It should require, at most, an IntegralCast.
621
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
622
0
                                     QualType returnType) {
623
0
  for (ArrayRef<ReturnStmt*>::iterator
624
0
         i = returns.begin(), e = returns.end(); i != e; ++i) {
625
0
    ReturnStmt *ret = *i;
626
0
    Expr *retValue = ret->getRetValue();
627
0
    if (S.Context.hasSameType(retValue->getType(), returnType))
628
0
      continue;
629
630
    // Right now we only support integral fixup casts.
631
0
    assert(returnType->isIntegralOrUnscopedEnumerationType());
632
0
    assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
633
634
0
    ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
635
636
0
    Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
637
0
    E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
638
0
                                 /*base path*/ nullptr, VK_PRValue,
639
0
                                 FPOptionsOverride());
640
0
    if (cleanups) {
641
0
      cleanups->setSubExpr(E);
642
0
    } else {
643
0
      ret->setRetValue(E);
644
0
    }
645
0
  }
646
0
}
647
648
1
void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
649
1
  assert(CSI.HasImplicitReturnType);
650
  // If it was ever a placeholder, it had to been deduced to DependentTy.
651
0
  assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
652
0
  assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
653
1
         "lambda expressions use auto deduction in C++14 onwards");
654
655
  // C++ core issue 975:
656
  //   If a lambda-expression does not include a trailing-return-type,
657
  //   it is as if the trailing-return-type denotes the following type:
658
  //     - if there are no return statements in the compound-statement,
659
  //       or all return statements return either an expression of type
660
  //       void or no expression or braced-init-list, the type void;
661
  //     - otherwise, if all return statements return an expression
662
  //       and the types of the returned expressions after
663
  //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
664
  //       array-to-pointer conversion (4.2 [conv.array]), and
665
  //       function-to-pointer conversion (4.3 [conv.func]) are the
666
  //       same, that common type;
667
  //     - otherwise, the program is ill-formed.
668
  //
669
  // C++ core issue 1048 additionally removes top-level cv-qualifiers
670
  // from the types of returned expressions to match the C++14 auto
671
  // deduction rules.
672
  //
673
  // In addition, in blocks in non-C++ modes, if all of the return
674
  // statements are enumerator-like expressions of some type T, where
675
  // T has a name for linkage, then we infer the return type of the
676
  // block to be that type.
677
678
  // First case: no return statements, implicit void return type.
679
0
  ASTContext &Ctx = getASTContext();
680
1
  if (CSI.Returns.empty()) {
681
    // It's possible there were simply no /valid/ return statements.
682
    // In this case, the first one we found may have at least given us a type.
683
1
    if (CSI.ReturnType.isNull())
684
1
      CSI.ReturnType = Ctx.VoidTy;
685
1
    return;
686
1
  }
687
688
  // Second case: at least one return statement has dependent type.
689
  // Delay type checking until instantiation.
690
0
  assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
691
0
  if (CSI.ReturnType->isDependentType())
692
0
    return;
693
694
  // Try to apply the enum-fuzz rule.
695
0
  if (!getLangOpts().CPlusPlus) {
696
0
    assert(isa<BlockScopeInfo>(CSI));
697
0
    const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
698
0
    if (ED) {
699
0
      CSI.ReturnType = Context.getTypeDeclType(ED);
700
0
      adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
701
0
      return;
702
0
    }
703
0
  }
704
705
  // Third case: only one return statement. Don't bother doing extra work!
706
0
  if (CSI.Returns.size() == 1)
707
0
    return;
708
709
  // General case: many return statements.
710
  // Check that they all have compatible return types.
711
712
  // We require the return types to strictly match here.
713
  // Note that we've already done the required promotions as part of
714
  // processing the return statement.
715
0
  for (const ReturnStmt *RS : CSI.Returns) {
716
0
    const Expr *RetE = RS->getRetValue();
717
718
0
    QualType ReturnType =
719
0
        (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
720
0
    if (Context.getCanonicalFunctionResultType(ReturnType) ==
721
0
          Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
722
      // Use the return type with the strictest possible nullability annotation.
723
0
      auto RetTyNullability = ReturnType->getNullability();
724
0
      auto BlockNullability = CSI.ReturnType->getNullability();
725
0
      if (BlockNullability &&
726
0
          (!RetTyNullability ||
727
0
           hasWeakerNullability(*RetTyNullability, *BlockNullability)))
728
0
        CSI.ReturnType = ReturnType;
729
0
      continue;
730
0
    }
731
732
    // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
733
    // TODO: It's possible that the *first* return is the divergent one.
734
0
    Diag(RS->getBeginLoc(),
735
0
         diag::err_typecheck_missing_return_type_incompatible)
736
0
        << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
737
    // Continue iterating so that we keep emitting diagnostics.
738
0
  }
739
0
}
740
741
QualType Sema::buildLambdaInitCaptureInitialization(
742
    SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
743
    std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
744
0
    bool IsDirectInit, Expr *&Init) {
745
  // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
746
  // deduce against.
747
0
  QualType DeductType = Context.getAutoDeductType();
748
0
  TypeLocBuilder TLB;
749
0
  AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
750
0
  TL.setNameLoc(Loc);
751
0
  if (ByRef) {
752
0
    DeductType = BuildReferenceType(DeductType, true, Loc, Id);
753
0
    assert(!DeductType.isNull() && "can't build reference to auto");
754
0
    TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
755
0
  }
756
0
  if (EllipsisLoc.isValid()) {
757
0
    if (Init->containsUnexpandedParameterPack()) {
758
0
      Diag(EllipsisLoc, getLangOpts().CPlusPlus20
759
0
                            ? diag::warn_cxx17_compat_init_capture_pack
760
0
                            : diag::ext_init_capture_pack);
761
0
      DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
762
0
                                                /*ExpectPackInType=*/false);
763
0
      TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
764
0
    } else {
765
      // Just ignore the ellipsis for now and form a non-pack variable. We'll
766
      // diagnose this later when we try to capture it.
767
0
    }
768
0
  }
769
0
  TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
770
771
  // Deduce the type of the init capture.
772
0
  QualType DeducedType = deduceVarTypeFromInitializer(
773
0
      /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
774
0
      SourceRange(Loc, Loc), IsDirectInit, Init);
775
0
  if (DeducedType.isNull())
776
0
    return QualType();
777
778
  // Are we a non-list direct initialization?
779
0
  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
780
781
  // Perform initialization analysis and ensure any implicit conversions
782
  // (such as lvalue-to-rvalue) are enforced.
783
0
  InitializedEntity Entity =
784
0
      InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
785
0
  InitializationKind Kind =
786
0
      IsDirectInit
787
0
          ? (CXXDirectInit ? InitializationKind::CreateDirect(
788
0
                                 Loc, Init->getBeginLoc(), Init->getEndLoc())
789
0
                           : InitializationKind::CreateDirectList(Loc))
790
0
          : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
791
792
0
  MultiExprArg Args = Init;
793
0
  if (CXXDirectInit)
794
0
    Args =
795
0
        MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
796
0
  QualType DclT;
797
0
  InitializationSequence InitSeq(*this, Entity, Kind, Args);
798
0
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
799
800
0
  if (Result.isInvalid())
801
0
    return QualType();
802
803
0
  Init = Result.getAs<Expr>();
804
0
  return DeducedType;
805
0
}
806
807
VarDecl *Sema::createLambdaInitCaptureVarDecl(
808
    SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
809
0
    IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
810
  // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
811
  // rather than reconstructing it here.
812
0
  TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
813
0
  if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
814
0
    PETL.setEllipsisLoc(EllipsisLoc);
815
816
  // Create a dummy variable representing the init-capture. This is not actually
817
  // used as a variable, and only exists as a way to name and refer to the
818
  // init-capture.
819
  // FIXME: Pass in separate source locations for '&' and identifier.
820
0
  VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
821
0
                                   InitCaptureType, TSI, SC_Auto);
822
0
  NewVD->setInitCapture(true);
823
0
  NewVD->setReferenced(true);
824
  // FIXME: Pass in a VarDecl::InitializationStyle.
825
0
  NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
826
0
  NewVD->markUsed(Context);
827
0
  NewVD->setInit(Init);
828
0
  if (NewVD->isParameterPack())
829
0
    getCurLambda()->LocalPacks.push_back(NewVD);
830
0
  return NewVD;
831
0
}
832
833
0
void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
834
0
  assert(Var->isInitCapture() && "init capture flag should be set");
835
0
  LSI->addCapture(Var, /*isBlock=*/false, ByRef,
836
0
                  /*isNested=*/false, Var->getLocation(), SourceLocation(),
837
0
                  Var->getType(), /*Invalid=*/false);
838
0
}
839
840
// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
841
// check that the current lambda is in a consistent or fully constructed state.
842
0
static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) {
843
0
  assert(!S.FunctionScopes.empty());
844
0
  return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
845
0
}
846
847
static TypeSourceInfo *
848
0
getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) {
849
  // C++11 [expr.prim.lambda]p4:
850
  //   If a lambda-expression does not include a lambda-declarator, it is as
851
  //   if the lambda-declarator were ().
852
0
  FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention(
853
0
      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
854
0
  EPI.HasTrailingReturn = true;
855
0
  EPI.TypeQuals.addConst();
856
0
  LangAS AS = S.getDefaultCXXMethodAddrSpace();
857
0
  if (AS != LangAS::Default)
858
0
    EPI.TypeQuals.addAddressSpace(AS);
859
860
  // C++1y [expr.prim.lambda]:
861
  //   The lambda return type is 'auto', which is replaced by the
862
  //   trailing-return type if provided and/or deduced from 'return'
863
  //   statements
864
  // We don't do this before C++1y, because we don't support deduced return
865
  // types there.
866
0
  QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
867
0
                                                ? S.Context.getAutoDeductType()
868
0
                                                : S.Context.DependentTy;
869
0
  QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
870
0
                                                std::nullopt, EPI);
871
0
  return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
872
0
}
873
874
static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro,
875
                                     Declarator &ParamInfo, Scope *CurScope,
876
                                     SourceLocation Loc,
877
0
                                     bool &ExplicitResultType) {
878
879
0
  ExplicitResultType = false;
880
881
0
  assert(
882
0
      (ParamInfo.getDeclSpec().getStorageClassSpec() ==
883
0
           DeclSpec::SCS_unspecified ||
884
0
       ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) &&
885
0
      "Unexpected storage specifier");
886
0
  bool IsLambdaStatic =
887
0
      ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
888
889
0
  TypeSourceInfo *MethodTyInfo;
890
891
0
  if (ParamInfo.getNumTypeObjects() == 0) {
892
0
    MethodTyInfo = getDummyLambdaType(S, Loc);
893
0
  } else {
894
    // Check explicit parameters
895
0
    S.CheckExplicitObjectLambda(ParamInfo);
896
897
0
    DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
898
899
0
    bool HasExplicitObjectParameter =
900
0
        ParamInfo.isExplicitObjectMemberFunction();
901
902
0
    ExplicitResultType = FTI.hasTrailingReturnType();
903
0
    if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
904
0
        !HasExplicitObjectParameter)
905
0
      FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, Loc);
906
907
0
    if (ExplicitResultType && S.getLangOpts().HLSL) {
908
0
      QualType RetTy = FTI.getTrailingReturnType().get();
909
0
      if (!RetTy.isNull()) {
910
        // HLSL does not support specifying an address space on a lambda return
911
        // type.
912
0
        LangAS AddressSpace = RetTy.getAddressSpace();
913
0
        if (AddressSpace != LangAS::Default)
914
0
          S.Diag(FTI.getTrailingReturnTypeLoc(),
915
0
                 diag::err_return_value_with_address_space);
916
0
      }
917
0
    }
918
919
0
    MethodTyInfo = S.GetTypeForDeclarator(ParamInfo, CurScope);
920
0
    assert(MethodTyInfo && "no type from lambda-declarator");
921
922
    // Check for unexpanded parameter packs in the method type.
923
0
    if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
924
0
      S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
925
0
                                        S.UPPC_DeclarationType);
926
0
  }
927
0
  return MethodTyInfo;
928
0
}
929
930
CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange,
931
0
                                              CXXRecordDecl *Class) {
932
933
  // C++20 [expr.prim.lambda.closure]p3:
934
  // The closure type for a lambda-expression has a public inline function
935
  // call operator (for a non-generic lambda) or function call operator
936
  // template (for a generic lambda) whose parameters and return type are
937
  // described by the lambda-expression's parameter-declaration-clause
938
  // and trailing-return-type respectively.
939
0
  DeclarationName MethodName =
940
0
      Context.DeclarationNames.getCXXOperatorName(OO_Call);
941
0
  DeclarationNameLoc MethodNameLoc =
942
0
      DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange.getBegin());
943
0
  CXXMethodDecl *Method = CXXMethodDecl::Create(
944
0
      Context, Class, SourceLocation(),
945
0
      DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
946
0
                          MethodNameLoc),
947
0
      QualType(), /*Tinfo=*/nullptr, SC_None,
948
0
      getCurFPFeatures().isFPConstrained(),
949
0
      /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),
950
0
      /*TrailingRequiresClause=*/nullptr);
951
0
  Method->setAccess(AS_public);
952
0
  return Method;
953
0
}
954
955
void Sema::AddTemplateParametersToLambdaCallOperator(
956
    CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
957
0
    TemplateParameterList *TemplateParams) {
958
0
  assert(TemplateParams && "no template parameters");
959
0
  FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create(
960
0
      Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
961
0
      TemplateParams, CallOperator);
962
0
  TemplateMethod->setAccess(AS_public);
963
0
  CallOperator->setDescribedFunctionTemplate(TemplateMethod);
964
0
}
965
966
void Sema::CompleteLambdaCallOperator(
967
    CXXMethodDecl *Method, SourceLocation LambdaLoc,
968
    SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
969
    TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
970
    StorageClass SC, ArrayRef<ParmVarDecl *> Params,
971
0
    bool HasExplicitResultType) {
972
973
0
  LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
974
975
0
  if (TrailingRequiresClause)
976
0
    Method->setTrailingRequiresClause(TrailingRequiresClause);
977
978
0
  TemplateParameterList *TemplateParams =
979
0
      getGenericLambdaTemplateParameterList(LSI, *this);
980
981
0
  DeclContext *DC = Method->getLexicalDeclContext();
982
0
  Method->setLexicalDeclContext(LSI->Lambda);
983
0
  if (TemplateParams) {
984
0
    FunctionTemplateDecl *TemplateMethod =
985
0
        Method->getDescribedFunctionTemplate();
986
0
    assert(TemplateMethod &&
987
0
           "AddTemplateParametersToLambdaCallOperator should have been called");
988
989
0
    LSI->Lambda->addDecl(TemplateMethod);
990
0
    TemplateMethod->setLexicalDeclContext(DC);
991
0
  } else {
992
0
    LSI->Lambda->addDecl(Method);
993
0
  }
994
0
  LSI->Lambda->setLambdaIsGeneric(TemplateParams);
995
0
  LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
996
997
0
  Method->setLexicalDeclContext(DC);
998
0
  Method->setLocation(LambdaLoc);
999
0
  Method->setInnerLocStart(CallOperatorLoc);
1000
0
  Method->setTypeSourceInfo(MethodTyInfo);
1001
0
  Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1002
0
                                                 TemplateParams, MethodTyInfo));
1003
0
  Method->setConstexprKind(ConstexprKind);
1004
0
  Method->setStorageClass(SC);
1005
0
  if (!Params.empty()) {
1006
0
    CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1007
0
    Method->setParams(Params);
1008
0
    for (auto P : Method->parameters()) {
1009
0
      assert(P && "null in a parameter list");
1010
0
      P->setOwningFunction(Method);
1011
0
    }
1012
0
  }
1013
1014
0
  buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1015
0
}
1016
1017
void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
1018
0
                                                Scope *CurrentScope) {
1019
1020
0
  LambdaScopeInfo *LSI = getCurLambda();
1021
0
  assert(LSI && "LambdaScopeInfo should be on stack!");
1022
1023
0
  if (Intro.Default == LCD_ByCopy)
1024
0
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1025
0
  else if (Intro.Default == LCD_ByRef)
1026
0
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1027
0
  LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1028
0
  LSI->IntroducerRange = Intro.Range;
1029
0
  LSI->AfterParameterList = false;
1030
1031
0
  assert(LSI->NumExplicitTemplateParams == 0);
1032
1033
  // Determine if we're within a context where we know that the lambda will
1034
  // be dependent, because there are template parameters in scope.
1035
0
  CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1036
0
      CXXRecordDecl::LDK_Unknown;
1037
0
  if (LSI->NumExplicitTemplateParams > 0) {
1038
0
    Scope *TemplateParamScope = CurScope->getTemplateParamParent();
1039
0
    assert(TemplateParamScope &&
1040
0
           "Lambda with explicit template param list should establish a "
1041
0
           "template param scope");
1042
0
    assert(TemplateParamScope->getParent());
1043
0
    if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
1044
0
      LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1045
0
  } else if (CurScope->getTemplateParamParent() != nullptr) {
1046
0
    LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1047
0
  }
1048
1049
0
  CXXRecordDecl *Class = createLambdaClosureType(
1050
0
      Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1051
0
  LSI->Lambda = Class;
1052
1053
0
  CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class);
1054
0
  LSI->CallOperator = Method;
1055
0
  Method->setLexicalDeclContext(CurContext);
1056
1057
0
  PushDeclContext(CurScope, Method);
1058
1059
0
  bool ContainsUnexpandedParameterPack = false;
1060
1061
  // Distinct capture names, for diagnostics.
1062
0
  llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1063
1064
  // Handle explicit captures.
1065
0
  SourceLocation PrevCaptureLoc =
1066
0
      Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1067
0
  for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1068
0
       PrevCaptureLoc = C->Loc, ++C) {
1069
0
    if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1070
0
      if (C->Kind == LCK_StarThis)
1071
0
        Diag(C->Loc, !getLangOpts().CPlusPlus17
1072
0
                         ? diag::ext_star_this_lambda_capture_cxx17
1073
0
                         : diag::warn_cxx14_compat_star_this_lambda_capture);
1074
1075
      // C++11 [expr.prim.lambda]p8:
1076
      //   An identifier or this shall not appear more than once in a
1077
      //   lambda-capture.
1078
0
      if (LSI->isCXXThisCaptured()) {
1079
0
        Diag(C->Loc, diag::err_capture_more_than_once)
1080
0
            << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1081
0
            << FixItHint::CreateRemoval(
1082
0
                   SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1083
0
        continue;
1084
0
      }
1085
1086
      // C++20 [expr.prim.lambda]p8:
1087
      //  If a lambda-capture includes a capture-default that is =,
1088
      //  each simple-capture of that lambda-capture shall be of the form
1089
      //  "&identifier", "this", or "* this". [ Note: The form [&,this] is
1090
      //  redundant but accepted for compatibility with ISO C++14. --end note ]
1091
0
      if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1092
0
        Diag(C->Loc, !getLangOpts().CPlusPlus20
1093
0
                         ? diag::ext_equals_this_lambda_capture_cxx20
1094
0
                         : diag::warn_cxx17_compat_equals_this_lambda_capture);
1095
1096
      // C++11 [expr.prim.lambda]p12:
1097
      //   If this is captured by a local lambda expression, its nearest
1098
      //   enclosing function shall be a non-static member function.
1099
0
      QualType ThisCaptureType = getCurrentThisType();
1100
0
      if (ThisCaptureType.isNull()) {
1101
0
        Diag(C->Loc, diag::err_this_capture) << true;
1102
0
        continue;
1103
0
      }
1104
1105
0
      CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1106
0
                          /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1107
0
                          C->Kind == LCK_StarThis);
1108
0
      if (!LSI->Captures.empty())
1109
0
        LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1110
0
      continue;
1111
0
    }
1112
1113
0
    assert(C->Id && "missing identifier for capture");
1114
1115
0
    if (C->Init.isInvalid())
1116
0
      continue;
1117
1118
0
    ValueDecl *Var = nullptr;
1119
0
    if (C->Init.isUsable()) {
1120
0
      Diag(C->Loc, getLangOpts().CPlusPlus14
1121
0
                       ? diag::warn_cxx11_compat_init_capture
1122
0
                       : diag::ext_init_capture);
1123
1124
      // If the initializer expression is usable, but the InitCaptureType
1125
      // is not, then an error has occurred - so ignore the capture for now.
1126
      // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1127
      // FIXME: we should create the init capture variable and mark it invalid
1128
      // in this case.
1129
0
      if (C->InitCaptureType.get().isNull())
1130
0
        continue;
1131
1132
0
      if (C->Init.get()->containsUnexpandedParameterPack() &&
1133
0
          !C->InitCaptureType.get()->getAs<PackExpansionType>())
1134
0
        DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1135
1136
0
      unsigned InitStyle;
1137
0
      switch (C->InitKind) {
1138
0
      case LambdaCaptureInitKind::NoInit:
1139
0
        llvm_unreachable("not an init-capture?");
1140
0
      case LambdaCaptureInitKind::CopyInit:
1141
0
        InitStyle = VarDecl::CInit;
1142
0
        break;
1143
0
      case LambdaCaptureInitKind::DirectInit:
1144
0
        InitStyle = VarDecl::CallInit;
1145
0
        break;
1146
0
      case LambdaCaptureInitKind::ListInit:
1147
0
        InitStyle = VarDecl::ListInit;
1148
0
        break;
1149
0
      }
1150
0
      Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1151
0
                                           C->EllipsisLoc, C->Id, InitStyle,
1152
0
                                           C->Init.get(), Method);
1153
0
      assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1154
0
      if (auto *V = dyn_cast<VarDecl>(Var))
1155
0
        CheckShadow(CurrentScope, V);
1156
0
      PushOnScopeChains(Var, CurrentScope, false);
1157
0
    } else {
1158
0
      assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1159
0
             "init capture has valid but null init?");
1160
1161
      // C++11 [expr.prim.lambda]p8:
1162
      //   If a lambda-capture includes a capture-default that is &, the
1163
      //   identifiers in the lambda-capture shall not be preceded by &.
1164
      //   If a lambda-capture includes a capture-default that is =, [...]
1165
      //   each identifier it contains shall be preceded by &.
1166
0
      if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1167
0
        Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1168
0
            << FixItHint::CreateRemoval(
1169
0
                SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1170
0
        continue;
1171
0
      } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1172
0
        Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1173
0
            << FixItHint::CreateRemoval(
1174
0
                SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1175
0
        continue;
1176
0
      }
1177
1178
      // C++11 [expr.prim.lambda]p10:
1179
      //   The identifiers in a capture-list are looked up using the usual
1180
      //   rules for unqualified name lookup (3.4.1)
1181
0
      DeclarationNameInfo Name(C->Id, C->Loc);
1182
0
      LookupResult R(*this, Name, LookupOrdinaryName);
1183
0
      LookupName(R, CurScope);
1184
0
      if (R.isAmbiguous())
1185
0
        continue;
1186
0
      if (R.empty()) {
1187
        // FIXME: Disable corrections that would add qualification?
1188
0
        CXXScopeSpec ScopeSpec;
1189
0
        DeclFilterCCC<VarDecl> Validator{};
1190
0
        if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1191
0
          continue;
1192
0
      }
1193
1194
0
      if (auto *BD = R.getAsSingle<BindingDecl>())
1195
0
        Var = BD;
1196
0
      else
1197
0
        Var = R.getAsSingle<VarDecl>();
1198
0
      if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1199
0
        continue;
1200
0
    }
1201
1202
    // C++11 [expr.prim.lambda]p10:
1203
    //   [...] each such lookup shall find a variable with automatic storage
1204
    //   duration declared in the reaching scope of the local lambda expression.
1205
    // Note that the 'reaching scope' check happens in tryCaptureVariable().
1206
0
    if (!Var) {
1207
0
      Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1208
0
      continue;
1209
0
    }
1210
1211
    // C++11 [expr.prim.lambda]p8:
1212
    //   An identifier or this shall not appear more than once in a
1213
    //   lambda-capture.
1214
0
    if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1215
0
        !Inserted) {
1216
0
      if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1217
0
          !Var->isInitCapture()) {
1218
0
        Diag(C->Loc, diag::err_capture_more_than_once)
1219
0
            << C->Id << It->second->getBeginLoc()
1220
0
            << FixItHint::CreateRemoval(
1221
0
                   SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1222
0
        Var->setInvalidDecl();
1223
0
      } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1224
0
        DiagPlaceholderVariableDefinition(C->Loc);
1225
0
      } else {
1226
        // Previous capture captured something different (one or both was
1227
        // an init-capture): no fixit.
1228
0
        Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1229
0
        continue;
1230
0
      }
1231
0
    }
1232
1233
    // Ignore invalid decls; they'll just confuse the code later.
1234
0
    if (Var->isInvalidDecl())
1235
0
      continue;
1236
1237
0
    VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1238
1239
0
    if (!Underlying->hasLocalStorage()) {
1240
0
      Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1241
0
      Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1242
0
      continue;
1243
0
    }
1244
1245
    // C++11 [expr.prim.lambda]p23:
1246
    //   A capture followed by an ellipsis is a pack expansion (14.5.3).
1247
0
    SourceLocation EllipsisLoc;
1248
0
    if (C->EllipsisLoc.isValid()) {
1249
0
      if (Var->isParameterPack()) {
1250
0
        EllipsisLoc = C->EllipsisLoc;
1251
0
      } else {
1252
0
        Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1253
0
            << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1254
0
                                   : SourceRange(C->Loc));
1255
1256
        // Just ignore the ellipsis.
1257
0
      }
1258
0
    } else if (Var->isParameterPack()) {
1259
0
      ContainsUnexpandedParameterPack = true;
1260
0
    }
1261
1262
0
    if (C->Init.isUsable()) {
1263
0
      addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1264
0
      PushOnScopeChains(Var, CurScope, false);
1265
0
    } else {
1266
0
      TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef
1267
0
                                                 : TryCapture_ExplicitByVal;
1268
0
      tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1269
0
    }
1270
0
    if (!LSI->Captures.empty())
1271
0
      LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1272
0
  }
1273
0
  finishLambdaExplicitCaptures(LSI);
1274
0
  LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1275
0
  PopDeclContext();
1276
0
}
1277
1278
void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
1279
0
                                        SourceLocation MutableLoc) {
1280
1281
0
  LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
1282
0
  LSI->Mutable = MutableLoc.isValid();
1283
0
  ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1284
1285
  // C++11 [expr.prim.lambda]p9:
1286
  //   A lambda-expression whose smallest enclosing scope is a block scope is a
1287
  //   local lambda expression; any other lambda expression shall not have a
1288
  //   capture-default or simple-capture in its lambda-introducer.
1289
  //
1290
  // For simple-captures, this is covered by the check below that any named
1291
  // entity is a variable that can be captured.
1292
  //
1293
  // For DR1632, we also allow a capture-default in any context where we can
1294
  // odr-use 'this' (in particular, in a default initializer for a non-static
1295
  // data member).
1296
0
  if (Intro.Default != LCD_None &&
1297
0
      !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1298
0
      (getCurrentThisType().isNull() ||
1299
0
       CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1300
0
                           /*BuildAndDiagnose=*/false)))
1301
0
    Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1302
0
}
1303
1304
void Sema::ActOnLambdaClosureParameters(
1305
0
    Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) {
1306
0
  LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
1307
0
  PushDeclContext(LambdaScope, LSI->CallOperator);
1308
1309
0
  for (const DeclaratorChunk::ParamInfo &P : Params) {
1310
0
    auto *Param = cast<ParmVarDecl>(P.Param);
1311
0
    Param->setOwningFunction(LSI->CallOperator);
1312
0
    if (Param->getIdentifier())
1313
0
      PushOnScopeChains(Param, LambdaScope, false);
1314
0
  }
1315
1316
  // After the parameter list, we may parse a noexcept/requires/trailing return
1317
  // type which need to know whether the call operator constiture a dependent
1318
  // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1319
  // now.
1320
0
  TemplateParameterList *TemplateParams =
1321
0
      getGenericLambdaTemplateParameterList(LSI, *this);
1322
0
  if (TemplateParams) {
1323
0
    AddTemplateParametersToLambdaCallOperator(LSI->CallOperator, LSI->Lambda,
1324
0
                                              TemplateParams);
1325
0
    LSI->Lambda->setLambdaIsGeneric(true);
1326
0
  }
1327
0
  LSI->AfterParameterList = true;
1328
0
}
1329
1330
void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
1331
                                        Declarator &ParamInfo,
1332
0
                                        const DeclSpec &DS) {
1333
1334
0
  LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);
1335
0
  LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier());
1336
1337
0
  SmallVector<ParmVarDecl *, 8> Params;
1338
0
  bool ExplicitResultType;
1339
1340
0
  SourceLocation TypeLoc, CallOperatorLoc;
1341
0
  if (ParamInfo.getNumTypeObjects() == 0) {
1342
0
    CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1343
0
  } else {
1344
0
    unsigned Index;
1345
0
    ParamInfo.isFunctionDeclarator(Index);
1346
0
    const auto &Object = ParamInfo.getTypeObject(Index);
1347
0
    TypeLoc =
1348
0
        Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1349
0
    CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1350
0
  }
1351
1352
0
  CXXRecordDecl *Class = LSI->Lambda;
1353
0
  CXXMethodDecl *Method = LSI->CallOperator;
1354
1355
0
  TypeSourceInfo *MethodTyInfo = getLambdaType(
1356
0
      *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1357
1358
0
  LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1359
1360
0
  if (ParamInfo.isFunctionDeclarator() != 0 &&
1361
0
      !FTIHasSingleVoidParameter(ParamInfo.getFunctionTypeInfo())) {
1362
0
    const auto &FTI = ParamInfo.getFunctionTypeInfo();
1363
0
    Params.reserve(Params.size());
1364
0
    for (unsigned I = 0; I < FTI.NumParams; ++I) {
1365
0
      auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1366
0
      Param->setScopeInfo(0, Params.size());
1367
0
      Params.push_back(Param);
1368
0
    }
1369
0
  }
1370
1371
0
  bool IsLambdaStatic =
1372
0
      ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
1373
1374
0
  CompleteLambdaCallOperator(
1375
0
      Method, Intro.Range.getBegin(), CallOperatorLoc,
1376
0
      ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1377
0
      ParamInfo.getDeclSpec().getConstexprSpecifier(),
1378
0
      IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1379
1380
0
  CheckCXXDefaultArguments(Method);
1381
1382
  // This represents the function body for the lambda function, check if we
1383
  // have to apply optnone due to a pragma.
1384
0
  AddRangeBasedOptnone(Method);
1385
1386
  // code_seg attribute on lambda apply to the method.
1387
0
  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(
1388
0
          Method, /*IsDefinition=*/true))
1389
0
    Method->addAttr(A);
1390
1391
  // Attributes on the lambda apply to the method.
1392
0
  ProcessDeclAttributes(CurScope, Method, ParamInfo);
1393
1394
  // CUDA lambdas get implicit host and device attributes.
1395
0
  if (getLangOpts().CUDA)
1396
0
    CUDASetLambdaAttrs(Method);
1397
1398
  // OpenMP lambdas might get assumumption attributes.
1399
0
  if (LangOpts.OpenMP)
1400
0
    ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1401
1402
0
  handleLambdaNumbering(Class, Method);
1403
1404
0
  for (auto &&C : LSI->Captures) {
1405
0
    if (!C.isVariableCapture())
1406
0
      continue;
1407
0
    ValueDecl *Var = C.getVariable();
1408
0
    if (Var && Var->isInitCapture()) {
1409
0
      PushOnScopeChains(Var, CurScope, false);
1410
0
    }
1411
0
  }
1412
1413
0
  auto CheckRedefinition = [&](ParmVarDecl *Param) {
1414
0
    for (const auto &Capture : Intro.Captures) {
1415
0
      if (Capture.Id == Param->getIdentifier()) {
1416
0
        Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1417
0
        Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1418
0
            << Capture.Id << true;
1419
0
        return false;
1420
0
      }
1421
0
    }
1422
0
    return true;
1423
0
  };
1424
1425
0
  for (ParmVarDecl *P : Params) {
1426
0
    if (!P->getIdentifier())
1427
0
      continue;
1428
0
    if (CheckRedefinition(P))
1429
0
      CheckShadow(CurScope, P);
1430
0
    PushOnScopeChains(P, CurScope);
1431
0
  }
1432
1433
  // C++23 [expr.prim.lambda.capture]p5:
1434
  // If an identifier in a capture appears as the declarator-id of a parameter
1435
  // of the lambda-declarator's parameter-declaration-clause or as the name of a
1436
  // template parameter of the lambda-expression's template-parameter-list, the
1437
  // program is ill-formed.
1438
0
  TemplateParameterList *TemplateParams =
1439
0
      getGenericLambdaTemplateParameterList(LSI, *this);
1440
0
  if (TemplateParams) {
1441
0
    for (const auto *TP : TemplateParams->asArray()) {
1442
0
      if (!TP->getIdentifier())
1443
0
        continue;
1444
0
      for (const auto &Capture : Intro.Captures) {
1445
0
        if (Capture.Id == TP->getIdentifier()) {
1446
0
          Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1447
0
          NoteTemplateParameterLocation(*TP);
1448
0
        }
1449
0
      }
1450
0
    }
1451
0
  }
1452
1453
  // C++20: dcl.decl.general p4:
1454
  // The optional requires-clause ([temp.pre]) in an init-declarator or
1455
  // member-declarator shall be present only if the declarator declares a
1456
  // templated function ([dcl.fct]).
1457
0
  if (Expr *TRC = Method->getTrailingRequiresClause()) {
1458
    // [temp.pre]/8:
1459
    // An entity is templated if it is
1460
    // - a template,
1461
    // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1462
    // templated entity,
1463
    // - a member of a templated entity,
1464
    // - an enumerator for an enumeration that is a templated entity, or
1465
    // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1466
    // appearing in the declaration of a templated entity. [Note 6: A local
1467
    // class, a local or block variable, or a friend function defined in a
1468
    // templated entity is a templated entity.  — end note]
1469
    //
1470
    // A templated function is a function template or a function that is
1471
    // templated. A templated class is a class template or a class that is
1472
    // templated. A templated variable is a variable template or a variable
1473
    // that is templated.
1474
1475
    // Note: we only have to check if this is defined in a template entity, OR
1476
    // if we are a template, since the rest don't apply. The requires clause
1477
    // applies to the call operator, which we already know is a member function,
1478
    // AND defined.
1479
0
    if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1480
0
      Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1481
0
    }
1482
0
  }
1483
1484
  // Enter a new evaluation context to insulate the lambda from any
1485
  // cleanups from the enclosing full-expression.
1486
0
  PushExpressionEvaluationContext(
1487
0
      LSI->CallOperator->isConsteval()
1488
0
          ? ExpressionEvaluationContext::ImmediateFunctionContext
1489
0
          : ExpressionEvaluationContext::PotentiallyEvaluated);
1490
0
  ExprEvalContexts.back().InImmediateFunctionContext =
1491
0
      LSI->CallOperator->isConsteval();
1492
0
  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1493
0
      getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();
1494
0
}
1495
1496
void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1497
0
                            bool IsInstantiation) {
1498
0
  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1499
1500
  // Leave the expression-evaluation context.
1501
0
  DiscardCleanupsInEvaluationContext();
1502
0
  PopExpressionEvaluationContext();
1503
1504
  // Leave the context of the lambda.
1505
0
  if (!IsInstantiation)
1506
0
    PopDeclContext();
1507
1508
  // Finalize the lambda.
1509
0
  CXXRecordDecl *Class = LSI->Lambda;
1510
0
  Class->setInvalidDecl();
1511
0
  SmallVector<Decl*, 4> Fields(Class->fields());
1512
0
  ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1513
0
              SourceLocation(), ParsedAttributesView());
1514
0
  CheckCompletedCXXClass(nullptr, Class);
1515
1516
0
  PopFunctionScopeInfo();
1517
0
}
1518
1519
template <typename Func>
1520
static void repeatForLambdaConversionFunctionCallingConvs(
1521
0
    Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1522
0
  CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1523
0
      CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1524
0
  CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1525
0
      CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1526
0
  CallingConv CallOpCC = CallOpProto.getCallConv();
1527
1528
  /// Implement emitting a version of the operator for many of the calling
1529
  /// conventions for MSVC, as described here:
1530
  /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1531
  /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1532
  /// vectorcall are generated by MSVC when it is supported by the target.
1533
  /// Additionally, we are ensuring that the default-free/default-member and
1534
  /// call-operator calling convention are generated as well.
1535
  /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1536
  /// 'member default', despite MSVC not doing so. We do this in order to ensure
1537
  /// that someone who intentionally places 'thiscall' on the lambda call
1538
  /// operator will still get that overload, since we don't have the a way of
1539
  /// detecting the attribute by the time we get here.
1540
0
  if (S.getLangOpts().MSVCCompat) {
1541
0
    CallingConv Convs[] = {
1542
0
        CC_C,        CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1543
0
        DefaultFree, DefaultMember, CallOpCC};
1544
0
    llvm::sort(Convs);
1545
0
    llvm::iterator_range<CallingConv *> Range(
1546
0
        std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1547
0
    const TargetInfo &TI = S.getASTContext().getTargetInfo();
1548
1549
0
    for (CallingConv C : Range) {
1550
0
      if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
1551
0
        F(C);
1552
0
    }
1553
0
    return;
1554
0
  }
1555
1556
0
  if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1557
0
    F(DefaultFree);
1558
0
    F(DefaultMember);
1559
0
  } else {
1560
0
    F(CallOpCC);
1561
0
  }
1562
0
}
1563
1564
// Returns the 'standard' calling convention to be used for the lambda
1565
// conversion function, that is, the 'free' function calling convention unless
1566
// it is overridden by a non-default calling convention attribute.
1567
static CallingConv
1568
getLambdaConversionFunctionCallConv(Sema &S,
1569
0
                                    const FunctionProtoType *CallOpProto) {
1570
0
  CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1571
0
      CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1572
0
  CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1573
0
      CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1574
0
  CallingConv CallOpCC = CallOpProto->getCallConv();
1575
1576
  // If the call-operator hasn't been changed, return both the 'free' and
1577
  // 'member' function calling convention.
1578
0
  if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1579
0
    return DefaultFree;
1580
0
  return CallOpCC;
1581
0
}
1582
1583
QualType Sema::getLambdaConversionFunctionResultType(
1584
0
    const FunctionProtoType *CallOpProto, CallingConv CC) {
1585
0
  const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1586
0
      CallOpProto->getExtProtoInfo();
1587
0
  FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1588
0
  InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1589
0
  InvokerExtInfo.TypeQuals = Qualifiers();
1590
0
  assert(InvokerExtInfo.RefQualifier == RQ_None &&
1591
0
         "Lambda's call operator should not have a reference qualifier");
1592
0
  return Context.getFunctionType(CallOpProto->getReturnType(),
1593
0
                                 CallOpProto->getParamTypes(), InvokerExtInfo);
1594
0
}
1595
1596
/// Add a lambda's conversion to function pointer, as described in
1597
/// C++11 [expr.prim.lambda]p6.
1598
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1599
                                         CXXRecordDecl *Class,
1600
                                         CXXMethodDecl *CallOperator,
1601
0
                                         QualType InvokerFunctionTy) {
1602
  // This conversion is explicitly disabled if the lambda's function has
1603
  // pass_object_size attributes on any of its parameters.
1604
0
  auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1605
0
    return P->hasAttr<PassObjectSizeAttr>();
1606
0
  };
1607
0
  if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1608
0
    return;
1609
1610
  // Add the conversion to function pointer.
1611
0
  QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1612
1613
  // Create the type of the conversion function.
1614
0
  FunctionProtoType::ExtProtoInfo ConvExtInfo(
1615
0
      S.Context.getDefaultCallingConvention(
1616
0
      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1617
  // The conversion function is always const and noexcept.
1618
0
  ConvExtInfo.TypeQuals = Qualifiers();
1619
0
  ConvExtInfo.TypeQuals.addConst();
1620
0
  ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1621
0
  QualType ConvTy =
1622
0
      S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1623
1624
0
  SourceLocation Loc = IntroducerRange.getBegin();
1625
0
  DeclarationName ConversionName
1626
0
    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1627
0
        S.Context.getCanonicalType(PtrToFunctionTy));
1628
  // Construct a TypeSourceInfo for the conversion function, and wire
1629
  // all the parameters appropriately for the FunctionProtoTypeLoc
1630
  // so that everything works during transformation/instantiation of
1631
  // generic lambdas.
1632
  // The main reason for wiring up the parameters of the conversion
1633
  // function with that of the call operator is so that constructs
1634
  // like the following work:
1635
  // auto L = [](auto b) {                <-- 1
1636
  //   return [](auto a) -> decltype(a) { <-- 2
1637
  //      return a;
1638
  //   };
1639
  // };
1640
  // int (*fp)(int) = L(5);
1641
  // Because the trailing return type can contain DeclRefExprs that refer
1642
  // to the original call operator's variables, we hijack the call
1643
  // operators ParmVarDecls below.
1644
0
  TypeSourceInfo *ConvNamePtrToFunctionTSI =
1645
0
      S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1646
0
  DeclarationNameLoc ConvNameLoc =
1647
0
      DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1648
1649
  // The conversion function is a conversion to a pointer-to-function.
1650
0
  TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1651
0
  FunctionProtoTypeLoc ConvTL =
1652
0
      ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1653
  // Get the result of the conversion function which is a pointer-to-function.
1654
0
  PointerTypeLoc PtrToFunctionTL =
1655
0
      ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1656
  // Do the same for the TypeSourceInfo that is used to name the conversion
1657
  // operator.
1658
0
  PointerTypeLoc ConvNamePtrToFunctionTL =
1659
0
      ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1660
1661
  // Get the underlying function types that the conversion function will
1662
  // be converting to (should match the type of the call operator).
1663
0
  FunctionProtoTypeLoc CallOpConvTL =
1664
0
      PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1665
0
  FunctionProtoTypeLoc CallOpConvNameTL =
1666
0
    ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1667
1668
  // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1669
  // These parameter's are essentially used to transform the name and
1670
  // the type of the conversion operator.  By using the same parameters
1671
  // as the call operator's we don't have to fix any back references that
1672
  // the trailing return type of the call operator's uses (such as
1673
  // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1674
  // - we can simply use the return type of the call operator, and
1675
  // everything should work.
1676
0
  SmallVector<ParmVarDecl *, 4> InvokerParams;
1677
0
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1678
0
    ParmVarDecl *From = CallOperator->getParamDecl(I);
1679
1680
0
    InvokerParams.push_back(ParmVarDecl::Create(
1681
0
        S.Context,
1682
        // Temporarily add to the TU. This is set to the invoker below.
1683
0
        S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1684
0
        From->getLocation(), From->getIdentifier(), From->getType(),
1685
0
        From->getTypeSourceInfo(), From->getStorageClass(),
1686
0
        /*DefArg=*/nullptr));
1687
0
    CallOpConvTL.setParam(I, From);
1688
0
    CallOpConvNameTL.setParam(I, From);
1689
0
  }
1690
1691
0
  CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1692
0
      S.Context, Class, Loc,
1693
0
      DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1694
0
      S.getCurFPFeatures().isFPConstrained(),
1695
0
      /*isInline=*/true, ExplicitSpecifier(),
1696
0
      S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1697
0
                                  : ConstexprSpecKind::Unspecified,
1698
0
      CallOperator->getBody()->getEndLoc());
1699
0
  Conversion->setAccess(AS_public);
1700
0
  Conversion->setImplicit(true);
1701
1702
  // A non-generic lambda may still be a templated entity. We need to preserve
1703
  // constraints when converting the lambda to a function pointer. See GH63181.
1704
0
  if (Expr *Requires = CallOperator->getTrailingRequiresClause())
1705
0
    Conversion->setTrailingRequiresClause(Requires);
1706
1707
0
  if (Class->isGenericLambda()) {
1708
    // Create a template version of the conversion operator, using the template
1709
    // parameter list of the function call operator.
1710
0
    FunctionTemplateDecl *TemplateCallOperator =
1711
0
            CallOperator->getDescribedFunctionTemplate();
1712
0
    FunctionTemplateDecl *ConversionTemplate =
1713
0
                  FunctionTemplateDecl::Create(S.Context, Class,
1714
0
                                      Loc, ConversionName,
1715
0
                                      TemplateCallOperator->getTemplateParameters(),
1716
0
                                      Conversion);
1717
0
    ConversionTemplate->setAccess(AS_public);
1718
0
    ConversionTemplate->setImplicit(true);
1719
0
    Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1720
0
    Class->addDecl(ConversionTemplate);
1721
0
  } else
1722
0
    Class->addDecl(Conversion);
1723
1724
  // If the lambda is not static, we need to add a static member
1725
  // function that will be the result of the conversion with a
1726
  // certain unique ID.
1727
  // When it is static we just return the static call operator instead.
1728
0
  if (CallOperator->isImplicitObjectMemberFunction()) {
1729
0
    DeclarationName InvokerName =
1730
0
        &S.Context.Idents.get(getLambdaStaticInvokerName());
1731
    // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1732
    // we should get a prebuilt TrivialTypeSourceInfo from Context
1733
    // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1734
    // then rewire the parameters accordingly, by hoisting up the InvokeParams
1735
    // loop below and then use its Params to set Invoke->setParams(...) below.
1736
    // This would avoid the 'const' qualifier of the calloperator from
1737
    // contaminating the type of the invoker, which is currently adjusted
1738
    // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1739
    // trailing return type of the invoker would require a visitor to rebuild
1740
    // the trailing return type and adjusting all back DeclRefExpr's to refer
1741
    // to the new static invoker parameters - not the call operator's.
1742
0
    CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1743
0
        S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1744
0
        InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1745
0
        S.getCurFPFeatures().isFPConstrained(),
1746
0
        /*isInline=*/true, CallOperator->getConstexprKind(),
1747
0
        CallOperator->getBody()->getEndLoc());
1748
0
    for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1749
0
      InvokerParams[I]->setOwningFunction(Invoke);
1750
0
    Invoke->setParams(InvokerParams);
1751
0
    Invoke->setAccess(AS_private);
1752
0
    Invoke->setImplicit(true);
1753
0
    if (Class->isGenericLambda()) {
1754
0
      FunctionTemplateDecl *TemplateCallOperator =
1755
0
          CallOperator->getDescribedFunctionTemplate();
1756
0
      FunctionTemplateDecl *StaticInvokerTemplate =
1757
0
          FunctionTemplateDecl::Create(
1758
0
              S.Context, Class, Loc, InvokerName,
1759
0
              TemplateCallOperator->getTemplateParameters(), Invoke);
1760
0
      StaticInvokerTemplate->setAccess(AS_private);
1761
0
      StaticInvokerTemplate->setImplicit(true);
1762
0
      Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1763
0
      Class->addDecl(StaticInvokerTemplate);
1764
0
    } else
1765
0
      Class->addDecl(Invoke);
1766
0
  }
1767
0
}
1768
1769
/// Add a lambda's conversion to function pointers, as described in
1770
/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1771
/// single pointer conversion. In the event that the default calling convention
1772
/// for free and member functions is different, it will emit both conventions.
1773
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1774
                                          CXXRecordDecl *Class,
1775
0
                                          CXXMethodDecl *CallOperator) {
1776
0
  const FunctionProtoType *CallOpProto =
1777
0
      CallOperator->getType()->castAs<FunctionProtoType>();
1778
1779
0
  repeatForLambdaConversionFunctionCallingConvs(
1780
0
      S, *CallOpProto, [&](CallingConv CC) {
1781
0
        QualType InvokerFunctionTy =
1782
0
            S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1783
0
        addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1784
0
                                     InvokerFunctionTy);
1785
0
      });
1786
0
}
1787
1788
/// Add a lambda's conversion to block pointer.
1789
static void addBlockPointerConversion(Sema &S,
1790
                                      SourceRange IntroducerRange,
1791
                                      CXXRecordDecl *Class,
1792
0
                                      CXXMethodDecl *CallOperator) {
1793
0
  const FunctionProtoType *CallOpProto =
1794
0
      CallOperator->getType()->castAs<FunctionProtoType>();
1795
0
  QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1796
0
      CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1797
0
  QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1798
1799
0
  FunctionProtoType::ExtProtoInfo ConversionEPI(
1800
0
      S.Context.getDefaultCallingConvention(
1801
0
          /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1802
0
  ConversionEPI.TypeQuals = Qualifiers();
1803
0
  ConversionEPI.TypeQuals.addConst();
1804
0
  QualType ConvTy =
1805
0
      S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1806
1807
0
  SourceLocation Loc = IntroducerRange.getBegin();
1808
0
  DeclarationName Name
1809
0
    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1810
0
        S.Context.getCanonicalType(BlockPtrTy));
1811
0
  DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1812
0
      S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1813
0
  CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1814
0
      S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1815
0
      S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1816
0
      S.getCurFPFeatures().isFPConstrained(),
1817
0
      /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
1818
0
      CallOperator->getBody()->getEndLoc());
1819
0
  Conversion->setAccess(AS_public);
1820
0
  Conversion->setImplicit(true);
1821
0
  Class->addDecl(Conversion);
1822
0
}
1823
1824
ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1825
                                  SourceLocation ImplicitCaptureLoc,
1826
0
                                  bool IsOpenMPMapping) {
1827
  // VLA captures don't have a stored initialization expression.
1828
0
  if (Cap.isVLATypeCapture())
1829
0
    return ExprResult();
1830
1831
  // An init-capture is initialized directly from its stored initializer.
1832
0
  if (Cap.isInitCapture())
1833
0
    return cast<VarDecl>(Cap.getVariable())->getInit();
1834
1835
  // For anything else, build an initialization expression. For an implicit
1836
  // capture, the capture notionally happens at the capture-default, so use
1837
  // that location here.
1838
0
  SourceLocation Loc =
1839
0
      ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1840
1841
  // C++11 [expr.prim.lambda]p21:
1842
  //   When the lambda-expression is evaluated, the entities that
1843
  //   are captured by copy are used to direct-initialize each
1844
  //   corresponding non-static data member of the resulting closure
1845
  //   object. (For array members, the array elements are
1846
  //   direct-initialized in increasing subscript order.) These
1847
  //   initializations are performed in the (unspecified) order in
1848
  //   which the non-static data members are declared.
1849
1850
  // C++ [expr.prim.lambda]p12:
1851
  //   An entity captured by a lambda-expression is odr-used (3.2) in
1852
  //   the scope containing the lambda-expression.
1853
0
  ExprResult Init;
1854
0
  IdentifierInfo *Name = nullptr;
1855
0
  if (Cap.isThisCapture()) {
1856
0
    QualType ThisTy = getCurrentThisType();
1857
0
    Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1858
0
    if (Cap.isCopyCapture())
1859
0
      Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1860
0
    else
1861
0
      Init = This;
1862
0
  } else {
1863
0
    assert(Cap.isVariableCapture() && "unknown kind of capture");
1864
0
    ValueDecl *Var = Cap.getVariable();
1865
0
    Name = Var->getIdentifier();
1866
0
    Init = BuildDeclarationNameExpr(
1867
0
      CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1868
0
  }
1869
1870
  // In OpenMP, the capture kind doesn't actually describe how to capture:
1871
  // variables are "mapped" onto the device in a process that does not formally
1872
  // make a copy, even for a "copy capture".
1873
0
  if (IsOpenMPMapping)
1874
0
    return Init;
1875
1876
0
  if (Init.isInvalid())
1877
0
    return ExprError();
1878
1879
0
  Expr *InitExpr = Init.get();
1880
0
  InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1881
0
      Name, Cap.getCaptureType(), Loc);
1882
0
  InitializationKind InitKind =
1883
0
      InitializationKind::CreateDirect(Loc, Loc, Loc);
1884
0
  InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1885
0
  return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1886
0
}
1887
1888
0
ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) {
1889
0
  LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1890
0
  ActOnFinishFunctionBody(LSI.CallOperator, Body);
1891
0
  return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1892
0
}
1893
1894
static LambdaCaptureDefault
1895
0
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1896
0
  switch (ICS) {
1897
0
  case CapturingScopeInfo::ImpCap_None:
1898
0
    return LCD_None;
1899
0
  case CapturingScopeInfo::ImpCap_LambdaByval:
1900
0
    return LCD_ByCopy;
1901
0
  case CapturingScopeInfo::ImpCap_CapturedRegion:
1902
0
  case CapturingScopeInfo::ImpCap_LambdaByref:
1903
0
    return LCD_ByRef;
1904
0
  case CapturingScopeInfo::ImpCap_Block:
1905
0
    llvm_unreachable("block capture in lambda");
1906
0
  }
1907
0
  llvm_unreachable("Unknown implicit capture style");
1908
0
}
1909
1910
0
bool Sema::CaptureHasSideEffects(const Capture &From) {
1911
0
  if (From.isInitCapture()) {
1912
0
    Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1913
0
    if (Init && Init->HasSideEffects(Context))
1914
0
      return true;
1915
0
  }
1916
1917
0
  if (!From.isCopyCapture())
1918
0
    return false;
1919
1920
0
  const QualType T = From.isThisCapture()
1921
0
                         ? getCurrentThisType()->getPointeeType()
1922
0
                         : From.getCaptureType();
1923
1924
0
  if (T.isVolatileQualified())
1925
0
    return true;
1926
1927
0
  const Type *BaseT = T->getBaseElementTypeUnsafe();
1928
0
  if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1929
0
    return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1930
0
           !RD->hasTrivialDestructor();
1931
1932
0
  return false;
1933
0
}
1934
1935
bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1936
0
                                       const Capture &From) {
1937
0
  if (CaptureHasSideEffects(From))
1938
0
    return false;
1939
1940
0
  if (From.isVLATypeCapture())
1941
0
    return false;
1942
1943
  // FIXME: maybe we should warn on these if we can find a sensible diagnostic
1944
  // message
1945
0
  if (From.isInitCapture() &&
1946
0
      From.getVariable()->isPlaceholderVar(getLangOpts()))
1947
0
    return false;
1948
1949
0
  auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1950
0
  if (From.isThisCapture())
1951
0
    diag << "'this'";
1952
0
  else
1953
0
    diag << From.getVariable();
1954
0
  diag << From.isNonODRUsed();
1955
0
  diag << FixItHint::CreateRemoval(CaptureRange);
1956
0
  return true;
1957
0
}
1958
1959
/// Create a field within the lambda class or captured statement record for the
1960
/// given capture.
1961
FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1962
0
                                   const sema::Capture &Capture) {
1963
0
  SourceLocation Loc = Capture.getLocation();
1964
0
  QualType FieldType = Capture.getCaptureType();
1965
1966
0
  TypeSourceInfo *TSI = nullptr;
1967
0
  if (Capture.isVariableCapture()) {
1968
0
    const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
1969
0
    if (Var && Var->isInitCapture())
1970
0
      TSI = Var->getTypeSourceInfo();
1971
0
  }
1972
1973
  // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1974
  // appropriate, at least for an implicit capture.
1975
0
  if (!TSI)
1976
0
    TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1977
1978
  // Build the non-static data member.
1979
0
  FieldDecl *Field =
1980
0
      FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1981
0
                        /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1982
0
                        /*Mutable=*/false, ICIS_NoInit);
1983
  // If the variable being captured has an invalid type, mark the class as
1984
  // invalid as well.
1985
0
  if (!FieldType->isDependentType()) {
1986
0
    if (RequireCompleteSizedType(Loc, FieldType,
1987
0
                                 diag::err_field_incomplete_or_sizeless)) {
1988
0
      RD->setInvalidDecl();
1989
0
      Field->setInvalidDecl();
1990
0
    } else {
1991
0
      NamedDecl *Def;
1992
0
      FieldType->isIncompleteType(&Def);
1993
0
      if (Def && Def->isInvalidDecl()) {
1994
0
        RD->setInvalidDecl();
1995
0
        Field->setInvalidDecl();
1996
0
      }
1997
0
    }
1998
0
  }
1999
0
  Field->setImplicit(true);
2000
0
  Field->setAccess(AS_private);
2001
0
  RD->addDecl(Field);
2002
2003
0
  if (Capture.isVLATypeCapture())
2004
0
    Field->setCapturedVLAType(Capture.getCapturedVLAType());
2005
2006
0
  return Field;
2007
0
}
2008
2009
ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
2010
0
                                 LambdaScopeInfo *LSI) {
2011
  // Collect information from the lambda scope.
2012
0
  SmallVector<LambdaCapture, 4> Captures;
2013
0
  SmallVector<Expr *, 4> CaptureInits;
2014
0
  SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2015
0
  LambdaCaptureDefault CaptureDefault =
2016
0
      mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
2017
0
  CXXRecordDecl *Class;
2018
0
  CXXMethodDecl *CallOperator;
2019
0
  SourceRange IntroducerRange;
2020
0
  bool ExplicitParams;
2021
0
  bool ExplicitResultType;
2022
0
  CleanupInfo LambdaCleanup;
2023
0
  bool ContainsUnexpandedParameterPack;
2024
0
  bool IsGenericLambda;
2025
0
  {
2026
0
    CallOperator = LSI->CallOperator;
2027
0
    Class = LSI->Lambda;
2028
0
    IntroducerRange = LSI->IntroducerRange;
2029
0
    ExplicitParams = LSI->ExplicitParams;
2030
0
    ExplicitResultType = !LSI->HasImplicitReturnType;
2031
0
    LambdaCleanup = LSI->Cleanup;
2032
0
    ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2033
0
    IsGenericLambda = Class->isGenericLambda();
2034
2035
0
    CallOperator->setLexicalDeclContext(Class);
2036
0
    Decl *TemplateOrNonTemplateCallOperatorDecl =
2037
0
        CallOperator->getDescribedFunctionTemplate()
2038
0
        ? CallOperator->getDescribedFunctionTemplate()
2039
0
        : cast<Decl>(CallOperator);
2040
2041
    // FIXME: Is this really the best choice? Keeping the lexical decl context
2042
    // set as CurContext seems more faithful to the source.
2043
0
    TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2044
2045
0
    PopExpressionEvaluationContext();
2046
2047
    // True if the current capture has a used capture or default before it.
2048
0
    bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2049
0
    SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
2050
0
        CaptureDefaultLoc : IntroducerRange.getBegin();
2051
2052
0
    for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2053
0
      const Capture &From = LSI->Captures[I];
2054
2055
0
      if (From.isInvalid())
2056
0
        return ExprError();
2057
2058
0
      assert(!From.isBlockCapture() && "Cannot capture __block variables");
2059
0
      bool IsImplicit = I >= LSI->NumExplicitCaptures;
2060
0
      SourceLocation ImplicitCaptureLoc =
2061
0
          IsImplicit ? CaptureDefaultLoc : SourceLocation();
2062
2063
      // Use source ranges of explicit captures for fixits where available.
2064
0
      SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2065
2066
      // Warn about unused explicit captures.
2067
0
      bool IsCaptureUsed = true;
2068
0
      if (!CurContext->isDependentContext() && !IsImplicit &&
2069
0
          !From.isODRUsed()) {
2070
        // Initialized captures that are non-ODR used may not be eliminated.
2071
        // FIXME: Where did the IsGenericLambda here come from?
2072
0
        bool NonODRUsedInitCapture =
2073
0
            IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2074
0
        if (!NonODRUsedInitCapture) {
2075
0
          bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2076
0
          SourceRange FixItRange;
2077
0
          if (CaptureRange.isValid()) {
2078
0
            if (!CurHasPreviousCapture && !IsLast) {
2079
              // If there are no captures preceding this capture, remove the
2080
              // following comma.
2081
0
              FixItRange = SourceRange(CaptureRange.getBegin(),
2082
0
                                       getLocForEndOfToken(CaptureRange.getEnd()));
2083
0
            } else {
2084
              // Otherwise, remove the comma since the last used capture.
2085
0
              FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2086
0
                                       CaptureRange.getEnd());
2087
0
            }
2088
0
          }
2089
2090
0
          IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2091
0
        }
2092
0
      }
2093
2094
0
      if (CaptureRange.isValid()) {
2095
0
        CurHasPreviousCapture |= IsCaptureUsed;
2096
0
        PrevCaptureLoc = CaptureRange.getEnd();
2097
0
      }
2098
2099
      // Map the capture to our AST representation.
2100
0
      LambdaCapture Capture = [&] {
2101
0
        if (From.isThisCapture()) {
2102
          // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2103
          // because it results in a reference capture. Don't warn prior to
2104
          // C++2a; there's nothing that can be done about it before then.
2105
0
          if (getLangOpts().CPlusPlus20 && IsImplicit &&
2106
0
              CaptureDefault == LCD_ByCopy) {
2107
0
            Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2108
0
            Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2109
0
                << FixItHint::CreateInsertion(
2110
0
                       getLocForEndOfToken(CaptureDefaultLoc), ", this");
2111
0
          }
2112
0
          return LambdaCapture(From.getLocation(), IsImplicit,
2113
0
                               From.isCopyCapture() ? LCK_StarThis : LCK_This);
2114
0
        } else if (From.isVLATypeCapture()) {
2115
0
          return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2116
0
        } else {
2117
0
          assert(From.isVariableCapture() && "unknown kind of capture");
2118
0
          ValueDecl *Var = From.getVariable();
2119
0
          LambdaCaptureKind Kind =
2120
0
              From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
2121
0
          return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2122
0
                               From.getEllipsisLoc());
2123
0
        }
2124
0
      }();
2125
2126
      // Form the initializer for the capture field.
2127
0
      ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2128
2129
      // FIXME: Skip this capture if the capture is not used, the initializer
2130
      // has no side-effects, the type of the capture is trivial, and the
2131
      // lambda is not externally visible.
2132
2133
      // Add a FieldDecl for the capture and form its initializer.
2134
0
      BuildCaptureField(Class, From);
2135
0
      Captures.push_back(Capture);
2136
0
      CaptureInits.push_back(Init.get());
2137
2138
0
      if (LangOpts.CUDA)
2139
0
        CUDACheckLambdaCapture(CallOperator, From);
2140
0
    }
2141
2142
0
    Class->setCaptures(Context, Captures);
2143
2144
    // C++11 [expr.prim.lambda]p6:
2145
    //   The closure type for a lambda-expression with no lambda-capture
2146
    //   has a public non-virtual non-explicit const conversion function
2147
    //   to pointer to function having the same parameter and return
2148
    //   types as the closure type's function call operator.
2149
0
    if (Captures.empty() && CaptureDefault == LCD_None)
2150
0
      addFunctionPointerConversions(*this, IntroducerRange, Class,
2151
0
                                    CallOperator);
2152
2153
    // Objective-C++:
2154
    //   The closure type for a lambda-expression has a public non-virtual
2155
    //   non-explicit const conversion function to a block pointer having the
2156
    //   same parameter and return types as the closure type's function call
2157
    //   operator.
2158
    // FIXME: Fix generic lambda to block conversions.
2159
0
    if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2160
0
      addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2161
2162
    // Finalize the lambda class.
2163
0
    SmallVector<Decl*, 4> Fields(Class->fields());
2164
0
    ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2165
0
                SourceLocation(), ParsedAttributesView());
2166
0
    CheckCompletedCXXClass(nullptr, Class);
2167
0
  }
2168
2169
0
  Cleanup.mergeFrom(LambdaCleanup);
2170
2171
0
  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2172
0
                                          CaptureDefault, CaptureDefaultLoc,
2173
0
                                          ExplicitParams, ExplicitResultType,
2174
0
                                          CaptureInits, EndLoc,
2175
0
                                          ContainsUnexpandedParameterPack);
2176
  // If the lambda expression's call operator is not explicitly marked constexpr
2177
  // and we are not in a dependent context, analyze the call operator to infer
2178
  // its constexpr-ness, suppressing diagnostics while doing so.
2179
0
  if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2180
0
      !CallOperator->isConstexpr() &&
2181
0
      !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2182
0
      !Class->getDeclContext()->isDependentContext()) {
2183
0
    CallOperator->setConstexprKind(
2184
0
        CheckConstexprFunctionDefinition(CallOperator,
2185
0
                                         CheckConstexprKind::CheckValid)
2186
0
            ? ConstexprSpecKind::Constexpr
2187
0
            : ConstexprSpecKind::Unspecified);
2188
0
  }
2189
2190
  // Emit delayed shadowing warnings now that the full capture list is known.
2191
0
  DiagnoseShadowingLambdaDecls(LSI);
2192
2193
0
  if (!CurContext->isDependentContext()) {
2194
0
    switch (ExprEvalContexts.back().Context) {
2195
    // C++11 [expr.prim.lambda]p2:
2196
    //   A lambda-expression shall not appear in an unevaluated operand
2197
    //   (Clause 5).
2198
0
    case ExpressionEvaluationContext::Unevaluated:
2199
0
    case ExpressionEvaluationContext::UnevaluatedList:
2200
0
    case ExpressionEvaluationContext::UnevaluatedAbstract:
2201
    // C++1y [expr.const]p2:
2202
    //   A conditional-expression e is a core constant expression unless the
2203
    //   evaluation of e, following the rules of the abstract machine, would
2204
    //   evaluate [...] a lambda-expression.
2205
    //
2206
    // This is technically incorrect, there are some constant evaluated contexts
2207
    // where this should be allowed.  We should probably fix this when DR1607 is
2208
    // ratified, it lays out the exact set of conditions where we shouldn't
2209
    // allow a lambda-expression.
2210
0
    case ExpressionEvaluationContext::ConstantEvaluated:
2211
0
    case ExpressionEvaluationContext::ImmediateFunctionContext:
2212
      // We don't actually diagnose this case immediately, because we
2213
      // could be within a context where we might find out later that
2214
      // the expression is potentially evaluated (e.g., for typeid).
2215
0
      ExprEvalContexts.back().Lambdas.push_back(Lambda);
2216
0
      break;
2217
2218
0
    case ExpressionEvaluationContext::DiscardedStatement:
2219
0
    case ExpressionEvaluationContext::PotentiallyEvaluated:
2220
0
    case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
2221
0
      break;
2222
0
    }
2223
0
  }
2224
2225
0
  return MaybeBindToTemporary(Lambda);
2226
0
}
2227
2228
ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
2229
                                               SourceLocation ConvLocation,
2230
                                               CXXConversionDecl *Conv,
2231
0
                                               Expr *Src) {
2232
  // Make sure that the lambda call operator is marked used.
2233
0
  CXXRecordDecl *Lambda = Conv->getParent();
2234
0
  CXXMethodDecl *CallOperator
2235
0
    = cast<CXXMethodDecl>(
2236
0
        Lambda->lookup(
2237
0
          Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
2238
0
  CallOperator->setReferenced();
2239
0
  CallOperator->markUsed(Context);
2240
2241
0
  ExprResult Init = PerformCopyInitialization(
2242
0
      InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
2243
0
      CurrentLocation, Src);
2244
0
  if (!Init.isInvalid())
2245
0
    Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2246
2247
0
  if (Init.isInvalid())
2248
0
    return ExprError();
2249
2250
  // Create the new block to be returned.
2251
0
  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
2252
2253
  // Set the type information.
2254
0
  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2255
0
  Block->setIsVariadic(CallOperator->isVariadic());
2256
0
  Block->setBlockMissingReturnType(false);
2257
2258
  // Add parameters.
2259
0
  SmallVector<ParmVarDecl *, 4> BlockParams;
2260
0
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2261
0
    ParmVarDecl *From = CallOperator->getParamDecl(I);
2262
0
    BlockParams.push_back(ParmVarDecl::Create(
2263
0
        Context, Block, From->getBeginLoc(), From->getLocation(),
2264
0
        From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2265
0
        From->getStorageClass(),
2266
0
        /*DefArg=*/nullptr));
2267
0
  }
2268
0
  Block->setParams(BlockParams);
2269
2270
0
  Block->setIsConversionFromLambda(true);
2271
2272
  // Add capture. The capture uses a fake variable, which doesn't correspond
2273
  // to any actual memory location. However, the initializer copy-initializes
2274
  // the lambda object.
2275
0
  TypeSourceInfo *CapVarTSI =
2276
0
      Context.getTrivialTypeSourceInfo(Src->getType());
2277
0
  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2278
0
                                    ConvLocation, nullptr,
2279
0
                                    Src->getType(), CapVarTSI,
2280
0
                                    SC_None);
2281
0
  BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2282
0
                             /*nested=*/false, /*copy=*/Init.get());
2283
0
  Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2284
2285
  // Add a fake function body to the block. IR generation is responsible
2286
  // for filling in the actual body, which cannot be expressed as an AST.
2287
0
  Block->setBody(new (Context) CompoundStmt(ConvLocation));
2288
2289
  // Create the block literal expression.
2290
0
  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2291
0
  ExprCleanupObjects.push_back(Block);
2292
0
  Cleanup.setExprNeedsCleanups(true);
2293
2294
0
  return BuildBlock;
2295
0
}
2296
2297
0
static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) {
2298
0
  if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) {
2299
0
    while (FD->getInstantiatedFromMemberFunction())
2300
0
      FD = FD->getInstantiatedFromMemberFunction();
2301
0
    return FD;
2302
0
  }
2303
2304
0
  if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)
2305
0
    return FD->getInstantiatedFromDecl();
2306
2307
0
  FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();
2308
0
  if (!FTD)
2309
0
    return nullptr;
2310
2311
0
  while (FTD->getInstantiatedFromMemberTemplate())
2312
0
    FTD = FTD->getInstantiatedFromMemberTemplate();
2313
2314
0
  return FTD->getTemplatedDecl();
2315
0
}
2316
2317
Sema::LambdaScopeForCallOperatorInstantiationRAII::
2318
    LambdaScopeForCallOperatorInstantiationRAII(
2319
        Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
2320
        LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2321
0
    : FunctionScopeRAII(SemaRef) {
2322
0
  if (!isLambdaCallOperator(FD)) {
2323
0
    FunctionScopeRAII::disable();
2324
0
    return;
2325
0
  }
2326
2327
0
  SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2328
2329
0
  FunctionDecl *Pattern = getPatternFunctionDecl(FD);
2330
0
  if (Pattern) {
2331
0
    SemaRef.addInstantiatedCapturesToScope(FD, Pattern, Scope, MLTAL);
2332
2333
0
    FunctionDecl *ParentFD = FD;
2334
0
    while (ShouldAddDeclsFromParentScope) {
2335
2336
0
      ParentFD =
2337
0
          dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(ParentFD));
2338
0
      Pattern =
2339
0
          dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(Pattern));
2340
2341
0
      if (!FD || !Pattern)
2342
0
        break;
2343
2344
0
      SemaRef.addInstantiatedParametersToScope(ParentFD, Pattern, Scope, MLTAL);
2345
0
      SemaRef.addInstantiatedLocalVarsToScope(ParentFD, Pattern, Scope);
2346
0
    }
2347
0
  }
2348
0
}