LLVM - 计算整数位数的最快方法

LLVM - fastest way to count how many bits of an integer are on

我有一个类型为 i256 的寄存器 %v1

我想知道有多少位等于1。

例如,如果 %v1 等于 110....001,我希望结果为 3

有没有快速实现的方法?

LLVM 对此有一个内在函数,称为 ctpop(count population 的缩写。)

Syntax:

This is an overloaded intrinsic. You can use llvm.ctpop on any integer bit width, or on any vector with integer elements. Not all targets support all bit widths or vector types, however.

declare i8 @llvm.ctpop.i8(i8  <src>)
declare i16 @llvm.ctpop.i16(i16 <src>)
declare i32 @llvm.ctpop.i32(i32 <src>)
declare i64 @llvm.ctpop.i64(i64 <src>)
declare i256 @llvm.ctpop.i256(i256 <src>)
declare <2 x i32> @llvm.ctlz.v2i32(<2 x i32> <src>, i1 <is_zero_undef>)

Overview:

The ‘llvm.ctpop’ family of intrinsics counts the number of bits set in a value.

Arguments:

The only argument is the value to be counted. The argument may be of any integer type, or a vector with integer elements. The return type must match the argument type.

Semantics:

The ‘llvm.ctpop’ intrinsic counts the 1’s in a variable, or within each element of a vector.

我相信像下面这样的东西应该有效。

declare i256 @llvm.ctpop.i256(i256)

%popcount = call i256 @llvm.ctpop.i256(i256 %v1)