Coverage Report

Created: 2020-02-18 08:44

/Users/buildslave/jenkins/workspace/coverage/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 "llvm/ADT/STLExtras.h"
24
using namespace clang;
25
using namespace sema;
26
27
/// Examines the FunctionScopeInfo stack to determine the nearest
28
/// enclosing lambda (to the current lambda) that is 'capture-ready' for
29
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
30
/// If successful, returns the index into Sema's FunctionScopeInfo stack
31
/// of the capture-ready lambda's LambdaScopeInfo.
32
///
33
/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34
/// lambda - is on top) to determine the index of the nearest enclosing/outer
35
/// lambda that is ready to capture the \p VarToCapture being referenced in
36
/// the current lambda.
37
/// As we climb down the stack, we want the index of the first such lambda -
38
/// that is the lambda with the highest index that is 'capture-ready'.
39
///
40
/// A lambda 'L' is capture-ready for 'V' (var or this) if:
41
///  - its enclosing context is non-dependent
42
///  - and if the chain of lambdas between L and the lambda in which
43
///    V is potentially used (i.e. the lambda at the top of the scope info
44
///    stack), can all capture or have already captured V.
45
/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46
///
47
/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48
/// for whether it is 'capture-capable' (see
49
/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50
/// capture.
51
///
52
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53
///  LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
54
///  is at the top of the stack and has the highest index.
55
/// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
56
///
57
/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58
/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59
/// which is capture-ready.  If the return value evaluates to 'false' then
60
/// no lambda is capture-ready for \p VarToCapture.
61
62
static inline Optional<unsigned>
63
getStackIndexOfNearestEnclosingCaptureReadyLambda(
64
    ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65
579
    VarDecl *VarToCapture) {
66
579
  // Label failure to capture.
67
579
  const Optional<unsigned> NoLambdaIsCaptureReady;
68
579
69
579
  // Ignore all inner captured regions.
70
579
  unsigned CurScopeIndex = FunctionScopes.size() - 1;
71
584
  while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72
584
                                  FunctionScopes[CurScopeIndex]))
73
5
    --CurScopeIndex;
74
579
  assert(
75
579
      isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76
579
      "The function on the top of sema's function-info stack must be a lambda");
77
579
78
579
  // If VarToCapture is null, we are attempting to capture 'this'.
79
579
  const bool IsCapturingThis = !VarToCapture;
80
579
  const bool IsCapturingVariable = !IsCapturingThis;
81
579
82
579
  // Start with the current lambda at the top of the stack (highest index).
83
579
  DeclContext *EnclosingDC =
84
579
      cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
85
579
86
897
  do {
87
897
    const clang::sema::LambdaScopeInfo *LSI =
88
897
        cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
89
897
    // IF we have climbed down to an intervening enclosing lambda that contains
90
897
    // the variable declaration - it obviously can/must not capture the
91
897
    // variable.
92
897
    // Since its enclosing DC is dependent, all the lambdas between it and the
93
897
    // innermost nested lambda are dependent (otherwise we wouldn't have
94
897
    // arrived here) - so we don't yet have a lambda that can capture the
95
897
    // variable.
96
897
    if (IsCapturingVariable &&
97
897
        
VarToCapture->getDeclContext()->Equals(EnclosingDC)817
)
98
129
      return NoLambdaIsCaptureReady;
99
768
100
768
    // For an enclosing lambda to be capture ready for an entity, all
101
768
    // intervening lambda's have to be able to capture that entity. If even
102
768
    // one of the intervening lambda's is not capable of capturing the entity
103
768
    // then no enclosing lambda can ever capture that entity.
104
768
    // For e.g.
105
768
    // const int x = 10;
106
768
    // [=](auto a) {    #1
107
768
    //   [](auto b) {   #2 <-- an intervening lambda that can never capture 'x'
108
768
    //    [=](auto c) { #3
109
768
    //       f(x, c);  <-- can not lead to x's speculative capture by #1 or #2
110
768
    //    }; }; };
111
768
    // If they do not have a default implicit capture, check to see
112
768
    // if the entity has already been explicitly captured.
113
768
    // If even a single dependent enclosing lambda lacks the capability
114
768
    // to ever capture this variable, there is no further enclosing
115
768
    // non-dependent lambda that can capture this variable.
116
768
    if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
117
186
      if (IsCapturingVariable && 
!LSI->isCaptured(VarToCapture)160
)
118
91
        return NoLambdaIsCaptureReady;
119
95
      if (IsCapturingThis && 
!LSI->isCXXThisCaptured()26
)
120
24
        return NoLambdaIsCaptureReady;
121
653
    }
122
653
    EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
123
653
124
653
    assert(CurScopeIndex);
125
653
    --CurScopeIndex;
126
653
  } while (!EnclosingDC->isTranslationUnit() &&
127
653
           EnclosingDC->isDependentContext() &&
128
653
           
isLambdaCallOperator(EnclosingDC)440
);
129
579
130
579
  assert(CurScopeIndex < (FunctionScopes.size() - 1));
131
335
  // If the enclosingDC is not dependent, then the immediately nested lambda
132
335
  // (one index above) is capture-ready.
133
335
  if (!EnclosingDC->isDependentContext())
134
213
    return CurScopeIndex + 1;
135
122
  return NoLambdaIsCaptureReady;
136
122
}
137
138
/// Examines the FunctionScopeInfo stack to determine the nearest
139
/// enclosing lambda (to the current lambda) that is 'capture-capable' for
140
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
141
/// If successful, returns the index into Sema's FunctionScopeInfo stack
142
/// of the capture-capable lambda's LambdaScopeInfo.
143
///
144
/// Given the current stack of lambdas being processed by Sema and
145
/// the variable of interest, to identify the nearest enclosing lambda (to the
146
/// current lambda at the top of the stack) that can truly capture
147
/// a variable, it has to have the following two properties:
148
///  a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
149
///     - climb down the stack (i.e. starting from the innermost and examining
150
///       each outer lambda step by step) checking if each enclosing
151
///       lambda can either implicitly or explicitly capture the variable.
152
///       Record the first such lambda that is enclosed in a non-dependent
153
///       context. If no such lambda currently exists return failure.
154
///  b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
155
///  capture the variable by checking all its enclosing lambdas:
156
///     - check if all outer lambdas enclosing the 'capture-ready' lambda
157
///       identified above in 'a' can also capture the variable (this is done
158
///       via tryCaptureVariable for variables and CheckCXXThisCapture for
159
///       'this' by passing in the index of the Lambda identified in step 'a')
160
///
161
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
162
/// LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
163
/// is at the top of the stack.
164
///
165
/// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
166
///
167
///
168
/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
169
/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
170
/// which is capture-capable.  If the return value evaluates to 'false' then
171
/// no lambda is capture-capable for \p VarToCapture.
172
173
Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
174
    ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
175
579
    VarDecl *VarToCapture, Sema &S) {
176
579
177
579
  const Optional<unsigned> NoLambdaIsCaptureCapable;
178
579
179
579
  const Optional<unsigned> OptionalStackIndex =
180
579
      getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
181
579
                                                        VarToCapture);
182
579
  if (!OptionalStackIndex)
183
366
    return NoLambdaIsCaptureCapable;
184
213
185
213
  const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
186
213
  assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
187
213
          S.getCurGenericLambda()) &&
188
213
         "The capture ready lambda for a potential capture can only be the "
189
213
         "current lambda if it is a generic lambda");
190
213
191
213
  const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
192
213
      cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
193
213
194
213
  // If VarToCapture is null, we are attempting to capture 'this'
195
213
  const bool IsCapturingThis = !VarToCapture;
196
213
  const bool IsCapturingVariable = !IsCapturingThis;
197
213
198
213
  if (IsCapturingVariable) {
199
203
    // Check if the capture-ready lambda can truly capture the variable, by
200
203
    // checking whether all enclosing lambdas of the capture-ready lambda allow
201
203
    // the capture - i.e. make sure it is capture-capable.
202
203
    QualType CaptureType, DeclRefType;
203
203
    const bool CanCaptureVariable =
204
203
        !S.tryCaptureVariable(VarToCapture,
205
203
                              /*ExprVarIsUsedInLoc*/ SourceLocation(),
206
203
                              clang::Sema::TryCapture_Implicit,
207
203
                              /*EllipsisLoc*/ SourceLocation(),
208
203
                              /*BuildAndDiagnose*/ false, CaptureType,
209
203
                              DeclRefType, &IndexOfCaptureReadyLambda);
210
203
    if (!CanCaptureVariable)
211
14
      return NoLambdaIsCaptureCapable;
212
10
  } else {
213
10
    // Check if the capture-ready lambda can truly capture 'this' by checking
214
10
    // whether all enclosing lambdas of the capture-ready lambda can capture
215
10
    // 'this'.
216
10
    const bool CanCaptureThis =
217
10
        !S.CheckCXXThisCapture(
218
10
             CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
219
10
             /*Explicit*/ false, /*BuildAndDiagnose*/ false,
220
10
             &IndexOfCaptureReadyLambda);
221
10
    if (!CanCaptureThis)
222
2
      return NoLambdaIsCaptureCapable;
223
197
  }
224
197
  return IndexOfCaptureReadyLambda;
225
197
}
226
227
static inline TemplateParameterList *
228
14.3k
getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229
14.3k
  if (!LSI->GLTemplateParameterList && 
!LSI->TemplateParams.empty()11.7k
) {
230
1.13k
    LSI->GLTemplateParameterList = TemplateParameterList::Create(
231
1.13k
        SemaRef.Context,
232
1.13k
        /*Template kw loc*/ SourceLocation(),
233
1.13k
        /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
234
1.13k
        LSI->TemplateParams,
235
1.13k
        /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
236
1.13k
        nullptr);
237
1.13k
  }
238
14.3k
  return LSI->GLTemplateParameterList;
239
14.3k
}
240
241
CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
242
                                             TypeSourceInfo *Info,
243
                                             bool KnownDependent,
244
7.15k
                                             LambdaCaptureDefault CaptureDefault) {
245
7.15k
  DeclContext *DC = CurContext;
246
7.17k
  while (!(DC->isFunctionOrMethod() || 
DC->isRecord()1.08k
||
DC->isFileContext()758
))
247
15
    DC = DC->getParent();
248
7.15k
  bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
249
7.15k
                                                               *this);
250
7.15k
  // Start constructing the lambda class.
251
7.15k
  CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
252
7.15k
                                                     IntroducerRange.getBegin(),
253
7.15k
                                                     KnownDependent,
254
7.15k
                                                     IsGenericLambda,
255
7.15k
                                                     CaptureDefault);
256
7.15k
  DC->addDecl(Class);
257
7.15k
258
7.15k
  return Class;
259
7.15k
}
260
261
/// Determine whether the given context is or is enclosed in an inline
262
/// function.
263
981k
static bool isInInlineFunction(const DeclContext *DC) {
264
1.35M
  while (!DC->isFileContext()) {
265
382k
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
266
21.3k
      if (FD->isInlined())
267
10.4k
        return true;
268
372k
269
372k
    DC = DC->getLexicalParent();
270
372k
  }
271
981k
272
981k
  
return false971k
;
273
981k
}
274
275
std::tuple<MangleNumberingContext *, Decl *>
276
995k
Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
277
995k
  // Compute the context for allocating mangling numbers in the current
278
995k
  // expression, if the ABI requires them.
279
995k
  Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
