[llvm-branch-commits] [llvm] X86: Fix optimizeCompareInstr crash on a compare from an undef register (PR #216540)

Matt Arsenault via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Sat Aug 15 23:54:36 PDT 2026


https://github.com/arsenm created https://github.com/llvm/llvm-project/pull/216540

getVRegDef returns null for undef sources, so the assert would fire.
Found by AI while working on other stuff.

Co-authored-by: Claude (Opus 4.8) <noreply at anthropic.com>

>From 1d1a003aa536e027b958bc7705862c86cf6f794f Mon Sep 17 00:00:00 2001
From: Matt Arsenault <Matthew.Arsenault at amd.com>
Date: Sat, 15 Aug 2026 23:48:54 +0200
Subject: [PATCH] X86: Fix optimizeCompareInstr crash on a compare from an
 undef register

getVRegDef returns null for undef sources, so the assert would fire.
Found by AI while working on other stuff.

Co-authored-by: Claude (Opus 4.8) <noreply at anthropic.com>
---
 llvm/lib/Target/X86/X86InstrInfo.cpp          |  3 ++-
 .../CodeGen/X86/optimize-compare-undef.mir    | 23 +++++++++++++++++++
 2 files changed, 25 insertions(+), 1 deletion(-)
 create mode 100644 llvm/test/CodeGen/X86/optimize-compare-undef.mir

diff --git a/llvm/lib/Target/X86/X86InstrInfo.cpp b/llvm/lib/Target/X86/X86InstrInfo.cpp
index 2087f2bfc9c88..c2beff2ec524c 100644
--- a/llvm/lib/Target/X86/X86InstrInfo.cpp
+++ b/llvm/lib/Target/X86/X86InstrInfo.cpp
@@ -5476,7 +5476,8 @@ bool X86InstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
   if (SrcReg2.isPhysical())
     return false;
   MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg);
-  assert(SrcRegDef && "Must have a definition (SSA)");
+  if (!SrcRegDef)
+    return false;
 
   MachineInstr *MI = nullptr;
   MachineInstr *Sub = nullptr;
diff --git a/llvm/test/CodeGen/X86/optimize-compare-undef.mir b/llvm/test/CodeGen/X86/optimize-compare-undef.mir
new file mode 100644
index 0000000000000..a19cf60d24606
--- /dev/null
+++ b/llvm/test/CodeGen/X86/optimize-compare-undef.mir
@@ -0,0 +1,23 @@
+# RUN: llc -mtriple=x86_64-- -run-pass=peephole-opt -o - %s | FileCheck %s
+# A compare whose source is an undef register with no def must not crash the
+# compare-optimization while it looks for an earlier flags-defining instruction
+# to reuse.
+
+---
+name: undef_cmp
+tracksRegLiveness: true
+body: |
+  bb.0:
+    ; CHECK-LABEL: name: undef_cmp
+    ; CHECK: TEST32rr undef %{{[0-9]+}}:gr32, undef %{{[0-9]+}}:gr32, implicit-def $eflags
+    successors: %bb.1, %bb.2
+    TEST32rr undef %0:gr32, undef %0:gr32, implicit-def $eflags
+    JCC_1 %bb.1, 4, implicit $eflags
+    JMP_1 %bb.2
+
+  bb.1:
+    RET64
+
+  bb.2:
+    RET64
+...



More information about the llvm-branch-commits mailing list