diff --git a/llvm/lib/Target/RISCV/RISCVMakeCompressible.cpp b/llvm/lib/Target/RISCV/RISCVMakeCompressible.cpp --- a/llvm/lib/Target/RISCV/RISCVMakeCompressible.cpp +++ b/llvm/lib/Target/RISCV/RISCVMakeCompressible.cpp @@ -293,8 +293,16 @@ assert((isCompressibleLoad(MI) || isCompressibleStore(MI)) && "Unsupported instruction for this optimization."); + int SkipN = 0; + + // Skip the first (value) operand to a store instruction (except if the store + // offset is zero) in order to avoid an incorrect transformation. + // e.g. sd a0, 808(a0) to addi a2, a0, 768; sd a2, 40(a2) + if (isCompressibleStore(MI) && OldRegImm.Imm != 0) + SkipN = 1; + // Update registers - for (MachineOperand &MO : MI.operands()) + for (MachineOperand &MO : drop_begin(MI.operands(), SkipN)) if (MO.isReg() && MO.getReg() == OldRegImm.Reg) { // Do not update operands that define the old register. // diff --git a/llvm/test/CodeGen/RISCV/make-compressible-for-store-address.mir b/llvm/test/CodeGen/RISCV/make-compressible-for-store-address.mir --- a/llvm/test/CodeGen/RISCV/make-compressible-for-store-address.mir +++ b/llvm/test/CodeGen/RISCV/make-compressible-for-store-address.mir @@ -33,7 +33,7 @@ ; CHECK-NEXT: renamable $x11 = ADDI $x0, 1 ; CHECK-NEXT: $x12 = ADDI $x10, 768 ; CHECK-NEXT: SD killed renamable $x11, $x12, 32 :: (store (s64) into %ir.1) - ; CHECK-NEXT: SD $x12, $x12, 40 :: (store (s64) into %ir.2) + ; CHECK-NEXT: SD renamable $x10, $x12, 40 :: (store (s64) into %ir.2) ; CHECK-NEXT: renamable $x11 = ADDI $x0, 2 ; CHECK-NEXT: SD killed renamable $x11, killed $x12, 48 :: (store (s64) into %ir.3) ; CHECK-NEXT: PseudoRET