280
995k
281
995k
  enum ContextKind {
282
995k
    Normal,
283
995k
    DefaultArgument,
284
995k
    DataMember,
285
995k
    StaticDataMember,
286
995k
    InlineVariable,
287
995k
    VariableTemplate
288
995k
  } Kind = Normal;
289
995k
290
995k
  // Default arguments of member function parameters that appear in a class
291
995k
  // definition, as well as the initializers of data members, receive special
292
995k
  // treatment. Identify them.
293
995k
  if (ManglingContextDecl) {
294
1.86k
    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
295
696
      if (const DeclContext *LexicalDC
296
135
          = Param->getDeclContext()->getLexicalParent())
297
135
        if (LexicalDC->isRecord())
298
101
          Kind = DefaultArgument;
299
1.16k
    } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
300
1.02k
      if (Var->getDeclContext()->isRecord())
301
21
        Kind = StaticDataMember;
302
1.00k
      else if (Var->getMostRecentDecl()->isInline())
303
4
        Kind = InlineVariable;
304
997
      else if (Var->getDescribedVarTemplate())
305
13
        Kind = VariableTemplate;
306
984
      else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
307
7
        if (!VTS->isExplicitSpecialization())
308
7
          Kind = VariableTemplate;
309
7
      }
310
1.02k
    } else 
if (143
isa<FieldDecl>(ManglingContextDecl)143
) {
311
143
      Kind = DataMember;
312
143
    }
313
1.86k
  }
314
995k
315
995k
  // Itanium ABI [5.1.7]:
316
995k
  //   In the following contexts [...] the one-definition rule requires closure
317
995k
  //   types in different translation units to "correspond":
318
995k
  bool IsInNonspecializedTemplate =
319
995k
      inTemplateInstantiation() || 
CurContext->isDependentContext()994k
;
320
995k
  switch (Kind) {
321
995k
  case Normal: {
322
995k
    //  -- the bodies of non-exported nonspecialized template functions
323
995k
    //  -- the bodies of inline functions
324
995k
    if ((IsInNonspecializedTemplate &&
325
995k
         
!(13.9k
ManglingContextDecl13.9k
&&
isa<ParmVarDecl>(ManglingContextDecl)583
)) ||
326
995k
        
isInInlineFunction(CurContext)981k
) {
327
26.3k
      while (auto *CD = dyn_cast<CapturedDecl>(DC))
328
1.96k
        DC = CD->getParent();
329
24.3k
      return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
330
24.3k
    }
331
971k
332
971k
    return std::make_tuple(nullptr, nullptr);
333
971k
  }
334
971k
335
971k
  case StaticDataMember:
336
21
    //  -- the initializers of nonspecialized static members of template classes
337
21
    if (!IsInNonspecializedTemplate)
338
2
      return std::make_tuple(nullptr, ManglingContextDecl);
339
19
    // Fall through to get the current context.
340
19
    LLVM_FALLTHROUGH;
341
19
342
287
  case DataMember:
343
287
    //  -- the in-class initializers of class members
344
287
  case DefaultArgument:
345
287
    //  -- default arguments appearing in class definitions
346
287
  case InlineVariable:
347
287
    //  -- the initializers of inline variables
348
287
  case VariableTemplate:
349
287
    //  -- the initializers of templated variables
350
287
    return std::make_tuple(
351
287
        &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
352
287
                                          ManglingContextDecl),
353
287
        ManglingContextDecl);
354
0
  }
355
0
356
0
  llvm_unreachable("unexpected context");
357
0
}
358
359
CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
360
                                           SourceRange IntroducerRange,
361
                                           TypeSourceInfo *MethodTypeInfo,
362
                                           SourceLocation EndLoc,
363
                                           ArrayRef<ParmVarDecl *> Params,
364
                                           ConstexprSpecKind ConstexprKind,
365
7.15k
                                           Expr *TrailingRequiresClause) {
366
7.15k
  QualType MethodType = MethodTypeInfo->getType();
367
7.15k
  TemplateParameterList *TemplateParams =
368
7.15k
      getGenericLambdaTemplateParameterList(getCurLambda(), *this);
369
7.15k
  // If a lambda appears in a dependent context or is a generic lambda (has
370
7.15k
  // template parameters) and has an 'auto' return type, deduce it to a
371
7.15k
  // dependent type.
372
7.15k
  if (Class->isDependentContext() || 
TemplateParams5.58k
) {
373
2.79k
    const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
374
2.79k
    QualType Result = FPT->getReturnType();
375
2.79k
    if (Result->isUndeducedType()) {
376
1.94k
      Result = SubstAutoType(Result, Context.DependentTy);
377
1.94k
      MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
378
1.94k
                                           FPT->getExtProtoInfo());
379
1.94k
    }
380
2.79k
  }
381
7.15k
382
7.15k
  // C++11 [expr.prim.lambda]p5:
383
7.15k
  //   The closure type for a lambda-expression has a public inline function
384
7.15k
  //   call operator (13.5.4) whose parameters and return type are described by
385
7.15k
  //   the lambda-expression's parameter-declaration-clause and
386
7.15k
  //   trailing-return-type respectively.
387
7.15k
  DeclarationName MethodName
388
7.15k
    = Context.DeclarationNames.getCXXOperatorName(OO_Call);
389
7.15k
  DeclarationNameLoc MethodNameLoc;
390
7.15k
  MethodNameLoc.CXXOperatorName.BeginOpNameLoc
391
7.15k
    = IntroducerRange.getBegin().getRawEncoding();
392
7.15k
  MethodNameLoc.CXXOperatorName.EndOpNameLoc
393
7.15k
    = IntroducerRange.getEnd().getRawEncoding();
394
7.15k
  CXXMethodDecl *Method = CXXMethodDecl::Create(
395
7.15k
      Context, Class, EndLoc,
396
7.15k
      DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
397
7.15k
                          MethodNameLoc),
398
7.15k
      MethodType, MethodTypeInfo, SC_None,
399
7.15k
      /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
400
7.15k
  Method->setAccess(AS_public);
401
7.15k
  if (!TemplateParams)
402
5.28k
    Class->addDecl(Method);
403
7.15k
404
7.15k
  // Temporarily set the lexical declaration context to the current
405
7.15k
  // context, so that the Scope stack matches the lexical nesting.
406
7.15k
  Method->setLexicalDeclContext(CurContext);
407
7.15k
  // Create a function template if we have a template parameter list
408
7.15k
  FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
409
1.87k
            FunctionTemplateDecl::Create(Context, Class,
410
1.87k
                                         Method->getLocation(), MethodName,
411
1.87k
                                         TemplateParams,
412
5.28k
                                         Method) : nullptr;
413
7.15k
  if (TemplateMethod) {
414
1.87k
    TemplateMethod->setAccess(AS_public);
415
1.87k
    Method->setDescribedFunctionTemplate(TemplateMethod);
416
1.87k
    Class->addDecl(TemplateMethod);
417
1.87k
    TemplateMethod->setLexicalDeclContext(CurContext);
418
1.87k
  }
419
7.15k
420
7.15k
  // Add parameters.
421
7.15k
  if (!Params.empty()) {
422
3.29k
    Method->setParams(Params);
423
3.29k
    CheckParmsForFunctionDef(Params,
424
3.29k
                             /*CheckParameterNames=*/false);
425
3.29k
426
3.29k
    for (auto P : Method->parameters())
427
3.99k
      P->setOwningFunction(Method);
428
3.29k
  }
429
7.15k
430
7.15k
  return Method;
431
7.15k
}
432
433
void Sema::handleLambdaNumbering(
434
    CXXRecordDecl *Class, CXXMethodDecl *Method,
435
7.15k
    Optional<std::tuple<unsigned, bool, Decl *>> Mangling) {
436
7.15k
  if (Mangling) {
437
7
    unsigned ManglingNumber;
438
7
    bool HasKnownInternalLinkage;
439
7
    Decl *ManglingContextDecl;
440
7
    std::tie(ManglingNumber, HasKnownInternalLinkage, ManglingContextDecl) =
441
7
        Mangling.getValue();
442
7
    Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
443
7
                             HasKnownInternalLinkage);
444
7
    return;
445
7
  }
446
7.15k
447
7.15k
  auto getMangleNumberingContext =
448
7.15k
      [this](CXXRecordDecl *Class,
449
7.15k
             Decl *ManglingContextDecl) -> MangleNumberingContext * {
450
88
    // Get mangle numbering context if there's any extra decl context.
451
88
    if (ManglingContextDecl)
452
0
      return &Context.getManglingNumberContext(
453
0
          ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
454
88
    // Otherwise, from that lambda's decl context.
455
88
    auto DC = Class->getDeclContext();
456
88
    while (auto *CD = dyn_cast<CapturedDecl>(DC))
457
0
      DC = CD->getParent();
458
88
    return &Context.getManglingNumberContext(DC);
459
88
  };
460
7.15k
461
7.15k
  MangleNumberingContext *MCtx;
462
7.15k
  Decl *ManglingContextDecl;
463
7.15k
  std::tie(MCtx, ManglingContextDecl) =
464
7.15k
      getCurrentMangleNumberContext(Class->getDeclContext());
465
7.15k
  bool HasKnownInternalLinkage = false;
466
7.15k
  if (!MCtx && 
getLangOpts().CUDA3.00k
) {
467
88
    // Force lambda numbering in CUDA/HIP as we need to name lambdas following
468
88
    // ODR. Both device- and host-compilation need to have a consistent naming
469
88
    // on kernel functions. As lambdas are potential part of these `__global__`
470
88
    // function names, they needs numbering following ODR.
471
88
    MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
472
88
    assert(MCtx && "Retrieving mangle numbering context failed!");
473
88
    HasKnownInternalLinkage = true;
474
88
  }
475
7.15k
  if (MCtx) {
476
4.22k
    unsigned ManglingNumber = MCtx->getManglingNumber(Method);
477
4.22k
    Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
478
4.22k
                             HasKnownInternalLinkage);
479
4.22k
  }
480
7.15k
}
481
482
void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
483
                                        CXXMethodDecl *CallOperator,
484
                                        SourceRange IntroducerRange,
485
                                        LambdaCaptureDefault CaptureDefault,
486
                                        SourceLocation CaptureDefaultLoc,
487
                                        bool ExplicitParams,
488
                                        bool ExplicitResultType,
489
7.15k
                                        bool Mutable) {
490
7.15k
  LSI->CallOperator = CallOperator;
491
7.15k
  CXXRecordDecl *LambdaClass = CallOperator->getParent();
492
7.15k
  LSI->Lambda = LambdaClass;
493
7.15k
  if (CaptureDefault == LCD_ByCopy)
494
703
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
495
6.45k
  else if (CaptureDefault == LCD_ByRef)
496
1.79k
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
497
7.15k
  LSI->CaptureDefaultLoc = CaptureDefaultLoc;
498
7.15k
  LSI->IntroducerRange = IntroducerRange;
499
7.15k
  LSI->ExplicitParams = ExplicitParams;
500
7.15k
  LSI->Mutable = Mutable;
501
7.15k
502
7.15k
  if (ExplicitResultType) {
503
954
    LSI->ReturnType = CallOperator->getReturnType();
504
954
505
954
    if (!LSI->ReturnType->isDependentType() &&
506
954
        
!LSI->ReturnType->isVoidType()738
) {
507
474
      if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
508
474
                              diag::err_lambda_incomplete_result)) {
509
2
        // Do nothing.
510
2
      }
511
474
    }
512
6.20k
  } else {
513
6.20k
    LSI->HasImplicitReturnType = true;
514
6.20k
  }
