# Testing GC.@preserve when doing compiler passes

**URL:** https://discourse.julialang.org/t/testing-gc-preserve-when-doing-compiler-passes/102241
**Category:** Internals & Design
**Tags:** question
**Created:** [July 29, 2023, 2:25pm UTC](https://discourse.julialang.org/t/testing-gc-preserve-when-doing-compiler-passes/102241 "2023-07-29T14:25:53Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![willtebbutt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/willtebbutt/32/6790_2.png) [@willtebbutt](https://discourse.julialang.org/u/willtebbutt)
#### Post date: [July 29, 2023, 2:25pm UTC](https://discourse.julialang.org/t/testing-gc-preserve-when-doing-compiler-passes/102241/1 "2023-07-29T14:25:53Z")

</div>

I’m looking to extend [Umlaut.jl](https://github.com/dfdx/Umlaut.jl)’s tracing to handle the `:gc_preserve_begin` and `:gc_preserve_end` statements that can be found in Julia’s IR. For example, you will find these if you use `GC.@preserve`:

```julia
foo(x) = GC.@preserve x 5x

@code_warntype foo(5.0)
MethodInstance for foo(::Float64)
  from foo(x) @ Main REPL[2]:1
Arguments
  #self#::Core.Const(foo)
  x::Float64
Body::Float64
1 ─ %1 = $(Expr(:gc_preserve_begin, :(x)))
│ %2 = (5 * x)::Float64
│ $(Expr(:gc_preserve_end, :(%1)))
└── return %2

```

I’d basically really like to know how to construct a test which reliably fails if `GC.@preserve` is not used as, if I have such a test, I can verify whether or not Umlaut is doing the right thing when it encounters a situation where `GC.@preserve` is necessary for correctness. Does anyone have any ideas?

---

<div class="post-metadata">

### Author: ![maleadt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/maleadt/32/10097_2.png) [@maleadt](https://discourse.julialang.org/u/maleadt)
#### Post date: [July 29, 2023, 4:08pm UTC](https://discourse.julialang.org/t/testing-gc-preserve-when-doing-compiler-passes/102241/2 "2023-07-29T16:08:22Z")

</div>

Something like this maybe:

```julia
mutable struct Object
    finalized::Bool
    @noinline function Object()
        finalizer(new(false)) do obj
            obj.finalized = true
        end
    end
end

function main()
    obj = Object()
    # GC.@preserve obj begin
        ptr = convert(Ptr{Bool}, Base.pointer_from_objref(obj))
        GC.gc(true)
        unsafe_load(ptr)
    # end
end

```

Seems to reliably return true resp. false depending on whether the `GC.@preserve` is used, at least on 1.9.

---

<div class="post-metadata">

### Author: ![willtebbutt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/willtebbutt/32/6790_2.png) [@willtebbutt](https://discourse.julialang.org/u/willtebbutt)
#### Post date: [July 31, 2023, 10:49am UTC](https://discourse.julialang.org/t/testing-gc-preserve-when-doing-compiler-passes/102241/3 "2023-07-31T10:49:25Z")

</div>

Thanks for the help here @maleadt – seems to be working well.
