Skip to content

Commit fa0fc98

Browse files
fix: allow disabling CSE inside certain subtrees
1 parent 0f0059a commit fa0fc98

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/code.jl

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,16 @@ end
703703

704704
@inline newsym(::Type{T}) where T = Sym{T}(gensym("cse"))
705705

706+
"""
707+
$(TYPEDSIGNATURES)
708+
709+
Return `true` if CSE should descend inside `sym`, which has operation `f` and
710+
arguments `args...`.
711+
"""
712+
function cse_inside_expr(sym, f, args...)
713+
return true
714+
end
715+
706716
"""
707717
$(SIGNATURES)
708718
@@ -727,10 +737,16 @@ function topological_sort(graph)
727737
return visited[node]
728738
end
729739
if iscall(node)
740+
op = operation(node)
741+
args = arguments(node)
742+
if !cse_inside_expr(node, op, args...)
743+
visited[node] = node
744+
return node
745+
end
730746
args = map(dfs, arguments(node))
731747
# use `term` instead of `maketerm` because we only care about the operation being performed
732748
# and not the representation. This avoids issues with `newsym` symbols not having sizes, etc.
733-
new_node = term(operation(node), args...)
749+
new_node = term(operation(node), args...; type = symtype(node))
734750
sym = newsym(symtype(new_node))
735751
push!(sorted_nodes, sym new_node)
736752
visited[node] = sym

test/code.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,17 @@ end
274274
expected = eval(toexpr(Let([x 1, y 2, z 3], sarr)))
275275
@test fn(1, 2, 3) expected
276276
end
277+
278+
function foo(args...) end
279+
280+
SymbolicUtils.Code.cse_inside_expr(sym, ::typeof(foo), args...) = false
281+
282+
@testset "`cse_inside_expr`" begin
283+
@syms x y
284+
ex1 = (x^2 + y^2)
285+
exfoo = term(foo, ex1; type = Real)
286+
ex2 = ex1 + exfoo
287+
letblock = cse(ex2)
288+
ex3 = letblock.body
289+
@test any(isequal(exfoo), arguments(ex3))
290+
end

0 commit comments

Comments
 (0)