[llvm] [VPlan] Optimize FindLast of (binop %IV, live-in) by sinking. (PR #183911)

via llvm-commits llvm-commits at lists.llvm.org
Mon Mar 30 07:04:19 PDT 2026


================
@@ -5761,12 +5808,32 @@ void VPlanTransforms::optimizeFindIVReductions(VPlan &Plan,
     // Positive step means we need UMax/SMax to find the last IV value, and
     // UMin/SMin otherwise.
     bool UseMax = SE.isKnownPositive(Step);
-    bool UseSigned = true;
-    std::optional<APInt> SentinelVal =
-        CheckSentinel(IVSCEV, UseMax, /*IsSigned=*/true);
-    if (!SentinelVal) {
-      SentinelVal = CheckSentinel(IVSCEV, UseMax, /*IsSigned=*/false);
-      UseSigned = false;
+    bool UseSigned;
+    std::optional<APInt> SentinelVal;
+    if (auto Sentinel = CheckSentinel(IVSCEV, UseMax)) {
+      SentinelVal = Sentinel->first;
+      UseSigned = Sentinel->second;
+    }
+
+    // Sinking the expression may enable or disable a sentinel (e.g., if the
+    // expression is a multiply or divide by large constant, respectively).
+    // Avoid sinking if it disables a sentinel.
+    if (!SentinelVal && SinkExpressionIV) {
+      // If we weren't able to use a sentinel with SinkExpressionIV, try if it
+      // is possible with FindLastExpression.
+      const SCEV *FindLastExpressionSCEV =
+          vputils::getSCEVExprForVPValue(FindLastExpression, PSE, &L);
+      if (match(FindLastExpressionSCEV,
+                m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step)))) {
+        if (auto Sentinel = CheckSentinel(FindLastExpressionSCEV, UseMax)) {
+          SentinelVal = Sentinel->first;
+          UseSigned = Sentinel->second;
+          // We can use the sentinel value with the original expression, reset
+          // IVSCEV and clear SinkExpressionIV.
+          IVSCEV = FindLastExpressionSCEV;
+          SinkExpressionIV = nullptr;
----------------
ayalz wrote:

Also update `UseMax`:
```suggestion
          SentinelVal = Sentinel->first;
          UseSigned = Sentinel->second;
          // We can use the sentinel value with the original expression, reset
          // IVSCEV and clear SinkExpressionIV.
          IVSCEV = FindLastExpressionSCEV;
          UseMax = OrigUseMax;
          SinkExpressionIV = nullptr;
```

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


More information about the llvm-commits mailing list