Skip to content

Some small deinit-barrier related optimizations #81159

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 4 commits into from
Apr 30, 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
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ let computeSideEffects = FunctionPass(name: "compute-side-effects") {

// Finally replace the function's side effects.
context.modifyEffects(in: function) { (effects: inout FunctionEffects) in
effects.sideEffects = SideEffects(arguments: collectedEffects.argumentEffects, global: collectedEffects.globalEffects)
let globalEffects = function.isProgramTerminationPoint ?
collectedEffects.globalEffects.forProgramTerminationPoints
: collectedEffects.globalEffects
effects.sideEffects = SideEffects(arguments: collectedEffects.argumentEffects, global: globalEffects)
}
}

Expand Down
19 changes: 13 additions & 6 deletions SwiftCompilerSources/Sources/SIL/Effects.swift
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,7 @@ extension Function {
break
}
if isProgramTerminationPoint {
// We can ignore any memory writes in a program termination point, because it's not relevant
// for the caller. But we need to consider memory reads, otherwise preceding memory writes
// would be eliminated by dead-store-elimination in the caller. E.g. String initialization
// for error strings which are printed by the program termination point.
// Regarding ownership: a program termination point must not touch any reference counted objects.
return SideEffects.GlobalEffects(memory: SideEffects.Memory(read: true))
return SideEffects.GlobalEffects.worstEffects.forProgramTerminationPoints
}
var result = SideEffects.GlobalEffects.worstEffects
switch effectAttribute {
Expand Down Expand Up @@ -568,6 +563,18 @@ public struct SideEffects : CustomStringConvertible, NoReflectionChildren {
return result
}

/// Effects with all effects removed which are not relevant for program termination points (like `fatalError`).
public var forProgramTerminationPoints: GlobalEffects {
// We can ignore any memory writes in a program termination point, because it's not relevant
// for the caller. But we need to consider memory reads, otherwise preceding memory writes
// would be eliminated by dead-store-elimination in the caller. E.g. String initialization
// for error strings which are printed by the program termination point.
// Regarding ownership: a program termination point must not touch any reference counted objects.
// Also, the deinit-barrier effect is not relevant because functions like `fatalError` and `exit` are
// not accessing objects (except strings).
return GlobalEffects(memory: Memory(read: memory.read))
}

public static var worstEffects: GlobalEffects {
GlobalEffects(memory: .worstEffects, ownership: .worstEffects, allocates: true, isDeinitBarrier: true)
}
Expand Down
4 changes: 4 additions & 0 deletions SwiftCompilerSources/Sources/SIL/Function.swift
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,10 @@ extension Function {
atIndex: calleeArgIdx,
withConvention: convention)
return effects.memory.read
},
// isDeinitBarrier
{ (f: BridgedFunction) -> Bool in
return f.function.getSideEffects().isDeinitBarrier
}
)
}
Expand Down
4 changes: 3 additions & 1 deletion include/swift/SIL/SILBridging.h
Original file line number Diff line number Diff line change
Expand Up @@ -549,14 +549,16 @@ struct BridgedFunction {
typedef EffectInfo (* _Nonnull GetEffectInfoFn)(BridgedFunction, SwiftInt);
typedef BridgedMemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool);
typedef bool (* _Nonnull ArgumentMayReadFn)(BridgedFunction, BridgedOperand, BridgedValue);
typedef bool (* _Nonnull IsDeinitBarrierFn)(BridgedFunction);

static void registerBridging(SwiftMetatype metatype,
RegisterFn initFn, RegisterFn destroyFn,
WriteFn writeFn, ParseFn parseFn,
CopyEffectsFn copyEffectsFn,
GetEffectInfoFn effectInfoFn,
GetMemBehaviorFn memBehaviorFn,
ArgumentMayReadFn argumentMayReadFn);
ArgumentMayReadFn argumentMayReadFn,
IsDeinitBarrierFn isDeinitBarrierFn);
};

