[LLVMdev] ctpop intrinsic question

Dan Gohman gohman at apple.com
Tue Feb 19 17:14:41 PST 2008


On Feb 19, 2008, at 4:26 PM, Tobias Oberstein wrote:

> Hello,
>
> is it correct, that the "llvm.ctpop" Hamming weight intrinsic is
> currently (LLVM 2.2) implemented in
>
> Line 254 in lib/CodeGen/IntrinsicLowering.cpp
>
> /// LowerCTPOP - Emit the code to lower ctpop of V before the  
> specified
> /// instruction IP.
> static Value *LowerCTPOP(Value *V, Instruction *IP) {
>   assert(V->getType()->isInteger() && "Can't ctpop a non-integer  
> type!");
>
>
> and that the implemented algorithm is essentially the first of the 3
> given tree reduction based algorithms given in
>
> http://en.wikipedia.org/wiki/Hamming_weight??

Yes.  Most targets, unless they have target-specific ways to implement
ctpop, actually use the code in SelectionDAGLegalize::ExpandBitCount in
lib/CodeGen/SelectionDAG/LegalizeDAG.cpp to do the lowering. It
also appears to use the same algorithm as the one you reference.

>
>
> How can I emit that intrinsic from LLVMBuilder?
>

Use Intrinsic::getDeclaration (see include/llvm/Intrinsics.h)
to get a Function* for the intrinsic function, which can then be  
called like
a normal function. ctpop has one overloaded type, so you must pass
Intrinsic::getDeclaration a pointer to an array of Type* for the type  
you
want to use (eg. Int64Ty), and a count of 1.

>
> What is the correct LLVM textual IR representation? I tried
>
> ; ModuleID = 'test'
>
> define i64 @popcount(i64 %x) {
> entry:
> 	%tmp = call i64 @llvm.ctpop.i64(i64 %x)
> 	ret i64 %tmp
> }

It's necessary to include a declaration for the intrinsic, which
would look like this:

declare i64 @llvm.ctpop.i64(i64)

Dan




More information about the llvm-dev mailing list