https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/224023

>From 01ac4ab3f780e1dc6bf16ff64ab12f5bb07e4c6f Mon Sep 17 00:00:00 2001
From: anutosh491 <[email protected]>
Date: Wed, 16 Sep 2026 19:26:29 +0530
Subject: [PATCH] [clang][lld] Dispatch registered linkers through ToolSession

---
 clang/include/clang/Driver/Job.h              | 14 +++++
 clang/lib/Driver/Job.cpp                      | 21 +++++++
 clang/test/Driver/in-process-link.c           | 55 +++++++++++++++++++
 clang/tools/driver/driver.cpp                 | 22 ++++++++
 lld/tools/lld/lld.cpp                         | 14 +++--
 .../tools/llvm-driver/passthrough-lld.test    |  3 +
 6 files changed, 124 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/Driver/in-process-link.c

diff --git a/clang/include/clang/Driver/Job.h b/clang/include/clang/Driver/Job.h
index 5ac3d2bae84bb7..50aa19c31d21b7 100644
--- a/clang/include/clang/Driver/Job.h
+++ b/clang/include/clang/Driver/Job.h
@@ -24,6 +24,10 @@
 #include <utility>
 #include <vector>
 
+namespace llvm {
+class ToolContext;
+}
+
 namespace clang {
 namespace driver {
 
@@ -151,6 +155,10 @@ class Command {
   /// Information on executable run provided by OS.
   mutable std::optional<llvm::sys::ProcessStatistics> ProcStat;
 
+  /// Non-owning host context used to invoke this command without spawning a
+  /// process.
+  const llvm::ToolContext *InProcessToolContext = nullptr;
+
   /// The bound architecture for this command (e.g. "arm64", "gfx90a").
   std::string BoundArchStr;
 
@@ -238,6 +246,12 @@ class Command {
 
   void replaceExecutable(const char *Exe) { Executable = Exe; }
 
+  /// Execute this command through a tool registered with the host session.
+  void setInProcessToolContext(const llvm::ToolContext &Context) {
+    InProcessToolContext = &Context;
+    InProcess = true;
+  }
+
   const char *getExecutable() const { return Executable; }
 
   const llvm::opt::ArgStringList &getArguments() const { return Arguments; }
diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp
index 7ceaae0860b2fe..e42ef0d60bc886 100644
--- a/clang/lib/Driver/Job.cpp
+++ b/clang/lib/Driver/Job.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/CrashRecoveryContext.h"
+#include "llvm/Support/Driver.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/IOSandbox.h"
 #include "llvm/Support/Path.h"
@@ -205,6 +206,10 @@ rewriteIncludes(const llvm::ArrayRef<const char *> &Args, 
size_t Idx,
 
 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
                     CrashReportInfo *CrashInfo) const {
+  if (InProcess && InProcessToolContext && Environment.empty() &&
+      RedirectFiles.empty())
+    OS << " (in-process)\n";
+
   // Always quote the exe.
   OS << ' ';
   llvm::sys::printArg(OS, Executable, /*Quote=*/true);
@@ -367,6 +372,22 @@ int Command::Execute(ArrayRef<std::optional<StringRef>> 
Redirects,
 
   auto Args = llvm::toStringRefArray(Argv.data());
 
+  if (InProcess && InProcessToolContext && Environment.empty() &&
+      RedirectFiles.empty() && Redirects.empty()) {
+    llvm::ErrorOr<int> Result = InProcessToolContext->callTool(
+        ArrayRef<const char *>(Argv).drop_back());
+    if (!Result) {
+      if (ErrMsg)
+        *ErrMsg = Result.getError().message();
+      if (ExecutionFailed)
+        *ExecutionFailed = true;
+      return -1;
+    }
+    if (ExecutionFailed)
+      *ExecutionFailed = false;
+    return *Result;
+  }
+
   // Use Job-specific redirect files if they are present.
   if (!RedirectFiles.empty()) {
     std::vector<std::optional<StringRef>> RedirectFilesOptional;
diff --git a/clang/test/Driver/in-process-link.c 
b/clang/test/Driver/in-process-link.c
new file mode 100644
index 00000000000000..2a1049a67cef4c
--- /dev/null
+++ b/clang/test/Driver/in-process-link.c
@@ -0,0 +1,55 @@
+// REQUIRES: llvm-driver, lld, aarch64-registered-target
+// REQUIRES: webassembly-registered-target
+
+// Clang and LLD are registered in one ToolSession. Verify that frontend and
+// linker jobs can execute in-process for both WebAssembly and native targets.
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang -fintegrated-cc1 --target=wasm32-unknown-unknown -nostdlib 
-fuse-ld=lld \
+// RUN:   -Wl,--no-entry -### %t/add.c %t/sub.c 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=PRINT
+// PRINT-COUNT-3: (in-process)
+// PRINT: {{.*}}wasm-ld
+
+// The mechanism is target-independent: a registered ELF linker is also
+// dispatched in-process.
+// RUN: %clang -fintegrated-cc1 --target=aarch64-unknown-linux-gnu -nostdlib 
-fuse-ld=lld \
+// RUN:   -Wl,-e,add -### %t/add.c 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=ELF-PRINT
+// ELF-PRINT-COUNT-2: (in-process)
+// ELF-PRINT: {{.*}}ld.lld
+
+// RUN: env CC_PRINT_PROC_STAT=1 %clang -fintegrated-cc1 \
+// RUN:   --target=wasm32-unknown-unknown -nostdlib -fuse-ld=lld \
+// RUN:   -Wl,--no-entry -### %t/add.c %t/sub.c 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=STATS 
--implicit-check-not='(in-process)'
+// STATS: {{.*}}wasm-ld
+
+// An unrelated external linker with a registered name remains out-of-process.
+// RUN: %if !system-windows %{ mkdir -p %t.external && touch %t.external/ld && 
\
+// RUN:   chmod +x %t.external/ld %}
+// RUN: %if !system-windows %{ %clang -fintegrated-cc1 
--target=aarch64-unknown-linux-gnu \
+// RUN:   -nostdlib -B%t.external -### %t/add.c 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=EXTERNAL %}
+// EXTERNAL: (in-process)
+// EXTERNAL-NOT: (in-process)
+// EXTERNAL: {{.*}}external{{[/\\]}}ld
+
+// RUN: env LLD_IN_TEST=2 %clang -fintegrated-cc1 
--target=aarch64-unknown-linux-gnu \
+// RUN:   -nostdlib -fuse-ld=lld -Wl,-e,add %t/add.c -o %t.elf
+// RUN: llvm-readobj --file-headers %t.elf \
+// RUN:   | FileCheck %s --check-prefix=ELF
+// ELF: Format: elf64-littleaarch64
+
+// RUN: env LLD_IN_TEST=2 %clang -fintegrated-cc1 
--target=wasm32-unknown-unknown \
+// RUN:   -nostdlib -fuse-ld=lld \
+// RUN:   -Wl,--no-entry -Wl,--export=add -Wl,--export=sub \
+// RUN:   %t/add.c %t/sub.c -o %t.wasm
+// RUN: llvm-readobj --file-headers %t.wasm | FileCheck %s --check-prefix=WASM
+// WASM: Format: WASM
+
+//--- add.c
+int add(int lhs, int rhs) { return lhs + rhs; }
+
+//--- sub.c
+int sub(int lhs, int rhs) { return lhs - rhs; }
diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index ab41b11c2046ca..4d4bef08eefba2 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -16,6 +16,7 @@
 #include "clang/Basic/HeaderInclude.h"
 #include "clang/Basic/Stack.h"
 #include "clang/Config/config.h"
+#include "clang/Driver/Action.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/ToolChain.h"
@@ -63,6 +64,14 @@ using namespace clang;
 using namespace clang::driver;
 using namespace llvm::opt;
 
+static bool isSessionOwnedTool(const llvm::ToolContext &Context,
+                               llvm::StringRef Executable) {
+  // A bare name means that Clang did not find an external executable. A path
+  // is session-owned only when it names the session's multicall binary.
+  return llvm::sys::path::parent_path(Executable).empty() ||
+         llvm::sys::fs::equivalent(Executable, Context.Path);
+}
+
 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
   if (!CanonicalPrefixes) {
     SmallString<128> ExecutablePath(Argv0);
@@ -389,6 +398,19 @@ int clang_main(int Argc, char **Argv, const 
llvm::ToolContext &ToolContext) {
   std::unique_ptr<Compilation> C(
       TheDriver.BuildCompilation(Args, CC1MainIsReusable));
 
+  // A host session may provide the linker as a callable tool. Other external
+  // commands retain the subprocess path.
+  if (ToolContext.hasSession() && !TheDriver.CCPrintProcessStats) {
+    for (Command &Job : C->getJobs()) {
+      if (!isa<LinkJobAction>(Job.getSource()))
+        continue;
+      if (!isSessionOwnedTool(ToolContext, Job.getExecutable()))
+        continue;
+      if (ToolContext.getCallableTool(Job.getExecutable()))
+        Job.setInProcessToolContext(ToolContext);
+    }
+  }
+
   Driver::ReproLevel ReproLevel = Driver::ReproLevel::OnCrash;
   if (Arg *A = C->getArgs().getLastArg(options::OPT_gen_reproducer_eq)) {
     auto Level =
diff --git a/lld/tools/lld/lld.cpp b/lld/tools/lld/lld.cpp
index 53f0cbc6d9814d..4ad0aaa1853fcf 100644
--- a/lld/tools/lld/lld.cpp
+++ b/lld/tools/lld/lld.cpp
@@ -72,7 +72,7 @@ LLD_HAS_DRIVER(mingw)
 LLD_HAS_DRIVER(macho)
 LLD_HAS_DRIVER(wasm)
 
-int lld_main(int argc, char **argv, const llvm::ToolContext &) {
+int lld_main(int argc, char **argv, const llvm::ToolContext &ToolContext) {
   sys::Process::UseANSIEscapeCodes(true);
 
   if (::getenv("FORCE_LLD_DIAGNOSTICS_CRASH")) {
@@ -83,9 +83,10 @@ int lld_main(int argc, char **argv, const llvm::ToolContext 
&) {
 
   ArrayRef<const char *> args(argv, argv + argc);
 
-  // Not running in lit tests, just take the shortest codepath with global
-  // exception handling and no memory cleanup on exit.
-  if (!inTestVerbosity()) {
+  // A standalone invocation can take the shortest path and let process exit
+  // reclaim its resources. A session-owned invocation must clean up before
+  // returning to its host.
+  if (!ToolContext.hasSession() && !inTestVerbosity()) {
     int r =
         lld::unsafeLldMain(args, llvm::outs(), llvm::errs(), LLD_ALL_DRIVERS,
                            /*exitEarly=*/true);
@@ -94,8 +95,11 @@ int lld_main(int argc, char **argv, const llvm::ToolContext 
&) {
 
   std::optional<int> mainRet;
   CrashRecoveryContext::Enable();
+  unsigned Iterations = inTestVerbosity();
+  if (!Iterations)
+    Iterations = 1;
 
-  for (unsigned i = inTestVerbosity(); i > 0; --i) {
+  for (unsigned i = Iterations; i > 0; --i) {
     // Disable stdout/stderr for all iterations but the last one.
     inTestOutputDisabled = (i != 1);
 
diff --git a/llvm/test/tools/llvm-driver/passthrough-lld.test 
b/llvm/test/tools/llvm-driver/passthrough-lld.test
index b31fa4e483b92c..de528162205623 100644
--- a/llvm/test/tools/llvm-driver/passthrough-lld.test
+++ b/llvm/test/tools/llvm-driver/passthrough-lld.test
@@ -4,5 +4,8 @@
 # RUN: %llvm ld --help | FileCheck %s
 # RUN: %llvm lld -flavor ld.lld --help | FileCheck %s
 # RUN: %llvm ld -flavor ld.lld --help | FileCheck %s
+# A session-owned LLD invocation must run even when test repetition is 
disabled.
+# RUN: env LLD_IN_TEST=0 %llvm wasm-ld --version | FileCheck %s 
--check-prefix=VERSION
 
 # CHECK: supported targets: elf
+# VERSION: LLD {{[0-9]+}}.{{[0-9]+}}.{{[0-9]+}}

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

Reply via email to