struct OptionalBridgedFunction {
Expand Down
2 changes: 2 additions & 0 deletions include/swift/SIL/SILFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -1218,6 +1218,8 @@ class SILFunction
// Used by the MemoryLifetimeVerifier
bool argumentMayRead(Operand *argOp, SILValue addr);

bool isDeinitBarrier();

Purpose getSpecialPurpose() const { return specialPurpose; }

/// Get this function's global_init attribute.
Expand Down
12 changes: 11 additions & 1 deletion lib/SIL/IR/SILFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ static BridgedFunction::CopyEffectsFn copyEffectsFunction = nullptr;
static BridgedFunction::GetEffectInfoFn getEffectInfoFunction = nullptr;
static BridgedFunction::GetMemBehaviorFn getMemBehvaiorFunction = nullptr;
static BridgedFunction::ArgumentMayReadFn argumentMayReadFunction = nullptr;
static BridgedFunction::IsDeinitBarrierFn isDeinitBarrierFunction = nullptr;

SILFunction::SILFunction(
SILModule &Module, SILLinkage Linkage, StringRef Name,
Expand Down Expand Up @@ -1175,7 +1176,8 @@ void BridgedFunction::registerBridging(SwiftMetatype metatype,
CopyEffectsFn copyEffectsFn,
GetEffectInfoFn effectInfoFn,
GetMemBehaviorFn memBehaviorFn,
ArgumentMayReadFn argumentMayReadFn) {
ArgumentMayReadFn argumentMayReadFn,
IsDeinitBarrierFn isDeinitBarrierFn) {
functionMetatype = metatype;
initFunction = initFn;
destroyFunction = destroyFn;
Expand All @@ -1185,6 +1187,7 @@ void BridgedFunction::registerBridging(SwiftMetatype metatype,
getEffectInfoFunction = effectInfoFn;
getMemBehvaiorFunction = memBehaviorFn;
argumentMayReadFunction = argumentMayReadFn;
isDeinitBarrierFunction = isDeinitBarrierFn;
}

std::pair<const char *, int> SILFunction::
Expand Down Expand Up @@ -1286,6 +1289,13 @@ bool SILFunction::argumentMayRead(Operand *argOp, SILValue addr) {
return argumentMayReadFunction({this}, {argOp}, {addr});
}

bool SILFunction::isDeinitBarrier() {
if (!isDeinitBarrierFunction)
return true;

return isDeinitBarrierFunction({this});
}

SourceFile *SILFunction::getSourceFile() const {
auto declRef = getDeclRef();
if (!declRef)
Expand Down
3 changes: 3 additions & 0 deletions lib/SILOptimizer/Utils/SILInliner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,9 @@ void SILInlineCloner::cloneInline(ArrayRef<SILValue> AppliedArgs) {
if (!enableLexicalLifetimes)
continue;

if (!Original.isDeinitBarrier())
continue;

// Exclusive mutating accesses don't entail a lexical scope.
if (paramInfo.getConvention() == ParameterConvention::Indirect_Inout)
continue;
Expand Down
12 changes: 10 additions & 2 deletions lib/Serialization/SerializeSIL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -529,8 +529,16 @@ void SILSerializer::writeSILFunction(const SILFunction &F, bool DeclOnly) {

unsigned numAttrs = NoBody ? 0 : F.getSpecializeAttrs().size();
auto resilience = F.getModule().getSwiftModule()->getResilienceStrategy();
bool serializeDerivedEffects = (resilience != ResilienceStrategy::Resilient) &&
!F.hasSemanticsAttr("optimize.no.crossmodule");
bool serializeDerivedEffects =
// We must not serialize computed effects if library evolution is turned on,
// because the copy of the function, which is emitted into the current module,
// might have different effects in different versions of the library.
(resilience != ResilienceStrategy::Resilient ||
// But we can serialize computed effects for @alwaysEmitIntoClient functions,
// even when library evolution is enabled, because no copy of the function is
// emitted in the original module.
F.getLinkage() == SILLinkage::PublicNonABI) &&
!F.hasSemanticsAttr("optimize.no.crossmodule");

F.visitArgEffects(
[&](int effectIdx, int argumentIndex, bool isDerived) {
Expand Down
31 changes: 31 additions & 0 deletions test/SIL/Serialization/effects.sil
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -module-name=NonLE -emit-module -o %t/NonLE.swiftmodule
// RUN: %target-swift-frontend %s -module-name=LE -enable-library-evolution -emit-module -o %t/LE.swiftmodule
// RUN: %target-sil-opt %t/NonLE.swiftmodule | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-NONLE
// RUN: %target-sil-opt %t/LE.swiftmodule | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-LE

sil_stage canonical

import Swift
import Builtin

// CHECK-LABEL: sil [serialized] [canonical] [ossa] @public_func :
// CHECK-NONLE-NEXT: [global: ]
// CHECK-NEXT: bb0:
sil [serialized] [ossa] @public_func : $@convention(thin) () -> () {
[global: ]
bb0:
%r = tuple ()
return %r
}

// CHECK-LABEL: sil non_abi [serialized] [canonical] [ossa] @public_non_abi_func :
// CHECK-NEXT: [global: ]
// CHECK-NEXT: bb0:
sil non_abi [serialized] [ossa] @public_non_abi_func : $@convention(thin) () -> () {
[global: ]
bb0:
%r = tuple ()
return %r
}

35 changes: 35 additions & 0 deletions test/SILOptimizer/mandatory_inlining_ownership.sil
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,41 @@ bb3:
return %9999 : $()
}

sil [transparent] [ossa] @deinit_barrier : $@convention(thin) (@in_guaranteed Int) -> () {
[global: deinit_barrier]
bb0(%0 : $*Int):
%1 = tuple ()
return %1
}

sil [transparent] [ossa] @no_deinit_barrier : $@convention(thin) (@in_guaranteed Int) -> () {
[global: ]
bb0(%0 : $*Int):
%1 = tuple ()
return %1
}

// CHECK-LABEL: sil [ossa] @inline_deinit_barrier :
// CHECK: alloc_stack [lexical] $Int
// CHECK: alloc_stack $Int
// CHECK: } // end sil function 'inline_deinit_barrier'
sil [ossa] @inline_deinit_barrier : $@convention(thin) (Int) -> () {
bb0(%0 : $Int):
%1 = alloc_stack $Int
store %0 to [trivial] %1
%2 = function_ref @deinit_barrier : $@convention(thin) (@in_guaranteed Int) -> ()
apply %2(%1) : $@convention(thin) (@in_guaranteed Int) -> ()
dealloc_stack %1

%10 = alloc_stack $Int
store %0 to [trivial] %10
%12 = function_ref @no_deinit_barrier : $@convention(thin) (@in_guaranteed Int) -> ()
apply %12(%10) : $@convention(thin) (@in_guaranteed Int) -> ()
dealloc_stack %10

%r = tuple ()
return %r
}

sil_vtable C2 {
#C2.i!modify: (C2) -> () -> () : @devirt_callee
Expand Down
24 changes: 24 additions & 0 deletions test/SILOptimizer/side_effects.sil
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,13 @@ bb0(%0 : $*X):
return %r : $()
}

sil [_semantics "programtermination_point"] @exitfunc_defined : $@convention(thin) () -> Never {
bb0:
%u = function_ref @unknown_func : $@convention(thin) () -> ()
%a = apply %u() : $@convention(thin) () -> ()
unreachable
}

// CHECK-LABEL: sil @call_noreturn
// CHECK-NEXT: [global: read]
// CHECK-NEXT: {{^[^[]}}
Expand All @@ -697,6 +704,23 @@ bb2:
return %r : $()
}

// CHECK-LABEL: sil @call_defined_noreturn
// CHECK-NEXT: [global: read]
// CHECK-NEXT: {{^[^[]}}
sil @call_defined_noreturn : $@convention(thin) () -> () {
bb0:
cond_br undef, bb1, bb2

bb1:
%u = function_ref @exitfunc_defined : $@convention(thin) () -> Never
%a = apply %u() : $@convention(thin) () -> Never
unreachable

bb2:
%r = tuple ()
return %r : $()
}

// CHECK-LABEL: sil @call_readnone
// CHECK-NEXT: [global: copy,deinit_barrier]
// CHECK-NEXT: {{^[^[]}}
Expand Down