8000 Clz instruction by cfbolz · Pull Request #160 · can-lehmann/metajit.cpp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions doc/jitir.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,20 @@ Type Checks:
- `is_float(a->type())`
- `is_float(type)`

### Clz

Count leading zero bits. Zero returns the operand bit width; poison propagates.

Arguments

- **a**: `Value*`

Return Type: `a->type()`

Type Checks:

- `is_int(a->type())`

### Popcount

Arguments
Expand Down
9 changes: 9 additions & 0 deletions fold.rules
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,15 @@ mul_high_u_power_of_two: MulHighU(x: T, C)
Cshift = width(T) - ctz(C)
=> ShrU(x, Cshift)

clz_constant: Clz(C)
Ccount = clz(C)
=> Ccount

clz_select: Clz(Select(c, C1, C2))
ClzC1 = clz(C1)
ClzC2 = clz(C2)
=> Select(c, ClzC1, ClzC2)

bit_reverse_constant: BitReverse(C)
Creversed = bit_reverse(C)
=> Creversed
Expand Down
6 changes: 6 additions & 0 deletions jitir.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,12 @@ def cmp(name, type_checks):
],
doc = "Convert a floating-point value to a different floating-point width."
),
Inst("Clz",
args = [Arg("a")],
type = "a->type()",
type_checks = ["is_int(a->type())"],
doc = "Count leading zero bits. Zero returns the operand bit width; poison propagates."
),
Inst("Popcount",
args = [Arg("a")],
type = "a->type()",
Expand Down
38 changes: 29 additions & 9 deletions jitir.tmpl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,11 @@ namespace metajit {
}
}

inline uint64_t clz(Type type, uint64_t value) {
value &= type_mask(type);
return value ? __builtin_clzll(value) - (64 - type_width(type)) : type_width(type);
}