515
7.15k
}
516
517
7.15k
void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
518
7.15k
  LSI->finishedExplicitCaptures();
519
7.15k
}
520
521
void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
522
                                                    ArrayRef<NamedDecl *> TParams,
523
67
                                                    SourceLocation RAngleLoc) {
524
67
  LambdaScopeInfo *LSI = getCurLambda();
525
67
  assert(LSI && "Expected a lambda scope");
526
67
  assert(LSI->NumExplicitTemplateParams == 0 &&
527
67
         "Already acted on explicit template parameters");
528
67
  assert(LSI->TemplateParams.empty() &&
529
67
         "Explicit template parameters should come "
530
67
         "before invented (auto) ones");
531
67
  assert(!TParams.empty() &&
532
67
         "No template parameters to act on");
533
67
  LSI->TemplateParams.append(TParams.begin(), TParams.end());
534
67
  LSI->NumExplicitTemplateParams = TParams.size();
535
67
  LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
536
67
}
537
538
void Sema::addLambdaParameters(
539
    ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
540
5.64k
    CXXMethodDecl *CallOperator, Scope *CurScope) {
541
5.64k
  // Introduce our parameters into the function scope
542
5.64k
  for (unsigned p = 0, NumParams = CallOperator->getNumParams();
543
8.24k
       p < NumParams; 
++p2.59k
) {
544
2.59k
    ParmVarDecl *Param = CallOperator->getParamDecl(p);
545
2.59k
546
2.59k
    // If this has an identifier, add it to the scope stack.
547
2.59k
    if (CurScope && Param->getIdentifier()) {
548
2.47k
      bool Error = false;
549
2.47k
      // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
550
2.47k
      // retroactively apply it.
551
2.47k
      for (const auto &Capture : Captures) {
552
307
        if (Capture.Id == Param->getIdentifier()) {
553
11
          Error = true;
554
11
          Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
555
11
          Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
556
11
              << Capture.Id << true;
557
11
        }
558
307
      }
559
2.47k
      if (!Error)
560
2.46k
        CheckShadow(CurScope, Param);
561
2.47k
562
2.47k
      PushOnScopeChains(Param, CurScope);
563
2.47k
    }
564
2.59k
  }
565
5.64k
}
566
567
/// If this expression is an enumerator-like expression of some type
568
/// T, return the type T; otherwise, return null.
569
///
570
/// Pointer comparisons on the result here should always work because
571
/// it's derived from either the parent of an EnumConstantDecl
572
/// (i.e. the definition) or the declaration returned by
573
/// EnumType::getDecl() (i.e. the definition).
574
385
static EnumDecl *findEnumForBlockReturn(Expr *E) {
575
385
  // An expression is an enumerator-like expression of type T if,
576
385
  // ignoring parens and parens-like expressions:
577
385
  E = E->IgnoreParens();
578
385
579
385
  //  - it is an enumerator whose enum type is T or
580
385
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
581
27
    if (EnumConstantDecl *D
582
27
          = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
583
27
      return cast<EnumDecl>(D->getDeclContext());
584
27
    }
585
0
    return nullptr;
586
0
  }
587
358
588
358
  //  - it is a comma expression whose RHS is an enumerator-like
589
358
  //    expression of type T or
590
358
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
591
26
    if (BO->getOpcode() == BO_Comma)
592
1
      return findEnumForBlockReturn(BO->getRHS());
593
25
    return nullptr;
594
25
  }
595
332
596
332
  //  - it is a statement-expression whose value expression is an
597
332
  //    enumerator-like expression of type T or
598
332
  if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
599
1
    if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
600
1
      return findEnumForBlockReturn(last);
601
0
    return nullptr;
602
0
  }
603
331
604
331
  //   - it is a ternary conditional operator (not the GNU ?:
605
331
  //     extension) whose second and third operands are
606
331
  //     enumerator-like expressions of type T or
607
331
  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
608
3
    if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
609
3
      if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
610
3
        return ED;
611
0
    return nullptr;
612
0
  }
613
328
614
328
  // (implicitly:)
615
328
  //   - it is an implicit integral conversion applied to an
616
328
  //     enumerator-like expression of type T or
617
328
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
618
137
    // We can sometimes see integral conversions in valid
619
137
    // enumerator-like expressions.
620
137
    if (ICE->getCastKind() == CK_IntegralCast)
621
3
      return findEnumForBlockReturn(ICE->getSubExpr());
622
325
623
325
    // Otherwise, just rely on the type.
624
325
  }
625
325
626
325
  //   - it is an expression of that formal enum type.
627
325
  if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
628
15
    return ET->getDecl();
629
15
  }
630
310
631
310
  // Otherwise, nope.
632
310
  return nullptr;
633
310
}
634
635
/// Attempt to find a type T for which the returned expression of the
636
/// given statement is an enumerator-like expression of that type.
637
465
static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
638
465
  if (Expr *retValue = ret->getRetValue())
639
374
    return findEnumForBlockReturn(retValue);
640
91
  return nullptr;
641
91
}
642
643
/// Attempt to find a common type T for which all of the returned
644
/// expressions in a block are enumerator-like expressions of that
645
/// type.
646
450
static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
647
450
  ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
648
450
649
450
  // Try to find one for the first return.
650
450
  EnumDecl *ED = findEnumForBlockReturn(*i);
651
450
  if (!ED) 
return nullptr424
;
652
26
653
26
  // Check that the rest of the returns have the same enum.
654
39
  
for (++i; 26
i != e;
++i13
) {
655
15
    if (findEnumForBlockReturn(*i) != ED)
656
2
      return nullptr;
657
15
  }
658
26
659
26
  // Never infer an anonymous enum type.
660
26
  
if (24
!ED->hasNameForLinkage()24
)
return nullptr3
;
661
21
662
21
  return ED;
663
21
}
664
665
/// Adjust the given return statements so that they formally return
666
/// the given type.  It should require, at most, an IntegralCast.
667
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
668
21
                                     QualType returnType) {
669
21
  for (ArrayRef<ReturnStmt*>::iterator
670
55
         i = returns.begin(), e = returns.end(); i != e; 
++i34
) {
671
34
    ReturnStmt *ret = *i;
672
34
    Expr *retValue = ret->getRetValue();
673
34
    if (S.Context.hasSameType(retValue->getType(), returnType))
674
14
      continue;
675
20
676
20
    // Right now we only support integral fixup casts.
677
20
    assert(returnType->isIntegralOrUnscopedEnumerationType());
678
20
    assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
679
20
680
20
    ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
681
20
682
20
    Expr *E = (cleanups ? 
cleanups->getSubExpr()0
: retValue);
683
20
    E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
684
20
                                 E, /*base path*/ nullptr, VK_RValue);
685
20
    if (cleanups) {
686
0
      cleanups->setSubExpr(E);
687
20
    } else {
688
20
      ret->setRetValue(E);
689
20
    }
690
20
  }
691
21
}
692
693
4.85k
void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
694
4.85k
  assert(CSI.HasImplicitReturnType);
695
4.85k
  // If it was ever a placeholder, it had to been deduced to DependentTy.
696
4.85k
  assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
697
4.85k
  assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
698
4.85k
         "lambda expressions use auto deduction in C++14 onwards");
699
4.85k
700
4.85k
  // C++ core issue 975:
701
4.85k
  //   If a lambda-expression does not include a trailing-return-type,
702
4.85k
  //   it is as if the trailing-return-type denotes the following type:
703
4.85k
  //     - if there are no return statements in the compound-statement,
704
4.85k
  //       or all return statements return either an expression of type
705
4.85k
  //       void or no expression or braced-init-list, the type void;
706
4.85k
  //     - otherwise, if all return statements return an expression
707
4.85k
  //       and the types of the returned expressions after
708
4.85k
  //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
709
4.85k
  //       array-to-pointer conversion (4.2 [conv.array]), and
710
4.85k
  //       function-to-pointer conversion (4.3 [conv.func]) are the
711
4.85k
  //       same, that common type;
712
4.85k
  //     - otherwise, the program is ill-formed.
713
4.85k
  //
714
4.85k
  // C++ core issue 1048 additionally removes top-level cv-qualifiers
715
4.85k
  // from the types of returned expressions to match the C++14 auto
716
4.85k
  // deduction rules.
717
4.85k
  //
718
4.85k
  // In addition, in blocks in non-C++ modes, if all of the return
719
4.85k
  // statements are enumerator-like expressions of some type T, where
720
4.85k
  // T has a name for linkage, then we infer the return type of the
721
4.85k
  // block to be that type.
722
4.85k
723
4.85k
  // First case: no return statements, implicit void return type.
724
4.85k
  ASTContext &Ctx = getASTContext();
725
4.85k
  if (CSI.Returns.empty()) {
726
3.88k
    // It's possible there were simply no /valid/ return statements.
727
3.88k
    // In this case, the first one we found may have at least given us a type.
728
3.88k
    if (CSI.ReturnType.isNull())
729
3.88k
      CSI.ReturnType = Ctx.VoidTy;
730
3.88k
    return;
731
3.88k
  }
732
971
733
971
  // Second case: at least one return statement has dependent type.
734
971
  // Delay type checking until instantiation.
735
971
  assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
736
971
  if (CSI.ReturnType->isDependentType())
737
69
    return;
738
902
739
902
  // Try to apply the enum-fuzz rule.
740
902
  if (!getLangOpts().CPlusPlus) {
741
450
    assert(isa<BlockScopeInfo>(CSI));
742
450
    const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
743
450
    if (ED) {
744
21
      CSI.ReturnType = Context.getTypeDeclType(ED);
745
21
      adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
746
21
      return;
747
21
    }
748
881
  }
749
881
750
881
  // Third case: only one return statement. Don't bother doing extra work!
751
881
  if (CSI.Returns.size() == 1)
752
831
    return;
753
50
754
50
  // General case: many return statements.
755
50
  // Check that they all have compatible return types.
756
50
757
50
  // We require the return types to strictly match here.
758
50
  // Note that we've already done the required promotions as part of
759
50
  // processing the return statement.
760
132
  
for (const ReturnStmt *RS : CSI.Returns)50
{
761
132
    const Expr *RetE = RS->getRetValue();
762
132
763
132
    QualType ReturnType =
764
132
        (RetE ? 
RetE->getType()127
:
Context.VoidTy5
).getUnqualifiedType();
765
132
    if (Context.getCanonicalFunctionResultType(ReturnType) ==
766
132
          Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
767
123
      // Use the return type with the strictest possible nullability annotation.
768
123
      auto RetTyNullability = ReturnType->getNullability(Ctx);
769
123
      auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
770
123
      if (BlockNullability &&
771
123
          
(4
!RetTyNullability4
||
772
4
           
hasWeakerNullability(*RetTyNullability, *BlockNullability)2
))
773
2
        CSI.ReturnType = ReturnType;
774
123
      continue;
775
123
    }
776
9
777
9
    // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
778
9
    // TODO: It's possible that the *first* return is the divergent one.
779
9
    Diag(RS->getBeginLoc(),
780
9
         diag::err_typecheck_missing_return_type_incompatible)
781
9
        << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
782
9
    // Continue iterating so that we keep emitting diagnostics.
783
9
  }
