Skip to content

Commit 79234c8

Browse files
authored
Merge pull request #160 from JuliaDiff/ox/globals
Don't inline accesses to nonconst globals
2 parents 02b48e0 + 4668967 commit 79234c8

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/codegen/forward_demand.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,11 @@ function forward_diff_no_inf!(ir::IRCode, to_diff::Vector{Pair{SSAValue,Int}};
254254
# TODO: Should we remember whether the callbacks wanted the arg?
255255
return transform!(ir, arg, order)
256256
elseif isa(arg, GlobalRef)
257+
if !isconst(arg)
258+
# Non-const GlabalRefs need to need to be accessed as seperate statements
259+
arg = insert_node!(ir, ssa, NewInstruction(arg, Any))
260+
end
261+
257262
return insert_node!(ir, ssa, NewInstruction(Expr(:call, ZeroBundle{order}, arg), Any))
258263
elseif isa(arg, QuoteNode)
259264
return ZeroBundle{order}(arg.value)

test/stage2_fwd.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,22 @@ module stage2_fwd
6262
f = Core.OpaqueClosure(ir2; do_compile=false)
6363
@test f(1.0) == Bar148(1.0) # This would error if we were not handling constructors (%new) right
6464
end
65+
66+
@testset "nonconst globals in forward_diff_no_inf!" begin
67+
@eval global _coeff::Float64=24.5
68+
plus_a_global(x) = x + _coeff
69+
70+
# this is needed as transform! is *always* called on Arguments regardless of what visit_custom says
71+
identity_transform!(ir, ssa::Core.SSAValue, order) = ir[ssa]
72+
function identity_transform!(ir, arg::Core.Argument, order)
73+
return Core.Compiler.insert_node!(ir, Core.SSAValue(1), Core.Compiler.NewInstruction(Expr(:call, Diffractor.ZeroBundle{1}, arg), Any))
74+
end
75+
76+
ir = first(only(Base.code_ircode(plus_a_global, Tuple{Float64})))
77+
Diffractor.forward_diff_no_inf!(ir, [Core.SSAValue(1) => 1]; transform! = identity_transform!)
78+
ir2 = Core.Compiler.compact!(ir)
79+
Core.Compiler.verify_ir(ir2) # This would error if we were not handling nonconst globals correctly
80+
f = Core.OpaqueClosure(ir2; do_compile=false)
81+
@test f(3.2) == 28.0
82+
end
6583
end

0 commit comments

Comments
 (0)