[PATCH] D158548: Limit bswap and bitreverse matching to legal integer width

Victor Mustya via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Aug 22 13:57:23 PDT 2023


vmustya created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
vmustya requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

The InstCombine pass matched a sequence of and-shl-add instructions into
bitreverse even when the demanded width is illegal for a target machine.
That produces the IR sequences like the following one:

  %trunc = trunc i32 %x to i9
  %rev = call i9 @llvm.bitreverse.i9(i9 %trunc)
  %mask = and i9 %rev, -128
  %reverse = zext i9 %mask to i32

The illegal bitreverse intrinsics are being emulated, so this combining
produces inefficient code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D158548

Files:
  llvm/lib/Transforms/Utils/Local.cpp
  llvm/test/Transforms/InstCombine/bitreverse.ll


Index: llvm/test/Transforms/InstCombine/bitreverse.ll
===================================================================
--- llvm/test/Transforms/InstCombine/bitreverse.ll
+++ llvm/test/Transforms/InstCombine/bitreverse.ll
@@ -261,6 +261,17 @@
   ret i8 %10
 }
 
+define i32 @illegal_width(i32 %x) {
+; CHECK-LABEL: @illegal_width
+; CHECK-NOT: call i9 @llvm.bitreverse.i9
+  %b0 = and i32 %x, 1
+  %b1 = and i32 %x, 2
+  %shift1 = mul nuw nsw i32 %b1, 64
+  %shift0 = shl nuw nsw i32 %b0, 8
+  %reverse = add i32 %shift0, %shift1
+  ret i32 %reverse
+}
+
 define i4 @shuf_4bits(<4 x i1> %x) {
 ; CHECK-LABEL: @shuf_4bits(
 ; CHECK-NEXT:    [[TMP1:%.*]] = bitcast <4 x i1> [[X:%.*]] to i4
Index: llvm/lib/Transforms/Utils/Local.cpp
===================================================================
--- llvm/lib/Transforms/Utils/Local.cpp
+++ llvm/lib/Transforms/Utils/Local.cpp
@@ -3391,6 +3391,11 @@
   if (DemandedBW > ITy->getScalarSizeInBits())
     return false;
 
+  // Check that the bswap/bitreverse will have legal bit width.
+  auto &DL = I->getModule()->getDataLayout();
+  if (DL.isIllegalInteger(DemandedBW))
+    return false;
+
   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
   // only byteswap values with an even number of bytes.
   APInt DemandedMask = APInt::getAllOnes(DemandedBW);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D158548.552495.patch
Type: text/x-patch
Size: 1336 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20230822/ce5719c8/attachment.bin>


More information about the llvm-commits mailing list