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