Skip to content
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2ad6cc8
[RISCV][TII] Add and use new hook fo optmize/canonicalize instruction…
asb Apr 30, 2025
d23c66c
Add changes missed in first push
asb Apr 30, 2025
5d00e6f
Fix errors in some patterns and remove PACK/PACKW
asb Apr 30, 2025
3048ba9
Use commuteInstruction helper
asb May 1, 2025
7da3f92
Move optimizeInstructoin to after the preprocessor undefs
asb May 1, 2025
109a5ba
(cherry-pick) [RISCV][NFC] Add missed // clang-format on
asb May 1, 2025
a02dc45
Reformat now issue with clang-format being disabled was fixed
asb May 1, 2025
8e73913
Consistently avoid use of pseudoinstructions in comments for transforms
asb May 1, 2025
1c8715d
Pull optimizeInstruction call outside of loop
asb May 1, 2025
825b1f6
Simplify and/mul* case as suggested in review
asb May 1, 2025
9500cee
Re-order instructions in switch
asb May 1, 2025
bb9e2c1
clang-format
asb May 1, 2025
3f2049f
reorder comment to match code logic
asb May 6, 2025
47ca1a0
generalise sltiu check to any non-zero immediate
asb May 6, 2025
ff42dca
Add sll/srl/sra mv-like case
asb May 6, 2025
dc4b2e5
handle sltiu rd, zero, 0
asb May 6, 2025
c765d58
Add suggested comments for 'normalize' pre-transforms
asb May 6, 2025
3ee7da3
Get rid of redundant newline
asb May 6, 2025
436a5e6
Set Changed=true if optimizeInstruction returned true in call from MCP
asb May 7, 2025
e2a1be0
Cover ADD as well
asb May 7, 2025
44f6605
Rename hook to simplifyInstruction
asb May 7, 2025
c93404a
Merge remote-tracking branch 'origin/main' into 2025q2-riscv-optimize…
asb May 8, 2025
19f4dc1
Add comment to .mir file
asb May 8, 2025
d6f8428
Rename test
asb May 8, 2025
920f408
Merge remote-tracking branch 'origin/main' into 2025q2-riscv-optimize…
asb May 8, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions llvm/include/llvm/CodeGen/TargetInstrInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,16 @@ class TargetInstrInfo : public MCInstrInfo {
return false;
}

/// If possible, converts the instruction to a more 'optimized'/canonical
/// form. Returns true if the instruction was modified.
///
/// This function is only called after register allocation. The MI will be
/// modified in place. This is called by passes such as
/// MachineCopyPropagation, where their mutation of the MI operands may
/// expose opportunities to convert the instruction to a simpler form (e.g.
/// a load of 0).
virtual bool optimizeInstruction(MachineInstr &MI) const { return false; }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name is way too general for a very narrowly applied optimization. Can't this just go in a separate post-RA pass

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@asb Can you say a bit about why this needs to be in MCP? As opposed to just after MCP? Does doing this in the process of copy propagation expose additional copies? (Not implausible, but do you actually see this?)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem this patch is solving is probably not unique to RISC-V. Having the ability for other targets to do this type of canonicalization seems like a good idea.

Are we suggesting a separate target independent pass using this hook? Or a target specific pass?

Copy link
Contributor Author

@asb asb May 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Craig's comment captures well the reason why I looked to do this in MCP. it seems like a transformation that's generally useful to other targets, and by adding and using a TII hook it's easy to reuse if we find any other target-specific or generic passes that might benefit (though as I say in the summary, all of the instances of these instructions I can find come from MCP). It could be done in another pass, but it felt like a simple change to have MCP "check its own work" might be cleaner than having yet another pass.

This specific change doesn't induce additional copy propagation, but looking at the generated diffs there are cases where you would expect copy propagation should be able to run again. I nod to this in the PR description above, but as this change alone is an improvement on before I leave that to a followup.

e.g. this snippet from imagick:

@@ -2753,11 +2753,11 @@
        bnez    s11, .LBB0_353
 .LBB0_357:                              #   in Loop: Header=BB0_310 Depth=1
        li      a2, 0
-       srliw   a5, zero, 31
-       slli    a3, zero, 33
+       li      a5, 0
+       li      a3, 0
        slli    a5, a5, 15
        srli    a3, a3, 56
-       and     a4, zero, a1
+       li      a4, 0
        bgeu    s8, a3, .LBB0_354

