Re: [Sbcl-commits] master: Recognize (integer-length (ldb (byte 64 0) (1- (logand n (- n))))) as ctz

Stas Boukarev <[email protected]>
Newsgroups gmane.lisp.steel-bank.devel
Message-ID <CAF63=11pDu7+f_m2-N9MY_Hj4OOjtaT64r3wwFqQXSgLWZew2w@mail.gmail.com>
Here's what it now says

The bit index is an unsigned offset from bit 0 of the source operand.
If the content of the source operand is zero, the destination operand
is unmodified.1

1: With a zero source operand on some older processors, use of a
32-bit operand size may clear the upper 32 bits of a 64-bit
destination while leaving the lower 32 bits unmodified.

And AMD says

If the second operand contains 0, the instruction sets ZF to 1 and
does not change the contents of the destination register

On Fri, Jan 9, 2026 at 8:29 PM Stas Boukarev <[email protected]> wrote:
>
> If you look at the new intel documentation they've changed that it
> does indeed not touch the original result, even going back to old cpus
> (unless maybe something from i386), except some not quite old cpus do
> touch 32-bit registers.
> clang does that as well.
>
> On Fri, Jan 9, 2026 at 8:22 PM Douglas Katzman via Sbcl-devel
> <[email protected]> wrote:
> >
> > I see what you're trying to do to support older CPUs that don't implement TZCNT, however this MOV is not technically correct.
> > If the processor treats TZCNT just like BSF, then the destination register is undefined (https://www.felixcloutier.com/x86/bsf), not unaffected when the input is 0.  So the output could be zero or random bits.  I realize that clang uses this technique, but my guess is they simply haven't gotten complaints. gcc takes the manufacturer's spec at face value, and uses a pedantically correct solution to fixup the result if the input was zero
> >  testq %rdi, %rdi
> >  movl $64, %eax
> >  cmovne %edx, %eax
> >
> >>
> >>
> >> +(define-vop ()
> >> +  (:translate count-trailing-zeros)
> >> +  (:policy :fast-safe)
> >> +  (:args (arg :scs (signed-reg unsigned-reg) :to :save))
> >> +  (:arg-types (:or signed-num unsigned-num))
> >> +  (:results (res :scs (unsigned-reg)))
> >> +  (:result-types unsigned-num)
> >> +  (:generator 5
> >> +    (inst mov res 64)
> >> +    (inst tzcnt res arg)))
> >
> > _______________________________________________
> > Sbcl-devel mailing list
> > [email protected]
> > https://lists.sourceforge.net/lists/listinfo/sbcl-devel


_______________________________________________
Sbcl-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/sbcl-devel
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.