inline uint64_t bit_reverse(Type type, uint64_t value) {
value = __builtin_bswap64(value);
value = ((value >> 4) & 0x0f0f0f0f0f0f0f0full) | ((value & 0x0f0f0f0f0f0f0f0full) << 4);
Expand Down Expand Up @@ -2777,21 +2782,21 @@ namespace metajit {
}

static uint64_t mask_through_highest_bit(uint64_t value) {
for (size_t shift = 1; shift < 64; shift *= 2) {
value |= value >> shift;
}
return value;
return value ? ~uint64_t(0) >> __builtin_clzll(value) : 0;
}

static Bits unsigned_range(Type type, uint64_t minimum, uint64_t maximum) {
assert(minimum <= maximum);
assert((maximum & ~type_mask(type)) == 0);
return Bits(type, ~mask_through_highest_bit(minimum ^ maximum), minimum);
}

static Bits unsigned_upper_bound(Type type, uint64_t bound) {
assert((bound & ~type_mask(type)) == 0);
return Bits(type, ~mask_through_highest_bit(bound), 0);
return unsigned_range(type, 0, bound);
}

static Bits unsigned_lower_bound(Type type, uint64_t bound) {
assert((bound & ~type_mask(type)) == 0);
uint64_t mask = ~mask_through_highest_bit(~bound & type_mask(type));
return Bits(type, mask, mask);
return unsigned_range(type, bound, type_mask(type));
}

uint64_t umin() const {
Expand Down Expand Up @@ -3239,6 +3244,10 @@ namespace metajit {
return {};
}

Bits clz() const {
return unsigned_range(type, metajit::clz(type, umax()), metajit::clz(type, umin()));
}

Bits bit_reverse() const {
return Bits(type, metajit::bit_reverse(type, mask), metajit::bit_reverse(type, value));
}
Expand All @@ -3264,6 +3273,8 @@ namespace metajit {
Bits a = at(values, select->arg(1));
Bits b = at(values, select->arg(2));
return cond.select(a, b);
} else if (dynmatch(ClzInst, clz, inst)) {
return at(values, clz->arg(0)).clz();
} else if (dynmatch(BitReverseInst, bit_reverse, inst)) {
return at(values, bit_reverse->arg(0)).bit_reverse();
} else if (dynmatch(ResizeUInst, resize_u, inst)) {
Expand Down Expand Up @@ -3650,6 +3661,13 @@ namespace metajit {
return Bits::constant(type, metajit::bit_reverse(type, value));
}

Bits clz() const {
if (is_poison) {
return Bits::poison(type);
}
return Bits::constant(type, metajit::clz(type, value));
}

Bits popcount() const {
if (is_poison) {
return Bits::poison(type);
Expand Down Expand Up @@ -3865,6 +3883,8 @@ namespace metajit {
_values[_inst] = a.ptr_to_int(ptr_to_int->type());
} else if (dynmatch(BitReverseInst, bit_reverse, _inst)) {
_values[_inst] = at(bit_reverse->arg(0)).bit_reverse();
} else if (dynmatch(ClzInst, clz, _inst)) {
_values[_inst] = at(clz->arg(0)).clz();
} else if (dynmatch(PopcountInst, popcount, _inst)) {
Bits a = at(popcount->arg(0));
_values[_inst] = a.popcount();
Expand Down
6 changes: 6 additions & 0 deletions llvmgen.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,12 @@ namespace metajit {
}
llvm_alloca->setAlignment(llvm::Align(alloca->align()));
return llvm_alloca;
} else if (dynmatch(ClzInst, clz, inst)) {
return _builder.CreateIntrinsic(
llvm::Intrinsic::ctlz,
{emit_type(clz->type())},
{emit_arg(clz->arg(0)), _builder.getFalse()}
);
} else if (dynmatch(PopcountInst, popcount, inst)) {
return _builder.CreateIntrinsic(
llvm::Intrinsic::ctpop,
Expand Down
2 changes: 2 additions & 0 deletions lowerllvm.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ namespace metajit {
} else if (llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(inst)) {
if (call->getIntrinsicID() == llvm::Intrinsic::bitreverse) {
return _builder.fold_bit_reverse(lower_operand(call->getArgOperand(0)));
} else if (call->getIntrinsicID() == llvm::Intrinsic::ctlz) {
return _builder.fold_clz(lower_operand(call->getArgOperand(0)));
} else if (call->getIntrinsicID() == llvm::Intrinsic::ctpop) {
return _builder.fold_popcount(lower_operand(call->getArgOperand(0)));
} else if (call->getCalledFunction() && call->getCalledFunction()->getName().starts_with("__metajit")) {
Expand Down
3 changes: 3 additions & 0 deletions ruledsl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ short-circuit evaluation.
`ctz(C)` counts trailing zero bits of an unsigned constant, returning the input
bit width for zero. Its result has an independently inferred numeric type.

`clz(C)` counts leading zero bits, returning the input bit width for zero.
Its result preserves the input type. It also works in type conditions.

`bit_reverse(C)` reverses the bits at the inferred width of `C` and preserves
its type. `mul_high_u(C1, C2)` returns the upper half of the full unsigned
product, with both arguments and the result sharing a type. Unlike ordinary
Expand Down
4 changes: 2 additions & 2 deletions ruledsl/lower.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,8 @@ def expression(self, node, inline=False):
expression = call("uint64_t", call("type_width", *args))
elif node.name == "bits":
expression = args[0]
elif node.name == "bit_reverse":
expression = call("metajit::bit_reverse", self.type_of(node), *args)
elif node.name in {"bit_reverse", "clz"}:
expression = call("metajit::" + node.name, self.type_of(node), *args)
elif node.name == "mul_high_u":
product = ir.Binary("*", call("__uint128_t", args[0]), args[1])
expression = call("uint64_t", ir.Binary(">>", product, call("type_width", self.type_of(node))))
Expand Down
4 changes: 3 additions & 1 deletion ruledsl/proof.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import z3

from . import ast
from .semantics import Value, bit_reverse, emit, mul_high_u, resize_bits
from .semantics import Value, bit_reverse, clz, emit, mul_high_u, resize_bits
from .source import SourceError
from .typecheck import KNOWN_BITS_FUNCTIONS, check
from .types import ConcreteType
Expand Down Expand Up @@ -235,6 +235,8 @@ def expression(self, node):
value = z3.BitVecVal(args[0].value.width, self.type_of(node).width)
elif node.name == "bits":
value = resize_bits(args[0].value, self.type_of(node).width)
elif node.name == "clz":
value = clz(args[0].value)
elif node.name == "bit_reverse":
value = bit_reverse(args[0].value)
elif node.name == "mul_high_u":
Expand Down
10 changes: 10 additions & 0 deletions ruledsl/semantics.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ def 10BC8 boolean_bits(condition):
return z3.If(condition, z3.BitVecVal(1, 1), z3.BitVecVal(0, 1))


def clz(bits):
result = z3.BitVecVal(bits.size(), bits.size())
for index in range(bits.size()):
result = z3.If(z3.Extract(index, index, bits) == 1,
z3.BitVecVal(bits.size() - index - 1, bits.size()), result)
return result


def bit_reverse(bits):
if bits.size() == 1:
return bits
Expand Down Expand Up @@ -82,6 +90,8 @@ def emit(kind, args, type_):
bits = z3.BitVecVal(0, type_.width)
for index in range(a.size()):
bits += z3.ZeroExt(type_.width - 1, z3.Extract(index, index, a))
elif kind == "Clz":
bits = clz(a)
elif kind == "BitReverse":
bits = bit_reverse(a)
else:
Expand Down
2 changes: 1 addition & 1 deletion ruledsl/signatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ class Signature:
for name in ("ResizeU", "ResizeS", "ResizeX"):
SIGNATURES[name] = Signature(("S",), "T", (("S", BIT_TYPES), ("T", BIT_TYPES)))

for name in ("Popcount", "BitReverse"):
for name in ("Popcount", "BitReverse", "Clz"):
SIGNATURES[name] = Signature(("T",), "T", (("T", INT_TYPES),))
SIGNATURES["Freeze"] = Signature(("T",), "T", (("T", BIT_TYPES),), unrestricted_types=("T",))
21 changes: 21 additions & 0 deletions ruledsl/test_proof.py
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -402,5 +402,26 @@ def test_timeout_must_be_positive(self):
prove("id: Add(x, 0)\n => x", timeout_ms=0)


class ClzTests(unittest.TestCase):
def test_semantics(self):
for type_ in INT_TYPES:
width = type_.width
cases = [(0, width), (1, width - 1), ((1 << width) - 1, 0)]
cases += [(1 << bit, width - bit - 1) for bit in range(width)]
for value, expected in cases:
result = emit("Clz", [Value.constant(value, type_)], type_)
self.assertEqual(z3.simplify(result.bits).as_long(), expected)
self.assertTrue(z3.is_false(z3.simplify(result.poison)))
poison = Value(z3.BitVecVal(0, width), z3.BoolVal(True), type_)
self.assertTrue(z3.is_true(z3.simplify(emit("Clz", [poison], type_).poison)))

def test_constant_rules(self):
source = (Path(__file__).resolve().parent.parent / "fold.rules").read_text()
rules = [rule for rule in parse(source) if rule.name in {"clz_constant", "clz_select"}]
self.assertEqual(len(rules), 2)
for rule in rules:
8 prove(source[rule.span.start:rule.span.end])


if __name__ == "__main__":
unittest.main()
2 changes: 2 additions & 0 deletions ruledsl/test_typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def test_failed_unification_preserves_root_domains(self):

def test_bit_operation_calculations_preserve_types_and_dependencies(self):
for operation, calculation, dependencies in (
("Clz(C)", "clz(C)", {"C"}),
("BitReverse(C)", "bit_reverse(C)", {"C"}),
("MulHighU(C1, C2)", "mul_high_u(C1, C2)", {"C1", "C2"})):
checked = check(f"constant: {operation}\n Cresult = {calculation}\n => Cresult")[0]
Expand All @@ -60,6 +61,7 @@ def test_bit_operation_calculations_preserve_types_and_dependencies(self):

def test_bit_operation_helpers_in_type_conditions(self):
checked = check("same: Add(x: T, 0)\n"
" where clz(bits(0, T)) == width(T) and clz(bits(1, T)) == width(T) - 1\n"
" where bit_reverse(bits(1, T)) == 1 << (width(T) - 1)\n"
" where mul_high_u(bits(-1, T), bits(-1, T)) == bits(-2, T)\n"
" => x")[0]
Expand Down
10 changes: 7 additions & 3 deletions ruledsl/typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ def requires_facts(self):
"not": operator.not_}


def clz(value, width):
return width - value.bit_length()


def bit_reverse(value, width):
result = 0
for index in range(width):
Expand All @@ -78,7 +82,7 @@ def mul_high_u(left, right, width):
return (left * right) >> width


CALCULATION_FUNCTIONS = {"bit_reverse": bit_reverse, "mul_high_u": mul_high_u}
CALCULATION_FUNCTIONS = {"clz": clz, "bit_reverse": bit_reverse, "mul_high_u": mul_high_u}


class Checker:
Expand Down Expand Up @@ -213,7 +217,7 @@ def expression(self, node):

def call(self, node):
arities = {"width": 1, "bits": 2, "min": 2, "max": 2, "ctz": 1,
"bit_reverse": 1, "mul_high_u": 2,
"bit_reverse": 1, "clz": 1, "mul_high_u": 2,
"known_zeros": 1, "known_ones": 1}
if node.name not in arities:
self.error(node, f"unknown calculation function {node.name!r}")
Expand All @@ -233,7 +237,7 @@ def call(self, node):
self.require(args[0], "constant", node.args[0])
if node.name == "ctz":
return ExprInfo("constant", self.constraints.fresh(), args[0].dependencies)
if node.name == "bit_reverse":
if node.name in {"bit_reverse", "clz"}:
return ExprInfo("constant", args[0].type, args[0].dependencies)
if node.name == "bits":
self.require(args[1], "type", node.args[1])
Expand Down
4 changes: 3 additions & 1 deletion tests/fuzzer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ namespace metajit {
}

Value* gen_int(RandomRange random_range) {
switch (rand() % 17) {
switch (rand() % 18) {
#define binop(name) \
return _builder->build_##name( \
gen(RandomRange(random_range.type())), \
Expand Down Expand Up @@ -147,6 +147,8 @@ namespace metajit {
case 15: binop(mul_high_u)
case 16:
return _builder->build_bit_reverse(gen(RandomRange(random_range.type())));
case 17:
return _builder->build_clz(gen(RandomRange(random_range.type())));
default:
assert(false && "Unreachable");

Expand Down
8 changes: 8 additions & 0 deletions tests/source/bit_manipulation.c
< 10A6A td class="blob-code blob-code-context js-file-line"> data->pop32 = __builtin_popcountg(data->in32);
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ typedef struct {
uint16_t pop16;
uint32_t pop32;
uint64_t pop64;
uint8_t clz8;
uint16_t clz16;
uint32_t clz32;
uint64_t clz64;
} test_data_t;

void run(test_data_t* data) {
Expand All @@ -24,4 +28,8 @@ void run(test_data_t* data) {
data->pop16 = __builtin_popcountg(data->in16);
data->pop64 = __builtin_popcountg(data->in64);
data->clz8 = __builtin_clzg(data->in8, 8);
data->clz16 = __builtin_clzg(data->in16, 16);
data->clz32 = __builtin_clzg(data->in32, 32);
data->clz64 = __builtin_clzg(data->in64, 64);
}
25 changes: 25 additions & 0 deletions tests/test_insts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,30 @@ void test_ptr_to_int(DiffTestSuite& suite) {
suite.diff_test("ptr_to_int_Int64").run(ptr_to_int_inputs<Type::Int64>);
}

template<Type type>
void clz_inputs(Builder& builder, TestData& data) {
data.output(builder.build_clz(data.input(type)));
data.output(builder.build_clz(data.input(RandomRange(type, 0, 0))));
data.output(builder.build_clz(data.input(RandomRange(type, type_mask(type), type_mask(type)))));
for (size_t bit = 0; bit < type_width(type); bit++) {
uint64_t value = uint64_t(1) << bit;
data.output(builder.build_clz(data.input(RandomRange(type, value, value))));
data.output(builder.build_clz(data.input(RandomRange(type, value - 1, value - 1))));
data.output(builder.build_clz(data.input(RandomRange(type, value + 1, value + 1))));
}
if (type != Type::Int64) {
Value* wide = data.input(Type::Int64);
data.output(builder.build_clz(builder.build_resize_x(wide, type)));
}
}

void test_clz(DiffTestSuite& suite) {
suite.diff_test("clz_Int8").run(clz_inputs<Type::Int8>);
suite.diff_test("clz_Int16").run(clz_inputs<Type::Int16>);
suite.diff_test("clz_Int32").run(clz_inputs<Type::Int32>);
suite.diff_test("clz_Int64").run(clz_inputs<Type::Int64>);
}

void test_popcount(DiffTestSuite& suite) {
#define popcount_type(type) \
suite.diff_test("popcount_" #type).run([](Builder& builder, TestData& data) { \
Expand Down Expand Up @@ -791,6 +815,7 @@ int main(int argc, char** argv) {
test_binop_f(suite);
test_convert_f(suite);
test_ptr_to_int(suite);
test_clz(suite);
test_popcount(suite);
test_bit_reverse(suite);

Expand Down
Loading
Loading
0