[llvm] [SPIRV] Add bitreverse expansion for kernel (PR #186412)

via llvm-commits llvm-commits at lists.llvm.org
Thu Mar 26 01:09:54 PDT 2026


================
@@ -3286,13 +3286,82 @@ bool SPIRVInstructionSelector::selectBitreverse(Register ResVReg,
                                                 SPIRVTypeInst ResType,
                                                 MachineInstr &I) const {
   Register OpReg = I.getOperand(1).getReg();
-  SPIRVTypeInst OpType = GR.getSPIRVTypeForVReg(OpReg);
-  switch (GR.getScalarOrVectorBitWidth(OpType)) {
-  case 16:
-    return selectBitreverse16(ResVReg, ResType, I, OpReg);
-  default:
-    return selectBitreverse32(ResVReg, ResType, I, OpReg);
+
+  // TODO: Fix shader behavior in case of VK_KHR_maintenance9 extension is set
+  if (STI.isShader()) {
+    SPIRVTypeInst OpType = GR.getSPIRVTypeForVReg(OpReg);
+    switch (GR.getScalarOrVectorBitWidth(OpType)) {
+    case 16:
+      return selectBitreverse16(ResVReg, ResType, I, OpReg);
+    default:
+      return selectBitreverseNative(ResVReg, ResType, I, OpReg);
+    }
   }
+
+  if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_bit_instructions))
+    return selectBitreverseNative(ResVReg, ResType, I, OpReg);
+
+  // Expansion bitreverse using bit manipulation operations
+  // Algo: https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
+  const unsigned BitWidth = GR.getScalarOrVectorBitWidth(ResType);
+  bool BitWidthIsPowerOfTwo = !(BitWidth & (BitWidth - 1));
+  // TODO: add support for any bit width and bitwidth more than 64.
+  if (BitWidth <= 64 && !(BitWidth && BitWidthIsPowerOfTwo))
----------------
idubinov wrote:

good catch!

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


More information about the llvm-commits mailing list