google / xls

XLS: Accelerated HW Synthesis
http://google.github.io/xls/
Apache License 2.0
1.15k stars 166 forks source link

Optimization opportunity: predetermine known outcomes of bit operations #1218

Open hzeller opened 7 months ago

hzeller commented 7 months ago

Consider the following function in /tmp/foo.x

fn foo(x: u32, b: u1) -> u32 {
  x & (b as u32)
}

We expect that the last bit is whatever is b & x[0] and the remaining bits zero.

Let's generate code from this

IR_CONVERTER=bazel-bin/xls/dslx/ir_convert/ir_converter_main
IR_OPT=bazel-bin/xls/tools/opt_main
CODEGEN=bazel-bin/xls/tools/codegen_main
${IR_CONVERTER} foo.x | ${IR_OPT} --top=__foo__foo - | ${CODEGEN} --module_name=foo --generator=combinational -

Result

The generated code does not see any optimization opportunity and essentially emits the code similar to the input, that ANDs 32 bits:

module foo(
  input wire [31:0] x,
  input wire b,
  output wire [31:0] out
);
  assign out = x & {31'h0000_0000, b};
endmodule

Expected Result

It would be good if the optimizer would recognize that we only actually need to AND one bit, while all the other bits are known to be zero already:

module foo(
  input wire [31:0] x,
  input wire b,
  output wire [31:0] out
);
  assign out = {31'h0000_0000, x[0] & b};
endmodule

Remarks

This is essentially a generalization of #1217

Maybe this actually does not make any difference as synthesis-tools might figure this out anyway. However, if this is done in the intermediate representation optimization, there might be follow-up optimization opportunities that currently might be left on the table ?

This example was with AND, but of course this is true for all bit-wise operations that do not depend on neighbors and have one known bit:

hzeller commented 5 months ago

(edit: changed name of function from top to foo as the former is a keyword now)