[llvm] [RISCV] Fix a correctness issue in optimizeCondBranch. Prevent optimizing compare with x0. NFC (PR #145440)

Philip Reames via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 24 08:02:05 PDT 2025


================
@@ -1449,11 +1449,14 @@ bool RISCVInstrInfo::optimizeCondBranch(MachineInstr &MI) const {
     return Register();
   };
 
-  if (isFromLoadImm(MRI, LHS, C0) && MRI.hasOneUse(LHS.getReg())) {
+  if (isFromLoadImm(MRI, LHS, C0) && LHS.getReg().isVirtual() &&
+      MRI.hasOneUse(LHS.getReg())) {
+    assert(isInt<12>(C0) && "Unexpected immediate");
     // Might be case 1.
-    // Signed integer overflow is UB. (UINT64_MAX is bigger so we don't need
-    // to worry about unsigned overflow here)
-    if (C0 < INT64_MAX)
+    // Don't change 0 to -1 since we can use x0.
+    // For unsigned cases changing -1U to 0 would be incorrect.
+    if (C0 &&
----------------
preames wrote:

Style wise, folding the C0 is non-zero check into the prior if-clause might make the code easier to read in both cases.

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


More information about the llvm-commits mailing list