784
50
}
785
786
QualType Sema::buildLambdaInitCaptureInitialization(
787
    SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
788
    Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
789
496
    Expr *&Init) {
790
496
  // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
791
496
  // deduce against.
792
496
  QualType DeductType = Context.getAutoDeductType();
793
496
  TypeLocBuilder TLB;
794
496
  AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
795
496
  TL.setNameLoc(Loc);
796
496
  if (ByRef) {
797
104
    DeductType = BuildReferenceType(DeductType, true, Loc, Id);
798
104
    assert(!DeductType.isNull() && "can't build reference to auto");
799
104
    TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
800
104
  }
801
496
  if (EllipsisLoc.isValid()) {
802
57
    if (Init->containsUnexpandedParameterPack()) {
803
56
      Diag(EllipsisLoc, getLangOpts().CPlusPlus2a
804
56
                            ? 
diag::warn_cxx17_compat_init_capture_pack29
805
56
                            : 
diag::ext_init_capture_pack27
);
806
56
      DeductType = Context.getPackExpansionType(DeductType, NumExpansions);
807
56
      TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
808
56
    } else {
809
1
      // Just ignore the ellipsis for now and form a non-pack variable. We'll
810
1
      // diagnose this later when we try to capture it.
811
1
    }
812
57
  }
813
496
  TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
814
496
815
496
  // Deduce the type of the init capture.
816
496
  QualType DeducedType = deduceVarTypeFromInitializer(
817
496
      /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
818
496
      SourceRange(Loc, Loc), IsDirectInit, Init);
819
496
  if (DeducedType.isNull())
820
35
    return QualType();
821
461
822
461
  // Are we a non-list direct initialization?
823
461
  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
824
461
825
461
  // Perform initialization analysis and ensure any implicit conversions
826
461
  // (such as lvalue-to-rvalue) are enforced.
827
461
  InitializedEntity Entity =
828
461
      InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
829
461
  InitializationKind Kind =
830
461
      IsDirectInit
831
461
          ? 
(CXXDirectInit 145
? InitializationKind::CreateDirect(
832
128
                                 Loc, Init->getBeginLoc(), Init->getEndLoc())
833
145
                           : 
InitializationKind::CreateDirectList(Loc)17
)
834
461
          : 
InitializationKind::CreateCopy(Loc, Init->getBeginLoc())316
;
835
461
836
461
  MultiExprArg Args = Init;
837
461
  if (CXXDirectInit)
838
128
    Args =
839
128
        MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
840
461
  QualType DclT;
841
461
  InitializationSequence InitSeq(*this, Entity, Kind, Args);
842
461
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
843
461
844
461
  if (Result.isInvalid())
845
3
    return QualType();
846
458
847
458
  Init = Result.getAs<Expr>();
848
458
  return DeducedType;
849
458
}
850
851
VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
852
                                              QualType InitCaptureType,
853
                                              SourceLocation EllipsisLoc,
854
                                              IdentifierInfo *Id,
855
458
                                              unsigned InitStyle, Expr *Init) {
856
458
  // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
857
458
  // rather than reconstructing it here.
858
458
  TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
859
458
  if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
860
56
    PETL.setEllipsisLoc(EllipsisLoc);
861
458
862
458
  // Create a dummy variable representing the init-capture. This is not actually
863
458
  // used as a variable, and only exists as a way to name and refer to the
864
458
  // init-capture.
865
458
  // FIXME: Pass in separate source locations for '&' and identifier.
866
458
  VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
867
458
                                   Loc, Id, InitCaptureType, TSI, SC_Auto);
868
458
  NewVD->setInitCapture(true);
869
458
  NewVD->setReferenced(true);
870
458
  // FIXME: Pass in a VarDecl::InitializationStyle.
871
458
  NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
872
458
  NewVD->markUsed(Context);
873
458
  NewVD->setInit(Init);
874
458
  if (NewVD->isParameterPack())
875
56
    getCurLambda()->LocalPacks.push_back(NewVD);
876
458
  return NewVD;
877
458
}
878
879
456
void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
880
456
  assert(Var->isInitCapture() && "init capture flag should be set");
881
456
  LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
882
456
                  /*isNested*/false, Var->getLocation(), SourceLocation(),
883
456
                  Var->getType(), /*Invalid*/false);
884
456
}
885
886
void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
887
                                        Declarator &ParamInfo,
888
5.64k
                                        Scope *CurScope) {
889
5.64k
  LambdaScopeInfo *const LSI = getCurLambda();
890
5.64k
  assert(LSI && "LambdaScopeInfo should be on stack!");
891
5.64k
892
5.64k
  // Determine if we're within a context where we know that the lambda will
893
5.64k
  // be dependent, because there are template parameters in scope.
894
5.64k
  bool KnownDependent;
895
5.64k
  if (LSI->NumExplicitTemplateParams > 0) {
896
67
    auto *TemplateParamScope = CurScope->getTemplateParamParent();
897
67
    assert(TemplateParamScope &&
898
67
           "Lambda with explicit template param list should establish a "
899
67
           "template param scope");
900
67
    assert(TemplateParamScope->getParent());
901
67
    KnownDependent = TemplateParamScope->getParent()
902
67
                                       ->getTemplateParamParent() != nullptr;
903
5.57k
  } else {
904
5.57k
    KnownDependent = CurScope->getTemplateParamParent() != nullptr;
905
5.57k
  }
906
5.64k
907
5.64k
  // Determine the signature of the call operator.
908
5.64k
  TypeSourceInfo *MethodTyInfo;
909
5.64k
  bool ExplicitParams = true;
910
5.64k
  bool ExplicitResultType = true;
911
5.64k
  bool ContainsUnexpandedParameterPack = false;
912
5.64k
  SourceLocation EndLoc;
913
5.64k
  SmallVector<ParmVarDecl *, 8> Params;
914
5.64k
  if (ParamInfo.getNumTypeObjects() == 0) {
915
1.36k
    // C++11 [expr.prim.lambda]p4:
916
1.36k
    //   If a lambda-expression does not include a lambda-declarator, it is as
917
1.36k
    //   if the lambda-declarator were ().
918
1.36k
    FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
919
1.36k
        /*IsVariadic=*/false, /*IsCXXMethod=*/true));
920
1.36k
    EPI.HasTrailingReturn = true;
921
1.36k
    EPI.TypeQuals.addConst();
922
1.36k
    LangAS AS = getDefaultCXXMethodAddrSpace();
923
1.36k
    if (AS != LangAS::Default)
924
1
      EPI.TypeQuals.addAddressSpace(AS);
925
1.36k
926
1.36k
    // C++1y [expr.prim.lambda]:
927
1.36k
    //   The lambda return type is 'auto', which is replaced by the
928
1.36k
    //   trailing-return type if provided and/or deduced from 'return'
929
1.36k
    //   statements
930
1.36k
    // We don't do this before C++1y, because we don't support deduced return
931
1.36k
    // types there.
932
1.36k
    QualType DefaultTypeForNoTrailingReturn =
933
1.36k
        getLangOpts().CPlusPlus14 ? 
Context.getAutoDeductType()883
934
1.36k
                                  : 
Context.DependentTy478
;
935
1.36k
    QualType MethodTy =
936
1.36k
        Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
937
1.36k
    MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
938
1.36k
    ExplicitParams = false;
939
1.36k
    ExplicitResultType = false;
940
1.36k
    EndLoc = Intro.Range.getEnd();
941
4.28k
  } else {
942
4.28k
    assert(ParamInfo.isFunctionDeclarator() &&
943
4.28k
           "lambda-declarator is a function");
944
4.28k
    DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
945
4.28k
946
4.28k
    // C++11 [expr.prim.lambda]p5:
947
4.28k
    //   This function call operator is declared const (9.3.1) if and only if
948
4.28k
    //   the lambda-expression's parameter-declaration-clause is not followed
949
4.28k
    //   by mutable. It is neither virtual nor declared volatile. [...]
950
4.28k
    if (!FTI.hasMutableQualifier()) {
951
4.14k
      FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
952
4.14k
                                                    SourceLocation());
953
4.14k
    }
954
4.28k
955
4.28k
    MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
956
4.28k
    assert(MethodTyInfo && "no type from lambda-declarator");
957
4.28k
    EndLoc = ParamInfo.getSourceRange().getEnd();
958
4.28k
959
4.28k
    ExplicitResultType = FTI.hasTrailingReturnType();
960
4.28k
961
4.28k
    if (FTIHasNonVoidParameters(FTI)) {
962
2.20k
      Params.reserve(FTI.NumParams);
963
4.80k
      for (unsigned i = 0, e = FTI.NumParams; i != e; 
++i2.59k
)
964
2.59k
        Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
965
2.20k
    }
966
4.28k
967
4.28k
    // Check for unexpanded parameter packs in the method type.
968
4.28k
    if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
969
27
      DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
970
27
                                      UPPC_DeclarationType);
971
4.28k
  }
972
5.64k
973
5.64k
  CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
974
5.64k
                                                 KnownDependent, Intro.Default);
975
5.64k
  CXXMethodDecl *Method =
976
5.64k
      startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
977
5.64k
                            ParamInfo.getDeclSpec().getConstexprSpecifier(),
978
5.64k
                            ParamInfo.getTrailingRequiresClause());
979
5.64k
  if (ExplicitParams)
980
4.28k
    CheckCXXDefaultArguments(Method);
981
5.64k
982
5.64k
  // This represents the function body for the lambda function, check if we
983
5.64k
  // have to apply optnone due to a pragma.
984
5.64k
  AddRangeBasedOptnone(Method);
985
5.64k
986
5.64k
  // code_seg attribute on lambda apply to the method.
987
5.64k
  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
988
2
    Method->addAttr(A);
989
5.64k
990
5.64k
  // Attributes on the lambda apply to the method.
991
5.64k
  ProcessDeclAttributes(CurScope, Method, ParamInfo);
992
5.64k
993
5.64k
  // CUDA lambdas get implicit attributes based on the scope in which they're
994
5.64k
  // declared.
995
5.64k
  if (getLangOpts().CUDA)
996
92
    CUDASetLambdaAttrs(Method);
997
5.64k
998
5.64k
  // Number the lambda for linkage purposes if necessary.
999
5.64k
  handleLambdaNumbering(Class, Method);
1000
5.64k
1001
5.64k
  // Introduce the function call operator as the current declaration context.
1002
5.64k
  PushDeclContext(CurScope, Method);
1003
5.64k
1004
5.64k
  // Build the lambda scope.
1005
5.64k
  buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
1006
5.64k
                   ExplicitParams, ExplicitResultType, !Method->isConst());
1007
5.64k
1008
5.64k
  // C++11 [expr.prim.lambda]p9:
1009
5.64k
  //   A lambda-expression whose smallest enclosing scope is a block scope is a
1010
5.64k
  //   local lambda expression; any other lambda expression shall not have a
1011
5.64k
  //   capture-default or simple-capture in its lambda-introducer.
1012
5.64k
  //
1013
5.64k
  // For simple-captures, this is covered by the check below that any named
1014
5.64k
  // entity is a variable that can be captured.
1015
5.64k
  //
1016
5.64k
  // For DR1632, we also allow a capture-default in any context where we can
1017
5.64k
  // odr-use 'this' (in particular, in a default initializer for a non-static
1018
5.64k
  // data member).
1019
5.64k
  if (Intro.Default != LCD_None && 
!Class->getParent()->isFunctionOrMethod()2.16k
&&
1020
5.64k
      
(31
getCurrentThisType().isNull()31
||
1021
31
       CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
1022
23
                           /*BuildAndDiagnose*/false)))
1023
8
    Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1024
5.64k
1025
5.64k
  // Distinct capture names, for diagnostics.
1026
5.64k
  llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
1027
5.64k
1028
5.64k
  // Handle explicit captures.
