[llvm] [InstCombine] Keep or disjoint after folding casted bitwise logic (PR #136815)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Tue Apr 22 23:12:18 PDT 2025


================
@@ -1846,27 +1846,29 @@ Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
   if (CastOpcode != Cast1->getOpcode())
     return nullptr;
 
-  // If the source types do not match, but the casts are matching extends, we
-  // can still narrow the logic op.
-  if (SrcTy != Cast1->getSrcTy()) {
-    Value *X, *Y;
-    if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
-        match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
-      // Cast the narrower source to the wider source type.
-      unsigned XNumBits = X->getType()->getScalarSizeInBits();
-      unsigned YNumBits = Y->getType()->getScalarSizeInBits();
-      if (XNumBits < YNumBits)
-        X = Builder.CreateCast(CastOpcode, X, Y->getType());
-      else
-        Y = Builder.CreateCast(CastOpcode, Y, X->getType());
-      // Do the logic op in the intermediate width, then widen more.
-      Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
-      return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
-    }
+  Value *X, *Y;
+  if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
+      match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
+    // Cast the narrower source to the wider source type.
+    unsigned XNumBits = X->getType()->getScalarSizeInBits();
+    unsigned YNumBits = Y->getType()->getScalarSizeInBits();
+    // If the source types do not match, but the casts are matching extends, we
+    // can still narrow the logic op.
+    if (XNumBits < YNumBits)
+      X = Builder.CreateCast(CastOpcode, X, Y->getType());
+    else if (YNumBits < XNumBits)
+      Y = Builder.CreateCast(CastOpcode, Y, X->getType());
+
+    // Do the logic op in the intermediate width, then widen more.
+    Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
+    if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(&I);
+        Disjoint && Disjoint->isDisjoint())
+      cast<PossiblyDisjointInst>(NarrowLogic)->setIsDisjoint(true);
+    return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
+  }
 
-    // Give up for other cast opcodes.
+  if (SrcTy != Cast1->getSrcTy())
----------------
dtcxzyw wrote:

Is this change necessary? Can you add a test with `SrcTy == Cast1->getSrcTy()`?
```
define i16 @or_disjoint_zext_zext(i8 %x, i8 %y) {
  %zx = zext i8 %x to i16
  %zy = zext i8 %y to i16
  %r = or disjoint i16 %zy, %zx
  ret i16 %r
}
```

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


More information about the llvm-commits mailing list