The slli/srli should be removable (canonicalised to loadimm of 0, and then redundant with the previous li). I haven't yet stepped through to see if this is a matter of doing another iteration in MCP or if there's some other barrier that prevents current MCP from handling the case.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is something that can constant fold, but didn't earlier? At this point I would hope that would have been cleaned long before this

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This specific example does look weird. From offline conversation, I'd thought this was mostly catching cleanup after tail duplication, but this looks like some kind of loop structure?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see the cause of confusion - this is indeed cleaning up after tail duplication - the use of the TailDuplicator utility class (llvm/lib/CodeGen/TailDuplicator.cpp) in MachineBlockPlacement.

Here is a roughly reduced example representing the above snippet:

; ModuleID = '<stdin>'
source_filename = "<stdin>"
target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128"
target triple = "riscv64-unknown-linux-gnu"

define i64 @ham(i1 %arg, i32 %arg1) {
bb:
  br label %bb2

bb2:                                              ; preds = %bb15, %bb
  %and = and i32 0, 8388607
  br i1 %arg, label %bb4, label %bb3

bb3:                                              ; preds = %bb2
  br label %bb4

bb4:                                              ; preds = %bb3, %bb2
  %phi = phi i32 [ %arg1, %bb3 ], [ 0, %bb2 ]
  %lshr = lshr i32 %phi, 16
  %and5 = and i32 %lshr, 32768
  %lshr6 = lshr i32 %phi, 23
  %and7 = and i32 %lshr6, 255
  %and8 = and i32 %phi, 8388607
  %icmp = icmp ult i32 %and7, 113
  br i1 %icmp, label %bb9, label %bb10

bb9:                                              ; preds = %bb4
  %or = or i32 %and8, %and5
  %trunc = trunc i32 %or to i16
  br label %bb15

bb10:                                             ; preds = %bb4
  br i1 %arg, label %bb11, label %bb13

bb11:                                             ; preds = %bb10
  %trunc12 = trunc i32 %and5 to i16
  br label %bb15

bb13:                                             ; preds = %bb10
  %trunc14 = trunc i32 %and8 to i16
  br label %bb15

bb15:                                             ; preds = %bb13, %bb11, %bb9
  %phi16 = phi i16 [ %trunc, %bb9 ], [ %trunc12, %bb11 ], [ %trunc14, %bb13 ]
  %trunc17 = trunc i16 %phi16 to i8
  store i8 %trunc17, ptr null, align 1
  br label %bb2
}

If you run that through llc -O3 you'll see the tail duplication happening as part of MachineBlockPlacement and then MCP runs.

So you have a block:

bb.4.bb4:
; predecessors: %bb.3, %bb.2
  successors: %bb.5(0x40000000), %bb.6(0x40000000); %bb.5(50.00%), %bb.6(50.00%)
  liveins: $x10, $x11, $x12, $x13, $x15
  renamable $x14 = SRLIW renamable $x15, 31
  renamable $x16 = SLLI renamable $x15, 33
  renamable $x14 = SLLI killed renamable $x14, 15
  renamable $x16 = SRLI killed renamable $x16, 56
  renamable $x15 = AND killed renamable $x15, renamable $x12
  BLTU renamable $x13, killed renamable $x16, %bb.6

After tail duplication is applied in MBP you get:

bb.2:
; predecessors: %bb.1
  successors: %bb.5(0x40000000), %bb.6(0x40000000); %bb.5(50.00%), %bb.6(50.00%)
  liveins: $x10, $x11, $x12, $x13
  $x15 = ADDI $x0, 0
  renamable $x14 = SRLIW renamable $x15, 31
  renamable $x16 = SLLI renamable $x15, 33
  renamable $x14 = SLLI killed renamable $x14, 15
  renamable $x16 = SRLI killed renamable $x16, 56
  renamable $x15 = AND killed renamable $x15, renamable $x12
  BGEU renamable $x13, killed renamable $x16, %bb.5
  PseudoBR %bb.6

bb.3.bb3:
; predecessors: %bb.1
  successors: %bb.5(0x40000000), %bb.6(0x40000000); %bb.5(50.00%), %bb.6(50.00%)
  liveins: $x10, $x11, $x12, $x13
  $x15 = ADDI renamable $x11, 0
  renamable $x14 = SRLIW renamable $x15, 31
  renamable $x16 = SLLI renamable $x15, 33
  renamable $x14 = SLLI killed renamable $x14, 15
  renamable $x16 = SRLI killed renamable $x16, 56
  renamable $x15 = AND killed renamable $x15, renamable $x12
  BGEU renamable $x13, killed renamable $x16, %bb.5

