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