Skip to content

Conversation

@uenoku
Copy link
Member

@uenoku uenoku commented Nov 3, 2025

This commit adds canonicalization patterns for unsigned division and
modulo operations when the divisor is a power of two constant. These
operations can be efficiently lowered to bit extraction and
concatenation operations.

This is done in CombToSynth already but would be good to perform as part of canonicalization.

@uenoku uenoku requested a review from darthscsi as a code owner November 3, 2025 21:44
Comment on lines +63 to +64
pm.addPass(createCSEPass());
pm.addPass(createSimpleCanonicalizerPass());
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for canonicalizing divu/modu before running CombToSynth.

Copy link
Contributor

@fabianschuiki fabianschuiki left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Is this also valid if the LHS contains any X? I remember the SV spec mentioning that if the operands contain any X, the result is all X. If you divide 'h1X0 / 16, you'd get 'h1X with the canonicalization, but since the LHS contains any X, the spec calls for 'hXX as a result. Do we view 'h1X as a refinement of 'hXX?

I also remember a discussion at a CIRCT ODM a while ago about making Comb just assume 2-valued bits, and then implement X semantics with dedicated ops around Comb. I liked that approach, because canonicalizations like the one in this PR can just not care about X.

Comment on lines -993 to -1006
if (auto rhsConstantOp = adaptor.getRhs().getDefiningOp<hw::ConstantOp>())
if (rhsConstantOp.getValue().isPowerOf2()) {
// Extract upper bits.
size_t extractAmount = rhsConstantOp.getValue().ceilLogBase2();
size_t width = op.getType().getIntOrFloatBitWidth();
Value upperBits = rewriter.createOrFold<comb::ExtractOp>(
op.getLoc(), adaptor.getLhs(), extractAmount,
width - extractAmount);
Value constZero = hw::ConstantOp::create(rewriter, op.getLoc(),
APInt::getZero(extractAmount));
replaceOpWithNewOpAndCopyNamehint<comb::ConcatOp>(
rewriter, op, op.getType(), ArrayRef<Value>{constZero, upperBits});
return success();
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice to have this in the canonicalizer! 🥳

@uenoku
Copy link
Member Author

uenoku commented Nov 5, 2025

Good point, I added an condition to check bin flag. Not sure how removal of bin flag ended up :)

@uenoku uenoku merged commit 5f978b4 into main Nov 19, 2025
7 checks passed
@uenoku uenoku deleted the dev/hidetou/divmod branch November 19, 2025 20:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants