From 597cec358f5b95e4e075751f5ba0978350d1b5d7 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:21:49 +0100 Subject: [PATCH] CLZ, CTZ and POPCOUNT: counts of bits, as report 2026-10.36 has them The built-ins CLZ(x), CTZ(x) and POPCOUNT(x): Sym enters them, Parse's builtin reads them, and Item's countBits checks x (an unsigned integer type, or a set for POPCOUNT; an untyped constant is refused, with help to give it a type), folds a constant by countOf, in a constant too, or has Gen count the bits. The result is an INT. The code keeps to the baseline x86-64, which has no lzcnt, tzcnt or popcnt, and the compiler doesn't ask which machine it is on. Gen.countZeros makes CLZ by bsr and CTZ by bsf, through X64.bitScan, on all 64 bits, since a narrow value's bits above its width are zero; 0, which neither finds a one in and says so by ZF, counts the width: bsr r, r; jnz L; mov r, -1; L: neg r; add r, w - 1 (CLZ) bsf r, r; jnz L; mov r, w; L: (CTZ) Gen.popCount sums the ones as Bytes.count does, with no loop: each two bits, then four, then each byte, in rax and rdx, and a multiply by 0101...H adds the eight bytes into the top one, shifted down by 56. Tests: conform/run/Count (each unsigned type at 0, 1, its top bit, all ones and a mixed value; constants; a U32 wrapped to 0; counts beside other values on the stack; sets); conform/err ClzUntyped, CtzSigned, PopcountReal and ClzSet, their messages in test/msg. compiler.md, the editors' built-in lists and CLAUDE.md's readings say so. Code lines 11,902 -> 11,997. --- diff --git a/CLAUDE.md b/CLAUDE.md index aac4ab9..ed138aa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -343,3 +343,10 @@ `MAX(U64)` and `MAX(UINT)`, above `high(I64)`, keep their type, as a hex literal above it is a `U64`. A `T` not an integer type is an error; `MAX(x)` of a variable is "x isn't a type". +- `CLZ(x)`, `CTZ(x)` and `POPCOUNT(x)` (report 2026-10.36) give an + `INT`, a constant of one when `x` is. They use only baseline x86-64, + no `lzcnt`, `tzcnt` or `popcnt`: `bsr` or `bsf` on all 64 bits (a + narrow value's upper ones are zero), with `jnz` past setting the + count of 0 to the width; `POPCOUNT` by `Bytes.count`'s sums of two, + four and eight bits and a multiply by `0101...H`, in rax and rdx. A + set's `POPCOUNT` counts its bits the same way. diff --git a/conform/err/ClzSet.raz b/conform/err/ClzSet.raz new file mode 100644 index 0000000..bc3a722 --- /dev/null +++ b/conform/err/ClzSet.raz @@ -0,0 +1,9 @@ +module ClzSet; +type Day = (mon, tue); + Days = set of Day; +proc main*; +var n: INT; s: Days; +begin + n := CLZ(s); +end; +end ClzSet. diff --git a/conform/err/ClzUntyped.raz b/conform/err/ClzUntyped.raz new file mode 100644 index 0000000..2df42d1 --- /dev/null +++ b/conform/err/ClzUntyped.raz @@ -0,0 +1,7 @@ +module ClzUntyped; +proc main*; +var n: INT; +begin + n := CLZ(1); +end; +end ClzUntyped. diff --git a/conform/err/CtzSigned.raz b/conform/err/CtzSigned.raz new file mode 100644 index 0000000..ef5268a --- /dev/null +++ b/conform/err/CtzSigned.raz @@ -0,0 +1,7 @@ +module CtzSigned; +proc main*; +var n: INT; x: I32; +begin + n := CTZ(x); +end; +end CtzSigned. diff --git a/conform/err/PopcountReal.raz b/conform/err/PopcountReal.raz new file mode 100644 index 0000000..2bcae4e --- /dev/null +++ b/conform/err/PopcountReal.raz @@ -0,0 +1,3 @@ +module PopcountReal; +const N = POPCOUNT(1.5); +end PopcountReal. diff --git a/conform/run/Count.expect b/conform/run/Count.expect new file mode 100644 index 0000000..c00cb13 --- /dev/null +++ b/conform/run/Count.expect @@ -0,0 +1,31 @@ +8 8 0 +7 0 1 +0 7 1 +0 0 8 +2 3 2 +16 16 0 +15 0 1 +0 15 1 +0 0 16 +4 8 4 +32 32 0 +31 0 1 +0 31 1 +0 0 32 +15 8 2 +64 64 0 +63 0 1 +0 63 1 +0 0 64 +0 4 8 +64 64 0 +63 0 1 +0 63 1 +0 0 64 +21 41 2 +63 3 8 +3 40 64 +15 8 0 +32 32 0 +1980 +4 3 0 diff --git a/conform/run/Count.raz b/conform/run/Count.raz new file mode 100644 index 0000000..d57f062 --- /dev/null +++ b/conform/run/Count.raz @@ -0,0 +1,73 @@ +(* CLZ(x), CTZ(x) and POPCOUNT(x) count the bits of x (report section + 6.1): of each unsigned type, at its own width, with 0 counting the + whole width; of variables, of a value an operator wrapped, beside + other values, and of constants, in a constant too; and POPCOUNT of a + set. Each line is CLZ, CTZ and POPCOUNT of one value. *) +module Count; +import Out; + +type + Day = (mon, tue, wed, thu, fri, sat, sun); + Days = set of Day; + +const + Top = CLZ(U64(1)); (* 63 *) + Low = CTZ(U16(8)); (* 3 *) + Ones = POPCOUNT(U32(0F0F0H)); (* 8 *) + Week = POPCOUNT({mon, wed, sun}); (* 3 *) + None = CLZ(U8(0)) + CTZ(U32(0)); (* 8 + 32 *) + +proc show(a, b, c: INT); +begin + Out.int(a); Out.str(" "); Out.int(b); Out.str(" "); Out.int(c); Out.ln; +end; + +proc u8(x: U8); +begin + show(CLZ(x), CTZ(x), POPCOUNT(x)); +end; + +proc u16(x: U16); +begin + show(CLZ(x), CTZ(x), POPCOUNT(x)); +end; + +proc u32(x: U32); +begin + show(CLZ(x), CTZ(x), POPCOUNT(x)); +end; + +proc u64(x: U64); +begin + show(CLZ(x), CTZ(x), POPCOUNT(x)); +end; + +proc uint(x: UINT); +begin + show(CLZ(x), CTZ(x), POPCOUNT(x)); +end; + +proc main*; +var c: U32; d: U64; n: INT; s, none: Days; +begin + u8(0); u8(1); u8(80H); u8(0FFH); u8(28H); + u16(0); u16(1); u16(8000H); u16(0FFFFH); u16(0F00H); + u32(0); u32(1); u32(80000000H); u32(0FFFFFFFFH); u32(10100H); + u64(0); u64(1); u64(8000000000000000H); u64(0FFFFFFFFFFFFFFFFH); u64(0F0000000000000F0H); + uint(0); uint(1); uint(UINT(1) shl 63); uint(UINT(0FFFFFFFFFFFFFFFFH)); uint(UINT(6) shl 40); + (* constants *) + show(Top, Low, Ones); + show(Week, None, POPCOUNT(U64(0FFFFFFFFFFFFFFFFH))); + show(CLZ(U16(1)), CTZ(U8(0)), POPCOUNT(U8(0))); + (* a U32 that wrapped to 0 is 0, whatever the machine held above it *) + c := 80000000H; + show(CLZ(c + c), CTZ(c + c), POPCOUNT(c + c)); + (* beside other values on the stack *) + d := 0F0H; + n := 1000 + CLZ(d) * 10 + CTZ(d) * 100 + POPCOUNT(d) * (POPCOUNT(d) + 1); + Out.int(n); Out.ln; + s := {tue, thu, sat, sun}; + show(POPCOUNT(s), POPCOUNT(s - {sun}), POPCOUNT(none)); +end; + +end Count. diff --git a/doc/compiler.md b/doc/compiler.md index 54a336c..1941b27 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -18,12 +18,12 @@ |---|---|---|---| | `src/Diag.raz` | 422 | 324 | Messages: positions, source excerpts, colour, counts | | `src/Scan.raz` | 1,169 | 965 | Symbols, literals, comments, positions | -| `src/Sym.raz` | 718 | 576 | Types, objects, scopes, layout | +| `src/Sym.raz` | 721 | 579 | Types, objects, scopes, layout | | `src/Chunk.raz` | 363 | 279 | The compiled program: chunks, fixups, line notes | -| `src/X64.raz` | 1,584 | 1,304 | The instruction encoder, jumps within a procedure, the assembler | -| `src/Gen.raz` | 2,592 | 1,843 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/Item.raz` | 2,244 | 1,800 | Items: types, constants, variables, operators, conversions, calls | -| `src/Parse.raz` | 4,400 | 3,800 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/X64.raz` | 1,605 | 1,318 | The instruction encoder, jumps within a procedure, the assembler | +| `src/Gen.raz` | 2,666 | 1,885 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/Item.raz` | 2,293 | 1,841 | Items: types, constants, variables, operators, conversions, calls | +| `src/Parse.raz` | 4,403 | 3,803 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/Link.raz` | 407 | 315 | Tree shaking, layout, patching, the places | | `src/Elf.raz` | 449 | 355 | Static and dynamic ELF, symbol table, line numbers | | `src/Raz.raz` | 418 | 333 | The command line | @@ -1156,6 +1156,32 @@ x86 takes it modulo 32, or 64, and a byte's or a word's rotation then goes round modulo 8 or 16 itself, the count modulo the width. +The counts of bits, `CLZ`, `CTZ` and `POPCOUNT`, are made with what +every x86-64 has, as `lzcnt`, `tzcnt` and `popcnt` came later and the +compiler doesn't ask which machine it is on. As a narrow integer's +bits above its width are zero, all of them count in 64 bits. +`countZeros` makes `CLZ` from `bsr`, the place of the highest one bit, +and `CTZ` from `bsf`, the place of the lowest; neither has a place to +give for 0, which they say by the zero flag, and 0 counts the whole +width. For a `U32`: + + CLZ(x) CTZ(x) + bsr r, r bsf r, r + jnz L jnz L + mov r, -1 mov r, 32 + L: neg r L: + add r, 31 + +`popCount` adds up the ones as `lib/Bytes.raz`'s `count` does, with +no loop: each two bits become the number of their ones, then each +four, then each byte, and a multiplication by `0101...H` adds the +eight bytes into the top one, in rax and rdx beside `x`'s register: + + mov rax, r; shr rax, 1; mov rdx, 5555...H; and rax, rdx; sub r, rax + mov rax, r; shr rax, 2; mov rdx, 3333...H; and rax, rdx; and r, rdx; add r, rax + mov rax, r; shr rax, 4; add r, rax; mov rdx, 0F0F...H; and r, rdx + mov rdx, 0101...H; imul r, rdx; shr r, 56 + Checks: `check` jumps, when the check fails, to code at the end of the procedure (`endFails`), so that a check that holds is a jump not taken. That code puts the values involved where `Rt.fail` wants them and calls @@ -1644,6 +1670,13 @@ but for `MAX(U64)` and `MAX(UINT)`, which are above `high(I64)`, where an untyped constant ends, and keep their type, as a hexadecimal number above it is a `U64`. + +`CLZ(x)`, `CTZ(x)` and `POPCOUNT(x)` (report 2026-10.36) are Item's +`countBits`, which refuses an `x` not of an unsigned type, or a set for +`POPCOUNT`, and an untyped constant with help that says to give it a +type, as `rotand` does; folds a constant by counting its bits one by one +(`countOf`); or has `Gen.countZeros` or `Gen.popCount` count them. The +result is an `INT`. Two mismatches in `coerce` that people meet on the way to it, a slice where its element's pointer is wanted and a pointer where a slice is, diff --git a/editor/emacs/raz-mode.el b/editor/emacs/raz-mode.el index 6ce46d2..65ec2b3 100644 --- a/editor/emacs/raz-mode.el +++ b/editor/emacs/raz-mode.el @@ -33,7 +33,8 @@ (defconst raz-builtins '("SIZE" "ADR" "LEN" "PTR" "NEW" "MSG" "SYSCALL" "FENCE" "CAS" "XCHG" "XADD" - "ARGC" "ARGV" "INC" "DEC" "COPY" "ROL" "ROR" "MIN" "MAX")) + "ARGC" "ARGV" "INC" "DEC" "COPY" "ROL" "ROR" "MIN" "MAX" + "CLZ" "CTZ" "POPCOUNT")) (defvar raz-mode-syntax-table (let ((st (make-syntax-table))) diff --git a/editor/vim/syntax/raz.vim b/editor/vim/syntax/raz.vim index 1bc7feb..279d454 100644 --- a/editor/vim/syntax/raz.vim +++ b/editor/vim/syntax/raz.vim @@ -16,6 +16,7 @@ syntax keyword razType I8 I16 I32 I64 INT UINT U8 U16 U32 U64 BOOL F32 F64 ERROR syntax keyword razBuiltin SIZE ADR LEN PTR NEW MSG SYSCALL FENCE CAS XCHG XADD syntax keyword razBuiltin ARGC ARGV INC DEC COPY ROL ROR MIN MAX +syntax keyword razBuiltin CLZ CTZ POPCOUNT syntax keyword razConstant true false nil " 123, 0FFH, 1.5, 2.0E-3 diff --git a/src/Gen.raz b/src/Gen.raz index 6b3a05e..3fd070a 100644 --- a/src/Gen.raz +++ b/src/Gen.raz @@ -1065,6 +1065,79 @@ stack[depth - 1].k := kWord; end; +(* CLZ, if leading, or CTZ of the unsigned integer of size bytes on top + (report section 6.1). bsr finds the place h of its highest one bit, + and the zeros above it are the width less 1 less h; bsf finds the + place of its lowest, which is the zeros below it. Neither finds a + place in 0, the one value with no one bit, and both say so by ZF: + then the count is the whole width, as if h were -1, or the lowest + one at the width. The bits above size bytes are zero, so a scan of + all 64 sees the value's own. The baseline x86-64 lacks lzcnt and + tzcnt, which would count 0 by themselves. For a U32: + + bsr r, r bsf r, r + jnz L jnz L + mov r, -1 mov r, 32 + L: neg r L: + add r, 31 *) +proc countZeros*(leading: BOOL; size: INT); +var r, w, L: INT; +begin + r := top(); + w := size * 8; + L := NoLabel; + X.bitScan(leading, r); + X.jcc(X.ccNE, L); + if leading then X.movRI(r, -1); else X.movRI(r, w); end; + X.fixLink(L); + if leading then + X.unary(3, r); (* neg *) + X.aluI(X.aluAdd, r, w - 1); + end; + stack[depth - 1].k := kWord; +end; + +(* POPCOUNT of the integer or set on top (report section 6.1), counted + as lib/Bytes.raz counts bytes, without a loop: each two bits are + made the sum of their ones, then each four, then each byte, and a + multiplication by 0101...H adds the eight bytes' sums into the top + byte. The baseline x86-64 lacks popcnt. rax and rdx are + free between the stack machine's operations. + + mov rax, r; shr rax, 1; mov rdx, 5555...H; and rax, rdx; sub r, rax + mov rax, r; shr rax, 2; mov rdx, 3333...H; and rax, rdx; and r, rdx; add r, rax + mov rax, r; shr rax, 4; add r, rax; mov rdx, 0F0F...H; and r, rdx + mov rdx, 0101...H; imul r, rdx; shr r, 56 *) +proc popCount*; +var r: INT; +begin + r := top(); + (* each two bits: their value less its upper bit, which is its ones *) + X.movRR(RAX, r); + X.shiftI(X.shShr, RAX, 1); + X.movRI(RDX, 5555555555555555H); + X.alu(X.aluAnd, RAX, RDX); + X.alu(X.aluSub, r, RAX); + (* each four bits: the sums of its two pairs *) + X.movRR(RAX, r); + X.shiftI(X.shShr, RAX, 2); + X.movRI(RDX, 3333333333333333H); + X.alu(X.aluAnd, RAX, RDX); + X.alu(X.aluAnd, r, RDX); + X.alu(X.aluAdd, r, RAX); + (* each byte: the sums of its two halves, at most 8, which fits four bits *) + X.movRR(RAX, r); + X.shiftI(X.shShr, RAX, 4); + X.alu(X.aluAdd, r, RAX); + X.movRI(RDX, 0F0F0F0F0F0F0F0FH); + X.alu(X.aluAnd, r, RDX); + (* the top byte of r times 0101...H is the sum of all eight *) + X.movRI(RDX, 0101010101010101H); + X.imul(r, RDX); + X.shiftI(X.shShr, r, 56); + stack[depth - 1].k := kWord; +end; + (* The left op the right of the two values on top, as a BOOL *) proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem; diff --git a/src/Item.raz b/src/Item.raz index cce88bf..d9296ac 100644 --- a/src/Item.raz +++ b/src/Item.raz @@ -1560,6 +1560,55 @@ return nil; end; +(* CLZ, CTZ or POPCOUNT, which, of v, a value w bits wide, folded *) +proc countOf(which: INT; v: U64; w: I64): I64; +var n, i: I64; +begin + n := 0; + if which = Sym.bPopcount then + for i := 0 to w - 1 do n := n + I64((v shr i) & 1); end; + elsif which = Sym.bClz then + while (n < w) and (((v shr (w - 1 - n)) & 1) = 0) do INC(n); end; + else + while (n < w) and (((v shr n) & 1) = 0) do INC(n); end; + end; + return n; +end; + +(* CLZ(x), CTZ(x) or POPCOUNT(x), which: the zero bits of x above its + highest one, below its lowest, or its one bits, an INT (report + section 6.1). x is of an unsigned integer type, whose width is what + 0 counts, or for POPCOUNT a set; an untyped constant has no width. + Of a constant the count is folded. *) +proc countBits*(var x: Item; which: INT): ERROR; +var name, s: []U8; ok: BOOL; +begin + if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then return notValue(x); end; + if which = Sym.bClz then name := "CLZ"; elsif which = Sym.bCtz then name := "CTZ"; else name := "POPCOUNT"; end; + if which = Sym.bPopcount then + s := say2("{} needs an unsigned integer or a set, found {}", name, what(x)); + else + s := say2("{} needs an unsigned integer, found {}", name, what(x)); + end; + if x.typ = Sym.tConst then + return Scan.markHelp(x.pos, s, + say1("an untyped constant has no width to count in: give it a type, as in U32({})", Diag.source(x.pos))); + end; + ok := (x.typ^.form = Sym.fInt) and not x.typ^.signed; + if (x.typ^.form = Sym.fSet) and (which = Sym.bPopcount) then ok := true; end; + if not ok then return Scan.markAt(x.pos, s); end; + if x.mode = mConst then + makeConst(x, Sym.tInt, countOf(which, U64(x.val), bits(x.typ))); + return nil; + end; + try value(x); + if which = Sym.bPopcount then Gen.popCount(); else Gen.countZeros(which = Sym.bClz, intSize(x.typ)); end; + x.typ := Sym.tInt; + x.mode := mStack; + x.made := false; (* a built-in's result, not an operator's *) + return nil; +end; + (* MIN(T), or MAX(T) if max: the smallest or the largest value of the integer type t, an untyped constant (report section 6.1); p is where T is written. MAX(U64) and MAX(UINT) are above high(I64), where the diff --git a/src/Parse.raz b/src/Parse.raz index 8517818..912d414 100644 --- a/src/Parse.raz +++ b/src/Parse.raz @@ -1106,6 +1106,9 @@ start := Scan.tokPos(); t := try parseType(); try Item.limit(x, t, which = Sym.bMax, Scan.spanFrom(start)); + | Sym.bClz, Sym.bCtz, Sym.bPopcount: + try expression(x, nil); + try Item.countBits(x, which); | Sym.bCopy: try expression(x, nil); try Item.copyDest(x); diff --git a/src/Sym.raz b/src/Sym.raz index f141974..29051d6 100644 --- a/src/Sym.raz +++ b/src/Sym.raz @@ -132,7 +132,7 @@ bSize* = 0; bAdr* = 1; bLen* = 2; bNew* = 3; bMsg* = 4; bSyscall* = 5; bFence* = 6; bCas* = 7; bXchg* = 8; bXadd* = 9; bArgc* = 10; bArgv* = 11; bInc* = 12; bDec* = 13; bCopy* = 14; bPtr* = 15; bRol* = 16; bRor* = 17; - bMin* = 18; bMax* = 19; + bMin* = 18; bMax* = 19; bClz* = 20; bCtz* = 21; bPopcount* = 22; MaxDepth* = 64; (* scopes open at once *) @@ -715,4 +715,7 @@ enter("ROR", oBuiltin, nil, bRor); enter("MIN", oBuiltin, nil, bMin); enter("MAX", oBuiltin, nil, bMax); + enter("CLZ", oBuiltin, nil, bClz); + enter("CTZ", oBuiltin, nil, bCtz); + enter("POPCOUNT", oBuiltin, nil, bPopcount); end Sym. diff --git a/src/X64.raz b/src/X64.raz index ac76f77..744a1a8 100644 --- a/src/X64.raz +++ b/src/X64.raz @@ -533,6 +533,17 @@ if n >= 0 then Chunk.put1(n); end; end; +(* bsr r, r, if reverse, or bsf r, r: the place of r's highest, or + lowest, one bit, 0F BD and 0F BC. ZF is set if r is 0, which has no + one bit, and r is then left undefined. *) +proc bitScan*(reverse: BOOL; r: INT); +var opc: INT; name: []U8; +begin + if reverse then opc := 0BD0FH; name := "bsr"; else opc := 0BC0FH; name := "bsf"; end; + if listing then say(text2(name, rn(r), rn(r))); end; + opR(0, true, opc, r, r, false); +end; + (* F7 /ext: 2 not, 3 neg, 6 div, 7 idiv *) proc unary*(ext, r: INT); begin diff --git a/test/msg/ClzSet.err b/test/msg/ClzSet.err new file mode 100644 index 0000000..021b44f --- /dev/null +++ b/test/msg/ClzSet.err @@ -0,0 +1,4 @@ +conform/err/ClzSet.raz:7:14: error: CLZ needs an unsigned integer, found Days + 7 | n := CLZ(s); + | ^ +raz: 1 error diff --git a/test/msg/ClzUntyped.err b/test/msg/ClzUntyped.err new file mode 100644 index 0000000..86d32b8 --- /dev/null +++ b/test/msg/ClzUntyped.err @@ -0,0 +1,5 @@ +conform/err/ClzUntyped.raz:5:14: error: CLZ needs an unsigned integer, found 1 + 5 | n := CLZ(1); + | ^ +help: an untyped constant has no width to count in: give it a type, as in U32(1) +raz: 1 error diff --git a/test/msg/CtzSigned.err b/test/msg/CtzSigned.err new file mode 100644 index 0000000..5133696 --- /dev/null +++ b/test/msg/CtzSigned.err @@ -0,0 +1,4 @@ +conform/err/CtzSigned.raz:5:14: error: CTZ needs an unsigned integer, found I32 + 5 | n := CTZ(x); + | ^ +raz: 1 error diff --git a/test/msg/PopcountReal.err b/test/msg/PopcountReal.err new file mode 100644 index 0000000..b946f24 --- /dev/null +++ b/test/msg/PopcountReal.err @@ -0,0 +1,4 @@ +conform/err/PopcountReal.raz:2:20: error: POPCOUNT needs an unsigned integer or a set, found 1.5 + 2 | const N = POPCOUNT(1.5); + | ^^^ +raz: 1 error