Skip to content

[6.2] Add lifetime dependencies on function types representing ~Escapable enum elements with ~Escapable payloads #82431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -8780,7 +8780,8 @@ class EnumCaseDecl final : public Decl,
/// EnumCaseDecl.
class EnumElementDecl : public DeclContext, public ValueDecl {
friend class EnumRawValuesRequest;

friend class LifetimeDependenceInfoRequest;

/// This is the type specified with the enum element, for
/// example 'Int' in 'case Y(Int)'. This is null if there is no type
/// associated with this element, as in 'case Z' or in all elements of enum
Expand All @@ -8792,6 +8793,11 @@ class EnumElementDecl : public DeclContext, public ValueDecl {
/// The raw value literal for the enum element, or null.
LiteralExpr *RawValueExpr;

protected:
struct {
unsigned NoLifetimeDependenceInfo : 1;
} LazySemanticInfo = {};

public:
EnumElementDecl(SourceLoc IdentifierLoc, DeclName Name,
ParameterList *Params,
Expand Down
3 changes: 1 addition & 2 deletions include/swift/AST/LifetimeDependence.h
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,7 @@ class LifetimeDependenceInfo {
/// Builds LifetimeDependenceInfo from a swift decl, either from the explicit
/// lifetime dependence specifiers or by inference based on types and
/// ownership modifiers.
static std::optional<ArrayRef<LifetimeDependenceInfo>>
get(AbstractFunctionDecl *decl);
static std::optional<ArrayRef<LifetimeDependenceInfo>> get(ValueDecl *decl);

/// Builds LifetimeDependenceInfo from SIL
static std::optional<llvm::ArrayRef<LifetimeDependenceInfo>>
Expand Down
5 changes: 2 additions & 3 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -5095,8 +5095,7 @@ class ImportDeclRequest
class LifetimeDependenceInfoRequest
: public SimpleRequest<
LifetimeDependenceInfoRequest,
std::optional<llvm::ArrayRef<LifetimeDependenceInfo>>(
AbstractFunctionDecl *),
std::optional<llvm::ArrayRef<LifetimeDependenceInfo>>(ValueDecl *),
RequestFlags::SeparatelyCached | RequestFlags::SplitCached> {
public:
using SimpleRequest::SimpleRequest;
Expand All @@ -5105,7 +5104,7 @@ class LifetimeDependenceInfoRequest
friend SimpleRequest;

std::optional<llvm::ArrayRef<LifetimeDependenceInfo>>
evaluate(Evaluator &evaluator, AbstractFunctionDecl *AFD) const;
evaluate(Evaluator &evaluator, ValueDecl *AFD) const;

public:
// Separate caching.
Expand Down
107 changes: 92 additions & 15 deletions lib/AST/LifetimeDependence.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ void LifetimeDependenceInfo::getConcatenatedData(
}

class LifetimeDependenceChecker {
AbstractFunctionDecl *afd;
ValueDecl *decl;

DeclContext *dc;
ASTContext &ctx;
Expand All @@ -273,9 +273,8 @@ class LifetimeDependenceChecker {
bool performedDiagnostics = false;

public:
LifetimeDependenceChecker(AbstractFunctionDecl *afd):
afd(afd), dc(afd->getDeclContext()), ctx(dc->getASTContext())
{
LifetimeDependenceChecker(AbstractFunctionDecl *afd)
: decl(afd), dc(afd->getDeclContext()), ctx(dc->getASTContext()) {
auto resultTypeRepr = afd->getResultTypeRepr();
returnLoc = resultTypeRepr ? resultTypeRepr->getLoc() : afd->getLoc();

Expand All @@ -287,18 +286,25 @@ class LifetimeDependenceChecker {
}
}

LifetimeDependenceChecker(EnumElementDecl *eed)
: decl(eed), dc(eed->getDeclContext()), ctx(dc->getASTContext()) {
auto *paramList = eed->getParameterList();
resultIndex = paramList ? eed->getParameterList()->size() + 1 : 1;
}

std::optional<llvm::ArrayRef<LifetimeDependenceInfo>>
currentDependencies() const {
if (lifetimeDependencies.empty()) {
return std::nullopt;
}
return afd->getASTContext().AllocateCopy(lifetimeDependencies);
return decl->getASTContext().AllocateCopy(lifetimeDependencies);
}

std::optional<llvm::ArrayRef<LifetimeDependenceInfo>> checkFuncDecl() {
assert(isa<FuncDecl>(afd) || isa<ConstructorDecl>(afd));
assert(isa<FuncDecl>(decl) || isa<ConstructorDecl>(decl));
assert(lifetimeDependencies.empty());

auto *afd = cast<AbstractFunctionDecl>(decl);
// Handle Builtins first because, even though Builtins require
// LifetimeDependence, we don't force the experimental feature
// to be enabled when importing the Builtin module.
Expand Down Expand Up @@ -351,6 +357,52 @@ class LifetimeDependenceChecker {
return currentDependencies();
}

std::optional<llvm::ArrayRef<LifetimeDependenceInfo>> checkEnumElementDecl() {
auto *eed = cast<EnumElementDecl>(decl);
auto *parentEnum = eed->getParentEnum();
auto enumType =
parentEnum->mapTypeIntoContext(parentEnum->getDeclaredInterfaceType());

// Add early bailout for imported enums.
if (parentEnum->hasClangNode()) {
return std::nullopt;
}

// Escapable enum, bailout.
if (!isDiagnosedNonEscapable(enumType)) {
return std::nullopt;
}
auto *params = eed->getParameterList();
// No payload, bailout.
if (!params) {
return std::nullopt;
}

auto resultIndex = params->size() + /*selfType*/ 1;
auto capacity = resultIndex + 1;
SmallBitVector inheritIndices(capacity);
SmallVector<LifetimeDependenceInfo, 1> lifetimeDependencies;

// Add all indices of ~Escapable parameters as lifetime dependence sources.
for (size_t i = 0; i < params->size(); i++) {
auto paramType = params->get(i)->getTypeInContext();
if (!isDiagnosedNonEscapable(paramType)) {
continue;
}
inheritIndices.set(i);
}
if (inheritIndices.none()) {
return std::nullopt;
}
auto lifetimeDependenceInfo = LifetimeDependenceInfo(
IndexSubset::get(eed->getASTContext(), inheritIndices), nullptr,
resultIndex,
/*isImmortal*/ false);
lifetimeDependencies.push_back(lifetimeDependenceInfo);

return eed->getASTContext().AllocateCopy(lifetimeDependencies);
}

protected:
template<typename ...ArgTypes>
InFlightDiagnostic diagnose(
Expand All @@ -367,9 +419,7 @@ class LifetimeDependenceChecker {
return ctx.Diags.diagnose(decl, Diagnostic(id, std::move(args)...));
}

bool isInit() const {
return isa<ConstructorDecl>(afd);
}
bool isInit() const { return isa<ConstructorDecl>(decl); }

// For initializers, the implicit self parameter is ignored and instead shows
// up as the result type.
Expand All @@ -381,11 +431,13 @@ class LifetimeDependenceChecker {
// the extra formal self parameter, a dependency targeting the formal result
// index would incorrectly target the SIL metatype parameter.
bool hasImplicitSelfParam() const {
auto *afd = cast<AbstractFunctionDecl>(decl);
return !isInit() && afd->hasImplicitSelfDecl();
}

// In SIL, implicit initializers and accessors become explicit.
bool isImplicitOrSIL() const {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (afd->isImplicit()) {
return true;
}
Expand All @@ -404,7 +456,7 @@ class LifetimeDependenceChecker {
bool isInterfaceFile() const {
// TODO: remove this check once all compilers that are rev-locked to the
// stdlib print the 'copy' dependence kind in the interface (Aug '25)
if (auto *sf = afd->getParentSourceFile()) {
if (auto *sf = decl->getDeclContext()->getParentSourceFile()) {
if (sf->Kind == SourceFileKind::Interface) {
return true;
}
Expand All @@ -418,6 +470,7 @@ class LifetimeDependenceChecker {
}

std::string diagnosticQualifier() const {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (afd->isImplicit()) {
if (isInit()) {
return "an implicit initializer";
Expand Down Expand Up @@ -462,6 +515,7 @@ class LifetimeDependenceChecker {
// initializers, the inout self parameter is actually considered the result
// type so is not handled here.
void diagnoseMissingSelfDependencies(DiagID diagID) {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (!hasImplicitSelfParam()) {
return;
}
Expand All @@ -482,6 +536,7 @@ class LifetimeDependenceChecker {
}

void diagnoseMissingInoutDependencies(DiagID diagID) {
auto *afd = cast<AbstractFunctionDecl>(decl);
unsigned paramIndex = 0;
for (auto *param : *afd->getParameters()) {
SWIFT_DEFER { paramIndex++; };
Expand Down Expand Up @@ -528,6 +583,7 @@ class LifetimeDependenceChecker {

bool isCompatibleWithOwnership(LifetimeDependenceKind kind, Type type,
ValueOwnership ownership) const {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (kind == LifetimeDependenceKind::Inherit) {
return true;
}
Expand Down Expand Up @@ -568,6 +624,7 @@ class LifetimeDependenceChecker {
};

TargetDeps createDeps(unsigned targetIndex) {
auto *afd = cast<AbstractFunctionDecl>(decl);
unsigned capacity = afd->hasImplicitSelfDecl()
? (afd->getParameters()->size() + 1)
: afd->getParameters()->size();
Expand Down Expand Up @@ -598,6 +655,7 @@ class LifetimeDependenceChecker {
}

Type getResultOrYield() const {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (auto *accessor = dyn_cast<AccessorDecl>(afd)) {
if (accessor->isCoroutine()) {
auto yieldTyInContext = accessor->mapTypeIntoContext(
Expand All @@ -617,11 +675,12 @@ class LifetimeDependenceChecker {

std::optional<LifetimeDependenceKind>
getDependenceKindFromDescriptor(LifetimeDescriptor descriptor,
ParamDecl *decl) {
ParamDecl *paramDecl) {
auto *afd = cast<AbstractFunctionDecl>(decl);
auto loc = descriptor.getLoc();
auto type = decl->getTypeInContext();
auto type = paramDecl->getTypeInContext();
auto parsedLifetimeKind = descriptor.getParsedLifetimeDependenceKind();
auto ownership = decl->getValueOwnership();
auto ownership = paramDecl->getValueOwnership();
auto loweredOwnership = ownership != ValueOwnership::Default
? ownership
: getLoweredOwnership(afd);
Expand Down Expand Up @@ -703,6 +762,7 @@ class LifetimeDependenceChecker {
// Finds the ParamDecl* and its index from a LifetimeDescriptor
std::optional<std::pair<ParamDecl *, unsigned>>
getParamDeclFromDescriptor(LifetimeDescriptor descriptor) {
auto *afd = cast<AbstractFunctionDecl>(decl);
switch (descriptor.getDescriptorKind()) {
case LifetimeDescriptor::DescriptorKind::Named: {
unsigned paramIndex = 0;
Expand Down Expand Up @@ -751,6 +811,7 @@ class LifetimeDependenceChecker {
}

std::optional<ArrayRef<LifetimeDependenceInfo>> checkAttribute() {
auto *afd = cast<AbstractFunctionDecl>(decl);
SmallVector<LifetimeDependenceInfo, 1> lifetimeDependencies;
llvm::SmallSet<unsigned, 1> lifetimeDependentTargets;
auto lifetimeAttrs = afd->getAttrs().getAttributes<LifetimeAttr>();
Expand All @@ -775,6 +836,7 @@ class LifetimeDependenceChecker {

std::optional<LifetimeDependenceInfo>
checkAttributeEntry(LifetimeEntry *entry) {
auto *afd = cast<AbstractFunctionDecl>(decl);
auto capacity = afd->hasImplicitSelfDecl()
? (afd->getParameters()->size() + 1)
: afd->getParameters()->size();
Expand Down Expand Up @@ -896,6 +958,7 @@ class LifetimeDependenceChecker {
/// If the current function is a mutating method and 'self' is non-Escapable,
/// return 'self's ParamDecl.
bool isMutatingNonEscapableSelf() {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (!hasImplicitSelfParam())
return false;

Expand All @@ -912,6 +975,7 @@ class LifetimeDependenceChecker {

// Infer method dependence: result depends on self. This includes _modify.
void inferNonEscapableResultOnSelf() {
auto *afd = cast<AbstractFunctionDecl>(decl);
Type selfTypeInContext = dc->getSelfTypeInContext();
if (selfTypeInContext->hasError()) {
return;
Expand Down Expand Up @@ -963,6 +1027,7 @@ class LifetimeDependenceChecker {

std::optional<LifetimeDependenceKind>
inferLifetimeDependenceKind(Type sourceType, ValueOwnership ownership) {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (!sourceType->isEscapable()) {
return LifetimeDependenceKind::Inherit;
}
Expand All @@ -985,6 +1050,7 @@ class LifetimeDependenceChecker {
// to an implicit setter, because the implementation is simply an assignment
// to stored property.
void inferImplicitInit() {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (afd->getParameters()->size() == 0) {
// Empty ~Escapable types can be implicitly initialized without any
// dependencies. In SIL, implicit initializers become explicit. Set
Expand Down Expand Up @@ -1024,6 +1090,7 @@ class LifetimeDependenceChecker {
// inference if any exist, infer scoped dependency, or infer no
// dependency. Implicit setters for Escapable properties are not inferred.
void inferNonEscapableResultOnParam() {
auto *afd = cast<AbstractFunctionDecl>(decl);
// This is only called when there is no 'self' argument that can be the
// source of a dependence.
assert(!hasImplicitSelfParam());
Expand Down Expand Up @@ -1073,6 +1140,7 @@ class LifetimeDependenceChecker {
// Lazy inference for .swiftinterface backward compatibility and
// experimentation. Inference cases can be added but not removed.
void lazillyInferNonEscapableResultOnParam() {
auto *afd = cast<AbstractFunctionDecl>(decl);
std::optional<unsigned> candidateParamIndex;
std::optional<LifetimeDependenceKind> candidateLifetimeKind;
unsigned paramIndex = 0;
Expand Down Expand Up @@ -1119,6 +1187,7 @@ class LifetimeDependenceChecker {
// Infer a mutating 'self' dependency when 'self' is non-Escapable and the
// result is 'void'.
void inferMutatingSelf() {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (!isMutatingNonEscapableSelf()) {
return;
}
Expand All @@ -1144,6 +1213,7 @@ class LifetimeDependenceChecker {

// Infer a mutating accessor's non-Escapable 'self' dependencies.
void inferMutatingAccessor(AccessorDecl *accessor) {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (!isImplicitOrSIL() && !useLazyInference()) {
// Explicit setters require explicit lifetime dependencies.
return;
Expand Down Expand Up @@ -1231,6 +1301,7 @@ class LifetimeDependenceChecker {
// Do not issue any diagnostics. This inference is triggered even when the
// feature is disabled!
void inferInoutParams() {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (isMutatingNonEscapableSelf()) {
return;
}
Expand Down Expand Up @@ -1263,6 +1334,7 @@ class LifetimeDependenceChecker {
}

void inferUnambiguousInoutParams() {
auto *afd = cast<AbstractFunctionDecl>(decl);
if (afd->getParameters()->size() != 1) {
return;
}
Expand All @@ -1280,6 +1352,7 @@ class LifetimeDependenceChecker {
}

void inferBuiltin() {
auto *afd = cast<AbstractFunctionDecl>(decl);
// Normal inout parameter inference works for most generic Builtins.
inferUnambiguousInoutParams();
if (!lifetimeDependencies.empty()) {
Expand Down Expand Up @@ -1313,8 +1386,12 @@ class LifetimeDependenceChecker {
};

std::optional<llvm::ArrayRef<LifetimeDependenceInfo>>
LifetimeDependenceInfo::get(AbstractFunctionDecl *afd) {
return LifetimeDependenceChecker(afd).checkFuncDecl();
LifetimeDependenceInfo::get(ValueDecl *decl) {
if (auto *afd = dyn_cast<AbstractFunctionDecl>(decl)) {
return LifetimeDependenceChecker(afd).checkFuncDecl();
}
auto *eed = cast<EnumElementDecl>(decl);
return LifetimeDependenceChecker(eed).checkEnumElementDecl();
}

// This implements the logic for SIL type descriptors similar to source-level
Expand Down
Loading