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