[llvm] [InstCombine] Fold `(X & Mask) == 0 ? TC : FC -> TC +/- (X & Mask)` (PR #100437)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jul 25 00:51:13 PDT 2024


================
@@ -186,6 +186,22 @@ static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
       return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
     }
 
+    // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) + TC
+    if (TC + AndMask == FC) {
+      if (CreateAnd)
+        V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
+      Constant *C = ConstantInt::get(SelType, TC);
+      return Builder.CreateAdd(V, C);
+    }
+
+    // (V & AndMaskC) == 0 ? TC : FC --> TC - (V & AndMaskC)
+    if (TC - AndMask == FC) {
+      if (CreateAnd)
+        V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
+      Constant *C = ConstantInt::get(SelType, TC);
+      return Builder.CreateSub(C, V);
+    }
----------------
goldsteinn wrote:

Think it would be easier to just loop through them and only write this code once i.e:

```
Constant * TCC = ConstantInt::get(TC);
Constant * FCC = ConstantInt::get(FC);
Constant * MaskC = ConstantInt::get(AndMask);

for(Opc : { Add, Sub, Shl...}) {
   if (SimplifyBinOp(Opc, TCC, MaskC) == FCC) {
      if (CreateAnd)
        V = Builder.CreateAnd(V, MaskC);
      return Builder.CreateBinOp(BinOp, V, C);
  }
}
```

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


More information about the llvm-commits mailing list