[PATCH] D32672: [ConstantRange] Remove costly udivrem from ConstantRange::truncate

Craig Topper via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sat Apr 29 12:07:16 PDT 2017


craig.topper created this revision.

Truncate currently uses a udivrem call which is going to be slow particularly for larger than 64-bit widths.

As far as I can tell all we were trying to do was modulo LowerDiv by (MaxValue+1) and make sure whatever value was effectively subtracted from LowerDiv was also subtracted from UpperDiv.

This patch recognizes that MaxValue+1 is a power of 2 so we can just use a bitwise AND to accomplish a modulo operation or isolate the upper bits.


https://reviews.llvm.org/D32672

Files:
  lib/IR/ConstantRange.cpp


Index: lib/IR/ConstantRange.cpp
===================================================================
--- lib/IR/ConstantRange.cpp
+++ lib/IR/ConstantRange.cpp
@@ -567,7 +567,6 @@
     return ConstantRange(DstTySize, /*isFullSet=*/true);
 
   APInt MaxValue = APInt::getLowBitsSet(getBitWidth(), DstTySize);
-  APInt MaxBitValue = APInt::getOneBitSet(getBitWidth(), DstTySize);
 
   APInt LowerDiv(Lower), UpperDiv(Upper);
   ConstantRange Union(DstTySize, /*isFullSet=*/false);
@@ -591,17 +590,19 @@
 
   // Chop off the most significant bits that are past the destination bitwidth.
   if (LowerDiv.uge(MaxValue)) {
-    APInt Div(getBitWidth(), 0);
-    APInt::udivrem(LowerDiv, MaxBitValue, Div, LowerDiv);
-    UpperDiv -= MaxBitValue * Div;
+    // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
+    APInt Adjust = LowerDiv & ~MaxValue;
+    LowerDiv -= Adjust;
+    UpperDiv -= Adjust;
   }
 
   if (UpperDiv.ule(MaxValue))
     return ConstantRange(LowerDiv.trunc(DstTySize),
                          UpperDiv.trunc(DstTySize)).unionWith(Union);
 
   // The truncated value wraps around. Check if we can do better than fullset.
-  UpperDiv -= MaxBitValue;
+  UpperDiv -= MaxValue;
+  UpperDiv -= 1;
   if (UpperDiv.ult(LowerDiv))
     return ConstantRange(LowerDiv.trunc(DstTySize),
                          UpperDiv.trunc(DstTySize)).unionWith(Union);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D32672.97195.patch
Type: text/x-patch
Size: 1384 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20170429/59b595a4/attachment.bin>


More information about the llvm-commits mailing list