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

>From 9de12810127d3fee3e24a19e979baf34014b88b1 Mon Sep 17 00:00:00 2001
From: anutosh491 <[email protected]>
Date: Tue, 10 Nov 2026 10:50:01 +0530
Subject: [PATCH] [clang] Allow embedding hosts to supply a job executor

---
 clang/include/clang/Driver/Compilation.h   |  17 ++
 clang/lib/Driver/Compilation.cpp           |   9 +-
 clang/unittests/Driver/CMakeLists.txt      |   1 +
 clang/unittests/Driver/CompilationTest.cpp | 178 +++++++++++++++++++++
 4 files changed, 202 insertions(+), 3 deletions(-)
 create mode 100644 clang/unittests/Driver/CompilationTest.cpp

diff --git a/clang/include/clang/Driver/Compilation.h 
b/clang/include/clang/Driver/Compilation.h
index 79960bb6e80a12..d4fefd4b78afb7 100644
--- a/clang/include/clang/Driver/Compilation.h
+++ b/clang/include/clang/Driver/Compilation.h
@@ -19,10 +19,12 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Option/Option.h"
 #include <cassert>
+#include <functional>
 #include <iterator>
 #include <map>
 #include <memory>
 #include <optional>
+#include <string>
 #include <utility>
 #include <vector>
 