1029
5.64k
  SourceLocation PrevCaptureLoc
1030
5.64k
    = Intro.Default == LCD_None? 
Intro.Range.getBegin()3.48k
:
Intro.DefaultLoc2.16k
;
1031
7.01k
  for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1032
5.64k
       
PrevCaptureLoc = C->Loc, ++C1.37k
) {
1033
1.37k
    if (C->Kind == LCK_This || 
C->Kind == LCK_StarThis1.15k
) {
1034
324
      if (C->Kind == LCK_StarThis)
1035
109
        Diag(C->Loc, !getLangOpts().CPlusPlus17
1036
109
                             ? 
diag::ext_star_this_lambda_capture_cxx172
1037
109
                             : 
diag::warn_cxx14_compat_star_this_lambda_capture107
);
1038
324
1039
324
      // C++11 [expr.prim.lambda]p8:
1040
324
      //   An identifier or this shall not appear more than once in a
1041
324
      //   lambda-capture.
1042
324
      if (LSI->isCXXThisCaptured()) {
1043
5
        Diag(C->Loc, diag::err_capture_more_than_once)
1044
5
            << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1045
5
            << FixItHint::CreateRemoval(
1046
5
                   SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1047
5
        continue;
1048
5
      }
1049
319
1050
319
      // C++2a [expr.prim.lambda]p8:
1051
319
      //  If a lambda-capture includes a capture-default that is =,
1052
319
      //  each simple-capture of that lambda-capture shall be of the form
1053
319
      //  "&identifier", "this", or "* this". [ Note: The form [&,this] is
1054
319
      //  redundant but accepted for compatibility with ISO C++14. --end note ]
1055
319
      if (Intro.Default == LCD_ByCopy && 
C->Kind != LCK_StarThis9
)
1056
5
        Diag(C->Loc, !getLangOpts().CPlusPlus2a
1057
5
                         ? 
diag::ext_equals_this_lambda_capture_cxx2a3
1058
5
                         : 
diag::warn_cxx17_compat_equals_this_lambda_capture2
);
1059
319
1060
319
      // C++11 [expr.prim.lambda]p12:
1061
319
      //   If this is captured by a local lambda expression, its nearest
1062
319
      //   enclosing function shall be a non-static member function.
1063
319
      QualType ThisCaptureType = getCurrentThisType();
1064
319
      if (ThisCaptureType.isNull()) {
1065
4
        Diag(C->Loc, diag::err_this_capture) << true;
1066
4
        continue;
1067
4
      }
1068
315
1069
315
      CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1070
315
                          /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1071
315
                          C->Kind == LCK_StarThis);
1072
315
      if (!LSI->Captures.empty())
1073
313
        LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1074
315
      continue;
1075
315
    }
1076
1.05k
1077
1.05k
    assert(C->Id && "missing identifier for capture");
1078
1.05k
1079
1.05k
    if (C->Init.isInvalid())
1080
5
      continue;
1081
1.04k
1082
1.04k
    VarDecl *Var = nullptr;
1083
1.04k
    if (C->Init.isUsable()) {
1084
365
      Diag(C->Loc, getLangOpts().CPlusPlus14
1085
365
                       ? 
diag::warn_cxx11_compat_init_capture294
1086
365
                       : 
diag::ext_init_capture71
);
1087
365
1088
365
      // If the initializer expression is usable, but the InitCaptureType
1089
365
      // is not, then an error has occurred - so ignore the capture for now.
1090
365
      // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1091
365
      // FIXME: we should create the init capture variable and mark it invalid
1092
365
      // in this case.
1093
365
      if (C->InitCaptureType.get().isNull())
1094
30
        continue;
1095
335
1096
335
      if (C->Init.get()->containsUnexpandedParameterPack() &&
1097
335
          
!C->InitCaptureType.get()->getAs<PackExpansionType>()72
)
1098
16
        DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1099
335
1100
335
      unsigned InitStyle;
1101
335
      switch (C->InitKind) {
1102
0
      case LambdaCaptureInitKind::NoInit:
1103
0
        llvm_unreachable("not an init-capture?");
1104
235
      case LambdaCaptureInitKind::CopyInit:
1105
235
        InitStyle = VarDecl::CInit;
1106
235
        break;
1107
84
      case LambdaCaptureInitKind::DirectInit:
1108
84
        InitStyle = VarDecl::CallInit;
1109
84
        break;
1110
16
      case LambdaCaptureInitKind::ListInit:
1111
16
        InitStyle = VarDecl::ListInit;
1112
16
        break;
1113
335
      }
1114
335
      Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1115
335
                                           C->EllipsisLoc, C->Id, InitStyle,
1116
335
                                           C->Init.get());
1117
335
      // C++1y [expr.prim.lambda]p11:
1118
335
      //   An init-capture behaves as if it declares and explicitly
1119
335
      //   captures a variable [...] whose declarative region is the
1120
335
      //   lambda-expression's compound-statement
1121
335
      if (Var)
1122
335
        PushOnScopeChains(Var, CurScope, false);
1123
680
    } else {
1124
680
      assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1125
680
             "init capture has valid but null init?");
1126
680
1127
680
      // C++11 [expr.prim.lambda]p8:
1128
680
      //   If a lambda-capture includes a capture-default that is &, the
1129
680
      //   identifiers in the lambda-capture shall not be preceded by &.
1130
680
      //   If a lambda-capture includes a capture-default that is =, [...]
1131
680
      //   each identifier it contains shall be preceded by &.
1132
680
      if (C->Kind == LCK_ByRef && 
Intro.Default == LCD_ByRef198
) {
1133
6
        Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1134
6
            << FixItHint::CreateRemoval(
1135
6
                SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1136
6
        continue;
1137
674
      } else if (C->Kind == LCK_ByCopy && 
Intro.Default == LCD_ByCopy482
) {
1138
1
        Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1139
1
            << FixItHint::CreateRemoval(
1140
1
                SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1141
1
        continue;
1142
1
      }
1143
673
1144
673
      // C++11 [expr.prim.lambda]p10:
1145
673
      //   The identifiers in a capture-list are looked up using the usual
1146
673
      //   rules for unqualified name lookup (3.4.1)
1147
673
      DeclarationNameInfo Name(C->Id, C->Loc);
1148
673
      LookupResult R(*this, Name, LookupOrdinaryName);
1149
673
      LookupName(R, CurScope);
1150
673
      if (R.isAmbiguous())
1151
1
        continue;
1152
672
      if (R.empty()) {
1153
1
        // FIXME: Disable corrections that would add qualification?
1154
1
        CXXScopeSpec ScopeSpec;
1155
1
        DeclFilterCCC<VarDecl> Validator{};
1156
1
        if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1157
0
          continue;
1158
672
      }
1159
672
1160
672
      Var = R.getAsSingle<VarDecl>();
1161
672
      if (Var && 
DiagnoseUseOfDecl(Var, C->Loc)666
)
1162
2
        continue;
1163
1.00k
    }
1164
1.00k
1165
1.00k
    // C++11 [expr.prim.lambda]p8:
1166
1.00k
    //   An identifier or this shall not appear more than once in a
1167
1.00k
    //   lambda-capture.
1168
1.00k
    if (!CaptureNames.insert(C->Id).second) {
1169
9
      if (Var && LSI->isCaptured(Var)) {
1170
7
        Diag(C->Loc, diag::err_capture_more_than_once)
1171
7
            << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1172
7
            << FixItHint::CreateRemoval(
1173
7
                   SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1174
7
      } else
1175
2
        // Previous capture captured something different (one or both was
1176
2
        // an init-cpature): no fixit.
1177
2
        Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1178
9
      continue;
1179
9
    }
1180
996
1181
996
    // C++11 [expr.prim.lambda]p10:
1182
996
    //   [...] each such lookup shall find a variable with automatic storage
1183
996
    //   duration declared in the reaching scope of the local lambda expression.
1184
996
    // Note that the 'reaching scope' check happens in tryCaptureVariable().
1185
996
    if (!Var) {
1186
6
      Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1187
6
      continue;
1188
6
    }
1189
990
1190
990
    // Ignore invalid decls; they'll just confuse the code later.
1191
990
    if (Var->isInvalidDecl())
1192
4
      continue;
1193
986
1194
986
    if (!Var->hasLocalStorage()) {
1195
2
      Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1196
2
      Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1197
2
      continue;
1198
2
    }
1199
984
1200
984
    // C++11 [expr.prim.lambda]p23:
1201
984
    //   A capture followed by an ellipsis is a pack expansion (14.5.3).
1202
984
    SourceLocation EllipsisLoc;
1203
984
    if (C->EllipsisLoc.isValid()) {
1204
121
      if (Var->isParameterPack()) {
1205
117
        EllipsisLoc = C->EllipsisLoc;
1206
117
      } else {
1207
4
        Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1208
4
            << (C->Init.isUsable() ? 
C->Init.get()->getSourceRange()1
1209
4
                                   : 
SourceRange(C->Loc)3
);
1210
4
1211
4
        // Just ignore the ellipsis.
1212
4
      }
1213
863
    } else if (Var->isParameterPack()) {
1214
13
      ContainsUnexpandedParameterPack = true;
1215
13
    }
1216
984
1217
984
    if (C->Init.isUsable()) {
1218
333
      addInitCapture(LSI, Var);
1219
651
    } else {
1220
651
      TryCaptureKind Kind = C->Kind == LCK_ByRef ? 
TryCapture_ExplicitByRef187
:
1221
651
                                                   
TryCapture_ExplicitByVal464
;
1222
651
      tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1223
651
    }
1224
984
    if (!LSI->Captures.empty())
1225
979
      LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1226
984
  }
1227
5.64k
  finishLambdaExplicitCaptures(LSI);
1228
5.64k
1229
5.64k
  LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1230
5.64k
1231
5.64k
  // Add lambda parameters into scope.
1232
5.64k
  addLambdaParameters(Intro.Captures, Method, CurScope);
1233
5.64k
1234
5.64k
  // Enter a new evaluation context to insulate the lambda from any
1235
5.64k
  // cleanups from the enclosing full-expression.
1236
5.64k
  PushExpressionEvaluationContext(
1237
5.64k
      LSI->CallOperator->isConsteval()
1238
5.64k
          ? 
ExpressionEvaluationContext::ConstantEvaluated4
1239
5.64k
          : 
ExpressionEvaluationContext::PotentiallyEvaluated5.64k
);
1240
5.64k
}
1241
1242
void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1243
177
                            bool IsInstantiation) {
1244
177
  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1245
177
1246
177
  // Leave the expression-evaluation context.
1247
177
  DiscardCleanupsInEvaluationContext();
1248
177
  PopExpressionEvaluationContext();
1249
177
1250
177
  // Leave the context of the lambda.
1251
177
  if (!IsInstantiation)
1252
158
    PopDeclContext();
1253
177
1254
177
  // Finalize the lambda.
1255
177
  CXXRecordDecl *Class = LSI->Lambda;
1256
177
  Class->setInvalidDecl();
1257
177
  SmallVector<Decl*, 4> Fields(Class->fields());
1258
177
  ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1259
177
              SourceLocation(), ParsedAttributesView());
1260
177
  CheckCompletedCXXClass(nullptr, Class);
1261
177
1262
177
  PopFunctionScopeInfo();
