[llvm] [ConstantRange] Improve `shlWithNoWrap` (PR #101800)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 3 09:43:34 PDT 2024


================
@@ -1624,12 +1624,43 @@ ConstantRange ConstantRange::shlWithNoWrap(const ConstantRange &Other,
     return getEmpty();
 
   ConstantRange Result = shl(Other);
+  if (!NoWrapKind)
+    return Result;
 
-  if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap)
-    Result = Result.intersectWith(sshl_sat(Other), RangeType);
+  KnownBits Known = toKnownBits();
+
+  if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap) {
+    ConstantRange ShAmtRange = Other;
+    if (isAllNonNegative())
+      ShAmtRange = ShAmtRange.intersectWith(
+          ConstantRange(APInt::getZero(getBitWidth()),
+                        APInt(getBitWidth(), Known.countMaxLeadingZeros())),
+          Unsigned);
+    else if (isAllNegative())
+      ShAmtRange = ShAmtRange.intersectWith(
+          ConstantRange(APInt::getZero(getBitWidth()),
+                        APInt(getBitWidth(), Known.countMaxLeadingOnes())),
+          Unsigned);
+    Result = Result.intersectWith(sshl_sat(ShAmtRange), RangeType);
+  }
 
-  if (NoWrapKind & OverflowingBinaryOperator::NoUnsignedWrap)
-    Result = Result.intersectWith(ushl_sat(Other), RangeType);
+  if (NoWrapKind & OverflowingBinaryOperator::NoUnsignedWrap) {
+    bool Overflow;
+    APInt LHSMin = getUnsignedMin();
+    APInt MinShl = LHSMin.ushl_ov(Other.getUnsignedMin(), Overflow);
+    if (Overflow)
+      return getEmpty();
+    APInt LHSMax = getUnsignedMax();
+    APInt MaxShl = LHSMax << Other.getUnsignedMax().getLimitedValue(
+                       LHSMax.countLeadingZeros());
----------------
nikic wrote:

We should also take the minimum shift amount into account. E.g. this case can be skipped if MinShAmt <= LeadingZeros. So for example Full << [1,..] should give [0, -1) not Full. And the case below can be similarly adjusted.

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


More information about the llvm-commits mailing list