[llvm] Reject invalid BF encoding when target is next instruction (PR #201533)

Hamza Khan via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 4 02:06:13 PDT 2026


https://github.com/HamzaKodez created https://github.com/llvm/llvm-project/pull/201533

When the BF instruction targets the immediately following label, the encoded branch offset becomes zero, causing LLVM to emit invalid machine code.

Add validation in the fixup_bf_branch path to reject this case and emit an error instead.

Add MC regression test to cover new validation.

Assisted by ChatGPT. Human-verified, debugged, tested and validating by author.

>From 10f270538c4304b822c964ef49cd22963deab8bb Mon Sep 17 00:00:00 2001
From: Hamza Khan <hamza.khan at arm.com>
Date: Tue, 12 May 2026 09:13:13 +0100
Subject: [PATCH] Reject invalid BF encoding when target is next instruction

When the BF instruction targets the immediately following label,
the encoded branch offset becomes zero. Which caused LLVM to emmit
invalid machine code.

Add validation in the fixup_bf_branch path to reject this
case and emit an error instead.

Add MC regression test to cover new validation.

Assisted by ChatGPT. Human-verified, debugged, tested and validating by author.
---
 llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp | 10 +++++++++-
 llvm/test/MC/ARM/bf-invalid-target.s               | 14 ++++++++++++++
 2 files changed, 23 insertions(+), 1 deletion(-)
 create mode 100644 llvm/test/MC/ARM/bf-invalid-target.s

diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp
index ebf58ea054233..81b63660eb0e7 100644
--- a/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp
+++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp
@@ -882,7 +882,15 @@ unsigned ARMAsmBackend::adjustFixupValue(const MCAssembler &Asm,
       Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
       return 0;
     }
-    uint32_t out = (((Value - 4) >> 1) & 0xf) << 23;
+
+    int64_t encoded = (Value - 4) >> 1;
+    if (encoded == 0) {
+      Ctx.reportError(Fixup.getLoc(),
+                      "invalid BF encoding: target must not be the next instruction");
+      return 0;
+    }
+
+    uint32_t out = (encoded & 0xf) << 23;
     return swapHalfWords(out, Endian == llvm::endianness::little);
   }
   case ARM::fixup_bf_target:
diff --git a/llvm/test/MC/ARM/bf-invalid-target.s b/llvm/test/MC/ARM/bf-invalid-target.s
new file mode 100644
index 0000000000000..9b7cd9dccd7be
--- /dev/null
+++ b/llvm/test/MC/ARM/bf-invalid-target.s
@@ -0,0 +1,14 @@
+@ RUN: not llvm-mc -triple arm-none-eabi -mcpu=cortex-m55 -filetype=obj %s -o /dev/null 2>&1 | FileCheck %s
+
+.text
+bf label, __myfunc
+label:
+  b __myfunc
+
+.section .text.foo, "ax", %progbits
+.type __myfunc, %function
+.global __myfunc
+__myfunc:
+  nop
+
+@ CHECK: error: invalid BF encoding: target must not be the next instruction
\ No newline at end of file



More information about the llvm-commits mailing list