Is Possible to Know if a Variable Changed in Memory?

This question is just for curiosity, but is it possible to know if a variables changed? For example

v = [1,2,3]

changed?(v)
false

v[1]=2
changed?(v)
true

No, whether the memory backing a variable is changed is not a property that is tracked per se. Though you could define such a thing for your own type, it’s not tracked on the language level.

Further, variables/bindings to not have a defined location in memory - they may not live in memory at all, if they are elided during compilation or removed entirely due to constant folding. At most, they refer to some object - where that object is in memory is not defined. For example:

julia> function foo(x)
           a = 0
           for i in 1:x
               a += i
           end
           a
       end
foo (generic function with 1 method)

julia> @code_llvm debuginfo=:none foo(10)
define i64 @julia_foo_356(i64 signext %0) #0 {
[...] # function setup

L17.preheader:                                    ; preds = %top
  %4 = shl nuw i64 %., 1
  %5 = add nsw i64 %., -1
  %6 = zext i64 %5 to i65
  %7 = add nsw i64 %., -2
  %8 = zext i64 %7 to i65
  %9 = mul i65 %6, %8
  %10 = lshr i65 %9, 1
  %11 = trunc i65 %10 to i64
  %12 = add i64 %4, %11
  %13 = add i64 %12, -1
  br label %L32

L32:                                              ; preds = %L17.preheader, %top
  %value_phi11 = phi i64 [ 0, %top ], [ %13, %L17.preheader ]
  ret i64 %value_phi11
}

So the compiler removed the loop and put a direct computation of the result there. If we then wrap this function in another one, hardcoding the argument:

julia> g() = foo(10)
g (generic function with 1 method)

julia> @code_llvm debuginfo=:none g()
define i64 @julia_g_411() #0 {
top:
[...] # function setup 
  ret i64 55
}

We can see that it removed all of the computation and just plainly gives you the result back.

It is not possible in julia as such, but it is possible with a debugger such as gdb (with the watch command).

1 Like