[llvm] [Peephole] Check instructions from CopyMIs are still COPY (PR #69511)

via llvm-commits llvm-commits at lists.llvm.org
Wed Oct 18 13:24:13 PDT 2023


https://github.com/weiguozhi created https://github.com/llvm/llvm-project/pull/69511

Function foldRedundantCopy records COPY instructions in CopyMIs and uses it later. But other optimizations may delete or modify it. So before using it we should check if the extracted instruction is existing and still a COPY instruction.

>From f477b08422de94b3c7569d7fa70513edf06695b9 Mon Sep 17 00:00:00 2001
From: Guozhi Wei <carrot at google.com>
Date: Wed, 18 Oct 2023 20:18:24 +0000
Subject: [PATCH] [Peephole] Check instructions from CopyMIs are still COPY

Function foldRedundantCopy records COPY instructions in CopyMIs and uses
it later. But other optimizations may delete or modify it. So before
using it we should check if the extracted instruction is existing and
still a COPY instruction.
---
 llvm/lib/CodeGen/PeepholeOptimizer.cpp |  4 +++-
 llvm/test/CodeGen/X86/peephole-copy.ll | 20 ++++++++++++++++++++
 2 files changed, 23 insertions(+), 1 deletion(-)
 create mode 100644 llvm/test/CodeGen/X86/peephole-copy.ll

diff --git a/llvm/lib/CodeGen/PeepholeOptimizer.cpp b/llvm/lib/CodeGen/PeepholeOptimizer.cpp
index f413ca5b04f48cf..09ae2680f5516ba 100644
--- a/llvm/lib/CodeGen/PeepholeOptimizer.cpp
+++ b/llvm/lib/CodeGen/PeepholeOptimizer.cpp
@@ -1445,7 +1445,9 @@ bool PeepholeOptimizer::foldRedundantCopy(
   }
 
   MachineInstr *PrevCopy = CopyMIs.find(SrcPair)->second;
-  if (!LocalMIs.count(PrevCopy))
+  // A COPY instruction can be deleted or changed by other optimizations.
+  // Check if the previous COPY instruction is existing and still a COPY.
+  if (!LocalMIs.count(PrevCopy) || !PrevCopy->isCopy())
     return false;
 
   assert(SrcSubReg == PrevCopy->getOperand(1).getSubReg() &&
diff --git a/llvm/test/CodeGen/X86/peephole-copy.ll b/llvm/test/CodeGen/X86/peephole-copy.ll
new file mode 100644
index 000000000000000..60f25a3bc7feee4
--- /dev/null
+++ b/llvm/test/CodeGen/X86/peephole-copy.ll
@@ -0,0 +1,20 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 3
+; RUN: llc < %s -mtriple=i686-- | FileCheck %s
+
+; In peephole optimization the modified COPY instruction should not cause
+; compiler failure.
+
+define dso_local void @c() {
+; CHECK-LABEL: c:
+; CHECK:       # %bb.0: # %entry
+; CHECK-NEXT:    movl $512, %eax # imm = 0x200
+; CHECK-NEXT:    #APP
+; CHECK-NEXT:    #NO_APP
+; CHECK-NEXT:    #APP
+; CHECK-NEXT:    #NO_APP
+; CHECK-NEXT:    retl
+entry:
+  tail call void asm sideeffect "", "q,~{dirflag},~{fpsr},~{flags}"(i32 512)
+  tail call void asm sideeffect "", "q,~{dirflag},~{fpsr},~{flags}"(i32 512)
+  ret void
+}



More information about the llvm-commits mailing list