1263
177
}
1264
1265
QualType Sema::getLambdaConversionFunctionResultType(
1266
3.48k
    const FunctionProtoType *CallOpProto) {
1267
3.48k
  // The function type inside the pointer type is the same as the call
1268
3.48k
  // operator with some tweaks. The calling convention is the default free
1269
3.48k
  // function convention, and the type qualifications are lost.
1270
3.48k
  const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1271
3.48k
      CallOpProto->getExtProtoInfo();
1272
3.48k
  FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1273
3.48k
  CallingConv CC = Context.getDefaultCallingConvention(
1274
3.48k
      CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1275
3.48k
  InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1276
3.48k
  InvokerExtInfo.TypeQuals = Qualifiers();
1277
3.48k
  assert(InvokerExtInfo.RefQualifier == RQ_None &&
1278
3.48k
      "Lambda's call operator should not have a reference qualifier");
1279
3.48k
  return Context.getFunctionType(CallOpProto->getReturnType(),
1280
3.48k
                                 CallOpProto->getParamTypes(), InvokerExtInfo);
1281
3.48k
}
1282
1283
/// Add a lambda's conversion to function pointer, as described in
1284
/// C++11 [expr.prim.lambda]p6.
1285
static void addFunctionPointerConversion(Sema &S,
1286
                                         SourceRange IntroducerRange,
1287
                                         CXXRecordDecl *Class,
1288
3.19k
                                         CXXMethodDecl *CallOperator) {
1289
3.19k
  // This conversion is explicitly disabled if the lambda's function has
1290
3.19k
  // pass_object_size attributes on any of its parameters.
1291
3.19k
  auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1292
2.94k
    return P->hasAttr<PassObjectSizeAttr>();
1293
2.94k
  };
1294
3.19k
  if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1295
2
    return;
1296
3.19k
1297
3.19k
  // Add the conversion to function pointer.
1298
3.19k
  QualType InvokerFunctionTy = S.getLambdaConversionFunctionResultType(
1299
3.19k
      CallOperator->getType()->castAs<FunctionProtoType>());
1300
3.19k
  QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1301
3.19k
1302
3.19k
  // Create the type of the conversion function.
1303
3.19k
  FunctionProtoType::ExtProtoInfo ConvExtInfo(
1304
3.19k
      S.Context.getDefaultCallingConvention(
1305
3.19k
      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1306
3.19k
  // The conversion function is always const and noexcept.
1307
3.19k
  ConvExtInfo.TypeQuals = Qualifiers();
1308
3.19k
  ConvExtInfo.TypeQuals.addConst();
1309
3.19k
  ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1310
3.19k
  QualType ConvTy =
1311
3.19k
      S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1312
3.19k
1313
3.19k
  SourceLocation Loc = IntroducerRange.getBegin();
1314
3.19k
  DeclarationName ConversionName
1315
3.19k
    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1316
3.19k
        S.Context.getCanonicalType(PtrToFunctionTy));
1317
3.19k
  DeclarationNameLoc ConvNameLoc;
1318
3.19k
  // Construct a TypeSourceInfo for the conversion function, and wire
1319
3.19k
  // all the parameters appropriately for the FunctionProtoTypeLoc
1320
3.19k
  // so that everything works during transformation/instantiation of
1321
3.19k
  // generic lambdas.
1322
3.19k
  // The main reason for wiring up the parameters of the conversion
1323
3.19k
  // function with that of the call operator is so that constructs
1324
3.19k
  // like the following work:
1325
3.19k
  // auto L = [](auto b) {                <-- 1
1326
3.19k
  //   return [](auto a) -> decltype(a) { <-- 2
1327
3.19k
  //      return a;
1328
3.19k
  //   };
1329
3.19k
  // };
1330
3.19k
  // int (*fp)(int) = L(5);
1331
3.19k
  // Because the trailing return type can contain DeclRefExprs that refer
1332
3.19k
  // to the original call operator's variables, we hijack the call
1333
3.19k
  // operators ParmVarDecls below.
1334
3.19k
  TypeSourceInfo *ConvNamePtrToFunctionTSI =
1335
3.19k
      S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1336
3.19k
  ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1337
3.19k
1338
3.19k
  // The conversion function is a conversion to a pointer-to-function.
1339
3.19k
  TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1340
3.19k
  FunctionProtoTypeLoc ConvTL =
1341
3.19k
      ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1342
3.19k
  // Get the result of the conversion function which is a pointer-to-function.
1343
3.19k
  PointerTypeLoc PtrToFunctionTL =
1344
3.19k
      ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1345
3.19k
  // Do the same for the TypeSourceInfo that is used to name the conversion
1346
3.19k
  // operator.
1347
3.19k
  PointerTypeLoc ConvNamePtrToFunctionTL =
1348
3.19k
      ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1349
3.19k
1350
3.19k
  // Get the underlying function types that the conversion function will
1351
3.19k
  // be converting to (should match the type of the call operator).
1352
3.19k
  FunctionProtoTypeLoc CallOpConvTL =
1353
3.19k
      PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1354
3.19k
  FunctionProtoTypeLoc CallOpConvNameTL =
1355
3.19k
    ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1356
3.19k
1357
3.19k
  // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1358
3.19k
  // These parameter's are essentially used to transform the name and
1359
3.19k
  // the type of the conversion operator.  By using the same parameters
1360
3.19k
  // as the call operator's we don't have to fix any back references that
1361
3.19k
  // the trailing return type of the call operator's uses (such as
1362
3.19k
  // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1363
3.19k
  // - we can simply use the return type of the call operator, and
1364
3.19k
  // everything should work.
1365
3.19k
  SmallVector<ParmVarDecl *, 4> InvokerParams;
1366
6.14k
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; 
++I2.94k
) {
1367
2.94k
    ParmVarDecl *From = CallOperator->getParamDecl(I);
1368
2.94k
1369
2.94k
    InvokerParams.push_back(ParmVarDecl::Create(
1370
2.94k
        S.Context,
1371
2.94k
        // Temporarily add to the TU. This is set to the invoker below.
1372
2.94k
        S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1373
2.94k
        From->getLocation(), From->getIdentifier(), From->getType(),
1374
2.94k
        From->getTypeSourceInfo(), From->getStorageClass(),
1375
2.94k
        /*DefArg=*/nullptr));
1376
2.94k
    CallOpConvTL.setParam(I, From);
1377
2.94k
    CallOpConvNameTL.setParam(I, From);
1378
2.94k
  }
1379
3.19k
1380
3.19k
  CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1381
3.19k
      S.Context, Class, Loc,
1382
3.19k
      DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1383
3.19k
      /*isInline=*/true, ExplicitSpecifier(),
1384
3.19k
      S.getLangOpts().CPlusPlus17 ? 
CSK_constexpr650
:
CSK_unspecified2.54k
,
1385
3.19k
      CallOperator->getBody()->getEndLoc());
1386
3.19k
  Conversion->setAccess(AS_public);
1387
3.19k
  Conversion->setImplicit(true);
1388
3.19k
1389
3.19k
  if (Class->isGenericLambda()) {
1390
1.34k
    // Create a template version of the conversion operator, using the template
1391
1.34k
    // parameter list of the function call operator.
1392
1.34k
    FunctionTemplateDecl *TemplateCallOperator =
1393
1.34k
            CallOperator->getDescribedFunctionTemplate();
1394
1.34k
    FunctionTemplateDecl *ConversionTemplate =
1395
1.34k
                  FunctionTemplateDecl::Create(S.Context, Class,
1396
1.34k
                                      Loc, ConversionName,
1397
1.34k
                                      TemplateCallOperator->getTemplateParameters(),
1398
1.34k
                                      Conversion);
1399
1.34k
    ConversionTemplate->setAccess(AS_public);
1400
1.34k
    ConversionTemplate->setImplicit(true);
1401
1.34k
    Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1402
1.34k
    Class->addDecl(ConversionTemplate);
1403
1.34k
  } else
1404
1.85k
    Class->addDecl(Conversion);
1405
3.19k
  // Add a non-static member function that will be the result of
1406
3.19k
  // the conversion with a certain unique ID.
1407
3.19k
  DeclarationName InvokerName = &S.Context.Idents.get(
1408
3.19k
                                                 getLambdaStaticInvokerName());
1409
3.19k
  // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1410
3.19k
  // we should get a prebuilt TrivialTypeSourceInfo from Context
1411
3.19k
  // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1412
3.19k
  // then rewire the parameters accordingly, by hoisting up the InvokeParams
1413
3.19k
  // loop below and then use its Params to set Invoke->setParams(...) below.
1414
3.19k
  // This would avoid the 'const' qualifier of the calloperator from
1415
3.19k
  // contaminating the type of the invoker, which is currently adjusted
1416
3.19k
  // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1417
3.19k
  // trailing return type of the invoker would require a visitor to rebuild
1418
3.19k
  // the trailing return type and adjusting all back DeclRefExpr's to refer
1419
3.19k
  // to the new static invoker parameters - not the call operator's.
1420
3.19k
  CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1421
3.19k
      S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1422
3.19k
      InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1423
3.19k
      /*isInline=*/true, CSK_unspecified, CallOperator->getBody()->getEndLoc());
1424
6.14k
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; 
++I2.94k
)
1425
2.94k
    InvokerParams[I]->setOwningFunction(Invoke);
1426
3.19k
  Invoke->setParams(InvokerParams);
1427
3.19k
  Invoke->setAccess(AS_private);
1428
3.19k
  Invoke->setImplicit(true);
1429
3.19k
  if (Class->isGenericLambda()) {
1430
1.34k
    FunctionTemplateDecl *TemplateCallOperator =
1431
1.34k
            CallOperator->getDescribedFunctionTemplate();
1432
1.34k
    FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1433
1.34k
                          S.Context, Class, Loc, InvokerName,
1434
1.34k
                          TemplateCallOperator->getTemplateParameters(),
1435
1.34k
                          Invoke);
1436
1.34k
    StaticInvokerTemplate->setAccess(AS_private);
1437
1.34k
    StaticInvokerTemplate->setImplicit(true);
1438
1.34k
    Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1439
1.34k
    Class->addDecl(StaticInvokerTemplate);
1440
1.34k
  } else
1441
1.85k
    Class->addDecl(Invoke);
1442
3.19k
}
1443
1444
/// Add a lambda's conversion to block pointer.
1445
static void addBlockPointerConversion(Sema &S,
1446
                                      SourceRange IntroducerRange,
1447
                                      CXXRecordDecl *Class,
1448
159
                                      CXXMethodDecl *CallOperator) {
1449
159
  QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1450
159
      CallOperator->getType()->castAs<FunctionProtoType>());
1451
159
  QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1452
159
1453
159
  FunctionProtoType::ExtProtoInfo ConversionEPI(
1454
159
      S.Context.getDefaultCallingConvention(
1455
159
          /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1456
159
  ConversionEPI.TypeQuals = Qualifiers();
1457
159
  ConversionEPI.TypeQuals.addConst();
1458
159
  QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1459
159
1460
159
  SourceLocation Loc = IntroducerRange.getBegin();
1461
159
  DeclarationName Name
1462
159
    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1463
159
        S.Context.getCanonicalType(BlockPtrTy));
1464
159
  DeclarationNameLoc NameLoc;
1465
159
  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1466
159
  CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1467
159
      S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1468
159
      S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1469
159
      /*isInline=*/true, ExplicitSpecifier(), CSK_unspecified,
1470
159
      CallOperator->getBody()->getEndLoc());
1471
159
  Conversion->setAccess(AS_public);
1472
159
  Conversion->setImplicit(true);
1473
159
  Class->addDecl(Conversion);
1474
159
}
1475
1476
ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1477
                                  SourceLocation ImplicitCaptureLoc,