Where obviously bb.2 can be cleaned up which MCP does to a certain extent.


/// A pair composed of a register and a sub-register index.
/// Used to give some type checking when modeling Reg:SubReg.
struct RegSubRegPair {
Expand Down
5 changes: 5 additions & 0 deletions llvm/lib/CodeGen/MachineCopyPropagation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,11 @@ void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
++NumCopyForwards;
Changed = true;
}
// Attempt to canonicalize/optimize the instruction now its arguments have
// been mutated.
if (TII->optimizeInstruction(MI)) {
LLVM_DEBUG(dbgs() << "MCP: After optimizeInstruction: " << MI);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to set Changed = true here or is guaranteed it was already set earlier?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. It's not clear to me that Changed = true will always have been set, so I've added an explicit assignment so it's obvious.

}
}

void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
Expand Down
225 changes: 225 additions & 0 deletions llvm/lib/Target/RISCV/RISCVInstrInfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2344,6 +2344,21 @@ static unsigned getSHXADDShiftAmount(unsigned Opc) {
}
}

// Returns the shift amount from a SHXADD.UW instruction. Returns 0 if the
// instruction is not a SHXADD.UW.
static unsigned getSHXADDUWShiftAmount(unsigned Opc) {
switch (Opc) {
default:
return 0;
case RISCV::SH1ADD_UW:
return 1;
case RISCV::SH2ADD_UW:
return 2;
case RISCV::SH3ADD_UW:
return 3;
}
}

