About Julia's inline assembly usage

I tried to use @asmcall in LLVM.jl. Is there way to copy register’s value to variable in julia code?

Did you ever get an answer? I’m starting to take an interest in in-line assembly within Julia and the register conventions and figuring out where in either registers or memory variables are at when in-line assembly is called should be documented. Unfortunately, the first Google search result is your query, rather than the answer.

If in doubt, first check the tests: https://github.com/maleadt/LLVM.jl/blob/9155a8c30d6743197728e63c167d078167f34725/test/interop.jl#L87-L93

2 Likes

I may also have misread the question; if you’re asking, “where did Julia put variable x”, I don’t think there’s an easy or reliable way to figure that out.

I’d just use Base.llvmcall, e.g.

const _Vec{W,T} = NTuple{W,Core.VecElement{T}}
# requires AVX2
@generated function vfmadd231(a::_Vec{4,Float64}, b::_Vec{4,Float64}, c::_Vec{4,Float64})
    vfmadd_str = """%res = call <4 x double> asm "vfmadd231pd \$3, \$2, \$1", "=v,0,v,v"(<4 x double> %2, <4 x double> %1, <4 x double> %0)
                        ret <4 x double> %res"""
    quote
        $(Expr(:meta, :inline))
        Base.llvmcall($vfmadd_str, _Vec{4,Float64}, Tuple{_Vec{4,Float64},_Vec{4,Float64},_Vec{4,Float64}}, a, b, c)
    end
end

The call syntax returns an llvm variable, that you can then return as a Julia variable.

However, why do you need asm call?
Normally, LLVM also provides target specific intrinsic functions matching whatever you need.
So what I do is look through the appropriate llvm tests to find the instruction and calling syntax I need, and then avoid using asm.
It’s still target specific, but easier to work with.

5 Likes

For me, it is more academic than anything–teaching someone how functions are implemented in assembly. I think understanding how compilers use the stack and registers is important to understanding how computers work.

For that I think that @code_lowered, @code_typed, @code_llvm and @code_native are really amazing tools that let you see how high-level code gets translated into successively lower level forms, ending with assembly code. I’m not sure that writing inline assembly is as helpful for teaching.

4 Likes

These (and later Cthulhu) were invaluable for me.

3 Likes