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