1478
324k
                                  bool IsOpenMPMapping) {
1479
324k
  // VLA captures don't have a stored initialization expression.
1480
324k
  if (Cap.isVLATypeCapture())
1481
6.68k
    return ExprResult();
1482
317k
1483
317k
  // An init-capture is initialized directly from its stored initializer.
1484
317k
  if (Cap.isInitCapture())
1485
452
    return Cap.getVariable()->getInit();
1486
316k
1487
316k
  // For anything else, build an initialization expression. For an implicit
1488
316k
  // capture, the capture notionally happens at the capture-default, so use
1489
316k
  // that location here.
1490
316k
  SourceLocation Loc =
1491
316k
      ImplicitCaptureLoc.isValid() ? 
ImplicitCaptureLoc315k
:
Cap.getLocation()1.18k
;
1492
316k
1493
316k
  // C++11 [expr.prim.lambda]p21:
1494
316k
  //   When the lambda-expression is evaluated, the entities that
1495
316k
  //   are captured by copy are used to direct-initialize each
1496
316k
  //   corresponding non-static data member of the resulting closure
1497
316k
  //   object. (For array members, the array elements are
1498
316k
  //   direct-initialized in increasing subscript order.) These
1499
316k
  //   initializations are performed in the (unspecified) order in
1500
316k
  //   which the non-static data members are declared.
1501
316k
1502
316k
  // C++ [expr.prim.lambda]p12:
1503
316k
  //   An entity captured by a lambda-expression is odr-used (3.2) in
1504
316k
  //   the scope containing the lambda-expression.
1505
316k
  ExprResult Init;
1506
316k
  IdentifierInfo *Name = nullptr;
1507
316k
  if (Cap.isThisCapture()) {
1508
9.16k
    QualType ThisTy = getCurrentThisType();
1509
9.16k
    Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1510
9.16k
    if (Cap.isCopyCapture())
1511
125
      Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1512
9.04k
    else
1513
9.04k
      Init = This;
1514
307k
  } else {
1515
307k
    assert(Cap.isVariableCapture() && "unknown kind of capture");
1516
307k
    VarDecl *Var = Cap.getVariable();
1517
307k
    Name = Var->getIdentifier();
1518
307k
    Init = BuildDeclarationNameExpr(
1519
307k
      CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1520
307k
  }
1521
316k
1522
316k
  // In OpenMP, the capture kind doesn't actually describe how to capture:
1523
316k
  // variables are "mapped" onto the device in a process that does not formally
1524
316k
  // make a copy, even for a "copy capture".
1525
316k
  if (IsOpenMPMapping)
1526
312k
    return Init;
1527
4.53k
1528
4.53k
  if (Init.isInvalid())
1529
0
    return ExprError();
1530
4.53k
1531
4.53k
  Expr *InitExpr = Init.get();
1532
4.53k
  InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1533
4.53k
      Name, Cap.getCaptureType(), Loc);
1534
4.53k
  InitializationKind InitKind =
1535
4.53k
      InitializationKind::CreateDirect(Loc, Loc, Loc);
1536
4.53k
  InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1537
4.53k
  return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1538
4.53k
}
1539
1540
ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1541
5.48k
                                 Scope *CurScope) {
1542
5.48k
  LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1543
5.48k
  ActOnFinishFunctionBody(LSI.CallOperator, Body);
1544
5.48k
  return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1545
5.48k
}
1546
1547
static LambdaCaptureDefault
1548
6.98k
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1549
6.98k
  switch (ICS) {
1550
4.48k
  case CapturingScopeInfo::ImpCap_None:
1551
4.48k
    return LCD_None;
1552
703
  case CapturingScopeInfo::ImpCap_LambdaByval:
1553
703
    return LCD_ByCopy;
1554
1.79k
  case CapturingScopeInfo::ImpCap_CapturedRegion:
1555
1.79k
  case CapturingScopeInfo::ImpCap_LambdaByref:
1556
1.79k
    return LCD_ByRef;
1557
1.79k
  case CapturingScopeInfo::ImpCap_Block:
1558
0
    llvm_unreachable("block capture in lambda");
1559
0
  }
1560
0
  llvm_unreachable("Unknown implicit capture style");
1561
0
}
1562
1563
608
bool Sema::CaptureHasSideEffects(const Capture &From) {
1564
608
  if (From.isInitCapture()) {
1565
187
    Expr *Init = From.getVariable()->getInit();
1566
187
    if (Init && Init->HasSideEffects(Context))
1567
48
      return true;
1568
560
  }
1569
560
1570
560
  if (!From.isCopyCapture())
1571
137
    return false;
1572
423
1573
423
  const QualType T = From.isThisCapture()
1574
423
                         ? 
getCurrentThisType()->getPointeeType()33
1575
423
                         : 
From.getCaptureType()390
;
1576
423
1577
423
  if (T.isVolatileQualified())
1578
2
    return true;
1579
421
1580
421
  const Type *BaseT = T->getBaseElementTypeUnsafe();
1581
421
  if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1582
81
    return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1583
81
           
!RD->hasTrivialDestructor()49
;
1584
340
1585
340
  return false;
1586
340
}
1587
1588
bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1589
608
                                       const Capture &From) {
1590
608
  if (CaptureHasSideEffects(From))
1591
85
    return false;
1592
523
1593
523
  if (From.isVLATypeCapture())
1594
11
    return false;
1595
512
1596
512
  auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1597
512
  if (From.isThisCapture())
1598
77
    diag << "'this'";
1599
435
  else
1600
435
    diag << From.getVariable();
1601
512
  diag << From.isNonODRUsed();
1602
512
  diag << FixItHint::CreateRemoval(CaptureRange);
1603
512
  return true;
1604
512
}
1605
1606
/// Create a field within the lambda class or captured statement record for the
1607
/// given capture.
1608
FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1609
324k
                                   const sema::Capture &Capture) {
1610
324k
  SourceLocation Loc = Capture.getLocation();
1611
324k
  QualType FieldType = Capture.getCaptureType();
1612
324k
1613
324k
  TypeSourceInfo *TSI = nullptr;
1614
324k
  if (Capture.isVariableCapture()) {
1615
308k
    auto *Var = Capture.getVariable();
1616
308k
    if (Var->isInitCapture())
1617
499
      TSI = Capture.getVariable()->getTypeSourceInfo();
1618
308k
  }
1619
324k
1620
324k
  // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1621
324k
  // appropriate, at least for an implicit capture.
1622
324k
  if (!TSI)
1623
323k
    TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1624
324k
1625
324k
  // Build the non-static data member.
1626
324k
  FieldDecl *Field =
1627
324k
      FieldDecl::Create(Context, RD, Loc, Loc, nullptr, FieldType, TSI, nullptr,
1628
324k
                        false, ICIS_NoInit);
1629
324k
  // If the variable being captured has an invalid type, mark the class as
1630
324k
  // invalid as well.
1631
324k
  if (!FieldType->isDependentType()) {
1632
320k
    if (RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
1633
1
      RD->setInvalidDecl();
1634
1
      Field->setInvalidDecl();
1635
320k
    } else {
1636
320k
      NamedDecl *Def;
1637
320k
      FieldType->isIncompleteType(&Def);
1638
320k
      if (Def && 
Def->isInvalidDecl()272
) {
1639
2
        RD->setInvalidDecl();
1640
2
        Field->setInvalidDecl();
1641
2
      }
1642
320k
    }
1643
320k
  }
1644
324k
  Field->setImplicit(true);
1645
324k
  Field->setAccess(AS_private);
1646
324k
  RD->addDecl(Field);
1647
324k
1648
324k
  if (Capture.isVLATypeCapture())
1649
6.68k
    Field->setCapturedVLAType(Capture.getCapturedVLAType());
1650
324k
1651
324k
  return Field;
1652
324k
}
1653
1654
ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1655
6.98k
                                 LambdaScopeInfo *LSI) {
1656
6.98k
  // Collect information from the lambda scope.
1657
6.98k
  SmallVector<LambdaCapture, 4> Captures;
1658
6.98k
  SmallVector<Expr *, 4> CaptureInits;
1659
6.98k
  SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1660
6.98k
  LambdaCaptureDefault CaptureDefault =
1661
6.98k
      mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1662
6.98k
  CXXRecordDecl *Class;
1663
6.98k
  CXXMethodDecl *CallOperator;
1664
6.98k
  SourceRange IntroducerRange;
1665
6.98k
  bool ExplicitParams;
1666
6.98k
  bool ExplicitResultType;
1667
6.98k
  CleanupInfo LambdaCleanup;
1668
6.98k
  bool ContainsUnexpandedParameterPack;
1669
6.98k
  bool IsGenericLambda;
1670
6.98k
  {
1671
6.98k
    CallOperator = LSI->CallOperator;
1672
6.98k
    Class = LSI->Lambda;
1673
6.98k
    IntroducerRange = LSI->IntroducerRange;
1674
6.98k
    ExplicitParams = LSI->ExplicitParams;
1675
6.98k
    ExplicitResultType = !LSI->HasImplicitReturnType;
1676
6.98k
    LambdaCleanup = LSI->Cleanup;
1677
6.98k
    ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1678
6.98k
    IsGenericLambda = Class->isGenericLambda();
1679
6.98k
1680
6.98k
    CallOperator->setLexicalDeclContext(Class);
1681
6.98k
    Decl *TemplateOrNonTemplateCallOperatorDecl =
1682
6.98k
        CallOperator->getDescribedFunctionTemplate()
1683
6.98k
        ? 
CallOperator->getDescribedFunctionTemplate()1.87k
1684
6.98k
        : 
cast<Decl>(CallOperator)5.10k
;
1685
6.98k
1686
6.98k
    // FIXME: Is this really the best choice? Keeping the lexical decl context
1687
6.98k
    // set as CurContext seems more faithful to the source.
1688
6.98k
    TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1689
6.98k
1690
6.98k
    PopExpressionEvaluationContext();
1691
6.98k
1692
6.98k
    // True if the current capture has a used capture or default before it.
1693
6.98k
    bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1694
6.98k
    SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1695
4.48k
        
CaptureDefaultLoc2.49k
: IntroducerRange.getBegin();
1696
6.98k
1697
11.9k
    for (unsigned I = 0, N = LSI->Captures.size(); I != N; 
++I4.93k
) {
1698
4.95k
      const Capture &From = LSI->Captures[I];
1699
4.95k
1700
4.95k
      if (From.isInvalid())
1701
21
        return ExprError();
1702
4.93k
1703
4.93k
      assert(!From.isBlockCapture() && "Cannot capture __block variables");
1704
4.93k
      bool IsImplicit = I >= LSI->NumExplicitCaptures;
1705
4.93k
      SourceLocation ImplicitCaptureLoc =
1706
4.93k
          IsImplicit ? 
CaptureDefaultLoc3.28k
:
SourceLocation()1.65k
;
1707
4.93k
1708
4.93k
      // Use source ranges of explicit captures for fixits where available.
1709
4.93k
      SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1710
4.93k
1711
4.93k
      // Warn about unused explicit captures.
1712
4.93k
      bool IsCaptureUsed = true;
1713
4.93k
      if (!CurContext->isDependentContext() && 
!IsImplicit4.46k
&&
1714
4.93k
          
!From.isODRUsed()1.28k
) {
1715
619
        // Initialized captures that are non-ODR used may not be eliminated.
1716
619
        // FIXME: Where did the IsGenericLambda here come from?
1717
619
        bool NonODRUsedInitCapture =
1718
619
            IsGenericLambda && 
From.isNonODRUsed()29
&&
From.isInitCapture()12
;
1719
619
        if (!NonODRUsedInitCapture) {
1720
608
          bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1721
608
          SourceRange FixItRange;
1722
608
          if (CaptureRange.isValid()) {
1723
480
            if (!CurHasPreviousCapture && 
!IsLast415
) {
1724
93
              // If there are no captures preceding this capture, remove the
1725
93
              // following comma.
1726
93
              FixItRange = SourceRange(CaptureRange.getBegin(),
1727
93
                                       getLocForEndOfToken(CaptureRange.getEnd()));
1728
387
            } else {
1729
387
              // Otherwise, remove the comma since the last used capture.
1730
387
              FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1731
387
                                       CaptureRange.getEnd());
1732
387
            }
1733
480
          }
1734
608
1735
608
          IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1736
608
        }
1737
619
      }
1738
4.93k
1739
4.93k
      if (CaptureRange.isValid()) {
1740
1.27k
        CurHasPreviousCapture |= IsCaptureUsed;
1741
1.27k
        PrevCaptureLoc = CaptureRange.getEnd();
1742
1.27k
      }
1743
4.93k
1744
4.93k
      // Map the capture to our AST representation.
1745
4.93k
      LambdaCapture Capture = [&] {
1746
4.93k
        if (From.isThisCapture()) {
1747
646
          // Capturing 'this' implicitly with a default of '[=]' is deprecated,
1748
646
          // because it results in a reference capture. Don't warn prior to
1749
646
          // C++2a; there's nothing that can be done about it before then.
1750
646
          if (getLangOpts().CPlusPlus2a && 
IsImplicit34
&&
1751
646
              
CaptureDefault == LCD_ByCopy22
) {
1752
20
            Diag(From.getLocation(), diag::warn_deprecated_this_capture);
1753
20
            Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1754
20
                << FixItHint::CreateInsertion(
1755
20
                       getLocForEndOfToken(CaptureDefaultLoc), ", this");
1756
20
          }
1757
646
          return LambdaCapture(From.getLocation(), IsImplicit,
1758
646
                               From.isCopyCapture() ? 
LCK_StarThis125
:
LCK_This521
);
1759
4.29k
        } else if (From.isVLATypeCapture()) {
1760
39
          return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
1761
4.25k
        } else {
1762
4.25k
          assert(From.isVariableCapture() && "unknown kind of capture");
1763
4.25k
          VarDecl *Var = From.getVariable();
1764
4.25k
          LambdaCaptureKind Kind =
1765
4.25k
              From.isCopyCapture() ? 
LCK_ByCopy1.22k
:
LCK_ByRef3.02k
;
1766
4.25k
          return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
1767
4.25k
                               From.getEllipsisLoc());
1768
4.25k
        }
1769
4.93k
      }();
1770
4.93k
1771
4.93k
      // Form the initializer for the capture field.
1772
4.93k
      ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1773
4.93k
1774
4.93k
      // FIXME: Skip this capture if the capture is not used, the initializer
1775
4.93k
      // has no side-effects, the type of the capture is trivial, and the
1776
4.93k
      // lambda is not externally visible.
1777
4.93k
1778
4.93k
      // Add a FieldDecl for the capture and form its initializer.
1779
4.93k
      BuildCaptureField(Class, From);
1780
4.93k
      Captures.push_back(Capture);
1781
4.93k
      CaptureInits.push_back(Init.get());
1782
4.93k
    }
