如何在Rust中使用__builtin_clzll函数?

3

GCC内置了__builtin_clzll函数,根据https://www.geeksforgeeks.org/builtin-functions-gcc-compiler/的描述:

__builtin_clz(x): This function is used to count the leading zeros of the integer. Note : clz = count leading zero’s 

我认为LLVM也有这些函数,而Rust是使用LLVM编译的。有没有办法在Rust中使用这个函数?

1个回答

9

Rust在所有内置整数类型上都有leading_zeros方法。如果编译在支持高效硬件前导零指令的CPU上,它将使用该指令:

pub fn foo(n: u32) -> u32 {
    n.leading_zeros()
}

rustc -O -C target-cpu=broadwell:

example::foo:
  lzcnt eax, edi
  ret

rustc -O --target arm-unknown-linux-gnueabihf -C target-cpu=cortex-a76

意思是使用 Rust 编译器编译 ARM 架构的 Linux 系统上的程序,优化级别为 O,目标 CPU 为 cortex-a76。
example::foo:
  clz r0, r0
  bx lr

1
这回答了“你如何做到<这个非常具体的事情>”,但更一般的答案是(某些?)内置函数(LLVM,而不是GCC,但它们在很大程度上重叠)可以通过std::intrinsics在夜间版本中使用。 - Masklinn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接