[llvm] [RISCV] Support getJumpTableIndex (PR #224197)

Piyou Chen via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 18 00:52:26 PDT 2026


================
@@ -1817,6 +1817,82 @@ bool RISCVInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
   }
 }
 
+static bool isJumpTableLoad(const MachineInstr &MI) {
+  return any_of(MI.memoperands(), [](const MachineMemOperand *MMO) {
+    const PseudoSourceValue *PSV = MMO->getPseudoValue();
+    return PSV && PSV->isJumpTable();
+  });
+}
+
+/// Walk back from \p Reg through a jump-table address computation and return
+/// the index of the table it reads, or -1 if \p Reg is not part of one.
+static int getJumpTableIndexFromReg(const MachineRegisterInfo &MRI,
+                                    Register Reg, unsigned Depth) {
+  // Set the limit for the recursive search depth.
+  constexpr unsigned MaxDepth = 6;
+  if (Depth > MaxDepth)
+    return -1;
+
+  if (!Reg.isVirtual())
+    return -1;
+
+  const MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
+  if (!MI)
+    return -1;
+
+  // MI has jump table operand, return it.
+  for (const MachineOperand &MO : MI->operands())
+    if (MO.isJTI())
+      return MO.getIndex();
+
+  // Handle intermediate instructions when resolving to the JumpTableIndex.
+  switch (MI->getOpcode()) {
+  case RISCV::ADD:
+  case RISCV::ADDI:
+  case RISCV::SLLI:
----------------
BeMg wrote:

```
// One of reduced case
// clang --target=riscv64 -march=rv64gc -S -O3
extern void use(int);

void sink_through_jt(unsigned char *p) {
    unsigned char *ip = p + 1;
    for (;;) {
        unsigned char op = *ip;
        unsigned char *ipn = ip + 1;
        int x = *(int*)ipn;
        int v = x + 7;
        switch (op) {
            case 1: { // m
                use(v);
                break;
            }
            case 2: { // other
                use(55);
                use(0);
                break;
            }
            case 3: use(101); break;
            case 4: use(102); break;
            case 5: use(103); break;
            case 6: use(104); break;
            case 7: use(105); break;
            case 8: use(106); break;
            case 9: use(107); break;
            case 10: use(108); break;
            case 11: use(109); break;
            case 12: use(110); break;
            case 13: use(111); break;
            default: use(100); break;
        }
        ip = ip + 1;
    }
}
```

And stop before machine-sink 

```
...
    %10:gpr = SLLI %7, 2
    %12:gpr = ADD %11, killed %10
    %13:gprjalrnonx7 = LW killed %12, 0 :: (load (s32) from jump-table)
    PseudoBRIND killed %13, 0
...
```

I'm collecting the dependencies starting from PseudoBRIND.

Does the SLLI won't show up on the path back to an instruction like `%11:gpr = PseudoMovAddr target-flags(riscv-hi) %jump-table.0, target-flags(riscv-lo) %jump-table.0`?


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


More information about the llvm-commits mailing list