[Mlir-commits] [mlir] [mlir][arith] Add InferExactOnIndexCast to cast folders (PR #184631)
Erick Ochoa Lopez
llvmlistbot at llvm.org
Wed Mar 4 10:48:00 PST 2026
================
@@ -1844,9 +1844,42 @@ bool arith::IndexCastOp::areCastCompatible(TypeRange inputs,
return areIndexCastCompatible(inputs, outputs);
}
+static unsigned getBitwidth(Type type, unsigned indexBitwidth) {
+ Type elemType = getElementTypeOrSelf(type);
+ if (isa<IndexType>(elemType))
+ return indexBitwidth;
+ return elemType.getIntOrFloatBitWidth();
+}
+
+template <typename CastOp>
+struct InferExactOnIndexCast final : OpRewritePattern<CastOp> {
+ InferExactOnIndexCast(MLIRContext *context)
+ : OpRewritePattern<CastOp>(context) {}
+
+ LogicalResult matchAndRewrite(CastOp op,
+ PatternRewriter &rewriter) const override {
+ if (op.getExact())
+ return failure();
+
+ DataLayout layout = DataLayout::closest(op);
+ unsigned indexBitwidth =
+ layout.getTypeSizeInBits(IndexType::get(op.getContext()));
+ unsigned srcBW = getBitwidth(op.getIn().getType(), indexBitwidth);
+ unsigned dstBW = getBitwidth(op.getType(), indexBitwidth);
+ if (srcBW > dstBW)
+ return rewriter.notifyMatchFailure(op, "source is wider than dest");
+
+ rewriter.modifyOpInPlace(op, [&] { op.setExact(true); });
+ return success();
+ }
+};
+
OpFoldResult arith::IndexCastOp::fold(FoldAdaptor adaptor) {
// index_cast(constant) -> constant
- unsigned resultBitwidth = 64; // Default for index integer attributes.
+ DataLayout layout = DataLayout::closest(*this);
----------------
amd-eochoalo wrote:
Ok, I think I understand. When I was coding this, the semantics I intended were:
* datalayout provides the actual bitwidth of index (not an upper bound)
* it provides a default (it is the user's responsibility to somehow change it, maybe we can offer that on a future PR).
Let me think about changing it such that datalayout provides an upper bound instead.
https://github.com/llvm/llvm-project/pull/184631
More information about the Mlir-commits
mailing list