@@ -44,6 +46,12 @@ class ToolChain;
 /// Compilation - A set of tasks to perform for a single driver
 /// invocation.
 class Compilation {
+public:
+  using JobExecutor = std::function<std::optional<int>(
+      const Command &Job, ArrayRef<std::optional<StringRef>> Redirects,
+      std::string &Error, bool &ExecutionFailed)>;
+
+private:
   /// The driver we were created by.
   const Driver &TheDriver;
 
@@ -135,6 +143,8 @@ class Compilation {
   /// ConstructJob calls so addCommand can stamp it onto each new Command.
   BoundArch CurrentBoundArch;
 
+  JobExecutor Executor;
+
 public:
   Compilation(const Driver &D, const ToolChain &DefaultToolChain,
               llvm::opt::InputArgList *Args,
@@ -246,6 +256,13 @@ class Compilation {
     PostCallback = CB;
   }
 
+  /// Installs a synchronous job executor. Return std::nullopt without changing
+  /// the error outputs to use Command::Execute. A handled job returns its exit
+  /// code and reports launch failures through Error and ExecutionFailed, as
+  /// Execute does. The host is responsible for tool isolation and crash
+  /// handling.
+  void setJobExecutor(JobExecutor Execute) { Executor = std::move(Execute); }
+
   /// Returns the sysroot path.
   StringRef getSysRoot() const;
 
diff --git a/clang/lib/Driver/Compilation.cpp b/clang/lib/Driver/Compilation.cpp
index e5340f471be156..6d991200dbb964 100644
--- a/clang/lib/Driver/Compilation.cpp
+++ b/clang/lib/Driver/Compilation.cpp
@@ -209,8 +209,11 @@ int Compilation::ExecuteCommand(const Command &C,
     return 0;
 
   std::string Error;
-  bool ExecutionFailed;
-  int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
+  bool ExecutionFailed = false;
+  std::optional<int> Result;
+  if (Executor)
+    Result = Executor(C, Redirects, Error, ExecutionFailed);
+  int Res = Result ? *Result : C.Execute(Redirects, &Error, &ExecutionFailed);
   if (PostCallback)
     PostCallback(C, Res);
   if (!Error.empty()) {
@@ -381,7 +384,7 @@ void Compilation::ExecuteJobs(const JobList &Jobs,
       !LogOnly && !getDriver().CCPrintOptions &&
       !getDriver().CCPrintProcessStats && !getDriver().CCGenDiagnostics &&
       !getDriver().IsCLMode() && !getArgs().hasArg(options::OPT_v) &&
-      Redirects.empty() && !PostCallback;
+      Redirects.empty() && !PostCallback && !Executor;
 
   // Jobs run as part of a parallel offload group. Group members are not
   // necessarily adjacent, so track them and skip them when the loop reaches
diff --git a/clang/unittests/Driver/CMakeLists.txt 
b/clang/unittests/Driver/CMakeLists.txt
index fadaacf511291f..79aa82eb250c33 100644
--- a/clang/unittests/Driver/CMakeLists.txt
+++ b/clang/unittests/Driver/CMakeLists.txt
@@ -1,4 +1,5 @@
 add_clang_unittest(ClangDriverTests
+  CompilationTest.cpp
   DistroTest.cpp
   DXCModeTest.cpp
   EscapedCommandLineTest.cpp
diff --git a/clang/unittests/Driver/CompilationTest.cpp 
b/clang/unittests/Driver/CompilationTest.cpp
new file mode 100644
index 00000000000000..64d01f9faa1ad7
--- /dev/null
+++ b/clang/unittests/Driver/CompilationTest.cpp
@@ -0,0 +1,178 @@
+//===- CompilationTest.cpp - Job execution tests 
---------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Driver/Compilation.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/Job.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::driver;
+
+namespace {
+class CompilationTest : public testing::Test {
+protected:
+  struct Diagnostics : DiagnosticConsumer {
+    std::string Message;
+    void HandleDiagnostic(DiagnosticsEngine::Level Level,
+                          const Diagnostic &Info) override {
+      DiagnosticConsumer::HandleDiagnostic(Level, Info);
+      llvm::SmallString<128> Text;
+      Info.FormatDiagnostic(Text);
+      Message = std::string(Text);
+    }
+  } Client;
+  DiagnosticOptions DiagOpts;
+  DiagnosticsEngine Diags{DiagnosticIDs::create(), DiagOpts, &Client, false};
+  Driver D{"/clang", "wasm32-unknown-unknown", Diags};
+  llvm::SmallString<128> Directory;
+  llvm::SmallString<128> Output;
+  llvm::SmallString<128> MissingLinker;
+  std::unique_ptr<Compilation> C;
+
+  void SetUp() override {
+    ASSERT_FALSE(
+        llvm::sys::fs::createUniqueDirectory("clang-executor", Directory));
+    Output = Directory;
+    llvm::sys::path::append(Output, "program.wasm");
+    MissingLinker = Directory;
+    llvm::sys::path::append(MissingLinker, "missing-linker");
+    D.setCheckInputsExist(false);
+    C.reset(D.BuildCompilation(
+        {"clang", "-nostdlib", "input.o", "-o", Output.c_str()}));
+    ASSERT_TRUE(C);
+    ASSERT_FALSE(C->containsError());
+    ASSERT_EQ(C->getJobs().size(), 1u);
+    C->getJobs().begin()->replaceExecutable(MissingLinker.c_str());
+  }
+
+  void TearDown() override {
+    C.reset();
+    llvm::sys::fs::remove_directories(Directory);
+  }
+};
+
+TEST_F(CompilationTest, DefaultExecution) {
+  const Command *Failed = nullptr;
+  EXPECT_EQ(C->ExecuteCommand(*C->getJobs().begin(), Failed), 1);
+  EXPECT_EQ(Failed, &*C->getJobs().begin());
+  EXPECT_EQ(Diags.getNumErrors(), 1u);
+}
+
+TEST_F(CompilationTest, UnhandledJobUsesDefaultExecution) {
+  unsigned Calls = 0;
+  C->setJobExecutor([&](const Command &, auto, auto &, bool &) {
+    ++Calls;
+    return std::optional<int>();
+  });
+  const Command *Failed = nullptr;
+  EXPECT_EQ(C->ExecuteCommand(*C->getJobs().begin(), Failed), 1);
+  EXPECT_EQ(Calls, 1u);
+  EXPECT_EQ(Failed, &*C->getJobs().begin());
+  EXPECT_EQ(Diags.getNumErrors(), 1u);
+}
+
+TEST_F(CompilationTest, HandledJobPreservesRedirectionsAndPostCallback) {
+  C->Redirect({std::nullopt, "executor-stdout", "executor-stderr"});
+  unsigned Calls = 0, Completed = 0;
+  C->setJobExecutor([&](const Command &Job, auto Redirects, auto &, bool &) {
+    ++Calls;
+    EXPECT_EQ(&Job, &*C->getJobs().begin());
+    EXPECT_EQ(Redirects.size(), 3u);
+    EXPECT_EQ(Redirects[1], "executor-stdout");
+    EXPECT_EQ(Redirects[2], "executor-stderr");
+    return std::optional<int>(0);
+  });
+  C->setPostCallback([&](const Command &, int Result) {
+    ++Completed;
+    EXPECT_EQ(Result, 0);
+  });
+  const Command *Failed = nullptr;
+  EXPECT_EQ(C->ExecuteCommand(*C->getJobs().begin(), Failed), 0);
+  EXPECT_EQ(Calls, 1u);
+  EXPECT_EQ(Completed, 1u);
+  EXPECT_EQ(Failed, nullptr);
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+}
+
+TEST_F(CompilationTest, LaunchFailureIsDiagnosed) {
+  C->setJobExecutor(
+      [](const Command &, auto, std::string &Error, bool &Failed) {
+        Error = "linker worker unavailable";
+        Failed = true;
+        return std::optional<int>(-1);
+      });
+  const Command *Failed = nullptr;
+  EXPECT_EQ(C->ExecuteCommand(*C->getJobs().begin(), Failed), 1);
+  EXPECT_EQ(Failed, &*C->getJobs().begin());
+  EXPECT_NE(Client.Message.find("linker worker unavailable"),
+            std::string::npos);
+}
+
+TEST_F(CompilationTest, ToolFailurePreservesDiagnosticsAndCleanup) {
+  llvm::SmallString<128> Temporary;
+  ASSERT_FALSE(
+      llvm::sys::fs::createTemporaryFile("clang-executor", "o", Temporary));
+  C->addTempFile(Temporary.c_str());
+  C->setJobExecutor([](const Command &, auto, auto &, bool &) {
+    return std::optional<int>(42);
+  });
+  llvm::SmallVector<std::pair<int, const Command *>, 1> Failures;
+  D.ExecuteCompilation(*C, Failures);
+  ASSERT_EQ(Failures.size(), 1u);
+  EXPECT_EQ(Failures[0].first, 42);
+  EXPECT_NE(Client.Message.find("linker command failed with exit code 42"),
+            std::string::npos);
+  C.reset();
+  EXPECT_FALSE(llvm::sys::fs::exists(Temporary));
+}
+
+TEST_F(CompilationTest, LogOnlyDoesNotExecuteJobs) {
+  C->setJobExecutor([](const Command &, auto, auto &, bool &) {
+    ADD_FAILURE() << "Log-only compilation must not invoke the executor";
+    return std::optional<int>(1);
+  });
+  const Command *Failed = nullptr;
+  EXPECT_EQ(C->ExecuteCommand(*C->getJobs().begin(), Failed, true), 0);
+  EXPECT_EQ(Failed, nullptr);
+}
+
+TEST_F(CompilationTest, GroupedJobsDoNotBypassExecutor) {
+  C.reset(D.BuildCompilation({"clang", "--offload-jobs=2", "-nostdlib",
+                              "input.o", "-o", Output.c_str()}));
+  ASSERT_TRUE(C);
+  ASSERT_FALSE(C->containsError());
+  const Tool &Creator = C->getJobs().begin()->getCreator();
+  C->getJobs().clear();
+  ActionList Inputs;
+  for (StringRef Arch : {"first", "second"}) {
+    auto *Action = C->MakeAction<LinkJobAction>(Inputs, types::TY_Image);
+    C->addCommand(std::make_unique<Command>(
+        *Action, Creator, ResponseFileSupport::None(), MissingLinker.c_str(),
+        llvm::opt::ArgStringList{}, ArrayRef<InputInfo>{}));
+    auto &Job = *C->getJobs().getJobs().back();
+    Job.setBoundArch(BoundArch(Arch));
+    Job.setOffloadDeviceParallelJobGroup("executor-group");
+  }
+  unsigned Calls = 0;
+  C->setJobExecutor([&](const Command &, auto, auto &, bool &) {
+    ++Calls;
+    return std::optional<int>(0);
+  });
+  llvm::SmallVector<std::pair<int, const Command *>, 2> Failures;
+  C->ExecuteJobs(C->getJobs(), Failures);
+  EXPECT_EQ(Calls, 2u);
+  EXPECT_TRUE(Failures.empty());
+}
+} // namespace

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

Reply via email to