[llvm] [InstCombine] Improve select equiv fold for plain condition (PR #83405)

via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 18 14:58:01 PDT 2024


================
@@ -500,6 +500,51 @@ static bool isSelect01(const APInt &C1I, const APInt &C2I) {
   return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
 }
 
+/// Try to simplify seletion chain with partially identical conditions, eg:
+///   %s1 = select i1 %c1, i32 23, i32 45
+///   %s2 = select i1 %c2, i32 666, i32 %s1
+///   %s3 = select i1 %c1, i32 789, i32 %s2
+/// -->
+///   %s2 = select i1 %c2, i32 666, i32 45
+///   %s3 = select i1 %c1, i32 789, i32 %s2
+static bool simplifySeqSelectWithSameCond(SelectInst &SI,
+                                          const SimplifyQuery &SQ,
+                                          InstCombinerImpl &IC) {
+  Value *CondVal = SI.getCondition();
+  auto trySimplifySeqSelect = [=, &SI, &IC](unsigned OpIndex) {
+    assert((OpIndex == 1 || OpIndex == 2) && "Unexpected operand index");
+    SelectInst *SINext = &SI;
+    Type *SelType = SINext->getType();
+    Value *ValOp = SINext->getOperand(OpIndex);
+    Value *CondNext;
+    // Don't need propagate FMF flag because we update the operand of SINext
+    // directly.
+    // It is not profitable to build a new select for SINext with multi-arms.
+    while (match(ValOp, m_Select(m_Value(CondNext), m_Value(), m_Value()))) {
+      if (CondNext == CondVal && SINext->hasOneUse()) {
----------------
goldsteinn wrote:

It should be `match(ValOp, m_OneUse(m_Select(....))` then drop the `SINext->hasOneUse()`, otherwise this won't fold the base select if it has multiple uses.

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


More information about the llvm-commits mailing list