[llvm] [GISel][RISCV] Compute CTPOP of small odd-sized integer correctly (PR #168559)

Hongyu Chen via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 18 09:19:50 PST 2025


================
@@ -7678,6 +7678,18 @@ LegalizerHelper::lowerBitCount(MachineInstr &MI) {
     unsigned Size = Ty.getSizeInBits();
     MachineIRBuilder &B = MIRBuilder;
 
+    // Lift small odd-size integer to 8-bit integer.
+    if (Size < 8) {
+      LLT NewTy = LLT::scalar(8);
+      auto ZExt = B.buildZExt(NewTy, SrcReg);
+      auto NewCTPOP = B.buildCTPOP(NewTy, ZExt);
+      Observer.changingInstr(MI);
+      MI.setDesc(TII.get(TargetOpcode::G_TRUNC));
+      MI.getOperand(1).setReg(NewCTPOP.getReg(0));
+      Observer.changedInstr(MI);
+      return Legalized;
+    }
+
     // Count set bits in blocks of 2 bits. Default approach would be
----------------
XChy wrote:

Nice catch. I found that this implementation is identical to `TargetLowering::expandCTPOP` in TargetLowering.cpp. And in TargetLowering.cpp, it bails out on sizes that are not a multiple of 8. I think we should lift all sizes that are not a multiple of 8

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


More information about the llvm-commits mailing list