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