[clang] [CIR] Implement simple folding for unary operations (PR #174882)

Sirui Mu via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 8 07:02:31 PST 2026


================
@@ -2479,6 +2479,39 @@ OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
       if (isBoolNot(previous))
         return previous.getInput();
 
+  // Fold constant unary operations.
+  if (auto srcConst = getInput().getDefiningOp<cir::ConstantOp>()) {
----------------
Lancern wrote:

> That said, WHICH direction we go (switch on kind, then type, vs type then kind) doesn't seem particularly motivated in 1 way or the other?

I didn't quite know how MLIR would actually fold a sequence of operations. My guess was, given a sequence of CIR operations such as:

```
%0 = cir.const #cir.int<1>
%1 = cir.unary(neg, %0)
%2 = cir.unary(neg, %1)
```

If we fold by testing whether the input comes from a constant operation, we might fail to fold `%2` because, well, its input does not come directly from a constant operation.

To verify this guess, I just go through several places in MLIR that folds operations [^1][^2]. It turns out that after successfully folding an operation, MLIR would always first materialize the folded result into a constant operation before folding the next. So after folding `%1`, the current MLIR implementation would always transform the operation sequence to something like:

```
%0 = cir.const #cir.int<1>
%1 = cir.const #cir.int<-1>
%2 = cir.unary(neg, %1)
```

before it starts to attempt folding `%2`. So Andy's implementation should work.

But I'm not sure whether we should rely on this behavior. Taking the folded input from the adaptor could avoid these problems.

[^1]: In function [`OpBuilder::tryFold`](https://github.com/llvm/llvm-project/blob/012097d4fe7f300a59f9d2b89e528e1bd449d4c1/mlir/lib/IR/Builders.cpp#L472-L474)
[^2]: In function [`GreedyPatternRewriteDriver::processWorklist`](https://github.com/llvm/llvm-project/blob/012097d4fe7f300a59f9d2b89e528e1bd449d4c1/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp#L492-L496)

https://github.com/llvm/llvm-project/pull/174882


More information about the cfe-commits mailing list