[llvm] [RISCV][TII] Add and use new hook to optimize/canonicalize instructions after MachineCopyPropagation (PR #137973)

Alex Bradbury via llvm-commits llvm-commits at lists.llvm.org
Thu May 1 05:59:46 PDT 2025


================
@@ -3850,6 +3865,207 @@ MachineInstr *RISCVInstrInfo::commuteInstructionImpl(MachineInstr &MI,
   return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
 }
 
+bool RISCVInstrInfo::optimizeInstruction(MachineInstr &MI) const {
+  switch (MI.getOpcode()) {
+  default:
+    break;
+  case RISCV::OR:
----------------
asb wrote:

Just to make sure I follow, are you suggesting changing from what I have now:
```cpp
  case RISCV::OR:
  case RISCV::XOR:
    // Normalize:
    // [x]or rd, zero, rs => [x]or rd, rs, zero
    if (MI.getOperand(1).getReg() == RISCV::X0)
      commuteInstruction(MI);
    // [x]or rd, rs, zero => addi rd, rs, 0
    if (MI.getOperand(2).getReg() == RISCV::X0) {
      MI.getOperand(2).ChangeToImmediate(0);
      MI.setDesc(get(RISCV::ADDI));
      return true;
    }
    // xor rd, rs, rs => li rd, 0
    if (MI.getOpcode() == RISCV::XOR &&
        MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
      MI.getOperand(1).setReg(RISCV::X0);
      MI.getOperand(2).ChangeToImmediate(0);
      MI.setDesc(get(RISCV::ADDI));
      return true;
    }
    break;
```

To:
```cpp
  case RISCV::OR:
    // Normalize:
    // or rd, zero, rs => or rd, rs, zero
    if (MI.getOperand(1).getReg() == RISCV::X0)
      commuteInstruction(MI);
    // or rd, rs, zero => addi rd, rs, 0
    if (MI.getOperand(2).getReg() == RISCV::X0) {
      MI.getOperand(2).ChangeToImmediate(0);
      MI.setDesc(get(RISCV::ADDI));
      return true;
    }
    break;
  case RISCV::XOR:
    // Normalize:
    // xor rd, zero, rs => xor rd, rs, zero
    if (MI.getOperand(1).getReg() == RISCV::X0)
      commuteInstruction(MI);
    // xor rd, rs, zero => addi rd, rs, 0
    if (MI.getOperand(2).getReg() == RISCV::X0) {
      MI.getOperand(2).ChangeToImmediate(0);
      MI.setDesc(get(RISCV::ADDI));
      return true;
    }
    // xor rd, rs, rs => li rd, 0
    if (MI.getOpcode() == RISCV::XOR &&
        MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
      MI.getOperand(1).setReg(RISCV::X0);
      MI.getOperand(2).ChangeToImmediate(0);
      MI.setDesc(get(RISCV::ADDI));
      return true;
    }
    break;
```

Happy to switch if you prefer, but at least to my eye it doesn't seem clear cut that this is better than before.

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


More information about the llvm-commits mailing list