[llvm] [SPIRV] Fix merge instruction displaced by MachineCSE (PR #202046)

via llvm-commits llvm-commits at lists.llvm.org
Sat Jun 6 08:07:28 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-spir-v

Author: Julian Klappenbach (jklappenbach)

<details>
<summary>Changes</summary>

MachineCSE can common a value into a loop/selection header and place it after
that block's OpLoopMerge, between the merge and its branch terminator. That
violates SPIR-V structured control flow (spirv-val rejects it; drivers hang).

Add SPIRVFixupMergePlacement, run after the machine-SSA opts, which re-seats any
displaced OpLoopMerge/OpSelectionMerge to immediately precede its terminator.
Safe: merges carry only block-label/immediate operands, no SSA deps.

Found lowering a tiled cooperative-matrix GEMM whose loop-invariant tile offsets
are exactly such commoned values. Regression: fixup-merge-placement.mir.

(cherry picked from commit 40fccdd5126b9aa34a8e30d5f0c140a2b8cac04a)

---
*Verified against current `llvm/main`: applies cleanly, the SPIR-V target builds, and the included lit test(s) pass (`llc … | FileCheck`, + `spirv-val` where applicable).*

---
Full diff: https://github.com/llvm/llvm-project/pull/202046.diff


5 Files Affected:

- (modified) llvm/lib/Target/SPIRV/CMakeLists.txt (+1) 
- (modified) llvm/lib/Target/SPIRV/SPIRV.h (+2) 
- (added) llvm/lib/Target/SPIRV/SPIRVFixupMergePlacement.cpp (+120) 
- (modified) llvm/lib/Target/SPIRV/SPIRVTargetMachine.cpp (+6) 
- (added) llvm/test/CodeGen/SPIRV/structurizer/fixup-merge-placement.mir (+79) 


``````````diff
diff --git a/llvm/lib/Target/SPIRV/CMakeLists.txt b/llvm/lib/Target/SPIRV/CMakeLists.txt
index 36ad7f976d6e9..0ebb73a8fe6a2 100644
--- a/llvm/lib/Target/SPIRV/CMakeLists.txt
+++ b/llvm/lib/Target/SPIRV/CMakeLists.txt
@@ -41,6 +41,7 @@ add_llvm_target(SPIRVCodeGen
   SPIRVPreLegalizer.cpp
   SPIRVPreLegalizerCombiner.cpp
   SPIRVPostLegalizer.cpp
+  SPIRVFixupMergePlacement.cpp
   SPIRVPrepareFunctions.cpp
   SPIRVPrepareGlobals.cpp
   SPIRVRegisterBankInfo.cpp
diff --git a/llvm/lib/Target/SPIRV/SPIRV.h b/llvm/lib/Target/SPIRV/SPIRV.h
index 42c4ef149539e..3fecdb77371e4 100644
--- a/llvm/lib/Target/SPIRV/SPIRV.h
+++ b/llvm/lib/Target/SPIRV/SPIRV.h
@@ -32,6 +32,7 @@ FunctionPass *createSPIRVRegularizerPass();
 FunctionPass *createSPIRVPreLegalizerCombiner();
 FunctionPass *createSPIRVPreLegalizerPass();
 FunctionPass *createSPIRVPostLegalizerPass();
+FunctionPass *createSPIRVFixupMergePlacementPass();
 ModulePass *createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM);
 ModulePass *createSPIRVPrepareGlobalsPass();
 ModulePass *createSPIRVCtorDtorLoweringLegacyPass();
@@ -46,6 +47,7 @@ void initializeSPIRVConvergenceRegionAnalysisWrapperPassPass(PassRegistry &);
 void initializeSPIRVPreLegalizerPass(PassRegistry &);
 void initializeSPIRVPreLegalizerCombinerPass(PassRegistry &);
 void initializeSPIRVPostLegalizerPass(PassRegistry &);
+void initializeSPIRVFixupMergePlacementPass(PassRegistry &);
 void initializeSPIRVStructurizerPass(PassRegistry &);
 void initializeSPIRVCBufferAccessLegacyPass(PassRegistry &);
 void initializeSPIRVPushConstantAccessLegacyPass(PassRegistry &);
diff --git a/llvm/lib/Target/SPIRV/SPIRVFixupMergePlacement.cpp b/llvm/lib/Target/SPIRV/SPIRVFixupMergePlacement.cpp
new file mode 100644
index 0000000000000..be17b6e7ecc08
--- /dev/null
+++ b/llvm/lib/Target/SPIRV/SPIRVFixupMergePlacement.cpp
@@ -0,0 +1,120 @@
+//===-- SPIRVFixupMergePlacement.cpp - keep merges before branches -*- C++ -*-//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// SPIR-V structured control flow (SPIR-V spec 2.11) requires that an
+// OpLoopMerge / OpSelectionMerge be the *second-to-last* instruction in its
+// block: it must immediately precede the block's branch terminator. The
+// SPIR-V structurizer (SPIRVStructurizer) inserts the merge intrinsic in
+// exactly that position. The problem is what happens afterwards.
+//
+// The merge survives instruction selection as a real OpLoopMerge /
+// OpSelectionMerge MachineInstr, and *then* the target-independent
+// machine-SSA-optimization passes run over it. MachineCSE in particular will
+// break the invariant: when a redundant computation appears in two successor
+// blocks, MachineCSE commons it and sinks the single surviving copy into their
+// common dominator -- which for a loop/selection header is exactly the block
+// that already holds the merge. MachineCSE inserts the commoned instruction
+// just before that block's terminator (its standard insertion point), i.e.
+// *after* the OpLoopMerge. The header then reads:
+//
+//     OpLoopMerge %merge %continue None
+//     %x = OpIMul ...        ; <-- commoned into the header by MachineCSE
+//     OpBranchConditional %cond %body %merge
+//
+// which spirv-val rejects ("OpLoopMerge must immediately precede ... a branch")
+// and which hangs drivers that consume it assuming valid structured CFG (this
+// was first observed as a real GPU hang lowering a tiled cooperative-matrix
+// GEMM, whose loop-invariant tile offsets are exactly such commoned values).
+//
+// This pass runs after the machine-SSA optimizations and restores the
+// invariant by sinking each block's merge instruction back down to immediately
+// before its branch terminator. That move is always safe: OpLoopMerge and
+// OpSelectionMerge carry only basic-block-label and immediate operands -- they
+// define no register and use no register -- so they have no data dependence on
+// the instructions they move past, and reordering them changes no value.
+//
+//===----------------------------------------------------------------------===//
+
+#include "SPIRV.h"
+#include "SPIRVInstrInfo.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/Support/Debug.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "spirv-fixup-merge-placement"
+
+namespace {
+class SPIRVFixupMergePlacement : public MachineFunctionPass {
+public:
+  static char ID;
+  SPIRVFixupMergePlacement() : MachineFunctionPass(ID) {}
+
+  bool runOnMachineFunction(MachineFunction &MF) override;
+
+  StringRef getPassName() const override {
+    return "SPIRV fixup merge placement";
+  }
+
+  MachineFunctionProperties getRequiredProperties() const override {
+    return MachineFunctionProperties().setIsSSA();
+  }
+};
+} // namespace
+
+static bool isStructuredMerge(const MachineInstr &MI) {
+  unsigned Opc = MI.getOpcode();
+  return Opc == SPIRV::OpLoopMerge || Opc == SPIRV::OpSelectionMerge;
+}
+
+bool SPIRVFixupMergePlacement::runOnMachineFunction(MachineFunction &MF) {
+  bool Changed = false;
+  for (MachineBasicBlock &MBB : MF) {
+    // A structured block carries at most one merge instruction (the
+    // structurizer guarantees this). Find it, if present.
+    MachineInstr *Merge = nullptr;
+    for (MachineInstr &MI : MBB) {
+      if (isStructuredMerge(MI)) {
+        Merge = &MI;
+        break;
+      }
+    }
+    if (!Merge)
+      continue;
+
+    // The merge must sit immediately before the block's branch terminator.
+    MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
+    if (Term == MBB.end())
+      continue; // No explicit terminator (e.g. unreachable) -- nothing to fix.
+
+    // Already second-to-last? Then the invariant holds.
+    if (&*Term == Merge->getNextNode())
+      continue;
+
+    // Otherwise a later pass (MachineCSE) slipped instructions between the
+    // merge and the terminator. Sink the merge down to just before the
+    // terminator, restoring `... <commoned insts> <merge> <branch>`.
+    LLVM_DEBUG(dbgs() << "SPIRVFixupMergePlacement: re-seating merge in "
+                      << MBB.getName() << "\n");
+    Merge->removeFromParent();
+    MBB.insert(Term, Merge);
+    Changed = true;
+  }
+  return Changed;
+}
+
+INITIALIZE_PASS(SPIRVFixupMergePlacement, DEBUG_TYPE,
+                "SPIRV fixup merge placement", false, false)
+
+char SPIRVFixupMergePlacement::ID = 0;
+
+FunctionPass *llvm::createSPIRVFixupMergePlacementPass() {
+  return new SPIRVFixupMergePlacement();
+}
diff --git a/llvm/lib/Target/SPIRV/SPIRVTargetMachine.cpp b/llvm/lib/Target/SPIRV/SPIRVTargetMachine.cpp
index 42e402aa62c27..a700651802111 100644
--- a/llvm/lib/Target/SPIRV/SPIRVTargetMachine.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVTargetMachine.cpp
@@ -69,6 +69,7 @@ extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVTarget() {
   initializeSPIRVRegularizerLegacyPass(PR);
   initializeSPIRVPreLegalizerPass(PR);
   initializeSPIRVPostLegalizerPass(PR);
+  initializeSPIRVFixupMergePlacementPass(PR);
   initializeSPIRVMergeRegionExitTargetsLegacyPass(PR);
   initializeSPIRVEmitIntrinsicsPass(PR);
   initializeSPIRVPrepareFunctionsLegacyPass(PR);
@@ -149,6 +150,11 @@ FunctionPass *SPIRVPassConfig::createTargetRegisterAllocator(bool) {
 // A place to disable passes that may break CFG.
 void SPIRVPassConfig::addMachineSSAOptimization() {
   TargetPassConfig::addMachineSSAOptimization();
+  // MachineCSE (and other SSA-opt passes just added above) can common a value
+  // into a loop/selection header and place it *after* that block's OpLoopMerge /
+  // OpSelectionMerge, violating SPIR-V's "merge immediately precedes the branch"
+  // rule. Re-seat any displaced merge right afterwards, while still in SSA form.
+  addPass(createSPIRVFixupMergePlacementPass());
 }
 
 // Disable passes that break from assuming no virtual registers exist.
diff --git a/llvm/test/CodeGen/SPIRV/structurizer/fixup-merge-placement.mir b/llvm/test/CodeGen/SPIRV/structurizer/fixup-merge-placement.mir
new file mode 100644
index 0000000000000..fc8bb491176df
--- /dev/null
+++ b/llvm/test/CodeGen/SPIRV/structurizer/fixup-merge-placement.mir
@@ -0,0 +1,79 @@
+# RUN: llc -mtriple=spirv-unknown-vulkan1.3-compute -run-pass=spirv-fixup-merge-placement %s -o - | FileCheck %s
+#
+# Unit test for SPIRVFixupMergePlacement. A loop header whose OpLoopMerge has an
+# instruction wedged between it and the block's OpBranchConditional (the shape
+# MachineCSE produces when it commons a value into the header -- see the pass
+# header comment) must be repaired so the merge again immediately precedes the
+# branch. The pass sinks the merge down past the wedged instruction.
+#
+# CHECK-LABEL: bb.1.header:
+# The commoned value stays put; the merge is re-seated immediately before the
+# branch (and nothing separates them).
+# CHECK:      OpIMulS
+# CHECK-NEXT: OpLoopMerge %bb.2, %bb.4, 0
+# CHECK-NEXT: OpBranchConditional {{.*}}%bb.3, %bb.2
+
+--- |
+  target triple = "spirv-unknown-vulkan1.3-compute"
+  define spir_func i32 @f() #0 {
+  entry:
+    br label %header
+  header:
+    br i1 true, label %body, label %merge
+  body:
+    br label %continue
+  continue:
+    br label %header
+  merge:
+    ret i32 0
+  }
+  attributes #0 = { convergent noinline nounwind }
+...
+---
+name:            f
+legalized:       true
+regBankSelected: false
+selected:        true
+tracksRegLiveness: true
+isSSA:           true
+registers:
+  - { id: 0, class: iid }
+  - { id: 1, class: type }
+  - { id: 2, class: type }
+  - { id: 9, class: type }
+  - { id: 10, class: type }
+  - { id: 13, class: iid }
+  - { id: 14, class: iid }
+  - { id: 15, class: iid }
+body:             |
+  bb.0.entry:
+    successors: %bb.1(0x80000000)
+
+    %2:type = OpTypeFunction %1
+    %10:type = OpTypeBool
+    %13:iid = OpConstantTrue %10
+    %14:iid = OpConstantI %1, 0
+    %1:type = OpTypeInt 32, 0
+    %0:iid = OpFunction %1, 2, %2
+    OpBranch %bb.1
+
+  bb.1.header:
+    successors: %bb.3(0x40000000), %bb.2(0x40000000)
+
+    OpLoopMerge %bb.2, %bb.4, 0
+    %15:iid = OpIMulS %1, %14, %14
+    OpBranchConditional %13, %bb.3, %bb.2
+
+  bb.2.merge:
+    OpReturnValue %14
+
+  bb.3.body:
+    successors: %bb.4(0x80000000)
+
+    OpBranch %bb.4
+
+  bb.4.continue:
+    successors: %bb.1(0x80000000)
+
+    OpBranch %bb.1
+...

``````````

</details>


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


More information about the llvm-commits mailing list