[llvm] [X86] Reimplement bundle alignment mode (PR #175830)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Sun Jun 14 19:27:09 PDT 2026


================
@@ -463,9 +471,55 @@ void X86_MC::emitInstruction(MCObjectStreamer &S, const MCInst &Inst,
   Backend.emitInstructionEnd(S, Inst);
 }
 
+/// If the upcoming instruction is inside the bundle lock, do nothing so that
+/// the ObjectStreamer emits the instruction to the current fragment. If not, it
+/// creates a new BA to group bundled fragments.
+void X86AsmBackend::emitInstructionBeginBundle(MCObjectStreamer &OS) {
+  assert(Asm->isBundlingEnabled());
+
+  if (OS.getCurrentSectionOnly()->isBundleLocked()) {
+    OS.getCurrentFragment()->setAllowAutoPadding(true);
+    return;
+  }
+  PendingBA = OS.newSpecialFragment<MCBoundaryAlignFragment>(
+      Align(Asm->getBundleAlignSize()), STI);
+  // We can set LastFragment now, before the instruction is emitted, as bundling
+  // emits one fragment per instruction. Deferring setLastFragment to
+  // post-emitInstruction would risk capturing a fragment that a subsequent
+  // emitCodeAlignment repurposes in-place to FT_Align, corrupting the BA's
+  // boundary range.
+  PendingBA->setLastFragment(OS.getCurrentFragment());
+
+  OS.getCurrentFragment()->setAllowAutoPadding(true);
+}
+
+/// If the just-emitted instruction is inside the bundle lock, check the current
+/// fragment is non-zero to ensure the instruction is placed as expected. If it
+/// is not locked, finalize pending BA Fragment. emitBundleUnlock will close the
+/// fragment and start a new empty fragment.
+void X86AsmBackend::emitInstructionEndBundle(MCObjectStreamer &OS) {
+  assert(Asm->isBundlingEnabled());
+
+  MCFragment *CF = OS.getCurrentFragment();
+
+  if (OS.getCurrentSectionOnly()->isBundleLocked()) {
+    // We're still inside the lock, do not close the current fragment with BA.
+    return;
+  }
+  assert(PendingBA && "MCBoundaryAlignFragment is expected for every "
+                      "instruction if it is not bundle-locked");
+
+  PendingBA = nullptr;
+
+  CF->getParent()->ensureMinAlignment(Align(Asm->getBundleAlignSize()));
+}
+
 /// Insert BoundaryAlignFragment before instructions to align branches.
 void X86AsmBackend::emitInstructionBegin(MCObjectStreamer &OS,
-                                         const MCInst &Inst, const MCSubtargetInfo &STI) {
+                                         const MCInst &Inst,
+                                         const MCSubtargetInfo &STI) {
+  if (Asm->isBundlingEnabled())
----------------
MaskRay wrote:

This early return silently breaks -x86-branches-within-32B-boundaries, the kind of corner case  https://discourse.llvm.org/t/rfc-lightweight-fault-isolation-lfi-target-for-x86-64/90774/6?u=maskray  warns about. It should be hard error perhaps in the clang driver

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


More information about the llvm-commits mailing list