Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use lzcnt with gcc

Tags:

c

gcc

I'm looking at some assembly code and I'm seeing tzcntl. A search for that instruction redirects to lzcnt. Are these the same instructions? Is it possible to use lzcnt with gcc?

I've seen this example: Intrinsic __lzcnt64 returns different values with different compile options

Although I'm confused about whether or not I need to use __lzcnt64 or if there is a 32 bit version.

So in summary:

  1. What's the difference between tzcntl and lzcnt, if any?
  2. How to properly use lzcnt with gcc (code, includes, and compiling)
  3. Can I select a 32 bit or 64 bit version?
like image 890
Jimbo Avatar asked Dec 13 '25 06:12

Jimbo


1 Answers

tzcnt counts trailing zeros, while lzcnt counts leading zeros.

The x86 compiler built-ins provide access to lzcnt instructions for various register widths:

unsigned short __builtin_ia32_lzcnt_u16(unsigned short);
unsigned int __builtin_ia32_lzcnt_u32(unsigned int);
unsigned long long __builtin_ia32_lzcnt_u64 (unsigned long long);

But these are only available with -mlzcnt and will give wrong results if the CPU doesn't support executing rep bsr as lzcnt.

But you can use the generic built-ins for bit counting. See the GCC documentation:

Built-in Function: int __builtin_clzll (unsigned long long)

Similar to __builtin_clz, except the argument type is unsigned long long.

like image 156
Florian Weimer Avatar answered Dec 15 '25 15:12

Florian Weimer