1783
6.98k
1784
6.98k
    // C++11 [expr.prim.lambda]p6:
1785
6.98k
    //   The closure type for a lambda-expression with no lambda-capture
1786
6.98k
    //   has a public non-virtual non-explicit const conversion function
1787
6.98k
    //   to pointer to function having the same parameter and return
1788
6.98k
    //   types as the closure type's function call operator.
1789
6.98k
    
if (6.95k
Captures.empty()6.95k
&&
CaptureDefault == LCD_None3.98k
)
1790
3.19k
      addFunctionPointerConversion(*this, IntroducerRange, Class,
1791
3.19k
                                   CallOperator);
1792
6.95k
1793
6.95k
    // Objective-C++:
1794
6.95k
    //   The closure type for a lambda-expression has a public non-virtual
1795
6.95k
    //   non-explicit const conversion function to a block pointer having the
1796
6.95k
    //   same parameter and return types as the closure type's function call
1797
6.95k
    //   operator.
1798
6.95k
    // FIXME: Fix generic lambda to block conversions.
1799
6.95k
    if (getLangOpts().Blocks && 
getLangOpts().ObjC3.57k
&&
!IsGenericLambda165
)
1800
159
      addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1801
6.95k
1802
6.95k
    // Finalize the lambda class.
1803
6.95k
    SmallVector<Decl*, 4> Fields(Class->fields());
1804
6.95k
    ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1805
6.95k
                SourceLocation(), ParsedAttributesView());
1806
6.95k
    CheckCompletedCXXClass(nullptr, Class);
1807
6.95k
  }
1808
6.95k
1809
6.95k
  Cleanup.mergeFrom(LambdaCleanup);
1810
6.95k
1811
6.95k
  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1812
6.95k
                                          CaptureDefault, CaptureDefaultLoc,
1813
6.95k
                                          Captures,
1814
6.95k
                                          ExplicitParams, ExplicitResultType,
1815
6.95k
                                          CaptureInits, EndLoc,
1816
6.95k
                                          ContainsUnexpandedParameterPack);
1817
6.95k
  // If the lambda expression's call operator is not explicitly marked constexpr
1818
6.95k
  // and we are not in a dependent context, analyze the call operator to infer
1819
6.95k
  // its constexpr-ness, suppressing diagnostics while doing so.
1820
6.95k
  if (getLangOpts().CPlusPlus17 && 
!CallOperator->isInvalidDecl()1.76k
&&
1821
6.95k
      
!CallOperator->isConstexpr()1.76k
&&
1822
6.95k
      
!isa<CoroutineBodyStmt>(CallOperator->getBody())1.66k
&&
1823
6.95k
      
!Class->getDeclContext()->isDependentContext()1.66k
) {
1824
1.16k
    CallOperator->setConstexprKind(
1825
1.16k
        CheckConstexprFunctionDefinition(CallOperator,
1826
1.16k
                                         CheckConstexprKind::CheckValid)
1827
1.16k
            ? 
CSK_constexpr1.13k
1828
1.16k
            : 
CSK_unspecified33
);
1829
1.16k
  }
1830
6.95k
1831
6.95k
  // Emit delayed shadowing warnings now that the full capture list is known.
1832
6.95k
  DiagnoseShadowingLambdaDecls(LSI);
1833
6.95k
1834
6.95k
  if (!CurContext->isDependentContext()) {
1835
5.43k
    switch (ExprEvalContexts.back().Context) {
1836
0
    // C++11 [expr.prim.lambda]p2:
1837
0
    //   A lambda-expression shall not appear in an unevaluated operand
1838
0
    //   (Clause 5).
1839
122
    case ExpressionEvaluationContext::Unevaluated:
1840
122
    case ExpressionEvaluationContext::UnevaluatedList:
1841
122
    case ExpressionEvaluationContext::UnevaluatedAbstract:
1842
122
    // C++1y [expr.const]p2:
1843
122
    //   A conditional-expression e is a core constant expression unless the
1844
122
    //   evaluation of e, following the rules of the abstract machine, would
1845
122
    //   evaluate [...] a lambda-expression.
1846
122
    //
1847
122
    // This is technically incorrect, there are some constant evaluated contexts
1848
122
    // where this should be allowed.  We should probably fix this when DR1607 is
1849
122
    // ratified, it lays out the exact set of conditions where we shouldn't
1850
122
    // allow a lambda-expression.
1851
122
    case ExpressionEvaluationContext::ConstantEvaluated:
1852
122
      // We don't actually diagnose this case immediately, because we
1853
122
      // could be within a context where we might find out later that
1854
122
      // the expression is potentially evaluated (e.g., for typeid).
1855
122
      ExprEvalContexts.back().Lambdas.push_back(Lambda);
1856
122
      break;
1857
122
1858
5.31k
    case ExpressionEvaluationContext::DiscardedStatement:
1859
5.31k
    case ExpressionEvaluationContext::PotentiallyEvaluated:
1860
5.31k
    case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1861
5.31k
      break;
1862
6.95k
    }
1863
6.95k
  }
1864
6.95k
1865
6.95k
  return MaybeBindToTemporary(Lambda);
1866
6.95k
}
1867
1868
ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1869
                                               SourceLocation ConvLocation,
1870
                                               CXXConversionDecl *Conv,
1871
31
                                               Expr *Src) {
1872
31
  // Make sure that the lambda call operator is marked used.
1873
31
  CXXRecordDecl *Lambda = Conv->getParent();
1874
31
  CXXMethodDecl *CallOperator
1875
31
    = cast<CXXMethodDecl>(
1876
31
        Lambda->lookup(
1877
31
          Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1878
31
  CallOperator->setReferenced();
1879
31
  CallOperator->markUsed(Context);
1880
31
1881
31
  ExprResult Init = PerformCopyInitialization(
1882
31
      InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(),
1883
31
                                                 /*NRVO=*/false),
1884
31
      CurrentLocation, Src);
1885
31
  if (!Init.isInvalid())
1886
31
    Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
1887
31
1888
31
  if (Init.isInvalid())
1889
0
    return ExprError();
1890
31
1891
31
  // Create the new block to be returned.
1892
31
  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1893
31
1894
31
  // Set the type information.
1895
31
  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1896
31
  Block->setIsVariadic(CallOperator->isVariadic());
1897
31
  Block->setBlockMissingReturnType(false);
1898
31
1899
31
  // Add parameters.
1900
31
  SmallVector<ParmVarDecl *, 4> BlockParams;
1901
42
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; 
++I11
) {
1902
11
    ParmVarDecl *From = CallOperator->getParamDecl(I);
1903
11
    BlockParams.push_back(ParmVarDecl::Create(
1904
11
        Context, Block, From->getBeginLoc(), From->getLocation(),
1905
11
        From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
1906
11
        From->getStorageClass(),
1907
11
        /*DefArg=*/nullptr));
1908
11
  }
1909
31
  Block->setParams(BlockParams);
1910
31
1911
31
  Block->setIsConversionFromLambda(true);
1912
31
1913
31
  // Add capture. The capture uses a fake variable, which doesn't correspond
1914
31
  // to any actual memory location. However, the initializer copy-initializes
1915
31
  // the lambda object.
1916
31
  TypeSourceInfo *CapVarTSI =
1917
31
      Context.getTrivialTypeSourceInfo(Src->getType());
1918
31
  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1919
31
                                    ConvLocation, nullptr,
1920
31
                                    Src->getType(), CapVarTSI,
1921
31
                                    SC_None);
1922
31
  BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
1923
31
                             /*nested=*/false, /*copy=*/Init.get());
1924
31
  Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
1925
31
1926
31
  // Add a fake function body to the block. IR generation is responsible
1927
31
  // for filling in the actual body, which cannot be expressed as an AST.
1928
31
  Block->setBody(new (Context) CompoundStmt(ConvLocation));
1929
31
1930
31
  // Create the block literal expression.
1931
31
  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1932
31
  ExprCleanupObjects.push_back(Block);
1933
31
  Cleanup.setExprNeedsCleanups(true);
1934
31
1935
31
  return BuildBlock;
1936
31
}