https://github.com/weliveindetail updated 
https://github.com/llvm/llvm-project/pull/231516

From 0c419fe352f9c1186e6e503137d68e44d7a6ed41 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 10:16:59 +0100
Subject: [PATCH 01/10] Squash and rebase after runCodeGenPipeline() refactor

---
 clang/test/CodeGen/codegen-plugins-thinlto.c | 21 +++++++++++
 lld/test/ELF/lto/pre-codegen-plugin.ll       | 32 ++++++++++++++++
 llvm/include/llvm/LTO/Config.h               |  9 +++--
 llvm/include/llvm/LTO/LTO.h                  |  7 ++++
 llvm/lib/LTO/LTO.cpp                         | 21 +++++++++++
 llvm/lib/LTO/LTOBackend.cpp                  | 39 ++++++++++++++------
 llvm/test/Feature/codegen-plugin.ll          | 10 +++++
 7 files changed, 124 insertions(+), 15 deletions(-)
 create mode 100644 clang/test/CodeGen/codegen-plugins-thinlto.c
 create mode 100644 lld/test/ELF/lto/pre-codegen-plugin.ll

diff --git a/clang/test/CodeGen/codegen-plugins-thinlto.c 
b/clang/test/CodeGen/codegen-plugins-thinlto.c
new file mode 100644
index 00000000000000..9f5fae5c1c65b4
--- /dev/null
+++ b/clang/test/CodeGen/codegen-plugins-thinlto.c
@@ -0,0 +1,21 @@
+// REQUIRES: plugins, llvm-examples
+// UNSUPPORTED: target={{.*windows.*}}
+// Plugins are currently broken on AIX, at least in the CI.
+// XFAIL: target={{.*}}-aix{{.*}}
+
+// RUN: %clang_cc1 -O2 -flto=thin -emit-llvm-bc %s -o %t.o
+// RUN: llvm-lto -thinlto -o %t %t.o
+// RUN: %clang_cc1 -O2 -x ir %t.o -fthinlto-index=%t.thinlto.bc -S -o - 
-fpass-plugin=%llvmshlibdir/Bye%pluginext 2>&1 | FileCheck %s 
--check-prefix=CHECK-INACTIVE
+// RUN: %clang_cc1 -O2 -x ir %t.o -fthinlto-index=%t.thinlto.bc -S -o - 
-fpass-plugin=%llvmshlibdir/Bye%pluginext -mllvm -last-words | FileCheck %s 
--check-prefix=CHECK-ACTIVE
+// RUN: %clang_cc1 -O2 -x ir %t.o -fthinlto-index=%t.thinlto.bc -emit-llvm -o 
- -fpass-plugin=%llvmshlibdir/Bye%pluginext -mllvm -last-words | FileCheck %s 
--check-prefix=CHECK-LLVM
+// RUN: not %clang_cc1 -O2 -x ir %t.o -fthinlto-index=%t.thinlto.bc -emit-obj 
-o - -fpass-plugin=%llvmshlibdir/Bye%pluginext -mllvm -last-words 2>&1 | 
FileCheck %s --check-prefix=CHECK-ERR
+
+// CHECK-INACTIVE-NOT: Bye
+// CHECK-INACTIVE: f:
+// CHECK-ACTIVE: CodeGen Bye
+// CHECK-LLVM: define{{.*}} i32 @f
+// CHECK-ERR: error: last words unsupported for binary output
+
+int f(int x) {
+  return x;
+}
diff --git a/lld/test/ELF/lto/pre-codegen-plugin.ll 
b/lld/test/ELF/lto/pre-codegen-plugin.ll
new file mode 100644
index 00000000000000..a1fc31d52424f4
--- /dev/null
+++ b/lld/test/ELF/lto/pre-codegen-plugin.ll
@@ -0,0 +1,32 @@
+; REQUIRES: x86, plugins, examples
+; UNSUPPORTED: target={{.*windows.*}}
+; Plugins are currently broken on AIX, at least in the CI.
+; XFAIL: target={{.*}}-aix{{.*}}
+
+; RUN: opt %s -o %t.o
+; RUN: ld.lld -shared --lto-emit-asm -%loadnewpmbye %t.o -o %t.inactive 2>&1 | 
count 0
+; RUN: FileCheck %s --check-prefix=INACTIVE < %t.inactive.lto.s
+; RUN: ld.lld -shared --lto-emit-asm -%loadnewpmbye -mllvm=%loadbye 
-mllvm=-last-words %t.o -o %t.active
+; RUN: FileCheck %s --check-prefix=ACTIVE < %t.active.lto.s
+; RUN: not ld.lld -shared -%loadnewpmbye -mllvm=%loadbye -mllvm=-last-words 
%t.o -o %t.err 2>&1 | FileCheck %s --check-prefix=ERR
+; RUN: ld.lld -shared --lto-emit-asm --lto-partitions=2 -%loadnewpmbye 
-mllvm=%loadbye -mllvm=-last-words %t.o -o %t.parallel
+; RUN: FileCheck %s --check-prefix=PARALLEL0 < %t.parallel.lto.s
+; RUN: FileCheck %s --check-prefix=PARALLEL1 < %t.parallel.lto.1.s
+
+;; Errors from loading plugins are reported by the linker.
+; RUN: not ld.lld -shared --load-pass-plugin=%t.dir/nonexistent.so %t.o -o 
/dev/null 2>&1 | FileCheck %s --check-prefix=LOADERR
+
+; INACTIVE-NOT: Bye
+; INACTIVE: f:
+; ACTIVE: CodeGen Bye
+; ERR: error: last words unsupported for binary output
+; PARALLEL0: CodeGen Bye
+; PARALLEL1: CodeGen Bye
+; LOADERR: error: Could not load library {{.*}}nonexistent.so
+
+target datalayout = 
"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i32 @f(i32 %x) {
+  ret i32 %x
+}
diff --git a/llvm/include/llvm/LTO/Config.h b/llvm/include/llvm/LTO/Config.h
index f3b7e8ccf0f930..bb4e41a28e32cc 100644
--- a/llvm/include/llvm/LTO/Config.h
+++ b/llvm/include/llvm/LTO/Config.h
@@ -55,11 +55,12 @@ struct Config {
   TargetOptions Options;
   std::vector<std::string> MAttrs;
   std::vector<std::string> MllvmArgs;
-  // LTO will register both lists of plugins, but
-  // if an LTO client has already loaded a set of plugins,
-  // they should register them via LoadedPassPlugins.
-  // LoadedPassPlugins is currently used by distributed thin-lto.
+  // Pass-plugins already loaded by the client. LTO does not take ownership, so
+  // they must outlive the lto::LTO object.
   std::vector<llvm::PassPlugin *> LoadedPassPlugins;
+  // Plugins that are passed by filename are loaded in lto::LTO::run(). Clients
+  // that call lto::backend() or lto::thinBackend() directly must use
+  // LoadedPassPlugins.
   std::vector<std::string> PassPluginFilenames;
   std::function<void(PassBuilder &)> PassBuilderCallback;
   std::optional<Reloc::Model> RelocModel = Reloc::PIC_;
diff --git a/llvm/include/llvm/LTO/LTO.h b/llvm/include/llvm/LTO/LTO.h
index cea66f99b99bb0..68c8c51afd7833 100644
--- a/llvm/include/llvm/LTO/LTO.h
+++ b/llvm/include/llvm/LTO/LTO.h
@@ -26,6 +26,7 @@
 #include "llvm/IR/ModuleSummaryIndex.h"
 #include "llvm/LTO/Config.h"
 #include "llvm/Object/IRSymtab.h"
+#include "llvm/Plugins/PassPlugin.h"
 #include "llvm/Support/Caching.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/StringSaver.h"
@@ -669,6 +670,12 @@ class LLVM_ABI LTO {
   // Setup optimization remarks according to the provided configuration.
   Error setupOptimizationRemarks();
 
+  // Pass-plugins that we load from Conf.PassPluginFilenames.
+  SmallVector<std::unique_ptr<PassPlugin>, 0> PassPlugins;
+
+  // Load pass-plugins from file once.
+  Error loadPassPlugins();
+
   // LibFuncs that were implemented in bitcode but were not extracted
   // from their libraries. Such functions cannot safely be called, since
   // they have lost their opportunity to be defined.
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index a2ba9384899aa6..c36e5daac2cd21 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -1313,11 +1313,32 @@ Error LTO::checkPartiallySplit() {
   return Error::success();
 }
 
+Error LTO::loadPassPlugins() {
+  if (Conf.PassPluginFilenames.empty())
+    return Error::success();
+  assert(PassPlugins.empty() && "Pass-plugins must be loaded only once");
+
+  // Load plugins from file and append them to the list of client loaded ones.
+  for (const std::string &PluginFN : Conf.PassPluginFilenames) {
+    Expected<PassPlugin> Plugin = PassPlugin::load(PluginFN);
+    if (!Plugin)
+      return Plugin.takeError();
+    PassPlugins.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
+    Conf.LoadedPassPlugins.push_back(PassPlugins.back().get());
+  }
+
+  Conf.PassPluginFilenames.clear();
+  return Error::success();
+}
+
 Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
   // Call the base class cleanup() explicitly since run() may be invoked on a
   // derived LTO object.
   llvm::scope_exit CleanUp([this]() { LTO::cleanup(); });
 
+  if (Error Err = loadPassPlugins())
+    return Err;
+
   // Compute "dead" symbols, we don't want to import/export these!
   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
   DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index f544da3117e70a..537b8006f65e55 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -200,23 +200,30 @@ Error Config::addSaveTemps(std::string OutputFileName, 
bool UseInputModulePath,
 #include "llvm/Support/Extension.def"
 #undef HANDLE_EXTENSION
 
+// Obtain dynamic pass-plugin infos for the given config in registration order
+static SmallVector<PassPluginLibraryInfo, 0>
+getPassPlugins(const Config &Conf) {
+  // lto::LTO loads plugins requested by file name before running backends
+  assert(Conf.PassPluginFilenames.empty() &&
+         "Pass-plugins must be loaded before running LTO backends");
+  SmallVector<PassPluginLibraryInfo, 0> Plugins;
+  for (const PassPlugin *Plugin : Conf.LoadedPassPlugins)
+    Plugins.push_back(Plugin->getInfo());
+  return Plugins;
+}
+
+// Call pass builder registration callbacks for all pass-plugins
 static void RegisterPassPlugins(const Config &Conf, PassBuilder &PB) {
+  // Static built-in plugins
 #define HANDLE_EXTENSION(Ext)                                                  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
 #undef HANDLE_EXTENSION
 
-  // Load requested pass plugins and let them register pass builder callbacks
-  for (auto &PluginFN : Conf.PassPluginFilenames) {
-    auto PassPlugin = PassPlugin::load(PluginFN);
-    if (!PassPlugin)
-      reportFatalUsageError(PassPlugin.takeError());
-    PassPlugin->registerPassBuilderCallbacks(PB);
-  }
-
-  // Register already loaded plugins
-  for (auto *LoadedPlugin : Conf.LoadedPassPlugins)
-    LoadedPlugin->registerPassBuilderCallbacks(PB);
+  // Dynamic plugins
+  for (const PassPluginLibraryInfo &Plugin : getPassPlugins(Conf))
+    if (Plugin.RegisterPassBuilderCallbacks)
+      Plugin.RegisterPassBuilderCallbacks(PB);
 }
 
 static std::unique_ptr<TargetMachine>
@@ -483,6 +490,16 @@ static void codegen(const Config &Conf, TargetMachine *TM,
   std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
   TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
 
+  // Allow plugins to handle or even take over code generation entirely.
+  for (const PassPluginLibraryInfo &Plugin : getPassPlugins(Conf)) {
+    if (Plugin.PreCodeGenCallback &&
+        Plugin.PreCodeGenCallback(Mod, *TM, Conf.CGFileType, *Stream->OS)) {
+      if (Error Err = Stream->commit())
+        reportFatalUsageError(std::move(Err));
+      return;
+    }
+  }
+
   const ModuleSummaryIndex *MSI =
       !isEmptyModule(Mod) ? &CombinedIndex : nullptr;
   if (runCodeGenPipeline(*TM, Mod, *Stream->OS,
diff --git a/llvm/test/Feature/codegen-plugin.ll 
b/llvm/test/Feature/codegen-plugin.ll
index 571c7e348520e9..bdbca8723c3afb 100644
--- a/llvm/test/Feature/codegen-plugin.ll
+++ b/llvm/test/Feature/codegen-plugin.ll
@@ -2,6 +2,15 @@
 ; RUN: llc < %s %loadnewpmbye | FileCheck %s --check-prefix=CHECK-ASM
 ; RUN: llc < %s %loadnewpmbye -plugin-arg=Bye,-last-words | FileCheck %s 
--check-prefix=CHECK-ACTIVE
 ; RUN: not llc < %s %loadnewpmbye -plugin-arg=Bye,-last-words -filetype=obj 
2>&1 | FileCheck %s --check-prefix=CHECK-ERR
+
+; LTO tools do not support -plugin-arg yet, so load Bye early to register its 
options
+; RUN: llvm-as %s -o %t.bc
+; RUN: llvm-lto2 run %t.bc -o %t.inactive -r %t.bc,somefunk,plx -r 
%t.bc,junk,plx -filetype=asm %loadnewpmbye
+; RUN: FileCheck %s --check-prefix=CHECK-ASM < %t.inactive.0
+; RUN: llvm-lto2 run %t.bc -o %t.active -r %t.bc,somefunk,plx -r 
%t.bc,junk,plx -filetype=asm %loadbye %loadnewpmbye -last-words
+; RUN: FileCheck %s --check-prefix=CHECK-ACTIVE < %t.active.0
+; RUN: not llvm-lto2 run %t.bc -o %t.err -r %t.bc,somefunk,plx -r 
%t.bc,junk,plx -filetype=obj %loadbye %loadnewpmbye -last-words 2>&1 | 
FileCheck %s --check-prefix=CHECK-LTO2-ERR
+
 ; REQUIRES: plugins, examples
 ; UNSUPPORTED: target={{.*windows.*}}
 ; Plugins are currently broken on AIX, at least in the CI.
@@ -9,6 +18,7 @@
 ; CHECK-ASM: somefunk:
 ; CHECK-ACTIVE: CodeGen Bye
 ; CHECK-ERR: error: last words unsupported for binary output
+; CHECK-LTO2-ERR: last words unsupported for binary output
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"

From aae08af20aac2579973778a8def651cf62d867ed Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 11:20:53 +0100
Subject: [PATCH 02/10] Forward declare PassPlugin and remove the header from
 LTO.h

---
 llvm/include/llvm/LTO/LTO.h | 2 +-
 llvm/lib/LTO/LTO.cpp        | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/include/llvm/LTO/LTO.h b/llvm/include/llvm/LTO/LTO.h
index 68c8c51afd7833..785c5dd208a70f 100644
--- a/llvm/include/llvm/LTO/LTO.h
+++ b/llvm/include/llvm/LTO/LTO.h
@@ -26,7 +26,6 @@
 #include "llvm/IR/ModuleSummaryIndex.h"
 #include "llvm/LTO/Config.h"
 #include "llvm/Object/IRSymtab.h"
-#include "llvm/Plugins/PassPlugin.h"
 #include "llvm/Support/Caching.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/StringSaver.h"
@@ -42,6 +41,7 @@ class IRMover;
 class LLVMContext;
 class MemoryBufferRef;
 class Module;
+class PassPlugin;
 class raw_pwrite_stream;
 class ToolOutputFile;
 
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index c36e5daac2cd21..3ec225a584aa77 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -38,6 +38,7 @@
 #include "llvm/Linker/IRMover.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Object/IRObjectFile.h"
+#include "llvm/Plugins/PassPlugin.h"
 #include "llvm/Support/Caching.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"

From 1c1149666646eb4be37bf7cc595e50762c1b7f55 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 11:14:20 +0100
Subject: [PATCH 03/10] Make loadPassPlugins() idempotent when a load fails

It can now be called multiple times and/or from several places. Upon failure 
none of the listed plugins is registered.
---
 llvm/include/llvm/LTO/LTO.h |  2 +-
 llvm/lib/LTO/LTO.cpp        | 14 ++++++++++----
 2 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/llvm/include/llvm/LTO/LTO.h b/llvm/include/llvm/LTO/LTO.h
index 785c5dd208a70f..486c2c35de6c00 100644
--- a/llvm/include/llvm/LTO/LTO.h
+++ b/llvm/include/llvm/LTO/LTO.h
@@ -673,7 +673,7 @@ class LLVM_ABI LTO {
   // Pass-plugins that we load from Conf.PassPluginFilenames.
   SmallVector<std::unique_ptr<PassPlugin>, 0> PassPlugins;
 
-  // Load pass-plugins from file once.
+  // Load pass-plugins from Conf.PassPluginFilenames.
   Error loadPassPlugins();
 
   // LibFuncs that were implemented in bitcode but were not extracted
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index 3ec225a584aa77..0afe4a7207f0be 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -1315,17 +1315,23 @@ Error LTO::checkPartiallySplit() {
 }
 
 Error LTO::loadPassPlugins() {
+  // Filenames are cleared on success, so repeated calls are no-ops.
   if (Conf.PassPluginFilenames.empty())
     return Error::success();
-  assert(PassPlugins.empty() && "Pass-plugins must be loaded only once");
 
-  // Load plugins from file and append them to the list of client loaded ones.
+  // Load plugins from file. Failures leave them all unregistered.
+  SmallVector<std::unique_ptr<PassPlugin>, 0> Loaded;
   for (const std::string &PluginFN : Conf.PassPluginFilenames) {
     Expected<PassPlugin> Plugin = PassPlugin::load(PluginFN);
     if (!Plugin)
       return Plugin.takeError();
-    PassPlugins.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
-    Conf.LoadedPassPlugins.push_back(PassPlugins.back().get());
+    Loaded.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
+  }
+
+  // Append them to the list of client loaded ones.
+  for (std::unique_ptr<PassPlugin> &Plugin : Loaded) {
+    Conf.LoadedPassPlugins.push_back(Plugin.get());
+    PassPlugins.push_back(std::move(Plugin));
   }
 
   Conf.PassPluginFilenames.clear();

From 172c3884cee0e22da2bfe0140fadf06effa6d224 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 11:26:01 +0100
Subject: [PATCH 04/10] Rename loadPassPlugins() -> setupPassPlugins() to
 indicate relation to Conf

The prefix is used similarly for the other private helper 
setupOptimizationRemarks()
---
 llvm/include/llvm/LTO/LTO.h | 6 +++---
 llvm/lib/LTO/LTO.cpp        | 4 ++--
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/llvm/include/llvm/LTO/LTO.h b/llvm/include/llvm/LTO/LTO.h
index 486c2c35de6c00..29c13e0fdbdcc1 100644
--- a/llvm/include/llvm/LTO/LTO.h
+++ b/llvm/include/llvm/LTO/LTO.h
@@ -670,11 +670,11 @@ class LLVM_ABI LTO {
   // Setup optimization remarks according to the provided configuration.
   Error setupOptimizationRemarks();
 
-  // Pass-plugins that we load from Conf.PassPluginFilenames.
+  // Pass-plugins that we loaded from the provided configuration.
   SmallVector<std::unique_ptr<PassPlugin>, 0> PassPlugins;
 
-  // Load pass-plugins from Conf.PassPluginFilenames.
-  Error loadPassPlugins();
+  // Load pass-plugins from the provided configuration.
+  Error setupPassPlugins();
 
   // LibFuncs that were implemented in bitcode but were not extracted
   // from their libraries. Such functions cannot safely be called, since
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index 0afe4a7207f0be..b304f2b68be1b6 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -1314,7 +1314,7 @@ Error LTO::checkPartiallySplit() {
   return Error::success();
 }
 
-Error LTO::loadPassPlugins() {
+Error LTO::setupPassPlugins() {
   // Filenames are cleared on success, so repeated calls are no-ops.
   if (Conf.PassPluginFilenames.empty())
     return Error::success();
@@ -1343,7 +1343,7 @@ Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
   // derived LTO object.
   llvm::scope_exit CleanUp([this]() { LTO::cleanup(); });
 
-  if (Error Err = loadPassPlugins())
+  if (Error Err = setupPassPlugins())
     return Err;
 
   // Compute "dead" symbols, we don't want to import/export these!

From 6cfaee5249de307aff996efd0158efde6d631f2d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 11:38:41 +0100
Subject: [PATCH 05/10] Register plugins passed by filename before
 client-loaded ones again

This matches the ordering before my initial patch
---
 llvm/lib/LTO/LTO.cpp | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index b304f2b68be1b6..4af8c040f5bc9a 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -1328,11 +1328,14 @@ Error LTO::setupPassPlugins() {
     Loaded.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
   }
 
-  // Append them to the list of client loaded ones.
+  // Register them ahead of the client loaded ones.
+  SmallVector<PassPlugin *> FromFiles;
   for (std::unique_ptr<PassPlugin> &Plugin : Loaded) {
-    Conf.LoadedPassPlugins.push_back(Plugin.get());
+    FromFiles.push_back(Plugin.get());
     PassPlugins.push_back(std::move(Plugin));
   }
+  Conf.LoadedPassPlugins.insert(Conf.LoadedPassPlugins.begin(),
+                                FromFiles.begin(), FromFiles.end());
 
   Conf.PassPluginFilenames.clear();
   return Error::success();

From ff61802fdcd190a0851612db7abc6e45ee536ffe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 12:19:00 +0100
Subject: [PATCH 06/10] Switch getPassPlugins() back to return PassPlugin
 pointers

---
 llvm/lib/LTO/LTOBackend.cpp | 23 +++++++++--------------
 1 file changed, 9 insertions(+), 14 deletions(-)

diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 537b8006f65e55..1b17cd0a782383 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -200,16 +200,12 @@ Error Config::addSaveTemps(std::string OutputFileName, 
bool UseInputModulePath,
 #include "llvm/Support/Extension.def"
 #undef HANDLE_EXTENSION
 
-// Obtain dynamic pass-plugin infos for the given config in registration order
-static SmallVector<PassPluginLibraryInfo, 0>
-getPassPlugins(const Config &Conf) {
-  // lto::LTO loads plugins requested by file name before running backends
+static ArrayRef<PassPlugin *> getPassPlugins(const Config &Conf) {
+  // lto::LTO::run() loaded plugins requested by file. Direct callers must pass
+  // them pre-loaded.
   assert(Conf.PassPluginFilenames.empty() &&
          "Pass-plugins must be loaded before running LTO backends");
-  SmallVector<PassPluginLibraryInfo, 0> Plugins;
-  for (const PassPlugin *Plugin : Conf.LoadedPassPlugins)
-    Plugins.push_back(Plugin->getInfo());
-  return Plugins;
+  return Conf.LoadedPassPlugins;
 }
 
 // Call pass builder registration callbacks for all pass-plugins
@@ -221,9 +217,8 @@ static void RegisterPassPlugins(const Config &Conf, 
PassBuilder &PB) {
 #undef HANDLE_EXTENSION
 
   // Dynamic plugins
-  for (const PassPluginLibraryInfo &Plugin : getPassPlugins(Conf))
-    if (Plugin.RegisterPassBuilderCallbacks)
-      Plugin.RegisterPassBuilderCallbacks(PB);
+  for (const PassPlugin *Plugin : getPassPlugins(Conf))
+    Plugin->registerPassBuilderCallbacks(PB);
 }
 
 static std::unique_ptr<TargetMachine>
@@ -491,9 +486,9 @@ static void codegen(const Config &Conf, TargetMachine *TM,
   TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
 
   // Allow plugins to handle or even take over code generation entirely.
-  for (const PassPluginLibraryInfo &Plugin : getPassPlugins(Conf)) {
-    if (Plugin.PreCodeGenCallback &&
-        Plugin.PreCodeGenCallback(Mod, *TM, Conf.CGFileType, *Stream->OS)) {
+  for (const PassPlugin *Plugin : getPassPlugins(Conf)) {
+    if (Plugin->invokePreCodeGenCallback(Mod, *TM, Conf.CGFileType,
+                                         *Stream->OS)) {
       if (Error Err = Stream->commit())
         reportFatalUsageError(std::move(Err));
       return;

From f9403abd7bf0ce528003f07b1b73c561087add99 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 12:32:56 +0100
Subject: [PATCH 07/10] Mention lto::opt() as the 3rd entry-point in
 lto::Config comment

---
 llvm/include/llvm/LTO/Config.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/include/llvm/LTO/Config.h b/llvm/include/llvm/LTO/Config.h
index bb4e41a28e32cc..fe00eeec0eab84 100644
--- a/llvm/include/llvm/LTO/Config.h
+++ b/llvm/include/llvm/LTO/Config.h
@@ -59,8 +59,8 @@ struct Config {
   // they must outlive the lto::LTO object.
   std::vector<llvm::PassPlugin *> LoadedPassPlugins;
   // Plugins that are passed by filename are loaded in lto::LTO::run(). Clients
-  // that call lto::backend() or lto::thinBackend() directly must use
-  // LoadedPassPlugins.
+  // that call lto::backend(), lto::thinBackend() or lto::opt() directly must
+  // use LoadedPassPlugins.
   std::vector<std::string> PassPluginFilenames;
   std::function<void(PassBuilder &)> PassBuilderCallback;
   std::optional<Reloc::Model> RelocModel = Reloc::PIC_;

From 509c6dfb204401a7bacc878167a8478e3cad3a8f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 17:24:27 +0100
Subject: [PATCH 08/10] Move codegen()'s plugin loop above the DWO block

This avoids both, a stray .dwo file and a needless directory creation, in case 
the plugin take over codegen. It matches the behavior in Clang.
---
 llvm/lib/LTO/LTOBackend.cpp | 29 +++++++++++++++--------------
 1 file changed, 15 insertions(+), 14 deletions(-)

diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 1b17cd0a782383..0fb7f415bcce65 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -456,28 +456,14 @@ static void codegen(const Config &Conf, TargetMachine *TM,
                                /*EmbedCmdline*/ false,
                                /*CmdArgs*/ std::vector<uint8_t>());
 
-  std::unique_ptr<ToolOutputFile> DwoOut;
   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
   if (!Conf.DwoDir.empty()) {
-    std::error_code EC;
-    if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
-      report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
-                         ": " + EC.message());
-
     DwoFile = Conf.DwoDir;
     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
     TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
   } else
     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
 
-  if (!DwoFile.empty()) {
-    std::error_code EC;
-    DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
-    if (EC)
-      report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
-                         EC.message());
-  }
-
   Expected<std::unique_ptr<CachedFileStream>> StreamOrErr =
       AddStream(Task, Mod.getModuleIdentifier());
   if (Error Err = StreamOrErr.takeError())
@@ -495,6 +481,21 @@ static void codegen(const Config &Conf, TargetMachine *TM,
     }
   }
 
+  // Only create the DWO output once we know the built-in pipeline runs.
+  std::unique_ptr<ToolOutputFile> DwoOut;
+  if (!DwoFile.empty()) {
+    if (!Conf.DwoDir.empty())
+      if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
+        report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
+                           ": " + EC.message());
+
+    std::error_code EC;
+    DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
+    if (EC)
+      report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
+                         EC.message());
+  }
+
   const ModuleSummaryIndex *MSI =
       !isEmptyModule(Mod) ? &CombinedIndex : nullptr;
   if (runCodeGenPipeline(*TM, Mod, *Stream->OS,

From 8541f64ae55cd9d9dcc76ccca13eb779d30d7709 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 17:32:18 +0100
Subject: [PATCH 09/10] Add concurrency notes in the plugin interface header

---
 llvm/include/llvm/Plugins/PassPlugin.h | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/llvm/include/llvm/Plugins/PassPlugin.h 
b/llvm/include/llvm/Plugins/PassPlugin.h
index deb6e7d0a4cfbb..70e5dc2953e0c4 100644
--- a/llvm/include/llvm/Plugins/PassPlugin.h
+++ b/llvm/include/llvm/Plugins/PassPlugin.h
@@ -42,7 +42,9 @@ extern "C" {
 /// This struct defines the core interface for pass plugins and is supposed to
 /// be filled out by plugin implementors. Unused function pointers can be set 
to
 /// nullptr. LLVM-side users of a plugin are expected to use the \c PassPlugin
-/// class below to interface with it.
+/// class below to interface with it. Hosts may invoke callbacks concurrently,
+/// e.g. for parallel ThinLTO backends, so plugins must guard any state they
+/// share between invocations.
 struct PassPluginLibraryInfo {
   /// The API version understood by this plugin, usually \c
   /// LLVM_PLUGIN_API_VERSION
@@ -60,7 +62,8 @@ struct PassPluginLibraryInfo {
   /// Callback called before running the back-end passes on the module. The
   /// callback can generate code itself by writing the expected output to OS 
and
   /// returning true to prevent the default pipeline and further plugin
-  /// callbacks from running.
+  /// callbacks from running. Failures should be reported through the module's
+  /// context and return false, as exiting from a worker thread is unsafe.
   bool (*PreCodeGenCallback)(Module &, TargetMachine &, CodeGenFileType,
                              raw_pwrite_stream &OS) = nullptr;
 

From b62faa16117f3abc777c0a5f95b28a4dc67802b6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= <[email protected]>
Date: Tue, 10 Nov 2026 17:39:02 +0100
Subject: [PATCH 10/10] Resort to report_fatal_error since lld installs no
 fatal error handler

See my previous attempt in 
https://github.com/llvm/llvm-project/pull/231470#issuecomment-6146786792
---
 llvm/lib/LTO/LTOBackend.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 0fb7f415bcce65..b3e4d19f8184d9 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -476,7 +476,7 @@ static void codegen(const Config &Conf, TargetMachine *TM,
     if (Plugin->invokePreCodeGenCallback(Mod, *TM, Conf.CGFileType,
                                          *Stream->OS)) {
       if (Error Err = Stream->commit())
-        reportFatalUsageError(std::move(Err));
+        report_fatal_error(std::move(Err));
       return;
     }
   }

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to