Comparing Julia functions

Is there a way to view the lower level code of a Julia function? I want to confirm whether the two functions are equivalent. For example:

function modify1(a,b)
    return a+b
end

function modify2(a,b)
    return (a+b)*(a-b)
end

function modify3(a,b)
    return modify1(a,b)*(a-b)
end

Now, I know modify2 and modify3 are equivalent; however, I want to see the lower-level code to make sure that is indeed the case (I have more complex functions that I want to compare). Is there a way to do so with or without looking at the lower-level code except by testing the functions for different input values?

You can use @code_lowered to inspect the lowered code of a function, for example:

julia> @code_lowered modify1(1, 2)
CodeInfo(
1 ─ %1 = a + b
└──      return %1
)

julia> @code_lowered modify2(1, 2)
CodeInfo(
1 ─ %1 = a + b
β”‚   %2 = a - b
β”‚   %3 = %1 * %2
└──      return %3
)

julia> @code_lowered modify3(1, 2)
CodeInfo(
1 ─ %1 = Main.modify1(a, b)
β”‚   %2 = a - b
β”‚   %3 = %1 * %2
└──      return %3
)

You can also use @code_native to inspect the actual assembly instructions:

julia> @code_native debuginfo=:none modify1(1, 2)
        .text
        pushq   %rbp
        movq    %rsp, %rbp
        leaq    (%rcx,%rdx), %rax
        popq    %rbp
        retq
        nopw    (%rax,%rax)

julia> @code_native debuginfo=:none modify2(1, 2)
        .text
        pushq   %rbp
        movq    %rsp, %rbp
        leaq    (%rdx,%rcx), %rax
        subq    %rdx, %rcx
        imulq   %rcx, %rax
        popq    %rbp
        retq
        nopw    %cs:(%rax,%rax)

julia> @code_native debuginfo=:none modify3(1, 2)
        .text
        pushq   %rbp
        movq    %rsp, %rbp
        leaq    (%rdx,%rcx), %rax
        subq    %rdx, %rcx
        imulq   %rcx, %rax
        popq    %rbp
        retq
        nopw    %cs:(%rax,%rax)
4 Likes

That’s helpful. Thanks!