[llvm] [InstCombine] Simplify and/or by replacing operands with constants (PR #77231)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Tue Jan 16 19:12:09 PST 2024
================
@@ -2159,6 +2159,61 @@ Instruction *InstCombinerImpl::foldBinOpOfDisplacedShifts(BinaryOperator &I) {
return BinaryOperator::Create(ShiftOp, NewC, ShAmt);
}
+// Try to simplify X | Y by replacing occurrences of Y in X with 0.
+// Similarly, simplify X & Y by replacing occurrences of Y in X with -1.
+static Value *simplifyAndOrWithOpReplaced(Value *X, Value *Y, bool IsAnd,
+ InstCombinerImpl &IC,
+ unsigned Depth = 0) {
+ if (isa<Constant>(X) || X == Y)
+ return nullptr;
+
+ auto RecursivelyReplaceUses = [&](Instruction::BinaryOps Opcode, Value *Op0,
+ Value *Op1) -> Value * {
+ if (Depth == 2)
+ return nullptr;
+
+ // TODO: Relax the one-use constraint to clean up existing hard-coded
+ // simplifications.
+ if (!X->hasOneUse())
+ return nullptr;
+ Value *NewOp0 = simplifyAndOrWithOpReplaced(Op0, Y, IsAnd, IC, Depth + 1);
+ Value *NewOp1 = simplifyAndOrWithOpReplaced(Op1, Y, IsAnd, IC, Depth + 1);
+ if (!NewOp0 && !NewOp1)
+ return nullptr;
+ return IC.Builder.CreateBinOp(Opcode, NewOp0 ? NewOp0 : Op0,
+ NewOp1 ? NewOp1 : Op1);
+ };
+
+ Value *Op0, *Op1;
+ if (match(X, m_And(m_Value(Op0), m_Value(Op1)))) {
+ if (Op0 == Y || Op1 == Y)
+ return IsAnd ? (Op0 == Y ? Op1 : Op0)
+ : Constant::getNullValue(X->getType());
----------------
dtcxzyw wrote:
> I will make it return the simplified result of X |/& Y.
Emm, it is hard to change the semantics of `simplifyAndOrWithOpReplaced` :(
I cannot guarantee that we never create more instructions than we save because we have to create two instructions in `RecursivelyReplaceUses` (one for `simplfiedOp0 bitop simplifiedOp1`, and the other for `simplifiedX and/or Y`).
I added some comments to clarify the semantics of `simplifyAndOrWithOpReplaced`.
https://github.com/llvm/llvm-project/pull/77231
More information about the llvm-commits
mailing list