在编译时检测CPU能力并对其进行“调度”

问题描述 投票:0回答:1

是否可以编写一个根据 Julia/LLVM 编译目标使用不同算法的函数?

目标是在编译时执行此操作,并希望使该函数可内联。

只是为了一些代码,这可能看起来像:

function do_it()
    if (CPU_has_avx512) # resolved at compile. code for one branch generated
        ...
    else
        ...
    end
end
julia llvm
1个回答
0
投票

您可以创建以下宏:

using CpuId
macro cpuf(what)
    quote
        $(CpuId.cpufeature(what.value))
    end
end

这显然在编译时用固定值替换了调用:

julia> @macroexpand @cpuf(:AVX)
quote
    #= REPL[75]:3 =#
    true
end

现在我们可以调度

Val
类型:

f1(::Val{true}) = 100
f1(::Val{false}) = -100
julia> f1(Val{@cpuf(:AVX)}())
100

这一切都会按照您的意愿编译:

julia> @code_llvm f1(Val{@cpuf(:AVX)}())
;  @ REPL[89]:1 within `f1`
; Function Attrs: uwtable
define i64 @julia_f1_935() #0 {
top:
  ret i64 100
}
© www.soinside.com 2019 - 2024. All rights reserved.