[llvm] [BOLT] Add --clone-at-origin option (PR #181003)

Maksim Panchenko via llvm-commits llvm-commits at lists.llvm.org
Wed Feb 11 19:20:21 PST 2026


https://github.com/maksfb updated https://github.com/llvm/llvm-project/pull/181003

>From 0cfbd8d91038a797edd2a94b8a3efbf2a7b70f48 Mon Sep 17 00:00:00 2001
From: Maksim Panchenko <maks at fb.com>
Date: Tue, 10 Feb 2026 10:13:34 -0800
Subject: [PATCH 1/3] [BOLT] Add --clone-at-origin option

Add --clone-at-origin as an alternative to patching function entries.
When enabled, BOLT creates clones at original addresses instead of
inserting trampolines. This is useful when original function is too
small for a trampoline or patching overhead is undesirable.

The clone preserves original code with references updated to point to
relocated functions. Original .eh_frame/.gcc_except_table remain valid.

Debug info changes for the clone will be included in a separate patch.

Future patches will build on top of this clone functionality.
---
 bolt/include/bolt/Core/BinaryFunction.h       |  14 ++-
 .../bolt/Passes/CreateClonesAtOrigin.h        |  38 +++++++
 bolt/include/bolt/Utils/CommandLineOpts.h     |   1 +
 bolt/lib/Core/BinaryFunction.cpp              |   4 +-
 bolt/lib/Passes/CMakeLists.txt                |   1 +
 bolt/lib/Passes/CreateClonesAtOrigin.cpp      |  81 +++++++++++++
 bolt/lib/Passes/PatchEntries.cpp              |   8 ++
 bolt/lib/Rewrite/BinaryPassManager.cpp        |   7 ++
 bolt/lib/Rewrite/RewriteInstance.cpp          |  34 +++++-
 bolt/lib/Utils/CommandLineOpts.cpp            |   7 ++
 .../AArch64/clone-at-origin-secondary-entry.s |  36 ++++++
 bolt/test/runtime/exceptions-clone.cpp        | 107 ++++++++++++++++++
 12 files changed, 334 insertions(+), 4 deletions(-)
 create mode 100644 bolt/include/bolt/Passes/CreateClonesAtOrigin.h
 create mode 100644 bolt/lib/Passes/CreateClonesAtOrigin.cpp
 create mode 100644 bolt/test/AArch64/clone-at-origin-secondary-entry.s
 create mode 100644 bolt/test/runtime/exceptions-clone.cpp

diff --git a/bolt/include/bolt/Core/BinaryFunction.h b/bolt/include/bolt/Core/BinaryFunction.h
index 80375b1167b0c..b1f7634ba899a 100644
--- a/bolt/include/bolt/Core/BinaryFunction.h
+++ b/bolt/include/bolt/Core/BinaryFunction.h
@@ -407,6 +407,10 @@ class BinaryFunction {
   /// All fragments for a parent function.
   FragmentsSetTy Fragments;
 
+  /// True if we created an alias clone at this function's original location
+  /// after relocating optimized version of the function.
+  bool HasCloneAtOrigin{false};
+
   /// The profile data for the number of times the function was executed.
   uint64_t ExecutionCount{COUNT_NO_PROFILE};
 
@@ -869,7 +873,7 @@ class BinaryFunction {
   /// Return relocation associated with a given \p Offset in the function,
   /// or nullptr if no such relocation exists.
   const Relocation *getRelocationAt(uint64_t Offset) const {
-    assert(CurrentState == State::Empty &&
+    assert(!isEmitted() &&
            "Relocations unavailable in the current function state.");
     auto RI = Relocations.find(Offset);
     return (RI == Relocations.end()) ? nullptr : &RI->second;
@@ -880,7 +884,7 @@ class BinaryFunction {
   /// exists.
   const Relocation *getRelocationInRange(uint64_t StartOffset,
                                          uint64_t EndOffset) const {
-    assert(CurrentState == State::Empty &&
+    assert(!isEmitted() &&
            "Relocations unavailable in the current function state.");
     auto RI = Relocations.lower_bound(StartOffset);
     if (RI != Relocations.end() && RI->first < EndOffset)
@@ -1950,6 +1954,12 @@ class BinaryFunction {
   /// Return true if the function is a secondary fragment of another function.
   bool isFragment() const { return IsFragment; }
 
+  /// Return true if this function has a clone at its original location.
+  bool hasCloneAtOrigin() const { return HasCloneAtOrigin; }
+
+  /// Mark that a clone exists at the original location.
+  void setHasCloneAtOrigin() { HasCloneAtOrigin = true; }
+
   /// Returns if this function is a child of \p Other function.
   bool isChildOf(const BinaryFunction &Other) const {
     return ParentFragments.contains(&Other);
diff --git a/bolt/include/bolt/Passes/CreateClonesAtOrigin.h b/bolt/include/bolt/Passes/CreateClonesAtOrigin.h
new file mode 100644
index 0000000000000..2881c1b44640d
--- /dev/null
+++ b/bolt/include/bolt/Passes/CreateClonesAtOrigin.h
@@ -0,0 +1,38 @@
+//===- bolt/Passes/CreateClonesAtOrigin.h -----------------------*- 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Pass for creating clones at origin of functions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef BOLT_PASSES_CREATE_CLONES_AT_ORIGIN_H
+#define BOLT_PASSES_CREATE_CLONES_AT_ORIGIN_H
+
+#include "bolt/Passes/BinaryPasses.h"
+
+namespace llvm {
+namespace bolt {
+
+/// Pass for creating clones at origin of functions.
+///
+/// This pass creates clones at the original function addresses and runs
+/// scanExternalRefs() to update references from clone code to relocated
+/// functions. Unlike patching (which redirects execution from original to
+/// optimized code), cloning keeps the original code executable.
+class CreateClonesAtOrigin : public BinaryFunctionPass {
+public:
+  explicit CreateClonesAtOrigin() : BinaryFunctionPass(false) {}
+
+  const char *getName() const override { return "create-clones-at-origin"; }
+  Error runOnFunctions(BinaryContext &BC) override;
+};
+
+} // namespace bolt
+} // namespace llvm
+
+#endif
diff --git a/bolt/include/bolt/Utils/CommandLineOpts.h b/bolt/include/bolt/Utils/CommandLineOpts.h
index 5c7f1b94315f0..e4e62378f30b3 100644
--- a/bolt/include/bolt/Utils/CommandLineOpts.h
+++ b/bolt/include/bolt/Utils/CommandLineOpts.h
@@ -80,6 +80,7 @@ extern llvm::cl::opt<bool> DiffOnly;
 extern llvm::cl::opt<bool> EnableBAT;
 extern llvm::cl::opt<bool> EqualizeBBCounts;
 extern llvm::cl::opt<bool> ForcePatch;
+extern llvm::cl::opt<bool> CloneAtOrigin;
 extern llvm::cl::opt<bool> RemoveSymtab;
 extern llvm::cl::opt<unsigned> ExecutionCountThreshold;
 extern llvm::cl::opt<HeatmapBlockSizes, false, HeatmapBlockSpecParser>
diff --git a/bolt/lib/Core/BinaryFunction.cpp b/bolt/lib/Core/BinaryFunction.cpp
index dbb58c5c1a97c..ec482c30c161c 100644
--- a/bolt/lib/Core/BinaryFunction.cpp
+++ b/bolt/lib/Core/BinaryFunction.cpp
@@ -104,7 +104,7 @@ JumpTables("jump-tables",
   cl::ZeroOrMore,
   cl::cat(BoltOptCategory));
 
-static cl::opt<bool> NoScan(
+cl::opt<bool> NoScan(
     "no-scan",
     cl::desc(
         "do not scan cold functions for external references (may result in "
@@ -456,6 +456,8 @@ void BinaryFunction::print(raw_ostream &OS, std::string Annotation) {
     OS << "\n  Personality : " << getPersonalityFunction()->getName();
   if (IsFragment)
     OS << "\n  IsFragment  : true";
+  if (HasCloneAtOrigin)
+    OS << "\n  HasCloneAtOrigin : true";
   if (isFolded())
     OS << "\n  FoldedInto  : " << *getFoldedIntoFunction();
   for (BinaryFunction *ParentFragment : ParentFragments)
diff --git a/bolt/lib/Passes/CMakeLists.txt b/bolt/lib/Passes/CMakeLists.txt
index ec012f05cc498..b250b3ae28c64 100644
--- a/bolt/lib/Passes/CMakeLists.txt
+++ b/bolt/lib/Passes/CMakeLists.txt
@@ -6,6 +6,7 @@ add_llvm_library(LLVMBOLTPasses
   BinaryPasses.cpp
   CMOVConversion.cpp
   CacheMetrics.cpp
+  CreateClonesAtOrigin.cpp
   DataflowAnalysis.cpp
   DataflowInfoManager.cpp
   FrameAnalysis.cpp
diff --git a/bolt/lib/Passes/CreateClonesAtOrigin.cpp b/bolt/lib/Passes/CreateClonesAtOrigin.cpp
new file mode 100644
index 0000000000000..96dcacdf27f2b
--- /dev/null
+++ b/bolt/lib/Passes/CreateClonesAtOrigin.cpp
@@ -0,0 +1,81 @@
+//===- bolt/Passes/CreateClonesAtOrigin.cpp -------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the CreateClonesAtOrigin pass that creates clones of
+// functions at their original addresses. Unlike patching (which redirects
+// execution from original to optimized code), cloning keeps the original code
+// executable and updates its references to relocated functions.
+//
+//===----------------------------------------------------------------------===//
+
+#include "bolt/Passes/CreateClonesAtOrigin.h"
+#include "bolt/Utils/CommandLineOpts.h"
+
+namespace opts {
+extern llvm::cl::opt<bool> NoScan;
+extern llvm::cl::opt<bool> UseOldText;
+extern llvm::cl::opt<unsigned> Verbosity;
+} // namespace opts
+
+namespace llvm {
+namespace bolt {
+
+Error CreateClonesAtOrigin::runOnFunctions(BinaryContext &BC) {
+  if (!opts::CloneAtOrigin)
+    return Error::success();
+
+  if (opts::UseOldText) {
+    BC.outs() << "BOLT-INFO: skipping clones at origin with --use-old-text\n";
+    return Error::success();
+  }
+
+  if (opts::Verbosity >= 1)
+    BC.outs() << "BOLT-INFO: creating clones at origin\n";
+
+  unsigned NumClonesCreated = 0;
+
+  // Iterate over input functions.
+  for (BinaryFunction &Function :
+       llvm::make_second_range(BC.getBinaryFunctions())) {
+
+    // Only clone functions that will be emitted (relocated).
+    if (!BC.shouldEmit(Function))
+      continue;
+
+    // Skip if already has a clone at origin.
+    if (Function.hasCloneAtOrigin())
+      continue;
+
+    // Mark the function as having a clone at origin.
+    Function.setHasCloneAtOrigin();
+
+    // Run scanExternalRefs() to update the clone's references to relocated
+    // functions.
+    const bool Success = opts::NoScan || Function.scanExternalRefs();
+    if (!Success) {
+      BC.errs()
+          << "BOLT-ERROR: internal error creating refs for emitted function\n";
+      exit(1);
+    }
+
+    ++NumClonesCreated;
+
+    if (opts::Verbosity >= 2)
+      BC.outs() << "BOLT-INFO: created clone at origin for " << Function
+                << '\n';
+  }
+
+  if (NumClonesCreated > 0)
+    BC.outs() << "BOLT-INFO: created " << NumClonesCreated
+              << " clones at origin\n";
+
+  return Error::success();
+}
+
+} // namespace bolt
+} // namespace llvm
diff --git a/bolt/lib/Passes/PatchEntries.cpp b/bolt/lib/Passes/PatchEntries.cpp
index 1b79c122c5f9b..dcea948d4358d 100644
--- a/bolt/lib/Passes/PatchEntries.cpp
+++ b/bolt/lib/Passes/PatchEntries.cpp
@@ -41,6 +41,10 @@ Error PatchEntries::runOnFunctions(BinaryContext &BC) {
       if (BF.isFolded())
         return false;
 
+      // Skip functions that already have clones at origin.
+      if (BF.hasCloneAtOrigin())
+        return false;
+
       // Patching is always needed if explicitly requested.
       if (BF.needsPatch())
         return true;
@@ -71,6 +75,10 @@ Error PatchEntries::runOnFunctions(BinaryContext &BC) {
     if (!BC.shouldEmit(Function))
       continue;
 
+    // Skip functions that already have clones at origin.
+    if (Function.hasCloneAtOrigin())
+      continue;
+
     // Check if we can skip patching the function.
     if (!opts::ForcePatch && !Function.hasEHRanges() &&
         !Function.needsPatch() && Function.getSize() < PatchThreshold)
diff --git a/bolt/lib/Rewrite/BinaryPassManager.cpp b/bolt/lib/Rewrite/BinaryPassManager.cpp
index 58d24e15cde01..1799f515a62fb 100644
--- a/bolt/lib/Rewrite/BinaryPassManager.cpp
+++ b/bolt/lib/Rewrite/BinaryPassManager.cpp
@@ -12,6 +12,7 @@
 #include "bolt/Passes/AllocCombiner.h"
 #include "bolt/Passes/AsmDump.h"
 #include "bolt/Passes/CMOVConversion.h"
+#include "bolt/Passes/CreateClonesAtOrigin.h"
 #include "bolt/Passes/FixRISCVCallsPass.h"
 #include "bolt/Passes/FixRelaxationPass.h"
 #include "bolt/Passes/FrameOptimizer.h"
@@ -524,6 +525,12 @@ Error BinaryFunctionPassManager::runAllPasses(BinaryContext &BC) {
   // memory profiling data.
   Manager.registerPass(std::make_unique<ReorderData>());
 
+  // Create clones at origin (if --clone-at-origin is specified).
+  // This must run before PatchEntries so that cloned functions are skipped
+  // during patching.
+  if (BC.HasRelocations)
+    Manager.registerPass(std::make_unique<CreateClonesAtOrigin>());
+
   // Patch original function entries
   if (BC.HasRelocations)
     Manager.registerPass(std::make_unique<PatchEntries>());
diff --git a/bolt/lib/Rewrite/RewriteInstance.cpp b/bolt/lib/Rewrite/RewriteInstance.cpp
index 4539b7221cb5f..61faf97af3e1b 100644
--- a/bolt/lib/Rewrite/RewriteInstance.cpp
+++ b/bolt/lib/Rewrite/RewriteInstance.cpp
@@ -2284,6 +2284,12 @@ Error RewriteInstance::readSpecialSections() {
 }
 
 void RewriteInstance::adjustCommandLineOptions() {
+  if (opts::CloneAtOrigin && opts::ForcePatch) {
+    BC->errs() << "BOLT-ERROR: --clone-at-origin is incompatible with "
+                  "--force-patch\n";
+    exit(1);
+  }
+
   if (BC->isAArch64() && !BC->HasRelocations)
     BC->errs() << "BOLT-WARNING: non-relocation mode for AArch64 is not fully "
                   "supported\n";
@@ -5154,6 +5160,23 @@ void RewriteInstance::updateELFSymbolTable(
     return SymbolName;
   };
 
+  // Add a clone symbol at the original address for functions with clone at
+  // origin.
+  auto addCloneSymbol = [&](const ELFSymTy &BaseSym, uint64_t OrigAddr,
+                            uint64_t Size, const BinaryFunction &BF) {
+    ELFSymTy CloneSym = BaseSym;
+    SmallVector<char, 256> Buf;
+    CloneSym.st_name =
+        AddToStrTab(Twine(cantFail(BaseSym.getName(StringSection)))
+                        .concat(".clone.0")
+                        .toStringRef(Buf));
+    CloneSym.st_value = OrigAddr;
+    CloneSym.st_size = Size;
+    CloneSym.st_shndx =
+        getNewSectionIndex(BF.getOriginSection()->getSectionRef().getIndex());
+    Symbols.emplace_back(CloneSym);
+  };
+
   // Add extra symbols for the function.
   //
   // Note that addExtraSymbols() could be called multiple times for the same
@@ -5237,6 +5260,10 @@ void RewriteInstance::updateELFSymbolTable(
       Symbols.emplace_back(DataMarkSym);
       Symbols.emplace_back(CodeMarkSym);
     }
+    // Add clone symbol for function with clone at origin.
+    if (Function.hasCloneAtOrigin())
+      addCloneSymbol(FunctionSymbol, Function.getAddress(), Function.getSize(),
+                     Function);
   };
 
   // For regular (non-dynamic) symbol table, exclude symbols referring
@@ -5368,7 +5395,7 @@ void RewriteInstance::updateELFSymbolTable(
         // Force secondary entry points to have zero size.
         NewSymbol.st_size = 0;
 
-        // Find fragment containing entrypoint
+        // Find fragment containing entry point.
         FunctionLayout::fragment_const_iterator FF = llvm::find_if(
             Function->getLayout().fragments(), [&](const FunctionFragment &FF) {
               uint64_t Lo = FF.getAddress();
@@ -5387,6 +5414,11 @@ void RewriteInstance::updateELFSymbolTable(
 
         NewSymbol.st_shndx =
             Function->getCodeSection(FF->getFragmentNum())->getIndex();
+
+        // Add clone symbol for secondary entry point if function has clone at
+        // origin.
+        if (Function->hasCloneAtOrigin())
+          addCloneSymbol(NewSymbol, Symbol.st_value, 0, *Function);
       } else {
         // Check if the symbol belongs to moved data object and update it.
         BinaryData *BD = opts::ReorderData.empty()
diff --git a/bolt/lib/Utils/CommandLineOpts.cpp b/bolt/lib/Utils/CommandLineOpts.cpp
index b7eb209af8aca..9c8a66901c077 100644
--- a/bolt/lib/Utils/CommandLineOpts.cpp
+++ b/bolt/lib/Utils/CommandLineOpts.cpp
@@ -92,6 +92,13 @@ llvm::cl::opt<bool> ForcePatch(
                    "execution follows only the new/optimized code."),
     llvm::cl::Hidden, llvm::cl::cat(BoltCategory));
 
+llvm::cl::opt<bool> CloneAtOrigin(
+    "clone-at-origin",
+    llvm::cl::desc("create clones of functions at their original addresses "
+                   "instead of patching entry points. The clone code will "
+                   "have its references to relocated functions updated."),
+    llvm::cl::Hidden, llvm::cl::cat(BoltCategory));
+
 cl::opt<bool> RemoveSymtab("remove-symtab", cl::desc("Remove .symtab section"),
                            cl::cat(BoltCategory));
 
diff --git a/bolt/test/AArch64/clone-at-origin-secondary-entry.s b/bolt/test/AArch64/clone-at-origin-secondary-entry.s
new file mode 100644
index 0000000000000..596676d20f29a
--- /dev/null
+++ b/bolt/test/AArch64/clone-at-origin-secondary-entry.s
@@ -0,0 +1,36 @@
+## Test that --clone-at-origin creates clone symbols for secondary entry points.
+
+# REQUIRES: system-linux
+
+# RUN: %clang %cflags -nostdlib %s -o %t.exe -Wl,-q
+# RUN: llvm-bolt %t.exe -o %t.bolt --clone-at-origin
+
+## Get the original alt_entry address.
+# RUN: llvm-nm %t.exe | grep " alt_entry$" | cut -d' ' -f1 > %t.alt_orig
+
+## Verify clone symbols exist for both main function and secondary entry point.
+# RUN: llvm-nm -n %t.bolt | FileCheck %s
+
+# CHECK: main_func.clone.0
+# CHECK: alt_entry.clone.0
+
+## Verify alt_entry clone address matches original.
+# RUN: llvm-nm %t.bolt | grep "alt_entry.clone.0" | cut -d' ' -f1 > %t.alt_clone
+# RUN: diff %t.alt_orig %t.alt_clone
+
+  .text
+  .globl main_func
+  .type main_func, %function
+main_func:
+  nop
+  .type alt_entry, %function
+alt_entry:
+  ret
+  .size main_func, .-main_func
+
+  .globl _start
+  .type _start, %function
+_start:
+  bl main_func
+  ret
+  .size _start, .-_start
diff --git a/bolt/test/runtime/exceptions-clone.cpp b/bolt/test/runtime/exceptions-clone.cpp
new file mode 100644
index 0000000000000..49bfe1d80be1f
--- /dev/null
+++ b/bolt/test/runtime/exceptions-clone.cpp
@@ -0,0 +1,107 @@
+// Test that clones at origin work correctly with C++ exception handling.
+//
+// The test creates two caller functions:
+// - caller_optimized: will be relocated/optimized by BOLT
+// - caller_skipped: will be skipped (not relocated) by BOLT
+//
+// With --no-scan, BOLT won't scan unrelocated code for references, so:
+// - caller_skipped's call to catch_exception remains at original address
+//   (clone)
+// - caller_optimized's call to catch_exception is rewritten to new address
+//
+// This tests that both versions of catch_exception work correctly.
+
+// clang-format off
+
+// REQUIRES: system-linux
+
+// RUN: %clangxx %cxxflags -no-pie -O1 -fno-inline %s -Wl,-q -o %t
+
+// Get the original catch_exception address for later verification.
+// RUN: llvm-nm %t | grep " catch_exception$" | cut -d' ' -f1 > %t.orig_addr
+
+// Run BOLT with clone-at-origin.
+// RUN: llvm-bolt %t -o %t.bolt \
+// RUN:   --skip-funcs=caller_skipped \
+// RUN:   --no-scan \
+// RUN:   --clone-at-origin \
+// RUN:   2>&1 | FileCheck %s --check-prefix=CHECK-BOLT
+
+// CHECK-BOLT: BOLT-INFO: created {{[0-9]+}} clones at origin
+
+// Verify the clone symbol exists in the output binary.
+// RUN: llvm-nm %t.bolt | grep ".clone.0" | FileCheck %s --check-prefix=CHECK-SYM
+
+// CHECK-SYM: .clone.0
+
+// Verify that the clone symbol address matches the original function address.
+// RUN: llvm-nm %t.bolt | grep "catch_exception.clone.0" | cut -d' ' -f1 > %t.clone_addr
+// RUN: diff %t.orig_addr %t.clone_addr
+
+// The relocated function should be at a DIFFERENT address than the original.
+// RUN: llvm-nm %t.bolt | grep " catch_exception$" | cut -d' ' -f1 > %t.bolt_addr
+// RUN: not diff %t.orig_addr %t.bolt_addr
+
+// Verify caller_skipped calls the clone (at original address).
+// RUN: llvm-objdump -d %t.bolt --disassemble-symbols=caller_skipped \
+// RUN:   | FileCheck %s --check-prefix=CHECK-SKIPPED-CALL
+
+// CHECK-SKIPPED-CALL: <caller_skipped>:
+// CHECK-SKIPPED-CALL: jmp{{.*}}<catch_exception.clone.0>
+
+// Verify caller_optimized calls the relocated function (not the clone).
+// RUN: llvm-objdump -d %t.bolt --disassemble-symbols=caller_optimized \
+// RUN:   | FileCheck %s --check-prefix=CHECK-OPTIMIZED-CALL
+
+// CHECK-OPTIMIZED-CALL: <caller_optimized>:
+// CHECK-OPTIMIZED-CALL: jmp{{.*}}<catch_exception>
+
+// Run the bolted binary - both callers should work:
+// - caller_skipped calls original code (clone) at original address
+// - caller_optimized calls relocated code at new address
+// RUN: %t.bolt 2>&1 | FileCheck %s --check-prefix=CHECK-EXEC
+
+// CHECK-EXEC: Testing exception handling with clones
+// CHECK-EXEC: caller_skipped -> catch_exception (original/clone):
+// CHECK-EXEC-NEXT: caught: 42
+// CHECK-EXEC: caller_optimized -> catch_exception (relocated):
+// CHECK-EXEC-NEXT: caught: 42
+// CHECK-EXEC: All exceptions handled correctly
+
+#include <cstdio>
+#include <exception>
+
+// This function will be cloned. It catches an exception.
+// Using extern "C" to avoid name mangling for easier testing.
+extern "C" __attribute__((noinline)) void catch_exception() {
+  try {
+    throw 42;
+  } catch (int e) {
+    printf("caught: %d\n", e);
+  }
+}
+
+// This caller will be SKIPPED by BOLT (not relocated).
+// Its call to catch_exception will remain pointing to the original address.
+// With --no-scan, this call won't be updated, so it calls the clone.
+extern "C" __attribute__((noinline)) void caller_skipped() {
+  printf("caller_skipped -> catch_exception (original/clone):\n");
+  catch_exception();
+}
+
+// This caller will be OPTIMIZED by BOLT (relocated).
+// Its call to catch_exception will be rewritten to the new address.
+extern "C" __attribute__((noinline)) void caller_optimized() {
+  printf("caller_optimized -> catch_exception (relocated):\n");
+  catch_exception();
+}
+
+int main() {
+  printf("Testing exception handling with clones\n");
+
+  caller_skipped();
+  caller_optimized();
+
+  printf("All exceptions handled correctly\n");
+  return 0;
+}

>From 8ee86079c4a624873c6e9fc60775867ecca989ca Mon Sep 17 00:00:00 2001
From: Maksim Panchenko <maks at fb.com>
Date: Tue, 10 Feb 2026 10:13:34 -0800
Subject: [PATCH 2/3] [BOLT] Refactor --clone-at-origin and --use-old-text
 interaction

---
 bolt/lib/Passes/CreateClonesAtOrigin.cpp |  5 -----
 bolt/lib/Rewrite/RewriteInstance.cpp     | 14 ++++++++++++++
 2 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/bolt/lib/Passes/CreateClonesAtOrigin.cpp b/bolt/lib/Passes/CreateClonesAtOrigin.cpp
index 96dcacdf27f2b..c643722a0f163 100644
--- a/bolt/lib/Passes/CreateClonesAtOrigin.cpp
+++ b/bolt/lib/Passes/CreateClonesAtOrigin.cpp
@@ -29,11 +29,6 @@ Error CreateClonesAtOrigin::runOnFunctions(BinaryContext &BC) {
   if (!opts::CloneAtOrigin)
     return Error::success();
 
-  if (opts::UseOldText) {
-    BC.outs() << "BOLT-INFO: skipping clones at origin with --use-old-text\n";
-    return Error::success();
-  }
-
   if (opts::Verbosity >= 1)
     BC.outs() << "BOLT-INFO: creating clones at origin\n";
 
diff --git a/bolt/lib/Rewrite/RewriteInstance.cpp b/bolt/lib/Rewrite/RewriteInstance.cpp
index 61faf97af3e1b..50af877f569a7 100644
--- a/bolt/lib/Rewrite/RewriteInstance.cpp
+++ b/bolt/lib/Rewrite/RewriteInstance.cpp
@@ -2425,6 +2425,20 @@ void RewriteInstance::adjustCommandLineOptions() {
     if (!opts::TerminalTrap.getNumOccurrences())
       opts::TerminalTrap = false;
   }
+
+  if (opts::CloneAtOrigin) {
+    if (opts::ForcePatch) {
+      BC->errs() << "BOLT-ERROR: --clone-at-origin is incompatible with "
+                    "--force-patch\n";
+      exit(1);
+    }
+
+    if (opts::UseOldText) {
+      BC->errs() << "BOLT-ERROR: --clone-at-origin is incompatible with "
+                    "--use-old-text\n";
+      exit(1);
+    }
+  }
 }
 
 namespace {

>From aaa13fba53504ddba86526e1a3c1de7a0c09c0e2 Mon Sep 17 00:00:00 2001
From: Maksim Panchenko <maks at fb.com>
Date: Wed, 11 Feb 2026 19:20:09 -0800
Subject: [PATCH 3/3] fixup! [BOLT] Refactor --clone-at-origin and
 --use-old-text interaction

---
 bolt/lib/Rewrite/RewriteInstance.cpp | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/bolt/lib/Rewrite/RewriteInstance.cpp b/bolt/lib/Rewrite/RewriteInstance.cpp
index 50af877f569a7..a406f968981bf 100644
--- a/bolt/lib/Rewrite/RewriteInstance.cpp
+++ b/bolt/lib/Rewrite/RewriteInstance.cpp
@@ -2284,12 +2284,6 @@ Error RewriteInstance::readSpecialSections() {
 }
 
 void RewriteInstance::adjustCommandLineOptions() {
-  if (opts::CloneAtOrigin && opts::ForcePatch) {
-    BC->errs() << "BOLT-ERROR: --clone-at-origin is incompatible with "
-                  "--force-patch\n";
-    exit(1);
-  }
-
   if (BC->isAArch64() && !BC->HasRelocations)
     BC->errs() << "BOLT-WARNING: non-relocation mode for AArch64 is not fully "
                   "supported\n";



More information about the llvm-commits mailing list