// Look for opportunities to combine (sh3add Z, (add X, (slli Y, 5))) into
// (sh3add (sh2add Y, Z), X).
static bool getSHXADDPatterns(const MachineInstr &Root,
Expand Down Expand Up @@ -3734,6 +3749,7 @@ bool RISCVInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
CASE_VFMA_CHANGE_OPCODE_LMULS_MF4(OLDOP, NEWOP, VFPR16, E16) \
CASE_VFMA_CHANGE_OPCODE_LMULS_MF2(OLDOP, NEWOP, VFPR32, E32) \
CASE_VFMA_CHANGE_OPCODE_LMULS_M1(OLDOP, NEWOP, VFPR64, E64)
// clang-format on

MachineInstr *RISCVInstrInfo::commuteInstructionImpl(MachineInstr &MI,
bool NewMI,
Expand Down Expand Up @@ -3872,6 +3888,215 @@ MachineInstr *RISCVInstrInfo::commuteInstructionImpl(MachineInstr &MI,
#undef CASE_VFMA_OPCODE_VV
#undef CASE_VFMA_SPLATS

bool RISCVInstrInfo::optimizeInstruction(MachineInstr &MI) const {
switch (MI.getOpcode()) {
default:
break;
case RISCV::OR:
case RISCV::XOR:
// Normalize (so we hit the next if clause).
// [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 => addi rd, zero, 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;
case RISCV::ORI:
case RISCV::XORI:
// [x]ori rd, zero, N => addi rd, zero, N
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::SUB:
// sub rd, rs, zero => addi rd, rs, 0
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does add rd, rs, zero never show up or we just aren't converting it to ADDI?

Copy link
Contributor Author

@asb asb May 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does show up, but we do have a a CompressPat that produces c.mv for either case. So there's no real difference if C is enabled, and I've been running my script on build directories that have C enabled.

But there's no reason not to handle ADD here, and in the case of a target without the C extension it at least means you'll get a canonical mv in such cases which is nicer to read in disassembly if nothing else. I've gone ahead and added it and a test.

if (MI.getOperand(2).getReg() == RISCV::X0) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::SUBW:
// subw rd, rs, zero => addiw rd, rs, 0
if (MI.getOperand(2).getReg() == RISCV::X0) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDIW));
return true;
}
break;
case RISCV::ADDW:
// Normalize (so we hit the next if clause).
// addw rd, zero, rs => addw rd, rs, zero
if (MI.getOperand(1).getReg() == RISCV::X0)
commuteInstruction(MI);
// addw rd, rs, zero => addiw rd, rs, 0
if (MI.getOperand(2).getReg() == RISCV::X0) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDIW));
return true;
}
break;
case RISCV::SH1ADD:
case RISCV::SH1ADD_UW:
case RISCV::SH2ADD:
case RISCV::SH2ADD_UW:
case RISCV::SH3ADD:
case RISCV::SH3ADD_UW:
// shNadd[.uw] rd, zero, rs => addi rd, rs, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.removeOperand(1);
MI.addOperand(MachineOperand::CreateImm(0));
MI.setDesc(get(RISCV::ADDI));
return true;
}
// shNadd[.uw] rd, rs, zero => slli[.uw] rd, rs, N
if (MI.getOperand(2).getReg() == RISCV::X0) {
MI.removeOperand(2);
unsigned Opc = MI.getOpcode();
if (Opc == RISCV::SH1ADD_UW || Opc == RISCV::SH2ADD_UW ||
Opc == RISCV::SH3ADD_UW) {
MI.addOperand(MachineOperand::CreateImm(getSHXADDUWShiftAmount(Opc)));
MI.setDesc(get(RISCV::SLLI_UW));
return true;
}
MI.addOperand(MachineOperand::CreateImm(getSHXADDShiftAmount(Opc)));
MI.setDesc(get(RISCV::SLLI));
return true;
}
break;
case RISCV::AND:
case RISCV::MUL:
case RISCV::MULH:
case RISCV::MULHSU:
case RISCV::MULHU:
case RISCV::MULW:
// and rd, zero, rs => addi rd, zero, 0
// mul* rd, zero, rs => addi rd, zero, 0
// and rd, rs, zero => addi rd, zero, 0
// mul* rd, rs, zero => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0 ||
MI.getOperand(2).getReg() == RISCV::X0) {
MI.getOperand(1).setReg(RISCV::X0);
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::ANDI:
// andi rd, zero, C => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.getOperand(2).setImm(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::SLL:
case RISCV::SRL:
case RISCV::SRA:
// shift rd, zero, rs => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
// shift 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::SLLW:
case RISCV::SRLW:
case RISCV::SRAW:
// shiftw rd, zero, rs => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::SLLI:
case RISCV::SRLI:
case RISCV::SRAI:
case RISCV::SLLIW:
case RISCV::SRLIW:
case RISCV::SRAIW:
case RISCV::SLLI_UW:
// shiftimm rd, zero, N => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.getOperand(2).setImm(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::SLTU:
case RISCV::ADD_UW:
// sltu rd, zero, zero => addi rd, zero, 0
// add.uw rd, zero, zero => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0 &&
MI.getOperand(2).getReg() == RISCV::X0) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
// add.uw rd, zero, rs => addi rd, rs, 0
if (MI.getOpcode() == RISCV::ADD_UW &&
MI.getOperand(1).getReg() == RISCV::X0) {
MI.removeOperand(1);
MI.addOperand(MachineOperand::CreateImm(0));
MI.setDesc(get(RISCV::ADDI));
}
break;
case RISCV::SLTIU:
// sltiu rd, zero, NZC => addi rd, zero, 1
// sltiu rd, zero, 0 => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.getOperand(2).setImm(MI.getOperand(2).getImm() != 0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::SEXT_H:
case RISCV::SEXT_B:
case RISCV::ZEXT_H_RV32:
case RISCV::ZEXT_H_RV64:
// sext.[hb] rd, zero => addi rd, zero, 0
// zext.h rd, zero => addi rd, zero, 0
if (MI.getOperand(1).getReg() == RISCV::X0) {
MI.addOperand(MachineOperand::CreateImm(0));
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
case RISCV::MIN:
case RISCV::MINU:
case RISCV::MAX:
case RISCV::MAXU:
// min|max rd, rs, rs => addi rd, rs, 0
if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
MI.getOperand(2).ChangeToImmediate(0);
MI.setDesc(get(RISCV::ADDI));
return true;
}
break;
}
return false;
}

// clang-format off
#define CASE_WIDEOP_OPCODE_COMMON(OP, LMUL) \
RISCV::PseudoV##OP##_##LMUL##_TIED
Expand Down
2 changes: 2 additions & 0 deletions llvm/lib/Target/RISCV/RISCVInstrInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,8 @@ class RISCVInstrInfo : public RISCVGenInstrInfo {
unsigned OpIdx1,
unsigned OpIdx2) const override;

bool optimizeInstruction(MachineInstr &MI) const override;

MachineInstr *convertToThreeAddress(MachineInstr &MI, LiveVariables *LV,
LiveIntervals *LIS) const override;

Expand Down
Loading