[clang] [clang][modules-driver] Add dependency scan and dependency graph (PR #152770)

Naveen Seth Hanig via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 26 18:14:19 PST 2025


https://github.com/naveen-seth updated https://github.com/llvm/llvm-project/pull/152770

>From 1e9a40cee69deb067c11d1fa3e6f61f045ae62aa Mon Sep 17 00:00:00 2001
From: Naveen Seth Hanig <naveen.hanig at outlook.com>
Date: Sat, 20 Dec 2025 00:44:19 +0100
Subject: [PATCH 1/2]  [clang][DependencyScanning] Remove dependency on
 clangDriver from clangDependencyScanning (#172347)

This is the final patch in a series that removes the dependency of
clangDependencyScanning on clangDriver, splitting the work
from #169964 into smaller changes (see comment linked below).

This patch updates the remaining parts of the scanning interface in
DependencyScanningWorker to only operate on -cc1 / frontend
command-lines.
This follows #171238, which applied this change to the by-name
scanning API.

This is part of a broader effort to support driver-managed builds for
compilations using C++ named modules and/or Clang modules. It is
required for linking the dependency scanning tooling against the
driver without introducing cyclic dependencies, which would otherwise
cause build failures when dynamic linking is enabled.
---
 .../DependencyScannerImpl.h                   |  18 --
 .../DependencyScanningWorker.h                |  55 ++++--
 clang/lib/DependencyScanning/CMakeLists.txt   |   1 -
 .../DependencyScannerImpl.cpp                 |  91 ----------
 .../DependencyScanningWorker.cpp              | 170 ++++++++++--------
 clang/lib/Tooling/DependencyScanningTool.cpp  | 158 +++++++++++++---
 .../DependencyScanningWorkerTest.cpp          |  12 +-
 7 files changed, 272 insertions(+), 233 deletions(-)

diff --git a/clang/include/clang/DependencyScanning/DependencyScannerImpl.h b/clang/include/clang/DependencyScanning/DependencyScannerImpl.h
index 453f4acb285a3..d50371512667d 100644
--- a/clang/include/clang/DependencyScanning/DependencyScannerImpl.h
+++ b/clang/include/clang/DependencyScanning/DependencyScannerImpl.h
@@ -89,28 +89,10 @@ struct TextDiagnosticsPrinterWithOutput {
         DiagPrinter(DiagnosticsOS, *DiagOpts) {}
 };
 
-std::pair<std::unique_ptr<driver::Driver>, std::unique_ptr<driver::Compilation>>
-buildCompilation(ArrayRef<std::string> ArgStrs, DiagnosticsEngine &Diags,
-                 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
-                 llvm::BumpPtrAllocator &Alloc);
-
 std::unique_ptr<CompilerInvocation>
 createCompilerInvocation(ArrayRef<std::string> CommandLine,
                          DiagnosticsEngine &Diags);
 
-std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
-          std::vector<std::string>>
-initVFSForTUBufferScanning(IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
-                           ArrayRef<std::string> CommandLine,
-                           StringRef WorkingDirectory,
-                           llvm::MemoryBufferRef TUBuffer);
-
-std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
-          std::vector<std::string>>
-initVFSForByNameScanning(IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
-                         ArrayRef<std::string> CommandLine,
-                         StringRef WorkingDirectory, StringRef ModuleName);
-
 void initializeScanCompilerInstance(
     CompilerInstance &ScanInstance,
     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
diff --git a/clang/include/clang/DependencyScanning/DependencyScanningWorker.h b/clang/include/clang/DependencyScanning/DependencyScanningWorker.h
index 3c5e7660a8c7b..75a84e378b5fa 100644
--- a/clang/include/clang/DependencyScanning/DependencyScanningWorker.h
+++ b/clang/include/clang/DependencyScanning/DependencyScanningWorker.h
@@ -16,7 +16,7 @@
 #include "clang/DependencyScanning/DependencyScanningService.h"
 #include "clang/DependencyScanning/ModuleDepCollector.h"
 #include "clang/Frontend/PCHContainerOperations.h"
-#include "llvm/Support/Error.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBufferRef.h"
 #include "llvm/Support/VirtualFileSystem.h"
@@ -93,11 +93,13 @@ class DependencyScanningWorker {
 
   ~DependencyScanningWorker();
 
-  /// Run the dependency scanning tool for a given clang driver command-line,
-  /// and report the discovered dependencies to the provided consumer. If
-  /// TUBuffer is not nullopt, it is used as TU input for the dependency
-  /// scanning. Otherwise, the input should be included as part of the
-  /// command-line.
+  /// Run the dependency scanning worker for the given frontend command-line,
+  /// and report the discovered dependencies to the provided consumer.
+  ///
+  /// OverlayFS should be based on the Worker's dependency scanning file-system
+  /// and can be used to provide any input specified on the command-line as
+  /// in-memory file. If no overlay file-system is provided, the Worker's
+  /// dependency scanning file-system is used instead.
   ///
   /// \returns false if clang errors occurred (with diagnostics reported to
   /// \c DiagConsumer), true otherwise.
@@ -105,7 +107,25 @@ class DependencyScanningWorker {
       StringRef WorkingDirectory, ArrayRef<std::string> CommandLine,
       DependencyConsumer &DepConsumer, DependencyActionController &Controller,
       DiagnosticConsumer &DiagConsumer,
-      std::optional<llvm::MemoryBufferRef> TUBuffer = std::nullopt);
+      llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS =
+          nullptr);
+
+  /// Run the dependency scanning tool for all given frontend command-lines,
+  /// and report the discovered dependencies to the provided consumer.
+  ///
+  /// OverlayFS should be based on the Worker's dependency scanning file-system
+  /// and can be used to provide any input specified on the command-line as
+  /// in-memory file. If no overlay file-system is provided, the Worker's
+  /// dependency scanning file-system is used instead.
+  ///
+  /// \returns false if clang errors occurred (with diagnostics reported to
+  /// \c DiagConsumer), true otherwise.
+  bool computeDependencies(
+      StringRef WorkingDirectory, ArrayRef<ArrayRef<std::string>> CommandLines,
+      DependencyConsumer &DepConsumer, DependencyActionController &Controller,
+      DiagnosticConsumer &DiagConsumer,
+      llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS =
+          nullptr);
 
   /// The three method below implements a new interface for by name
   /// dependency scanning. They together enable the dependency scanning worker
@@ -162,16 +182,21 @@ class DependencyScanningWorker {
 
   friend CompilerInstanceWithContext;
   std::unique_ptr<CompilerInstanceWithContext> CIWithContext;
-
-  /// Actually carries out the scan. If \c OverlayFS is provided, it must be
-  /// based on top of DepFS.
-  bool scanDependencies(
-      StringRef WorkingDirectory, ArrayRef<std::string> CommandLine,
-      DependencyConsumer &Consumer, DependencyActionController &Controller,
-      DiagnosticConsumer &DC,
-      IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS = nullptr);
 };
 
+std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
+          std::vector<std::string>>
+initVFSForTUBufferScanning(IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
+                           ArrayRef<std::string> CommandLine,
+                           StringRef WorkingDirectory,
+                           llvm::MemoryBufferRef TUBuffer);
+
+std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
+          std::vector<std::string>>
+initVFSForByNameScanning(IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
+                         ArrayRef<std::string> CommandLine,
+                         StringRef WorkingDirectory, StringRef ModuleName);
+
 } // end namespace dependencies
 } // end namespace clang
 
diff --git a/clang/lib/DependencyScanning/CMakeLists.txt b/clang/lib/DependencyScanning/CMakeLists.txt
index 2976f7c236f2e..4c30c3ee57cfd 100644
--- a/clang/lib/DependencyScanning/CMakeLists.txt
+++ b/clang/lib/DependencyScanning/CMakeLists.txt
@@ -20,7 +20,6 @@ add_clang_library(clangDependencyScanning
   LINK_LIBS
   clangAST
   clangBasic
-  clangDriver
   clangFrontend
   clangLex
   clangSerialization
diff --git a/clang/lib/DependencyScanning/DependencyScannerImpl.cpp b/clang/lib/DependencyScanning/DependencyScannerImpl.cpp
index d1369b26fda8b..751b0fd7a0740 100644
--- a/clang/lib/DependencyScanning/DependencyScannerImpl.cpp
+++ b/clang/lib/DependencyScanning/DependencyScannerImpl.cpp
@@ -379,42 +379,6 @@ DiagnosticsEngineWithDiagOpts::DiagnosticsEngineWithDiagOpts(
                                                    /*ShouldOwnClient=*/false);
 }
 
-std::pair<std::unique_ptr<driver::Driver>, std::unique_ptr<driver::Compilation>>
-dependencies::buildCompilation(ArrayRef<std::string> ArgStrs,
-                               DiagnosticsEngine &Diags,
-                               IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
-                               llvm::BumpPtrAllocator &Alloc) {
-  SmallVector<const char *, 256> Argv;
-  Argv.reserve(ArgStrs.size());
-  for (const std::string &Arg : ArgStrs)
-    Argv.push_back(Arg.c_str());
-
-  std::unique_ptr<driver::Driver> Driver = std::make_unique<driver::Driver>(
-      Argv[0], llvm::sys::getDefaultTargetTriple(), Diags,
-      "clang LLVM compiler", FS);
-  Driver->setTitle("clang_based_tool");
-
-  bool CLMode = driver::IsClangCL(
-      driver::getDriverMode(Argv[0], ArrayRef(Argv).slice(1)));
-
-  if (llvm::Error E =
-          driver::expandResponseFiles(Argv, CLMode, Alloc, FS.get())) {
-    Diags.Report(diag::err_drv_expand_response_file)
-        << llvm::toString(std::move(E));
-    return std::make_pair(nullptr, nullptr);
-  }
-
-  std::unique_ptr<driver::Compilation> Compilation(
-      Driver->BuildCompilation(Argv));
-  if (!Compilation)
-    return std::make_pair(nullptr, nullptr);
-
-  if (Compilation->containsError())
-    return std::make_pair(nullptr, nullptr);
-
-  return std::make_pair(std::move(Driver), std::move(Compilation));
-}
-
 std::unique_ptr<CompilerInvocation>
 dependencies::createCompilerInvocation(ArrayRef<std::string> CommandLine,
                                        DiagnosticsEngine &Diags) {
@@ -430,61 +394,6 @@ dependencies::createCompilerInvocation(ArrayRef<std::string> CommandLine,
   return Invocation;
 }
 
-std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
-          std::vector<std::string>>
-dependencies::initVFSForTUBufferScanning(
-    IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
-    ArrayRef<std::string> CommandLine, StringRef WorkingDirectory,
-    llvm::MemoryBufferRef TUBuffer) {
-  // Reset what might have been modified in the previous worker invocation.
-  BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
-
-  auto OverlayFS =
-      llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
-  auto InMemoryFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
-  InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
-  auto InputPath = TUBuffer.getBufferIdentifier();
-  InMemoryFS->addFile(
-      InputPath, 0, llvm::MemoryBuffer::getMemBufferCopy(TUBuffer.getBuffer()));
-  IntrusiveRefCntPtr<llvm::vfs::FileSystem> InMemoryOverlay = InMemoryFS;
-
-  OverlayFS->pushOverlay(InMemoryOverlay);
-  std::vector<std::string> ModifiedCommandLine(CommandLine);
-  ModifiedCommandLine.emplace_back(InputPath);
-
-  return std::make_pair(OverlayFS, ModifiedCommandLine);
-}
-
-std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
-          std::vector<std::string>>
-dependencies::initVFSForByNameScanning(
-    IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
-    ArrayRef<std::string> CommandLine, StringRef WorkingDirectory,
-    StringRef ModuleName) {
-  // Reset what might have been modified in the previous worker invocation.
-  BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
-
-  // If we're scanning based on a module name alone, we don't expect the client
-  // to provide us with an input file. However, the driver really wants to have
-  // one. Let's just make it up to make the driver happy.
-  auto OverlayFS =
-      llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
-  auto InMemoryFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
-  InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
-  SmallString<128> FakeInputPath;
-  // TODO: We should retry the creation if the path already exists.
-  llvm::sys::fs::createUniquePath(ModuleName + "-%%%%%%%%.input", FakeInputPath,
-                                  /*MakeAbsolute=*/false);
-  InMemoryFS->addFile(FakeInputPath, 0, llvm::MemoryBuffer::getMemBuffer(""));
-  IntrusiveRefCntPtr<llvm::vfs::FileSystem> InMemoryOverlay = InMemoryFS;
-  OverlayFS->pushOverlay(InMemoryOverlay);
-
-  std::vector<std::string> ModifiedCommandLine(CommandLine);
-  ModifiedCommandLine.emplace_back(FakeInputPath);
-
-  return std::make_pair(OverlayFS, ModifiedCommandLine);
-}
-
 void dependencies::initializeScanCompilerInstance(
     CompilerInstance &ScanInstance,
     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
diff --git a/clang/lib/DependencyScanning/DependencyScanningWorker.cpp b/clang/lib/DependencyScanning/DependencyScanningWorker.cpp
index ea2a6d67948c3..266660cdfab28 100644
--- a/clang/lib/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/DependencyScanning/DependencyScanningWorker.cpp
@@ -13,6 +13,7 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Serialization/ObjectFilePCHContainerReader.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/Support/VirtualFileSystem.h"
 
 using namespace clang;
@@ -40,24 +41,6 @@ DependencyScanningWorker::DependencyScanningWorker(
 DependencyScanningWorker::~DependencyScanningWorker() = default;
 DependencyActionController::~DependencyActionController() = default;
 
-static bool forEachDriverJob(
-    ArrayRef<std::string> ArgStrs, DiagnosticsEngine &Diags,
-    IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
-    llvm::function_ref<bool(const driver::Command &Cmd)> Callback) {
-  // Compilation holds a non-owning a reference to the Driver, hence we need to
-  // keep the Driver alive when we use Compilation. Arguments to commands may be
-  // owned by Alloc when expanded from response files.
-  llvm::BumpPtrAllocator Alloc;
-  auto [Driver, Compilation] = buildCompilation(ArgStrs, Diags, FS, Alloc);
-  if (!Compilation)
-    return false;
-  for (const driver::Command &Job : Compilation->getJobs()) {
-    if (!Callback(Job))
-      return false;
-  }
-  return true;
-}
-
 static bool createAndRunToolInvocation(
     ArrayRef<std::string> CommandLine, DependencyScanningAction &Action,
     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
@@ -72,12 +55,22 @@ static bool createAndRunToolInvocation(
                               Diags.getClient());
 }
 
-bool DependencyScanningWorker::scanDependencies(
+bool DependencyScanningWorker::computeDependencies(
     StringRef WorkingDirectory, ArrayRef<std::string> CommandLine,
-    DependencyConsumer &Consumer, DependencyActionController &Controller,
-    DiagnosticConsumer &DC,
-    IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS) {
-  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = DepFS;
+    DependencyConsumer &DepConsumer, DependencyActionController &Controller,
+    DiagnosticConsumer &DiagConsumer,
+    llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS) {
+  return computeDependencies(WorkingDirectory,
+                             ArrayRef<ArrayRef<std::string>>(CommandLine),
+                             DepConsumer, Controller, DiagConsumer, OverlayFS);
+}
+
+bool DependencyScanningWorker::computeDependencies(
+    StringRef WorkingDirectory, ArrayRef<ArrayRef<std::string>> CommandLines,
+    DependencyConsumer &DepConsumer, DependencyActionController &Controller,
+    DiagnosticConsumer &DiagConsumer,
+    llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS) {
+  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr;
   if (OverlayFS) {
 #ifndef NDEBUG
     bool SawDepFS = false;
@@ -86,73 +79,39 @@ bool DependencyScanningWorker::scanDependencies(
     assert(SawDepFS && "OverlayFS not based on DepFS");
 #endif
     FS = std::move(OverlayFS);
+  } else {
+    FS = DepFS;
+    FS->setCurrentWorkingDirectory(WorkingDirectory);
   }
 
-  DiagnosticsEngineWithDiagOpts DiagEngineWithCmdAndOpts(CommandLine, FS, DC);
-  DependencyScanningAction Action(Service, WorkingDirectory, Consumer,
+  DependencyScanningAction Action(Service, WorkingDirectory, DepConsumer,
                                   Controller, DepFS);
 
-  bool Success = false;
-  if (CommandLine[1] == "-cc1") {
-    Success =
-        createAndRunToolInvocation(CommandLine, Action, FS, PCHContainerOps,
-                                   *DiagEngineWithCmdAndOpts.DiagEngine);
-  } else {
-    Success = forEachDriverJob(
-        CommandLine, *DiagEngineWithCmdAndOpts.DiagEngine, FS,
-        [&](const driver::Command &Cmd) {
-          if (StringRef(Cmd.getCreator().getName()) != "clang") {
-            // Non-clang command. Just pass through to the dependency
-            // consumer.
-            Consumer.handleBuildCommand(
-                {Cmd.getExecutable(),
-                 {Cmd.getArguments().begin(), Cmd.getArguments().end()}});
-            return true;
-          }
-
-          // Insert -cc1 command line options into Argv
-          std::vector<std::string> Argv;
-          Argv.push_back(Cmd.getExecutable());
-          llvm::append_range(Argv, Cmd.getArguments());
-
-          // Create an invocation that uses the underlying file
-          // system to ensure that any file system requests that
-          // are made by the driver do not go through the
-          // dependency scanning filesystem.
-          return createAndRunToolInvocation(
-              std::move(Argv), Action, FS, PCHContainerOps,
-              *DiagEngineWithCmdAndOpts.DiagEngine);
-        });
-  }
+  const bool Success = llvm::all_of(CommandLines, [&](const auto &Cmd) {
+    if (StringRef(Cmd[1]) != "-cc1") {
+      // Non-clang command. Just pass through to the dependency consumer.
+      DepConsumer.handleBuildCommand(
+          {Cmd.front(), {Cmd.begin() + 1, Cmd.end()}});
+      return true;
+    }
 
-  if (Success && !Action.hasScanned())
-    DiagEngineWithCmdAndOpts.DiagEngine->Report(
-        diag::err_fe_expected_compiler_job)
-        << llvm::join(CommandLine, " ");
+    auto DiagEngineWithDiagOpts =
+        DiagnosticsEngineWithDiagOpts(Cmd, OverlayFS, DiagConsumer);
+    auto &Diags = *DiagEngineWithDiagOpts.DiagEngine;
+
+    // Create an invocation that uses the underlying file system to ensure that
+    // any file system requests that are made by the driver do not go through
+    // the dependency scanning filesystem.
+    return createAndRunToolInvocation(Cmd, Action, FS, PCHContainerOps, Diags);
+  });
 
   // Ensure finish() is called even if we never reached ExecuteAction().
   if (!Action.hasDiagConsumerFinished())
-    DC.finish();
+    DiagConsumer.finish();
 
   return Success && Action.hasScanned();
 }
 
-bool DependencyScanningWorker::computeDependencies(
-    StringRef WorkingDirectory, ArrayRef<std::string> CommandLine,
-    DependencyConsumer &Consumer, DependencyActionController &Controller,
-    DiagnosticConsumer &DC, std::optional<llvm::MemoryBufferRef> TUBuffer) {
-  if (TUBuffer) {
-    auto [FinalFS, FinalCommandLine] = initVFSForTUBufferScanning(
-        DepFS, CommandLine, WorkingDirectory, *TUBuffer);
-    return scanDependencies(WorkingDirectory, FinalCommandLine, Consumer,
-                            Controller, DC, FinalFS);
-  }
-
-  DepFS->setCurrentWorkingDirectory(WorkingDirectory);
-  return scanDependencies(WorkingDirectory, CommandLine, Consumer, Controller,
-                          DC);
-}
-
 bool DependencyScanningWorker::initializeCompilerInstanceWithContext(
     StringRef CWD, ArrayRef<std::string> CommandLine, DiagnosticConsumer &DC) {
   auto [OverlayFS, ModifiedCommandLine] =
@@ -184,3 +143,58 @@ bool DependencyScanningWorker::computeDependenciesByNameWithContext(
 bool DependencyScanningWorker::finalizeCompilerInstanceWithContext() {
   return CIWithContext->finalize();
 }
+
+std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
+          std::vector<std::string>>
+dependencies::initVFSForTUBufferScanning(
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
+    ArrayRef<std::string> CommandLine, StringRef WorkingDirectory,
+    llvm::MemoryBufferRef TUBuffer) {
+  // Reset what might have been modified in the previous worker invocation.
+  BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
+
+  auto OverlayFS =
+      llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
+  auto InMemoryFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
+  InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
+  auto InputPath = TUBuffer.getBufferIdentifier();
+  InMemoryFS->addFile(
+      InputPath, 0, llvm::MemoryBuffer::getMemBufferCopy(TUBuffer.getBuffer()));
+  IntrusiveRefCntPtr<llvm::vfs::FileSystem> InMemoryOverlay = InMemoryFS;
+
+  OverlayFS->pushOverlay(InMemoryOverlay);
+  std::vector<std::string> ModifiedCommandLine(CommandLine);
+  ModifiedCommandLine.emplace_back(InputPath);
+
+  return std::make_pair(OverlayFS, ModifiedCommandLine);
+}
+
+std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
+          std::vector<std::string>>
+dependencies::initVFSForByNameScanning(
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
+    ArrayRef<std::string> CommandLine, StringRef WorkingDirectory,
+    StringRef ModuleName) {
+  // Reset what might have been modified in the previous worker invocation.
+  BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
+
+  // If we're scanning based on a module name alone, we don't expect the client
+  // to provide us with an input file. However, the driver really wants to have
+  // one. Let's just make it up to make the driver happy.
+  auto OverlayFS =
+      llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
+  auto InMemoryFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
+  InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
+  SmallString<128> FakeInputPath;
+  // TODO: We should retry the creation if the path already exists.
+  llvm::sys::fs::createUniquePath(ModuleName + "-%%%%%%%%.input", FakeInputPath,
+                                  /*MakeAbsolute=*/false);
+  InMemoryFS->addFile(FakeInputPath, 0, llvm::MemoryBuffer::getMemBuffer(""));
+  IntrusiveRefCntPtr<llvm::vfs::FileSystem> InMemoryOverlay = InMemoryFS;
+  OverlayFS->pushOverlay(InMemoryOverlay);
+
+  std::vector<std::string> ModifiedCommandLine(CommandLine);
+  ModifiedCommandLine.emplace_back(FakeInputPath);
+
+  return std::make_pair(OverlayFS, ModifiedCommandLine);
+}
diff --git a/clang/lib/Tooling/DependencyScanningTool.cpp b/clang/lib/Tooling/DependencyScanningTool.cpp
index 0d4ef55a1b03e..c4cd861e0e73b 100644
--- a/clang/lib/Tooling/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanningTool.cpp
@@ -7,10 +7,15 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Tooling/DependencyScanningTool.h"
+#include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/DependencyScanning/DependencyScannerImpl.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Frontend/Utils.h"
+#include "llvm/ADT/SmallVectorExtras.h"
+#include "llvm/ADT/iterator.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/TargetParser/Host.h"
 #include <optional>
 
 using namespace clang;
@@ -74,14 +79,124 @@ class MakeDependencyPrinterConsumer : public DependencyConsumer {
 };
 } // anonymous namespace
 
+static std::pair<std::unique_ptr<driver::Driver>,
+                 std::unique_ptr<driver::Compilation>>
+buildCompilation(ArrayRef<std::string> ArgStrs, DiagnosticsEngine &Diags,
+                 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
+                 llvm::BumpPtrAllocator &Alloc) {
+  SmallVector<const char *, 256> Argv;
+  Argv.reserve(ArgStrs.size());
+  for (const std::string &Arg : ArgStrs)
+    Argv.push_back(Arg.c_str());
+
+  std::unique_ptr<driver::Driver> Driver = std::make_unique<driver::Driver>(
+      Argv[0], llvm::sys::getDefaultTargetTriple(), Diags,
+      "clang LLVM compiler", FS);
+  Driver->setTitle("clang_based_tool");
+
+  bool CLMode = driver::IsClangCL(
+      driver::getDriverMode(Argv[0], ArrayRef(Argv).slice(1)));
+
+  if (llvm::Error E =
+          driver::expandResponseFiles(Argv, CLMode, Alloc, FS.get())) {
+    Diags.Report(diag::err_drv_expand_response_file)
+        << llvm::toString(std::move(E));
+    return std::make_pair(nullptr, nullptr);
+  }
+
+  std::unique_ptr<driver::Compilation> Compilation(
+      Driver->BuildCompilation(Argv));
+  if (!Compilation)
+    return std::make_pair(nullptr, nullptr);
+
+  if (Compilation->containsError())
+    return std::make_pair(nullptr, nullptr);
+
+  if (Compilation->getJobs().empty()) {
+    Diags.Report(diag::err_fe_expected_compiler_job)
+        << llvm::join(ArgStrs, " ");
+    return std::make_pair(nullptr, nullptr);
+  }
+
+  return std::make_pair(std::move(Driver), std::move(Compilation));
+}
+
+/// Constructs the full frontend command line, including executable, for the
+/// given driver \c Cmd.
+static SmallVector<std::string, 0>
+buildCC1CommandLine(const driver::Command &Cmd) {
+  const auto &Args = Cmd.getArguments();
+  SmallVector<std::string, 0> Out;
+  Out.reserve(Args.size() + 1);
+  Out.emplace_back(Cmd.getExecutable());
+  llvm::append_range(Out, Args);
+  return Out;
+}
+
+static bool computeDependenciesForDriverCommandLine(
+    DependencyScanningWorker &Worker, StringRef WorkingDirectory,
+    ArrayRef<std::string> CommandLine, DependencyConsumer &Consumer,
+    DependencyActionController &Controller, DiagnosticConsumer &DiagConsumer,
+    IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS) {
+  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr;
+  if (OverlayFS) {
+    FS = OverlayFS;
+  } else {
+    FS = &Worker.getVFS();
+    FS->setCurrentWorkingDirectory(WorkingDirectory);
+  }
+
+  // Compilation holds a non-owning a reference to the Driver, hence we need to
+  // keep the Driver alive when we use Compilation. Arguments to commands may be
+  // owned by Alloc when expanded from response files.
+  llvm::BumpPtrAllocator Alloc;
+  auto DiagEngineWithDiagOpts =
+      DiagnosticsEngineWithDiagOpts(CommandLine, FS, DiagConsumer);
+  const auto [Driver, Compilation] = buildCompilation(
+      CommandLine, *DiagEngineWithDiagOpts.DiagEngine, FS, Alloc);
+  if (!Compilation)
+    return false;
+
+  SmallVector<SmallVector<std::string, 0>> FrontendCommandLines;
+  for (const auto &Cmd : Compilation->getJobs())
+    FrontendCommandLines.push_back(buildCC1CommandLine(Cmd));
+  SmallVector<ArrayRef<std::string>> FrontendCommandLinesView(
+      FrontendCommandLines.begin(), FrontendCommandLines.end());
+
+  return Worker.computeDependencies(WorkingDirectory, FrontendCommandLinesView,
+                                    Consumer, Controller, DiagConsumer,
+                                    OverlayFS);
+}
+
+static llvm::Error makeErrorFromDiagnosticsOS(
+    TextDiagnosticsPrinterWithOutput &DiagPrinterWithOS) {
+  return llvm::make_error<llvm::StringError>(
+      DiagPrinterWithOS.DiagnosticsOS.str(), llvm::inconvertibleErrorCode());
+}
+
+static bool computeDependencies(
+    DependencyScanningWorker &Worker, StringRef WorkingDirectory,
+    ArrayRef<std::string> CommandLine, DependencyConsumer &Consumer,
+    DependencyActionController &Controller, DiagnosticConsumer &DiagConsumer,
+    llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS =
+        nullptr) {
+  const auto IsCC1Input = (CommandLine.size() >= 2 && CommandLine[1] == "-cc1");
+  return IsCC1Input ? Worker.computeDependencies(WorkingDirectory, CommandLine,
+                                                 Consumer, Controller,
+                                                 DiagConsumer, OverlayFS)
+                    : computeDependenciesForDriverCommandLine(
+                          Worker, WorkingDirectory, CommandLine, Consumer,
+                          Controller, DiagConsumer, OverlayFS);
+}
+
 std::optional<std::string>
 DependencyScanningTool::getDependencyFile(ArrayRef<std::string> CommandLine,
                                           StringRef CWD,
                                           DiagnosticConsumer &DiagConsumer) {
   MakeDependencyPrinterConsumer DepConsumer;
   CallbackActionController Controller(nullptr);
-  if (!Worker.computeDependencies(CWD, CommandLine, DepConsumer, Controller,
-                                  DiagConsumer))
+  if (!computeDependencies(Worker, CWD, CommandLine, DepConsumer, Controller,
+                           DiagConsumer))
     return std::nullopt;
   std::string Output;
   DepConsumer.printDependencies(Output);
@@ -132,8 +247,8 @@ std::optional<P1689Rule> DependencyScanningTool::getP1689ModuleDependencyFile(
   P1689Rule Rule;
   P1689ModuleDependencyPrinterConsumer Consumer(Rule, Command);
   P1689ActionController Controller;
-  if (!Worker.computeDependencies(CWD, Command.CommandLine, Consumer,
-                                  Controller, DiagConsumer))
+  if (!computeDependencies(Worker, CWD, Command.CommandLine, Consumer,
+                           Controller, DiagConsumer))
     return std::nullopt;
 
   MakeformatOutputPath = Consumer.getMakeFormatDependencyOutputPath();
@@ -152,8 +267,19 @@ DependencyScanningTool::getTranslationUnitDependencies(
   FullDependencyConsumer Consumer(AlreadySeen);
   CallbackActionController Controller(LookupModuleOutput);
 
-  if (!Worker.computeDependencies(CWD, CommandLine, Consumer, Controller,
-                                  DiagConsumer, TUBuffer))
+  // If we are scanning from a TUBuffer, create an overlay filesystem with the
+  // input as an in-memory file and add it to the command line.
+  IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS = nullptr;
+  std::vector<std::string> CommandLineWithTUBufferInput;
+  if (TUBuffer) {
+    std::tie(OverlayFS, CommandLineWithTUBufferInput) =
+        initVFSForTUBufferScanning(&Worker.getVFS(), CommandLine, CWD,
+                                   *TUBuffer);
+    CommandLine = CommandLineWithTUBufferInput;
+  }
+
+  if (!computeDependencies(Worker, CWD, CommandLine, Consumer, Controller,
+                           DiagConsumer, OverlayFS))
     return std::nullopt;
   return Consumer.takeTranslationUnitDeps();
 }
@@ -176,19 +302,7 @@ DependencyScanningTool::getModuleDependencies(
   return Result;
 }
 
-/// Constructs the full -cc1 command line, including executable, for the given
-/// driver \c Cmd.
-static std::vector<std::string>
-buildCC1CommandLine(const driver::Command &Cmd) {
-  const auto &Args = Cmd.getArguments();
-  std::vector<std::string> Out;
-  Out.reserve(Args.size() + 1);
-  Out.emplace_back(Cmd.getExecutable());
-  llvm::append_range(Out, Args);
-  return Out;
-}
-
-static std::optional<std::vector<std::string>> getFirstCC1CommandLine(
+static std::optional<SmallVector<std::string, 0>> getFirstCC1CommandLine(
     ArrayRef<std::string> CommandLine, DiagnosticsEngine &Diags,
     llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> ScanFS) {
   // Compilation holds a non-owning a reference to the Driver, hence we need to
@@ -210,12 +324,6 @@ static std::optional<std::vector<std::string>> getFirstCC1CommandLine(
   return std::nullopt;
 }
 
-static llvm::Error makeErrorFromDiagnosticsOS(
-    TextDiagnosticsPrinterWithOutput &DiagPrinterWithOS) {
-  return llvm::make_error<llvm::StringError>(
-      DiagPrinterWithOS.DiagnosticsOS.str(), llvm::inconvertibleErrorCode());
-}
-
 bool DependencyScanningTool::initializeWorkerCIWithContextFromCommandline(
     DependencyScanningWorker &Worker, StringRef CWD,
     ArrayRef<std::string> CommandLine, DiagnosticConsumer &DC) {
diff --git a/clang/unittests/DependencyScanning/DependencyScanningWorkerTest.cpp b/clang/unittests/DependencyScanning/DependencyScanningWorkerTest.cpp
index e6a5684b10cc9..872c7effde3d3 100644
--- a/clang/unittests/DependencyScanning/DependencyScanningWorkerTest.cpp
+++ b/clang/unittests/DependencyScanning/DependencyScanningWorkerTest.cpp
@@ -47,9 +47,10 @@ TEST(DependencyScanner, ScanDepsWithDiagConsumer) {
   {
     // Check that a successful scan calls DiagConsumer.finish().
     std::vector<std::string> Args = {"clang",
-                                     "-target",
+                                     "-cc1",
+                                     "-triple",
                                      "x86_64-apple-macosx10.7",
-                                     "-c",
+                                     "-emit-obj",
                                      "test.cpp",
                                      "-o"
                                      "test.cpp.o"};
@@ -65,7 +66,7 @@ TEST(DependencyScanner, ScanDepsWithDiagConsumer) {
   {
     // Check that an invalid command-line, which never enters the scanning
     // action calls DiagConsumer.finish().
-    std::vector<std::string> Args = {"clang", "-invalid-arg"};
+    std::vector<std::string> Args = {"clang", "-cc1", "-invalid-arg"};
     EnsureFinishedConsumer DiagConsumer;
     bool Success = Worker.computeDependencies(CWD, Args, DC, AC, DiagConsumer);
 
@@ -78,9 +79,10 @@ TEST(DependencyScanner, ScanDepsWithDiagConsumer) {
     // Check that a valid command line that produces no scanning jobs calls
     // DiagConsumer.finish().
     std::vector<std::string> Args = {"clang",
-                                     "-target",
+                                     "-cc1",
+                                     "-triple",
                                      "x86_64-apple-macosx10.7",
-                                     "-c",
+                                     "-emit-obj",
                                      "-x",
                                      "assembler",
                                      "test.s",

>From 6990f3b88fb4b93e41596a94d9184c009c4b1614 Mon Sep 17 00:00:00 2001
From: Naveen Seth Hanig <naveen.hanig at outlook.com>
Date: Thu, 18 Dec 2025 18:59:00 +0100
Subject: [PATCH 2/2] [clang][modules-driver] Add dependency scan and
 dependency graph

This patch is part of a series to support driver-managed module builds.
It adds support for discovery of module dependencies from within the
driver and for generation of the module dependency graph.

Source inputs provided on the command line can import modules defined
in the standard module manifest, which are then scanned on demand.

The dependency scan and graph support both Clang modules and C++ named
modules. The generated dependency graph can be output in Graphviz DOT
format as a remark.

The RFC for driver-managed module builds:
https://discourse.llvm.org/t/rfc-modules-support-simple-c-20-modules-use-from-the-clang-driver-without-a-build-system/86456

The RFC for linking the driver against clangDependencyScanning:
https://discourse.llvm.org/t/rfc-driver-link-the-driver-against-clangdependencyscanning-clangast-clangfrontend-clangserialization-and-clanglex/87469
---
 .../clang/Basic/DiagnosticDriverKinds.td      |   22 +
 clang/include/clang/Basic/DiagnosticGroups.td |    1 +
 clang/include/clang/Driver/Job.h              |    9 +
 clang/include/clang/Driver/ModulesDriver.h    |   96 ++
 clang/include/clang/Options/Options.td        |    9 +
 clang/lib/Driver/CMakeLists.txt               |    2 +
 clang/lib/Driver/Driver.cpp                   |   47 +
 clang/lib/Driver/Job.cpp                      |   10 +
 clang/lib/Driver/ModulesDriver.cpp            | 1294 +++++++++++++++++
 ...es-driver-dep-graph-with-system-inputs.cpp |  102 ++
 .../test/Driver/modules-driver-dep-graph.cpp  |   95 ++
 .../modules-driver-dep-scan-diagnostics.cpp   |   25 +
 .../modules-driver-duplicate-named-module.cpp |   20 +
 ...dules-driver-malformed-module-manifest.cpp |   41 +
 ...-driver-manifest-local-system-includes.cpp |   76 +
 15 files changed, 1849 insertions(+)
 create mode 100644 clang/include/clang/Driver/ModulesDriver.h
 create mode 100644 clang/lib/Driver/ModulesDriver.cpp
 create mode 100644 clang/test/Driver/modules-driver-dep-graph-with-system-inputs.cpp
 create mode 100644 clang/test/Driver/modules-driver-dep-graph.cpp
 create mode 100644 clang/test/Driver/modules-driver-dep-scan-diagnostics.cpp
 create mode 100644 clang/test/Driver/modules-driver-duplicate-named-module.cpp
 create mode 100644 clang/test/Driver/modules-driver-malformed-module-manifest.cpp
 create mode 100644 clang/test/Driver/modules-driver-manifest-local-system-includes.cpp

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 5cae8fb86347f..6b3f05fa728b0 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -605,6 +605,28 @@ def err_drv_reduced_module_output_overrided : Warning<
   "please consider use '-fmodule-output=' to specify the output file for reduced BMI explicitly">,
   InGroup<DiagGroup<"reduced-bmi-output-overrided">>;
 
+def remark_performing_driver_managed_module_build : Remark<
+  "performing driver managed module build">,
+  InGroup<ModulesDriver>;
+def remark_modules_manifest_not_found : Remark<
+  "standard modules manifest file not found; import of standard library "
+  "modules not supported">,
+  InGroup<ModulesDriver>;
+def remark_using_modules_manifest : Remark<
+  "using standard modules manifest file '%0'">,
+   InGroup<ModulesDriver>;
+def err_modules_manifest_failed_parse : Error<
+  "failure while parsing standard modules manifest: '%0'">;
+def err_failed_dependency_scan : Error<
+  "failed to perform dependency scan">;
+def err_mod_graph_named_module_redefinition : Error<
+  "duplicate definitions of C++20 named module '%0' in '%1' and '%2'">;
+def err_building_dependency_graph : Error<
+  "failed to construct the module dependency graph">;
+def remark_printing_module_graph : Remark<
+  "printing module dependency graph">,
+  InGroup<ModulesDriver>;
+
 def warn_drv_delayed_template_parsing_after_cxx20 : Warning<
   "-fdelayed-template-parsing is deprecated after C++20">,
   InGroup<DiagGroup<"delayed-template-parsing-in-cxx20">>;
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index 3764475fbd3df..8582f22ce6f88 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -650,6 +650,7 @@ def ModuleConflict : DiagGroup<"module-conflict">;
 def ModuleFileExtension : DiagGroup<"module-file-extension">;
 def ModuleIncludeDirectiveTranslation : DiagGroup<"module-include-translation">;
 def ModuleMap : DiagGroup<"module-map">;
+def ModulesDriver : DiagGroup<"modules-driver">;
 def RoundTripCC1Args : DiagGroup<"round-trip-cc1-args">;
 def NewlineEOF : DiagGroup<"newline-eof">;
 def Nullability : DiagGroup<"nullability">;
diff --git a/clang/include/clang/Driver/Job.h b/clang/include/clang/Driver/Job.h
index 561866197b780..6a353c81e86ad 100644
--- a/clang/include/clang/Driver/Job.h
+++ b/clang/include/clang/Driver/Job.h
@@ -223,6 +223,8 @@ class Command {
 
   const llvm::opt::ArgStringList &getArguments() const { return Arguments; }
 
+  llvm::opt::ArgStringList &getArguments() { return Arguments; }
+
   const std::vector<InputInfo> &getInputInfos() const { return InputInfoList; }
 
   const std::vector<std::string> &getOutputFilenames() const {
@@ -238,6 +240,10 @@ class Command {
   void PrintFileNames() const;
 };
 
+/// Constructs the full frontend command line, including executable, for the
+/// given driver \c Job.
+SmallVector<std::string, 0> buildCommandLine(const Command &Job);
+
 /// Use the CC1 tool callback when available, to avoid creating a new process
 class CC1Command : public Command {
 public:
@@ -279,6 +285,9 @@ class JobList {
 
   const list_type &getJobs() const { return Jobs; }
 
+  // Returns and transfers ownership of all jobs, leaving this list empty.
+  list_type takeJobs() { return std::exchange(Jobs, {}); };
+
   bool empty() const { return Jobs.empty(); }
   size_type size() const { return Jobs.size(); }
   iterator begin() { return Jobs.begin(); }
diff --git a/clang/include/clang/Driver/ModulesDriver.h b/clang/include/clang/Driver/ModulesDriver.h
new file mode 100644
index 0000000000000..4dce9ec44ea3a
--- /dev/null
+++ b/clang/include/clang/Driver/ModulesDriver.h
@@ -0,0 +1,96 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file defines functionality to support driver managed builds for
+/// compilations which use Clang modules or standard C++20 named modules.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_DRIVER_MODULESDRIVER_H
+#define LLVM_CLANG_DRIVER_MODULESDRIVER_H
+
+#include "clang/Driver/Types.h"
+#include "llvm/Support/Error.h"
+
+namespace llvm {
+namespace vfs {
+class FileSystem;
+} // namespace vfs
+namespace opt {
+class Arg;
+} // namespace opt
+} // namespace llvm
+
+namespace clang {
+class DiagnosticsEngine;
+namespace driver {
+class Compilation;
+} // namespace driver
+} // namespace clang
+
+namespace clang::driver::modules {
+
+/// A list of inputs and their types for the given arguments.
+/// Identical to Driver::InputTy.
+using InputTy = std::pair<types::ID, const llvm::opt::Arg *>;
+
+/// A list of inputs and their types for the given arguments.
+/// Identical to Driver::InputList.
+using InputList = llvm::SmallVector<InputTy, 16>;
+
+/// The parsed Standard library module manifest.
+struct StdModuleManifest {
+  struct LocalModuleArgs {
+    std::vector<std::string> SystemIncludeDirs;
+  };
+
+  struct Module {
+    bool IsStdlib = false;
+    std::string LogicalName;
+    std::string SourcePath;
+    std::optional<LocalModuleArgs> LocalArgs;
+  };
+
+  std::vector<Module> ModuleEntries;
+};
+
+/// Reads the Standard library module manifest from the specified path.
+///
+/// All source file paths in the returned manifest are made absolute.
+///
+/// \param StdModuleManifestPath Path to the manifest file.
+/// \param VFS The llvm::vfs::FileSystem to be used for all file accesses.
+///
+/// \returns The parsed manifest on success, a llvm::FileError on failure to
+/// read the manifest, or a llvm::json::ParseError on failure to parse it.
+llvm::Expected<StdModuleManifest>
+readStdModuleManifest(llvm::StringRef StdModuleManifestPath,
+                      llvm::vfs::FileSystem &VFS);
+
+/// Constructs compilation inputs for each module listed in the provided
+/// Standard library module manifest.
+///
+/// \param Manifest The standard modules manifest
+/// \param C The compilation being built.
+/// \param Inputs The input list to which the corresponding input entries are
+/// appended.
+void buildStdModuleManifestInputs(const StdModuleManifest &Manifest,
+                                  Compilation &C, InputList &Inputs);
+
+/// Reorders and builds compilation jobs based on discovered module
+/// dependencies.
+///
+/// \param C The compilation being built.
+/// \param Manifest The standard modules manifest
+void planDriverManagedModuleCompilation(Compilation &C,
+                                        const StdModuleManifest &Manifest);
+
+} // namespace clang::driver::modules
+
+#endif
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index 8cd31a3be109a..9a9b5385810a3 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -3480,6 +3480,15 @@ def fmodules_single_module_parse_mode :
   Group<f_Group>, Flags<[]>, Visibility<[CC1Option]>,
   MarshallingInfoFlag<PreprocessorOpts<"SingleModuleParseMode">>;
 
+def fmodules_driver :
+  Flag<["-"], "fmodules-driver">,
+  Group<f_Group>, Visibility<[ClangOption]>,
+  HelpText<"Enable support for driver managed module builds (experimental)">;
+def fno_modules_driver :
+  Flag<["-"], "fno-modules-driver">,
+  Group<f_Group>, Visibility<[ClangOption]>,
+  HelpText<"Disable support for driver managed module builds (experimental)">;
+
 def fincremental_extensions :
   Flag<["-"], "fincremental-extensions">,
   Group<f_Group>, Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index 0026ba8991719..1e6323430aa1e 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_library(clangDriver
   Distro.cpp
   Driver.cpp
   Job.cpp
+  ModulesDriver.cpp
   Multilib.cpp
   MultilibBuilder.cpp
   OffloadBundler.cpp
@@ -99,6 +100,7 @@ add_clang_library(clangDriver
 
   LINK_LIBS
   clangBasic
+  clangDependencyScanning
   clangFrontend
   clangSerialization
   clangLex
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 6a2ee1794b7d7..348510ad63062 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -61,6 +61,7 @@
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/InputInfo.h"
 #include "clang/Driver/Job.h"
+#include "clang/Driver/ModulesDriver.h"
 #include "clang/Driver/Phases.h"
 #include "clang/Driver/SanitizerArgs.h"
 #include "clang/Driver/Tool.h"
@@ -90,6 +91,7 @@
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/IOSandbox.h"
+#include "llvm/Support/JSON.h"
 #include "llvm/Support/MD5.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/PrettyStackTrace.h"
@@ -1808,6 +1810,48 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
   // Populate the tool chains for the offloading devices, if any.
   CreateOffloadingDeviceToolChains(*C, Inputs);
 
+  const bool UseModulesDriver = C->getArgs().hasFlag(
+      options::OPT_fmodules_driver, options::OPT_fno_modules_driver, false);
+  modules::StdModuleManifest Manifest;
+  if (UseModulesDriver) {
+    Diags.Report(diag::remark_performing_driver_managed_module_build);
+
+    // Read the standard modules manifest, and if available, add all discovered
+    // modules to the compilation. Compilation jobs for modules discovered from
+    // the manifest, which are not imported by any other source input, are
+    // pruned later.
+    const auto StdModuleManifestPath =
+        GetStdModuleManifestPath(*C, C->getDefaultToolChain());
+    if (!llvm::sys::fs::exists(StdModuleManifestPath)) {
+      Diags.Report(diag::remark_modules_manifest_not_found);
+    } else {
+      Diags.Report(diag::remark_using_modules_manifest)
+          << StdModuleManifestPath;
+      if (auto ManifestOrErr =
+              modules::readStdModuleManifest(StdModuleManifestPath, getVFS())) {
+        Manifest = std::move(*ManifestOrErr);
+      } else {
+        llvm::handleAllErrors(
+            ManifestOrErr.takeError(),
+            [&](llvm::json::ParseError &Err) {
+              Diags.Report(diag::err_modules_manifest_failed_parse)
+                  << Err.message();
+            },
+            [&](llvm::FileError &Err) {
+              Diags.Report(diag::err_cannot_open_file)
+                  << Err.getFileName() << Err.messageWithoutFileInfo();
+            });
+      }
+    }
+
+    // Only allow on-demand imports of standard library modules.
+    llvm::erase_if(Manifest.ModuleEntries, [](const auto &ModuleEntry) {
+      return !ModuleEntry.IsStdlib;
+    });
+
+    modules::buildStdModuleManifestInputs(Manifest, *C, Inputs);
+  }
+
   // Construct the list of abstract actions to perform for this compilation. On
   // MachO targets this uses the driver-driver and universal actions.
   if (TC.getTriple().isOSBinFormatMachO())
@@ -1822,6 +1866,9 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
 
   BuildJobs(*C);
 
+  if (UseModulesDriver)
+    modules::planDriverManagedModuleCompilation(*C, Manifest);
+
   return C;
 }
 
diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp
index da7a1f2e07e90..3a6a86d10bb56 100644
--- a/clang/lib/Driver/Job.cpp
+++ b/clang/lib/Driver/Job.cpp
@@ -387,6 +387,16 @@ int Command::Execute(ArrayRef<std::optional<StringRef>> Redirects,
                                    ErrMsg, ExecutionFailed, &ProcStat);
 }
 
+SmallVector<std::string, 0> driver::buildCommandLine(const Command &Job) {
+  const auto &JobArgs = Job.getArguments();
+  SmallVector<std::string, 0> Out;
+  Out.reserve(JobArgs.size() + 1);
+  Out.emplace_back(Job.getExecutable());
+  for (const auto &Arg : JobArgs)
+    Out.emplace_back(Arg);
+  return Out;
+}
+
 CC1Command::CC1Command(const Action &Source, const Tool &Creator,
                        ResponseFileSupport ResponseSupport,
                        const char *Executable,
diff --git a/clang/lib/Driver/ModulesDriver.cpp b/clang/lib/Driver/ModulesDriver.cpp
new file mode 100644
index 0000000000000..cc2306560a162
--- /dev/null
+++ b/clang/lib/Driver/ModulesDriver.cpp
@@ -0,0 +1,1294 @@
+//===--- ModulesDriver.cpp - Driver managed module builds -----------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file defines functionality to support driver managed builds for
+/// compilations which use Clang modules or standard C++20 named modules.
+///
+//===----------------------------------------------------------------------===//
+
+#include "clang/Driver/ModulesDriver.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/DependencyScanning/DependencyScanningUtils.h"
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Frontend/StandaloneDiagnostic.h"
+#include "llvm/ADT/DirectedGraph.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/TypeSwitch.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/DOTGraphTraits.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/GraphWriter.h"
+#include "llvm/Support/JSON.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/ThreadPool.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include <optional>
+
+using namespace llvm::opt;
+
+using namespace clang;
+using namespace driver;
+using namespace modules;
+
+namespace deps = clang::dependencies;
+
+using JobVector = JobList::list_type;
+using StandaloneDiagList = SmallVector<StandaloneDiagnostic, 0>;
+
+namespace clang::driver::modules {
+
+static bool fromJSON(const llvm::json::Value &Params,
+                     StdModuleManifest::LocalModuleArgs &LocalArgs,
+                     llvm::json::Path P) {
+  llvm::json::ObjectMapper O(Params, P);
+  return O.mapOptional("system-include-directories",
+                       LocalArgs.SystemIncludeDirs);
+}
+
+static bool fromJSON(const llvm::json::Value &Params,
+                     StdModuleManifest::Module &ModuleEntry,
+                     llvm::json::Path P) {
+  llvm::json::ObjectMapper O(Params, P);
+  return O.map("is-std-library", ModuleEntry.IsStdlib) &&
+         O.map("logical-name", ModuleEntry.LogicalName) &&
+         O.map("source-path", ModuleEntry.SourcePath) &&
+         O.mapOptional("local-arguments", ModuleEntry.LocalArgs);
+}
+
+static bool fromJSON(const llvm::json::Value &Params,
+                     StdModuleManifest &Manifest, llvm::json::Path P) {
+  llvm::json::ObjectMapper O(Params, P);
+  return O.map("modules", Manifest.ModuleEntries);
+}
+
+} // namespace clang::driver::modules
+
+/// Parses the Standard library module manifest from \c Buffer.
+///
+/// The source file paths listed in the manifest are relative to its own
+/// path.
+static Expected<StdModuleManifest> parseStdModuleManifest(StringRef Buffer) {
+  auto ParsedJsonOrErr = llvm::json::parse(Buffer);
+  if (!ParsedJsonOrErr)
+    return ParsedJsonOrErr.takeError();
+
+  StdModuleManifest Manifest;
+  llvm::json::Path::Root Root;
+  if (!fromJSON(*ParsedJsonOrErr, Manifest, Root))
+    return Root.getError();
+
+  return Manifest;
+}
+
+/// Converts all file paths in \c Manifest from paths relative to
+/// \c ManifestPath (the manifest's location itself) to absolute.
+static void makeStdModuleManifestPathsAbsolute(StdModuleManifest &Manifest,
+                                               StringRef ManifestPath) {
+  SmallString<124> ManifestDir(ManifestPath);
+  llvm::sys::path::remove_filename(ManifestDir);
+
+  SmallString<256> TempPath;
+  auto ensureAbsolutePath = [&](std::string &Path) {
+    if (llvm::sys::path::is_absolute(Path))
+      return;
+    TempPath = ManifestDir;
+    llvm::sys::path::append(TempPath, Path);
+    llvm::sys::path::remove_dots(TempPath, true);
+    Path = std::string(TempPath);
+  };
+
+  for (auto &ModuleEntry : Manifest.ModuleEntries) {
+    ensureAbsolutePath(ModuleEntry.SourcePath);
+    if (!ModuleEntry.LocalArgs)
+      continue;
+    for (auto &IncludeDir : ModuleEntry.LocalArgs->SystemIncludeDirs)
+      ensureAbsolutePath(IncludeDir);
+  }
+}
+
+Expected<StdModuleManifest>
+driver::modules::readStdModuleManifest(StringRef ManifestPath,
+                                       llvm::vfs::FileSystem &VFS) {
+  auto MemBufOrErr = VFS.getBufferForFile(ManifestPath);
+  if (!MemBufOrErr)
+    return llvm::createFileError(ManifestPath, MemBufOrErr.getError());
+  const auto MemBuf = std::move(*MemBufOrErr);
+
+  auto ManifestOrErr = parseStdModuleManifest(MemBuf->getBuffer());
+  if (!ManifestOrErr)
+    return ManifestOrErr.takeError();
+  auto Manifest = std::move(*ManifestOrErr);
+
+  // All paths in the manifest are relative to \c ManifestPath.
+  // Make them absolute.
+  makeStdModuleManifestPathsAbsolute(Manifest, ManifestPath);
+
+  return Manifest;
+}
+
+/// Appends a compilation input for the given \c Entry of the Standard library
+/// module manifest.
+static void
+appendStdModuleManifestInput(const StdModuleManifest::Module &ModuleEntry,
+                             Compilation &C, InputList &Inputs) {
+  auto &Args = C.getArgs();
+  const auto &Opts = C.getDriver().getOpts();
+
+  C.getDriver().DiagnoseInputExistence(Args, ModuleEntry.SourcePath,
+                                       types::TY_CXXModule,
+                                       /*TypoCorrect=*/false);
+
+  auto *A = new Arg(Opts.getOption(options::OPT_INPUT), ModuleEntry.SourcePath,
+                    Args.getBaseArgs().MakeIndex(ModuleEntry.SourcePath),
+                    Args.getBaseArgs().MakeArgString(ModuleEntry.SourcePath));
+  Args.AddSynthesizedArg(A);
+  A->claim();
+  Inputs.emplace_back(types::TY_CXXModule, A);
+}
+
+void driver::modules::buildStdModuleManifestInputs(
+    const StdModuleManifest &Manifest, Compilation &C, InputList &Inputs) {
+  for (const auto &Module : Manifest.ModuleEntries)
+    appendStdModuleManifestInput(Module, C, Inputs);
+}
+
+/// Returns true if the driver \c Job is eligible as a dependency scan
+/// input.
+///
+/// A job is eligible if it is a clang \c -cc1 invocation and all its inputs
+/// are source files.
+static bool isJobForDependencyScan(const Command &Job) {
+  if (StringRef(Job.getCreator().getName()) != "clang")
+    return false;
+  auto IsSrcInput = [](const InputInfo &II) {
+    return types::isSrcFile(II.getType());
+  };
+  return llvm::all_of(Job.getInputInfos(), IsSrcInput);
+}
+
+/// Splits driver jobs into those eligible for dependency scanning and the rest.
+///
+/// Non-eligible jobs are either not \c -cc1 jobs or depend on outputs from
+/// eligible jobs. The original order of jobs is preserved.
+///
+/// \returns the pair: (dependency scan input jobs, rest jobs).
+static std::pair<JobVector, JobVector>
+splitCommandsByScanEligibility(JobVector &&Jobs) {
+  std::pair<JobVector, JobVector> Out;
+  auto &[ScanInputJobs, OtherJobs] = Out;
+  for (auto &Job : Jobs) {
+    if (isJobForDependencyScan(*Job))
+      ScanInputJobs.push_back(std::move(Job));
+    else
+      OtherJobs.push_back(std::move(Job));
+  }
+  return Out;
+}
+
+namespace {
+
+/// The full dependencies for a single compilation input.
+struct InputDependencies {
+  /// The identifier of the C++20 module this translation unit exports.
+  ///
+  /// If the translation unit is not a module then \c ID.ModuleName is empty.
+  deps::ModuleID ID;
+
+  /// Whether this is a "system" module.
+  bool IsSystem;
+
+  /// A collection of absolute paths to files that this translation unit
+  /// directly depends on, not including transitive dependencies.
+  std::vector<std::string> FileDeps;
+
+  /// A list of modules this translation unit directly depends on, not including
+  /// transitive dependencies.
+  ///
+  /// This may include modules with a different context hash when it can be
+  /// determined that the differences are benign for this compilation.
+  std::vector<deps::ModuleID> ClangModuleDeps;
+
+  /// A list of the C++20 named modules this translation unit depends on.
+  std::vector<std::string> NamedModuleDeps;
+
+  /// The compiler invocation with modifications to properly import all Clang
+  /// module dependencies. Does not include argv[0].
+  std::vector<std::string> BuildArgs;
+};
+
+/// The full dependencies for each compilation input and for all discovered
+/// Clang modules.
+struct DependencyScanResult {
+  /// The full dependencies for each compilation input, in the same order as the
+  /// inputs.
+  ///
+  /// System modules inputs that are not imported are represented as
+  /// std::nullopt.
+  llvm::SmallVector<std::optional<InputDependencies>, 0> InputDeps;
+
+  /// The full Clang module dependenies for this compilation.
+  SmallVector<deps::ModuleDeps, 0> ClangModuleDeps;
+};
+
+/// Merges and deterministically orders scan results from multiple threads
+/// into a single DependencyScanResult.
+class ScanResultCollector {
+public:
+  explicit ScanResultCollector(size_t NumInputs)
+      : InputDeps(NumInputs), ClangModuleGraphs(NumInputs) {}
+
+  /// Adds the dependency scan result for the input at \c InputIndex.
+  ///
+  /// Thread safe, given that each index is written to exactly once.
+  void handleTUResult(deps::TranslationUnitDeps &&TUDeps, bool IsSystem,
+                      size_t InputIndex);
+
+  /// Finalizes and takes the aggregated results.
+  ///
+  /// Not thread-safe.
+  DependencyScanResult takeScanResults();
+
+private:
+  SmallVector<std::optional<InputDependencies>, 0> InputDeps;
+  llvm::SmallVector<std::vector<deps::ModuleDeps>, 0> ClangModuleGraphs;
+};
+
+} // anonymous namespace
+
+void ScanResultCollector::handleTUResult(deps::TranslationUnitDeps &&TUDeps,
+                                         bool IsSystem, size_t InputIndex) {
+  assert(!InputDeps[InputIndex].has_value() &&
+         "Each slot should be written to at most once.");
+  InputDeps[InputIndex].emplace();
+  auto &NewInputDep = InputDeps[InputIndex].value();
+  NewInputDep.ID = std::move(TUDeps.ID);
+  NewInputDep.IsSystem = IsSystem;
+  NewInputDep.FileDeps = std::move(TUDeps.FileDeps);
+  NewInputDep.NamedModuleDeps = std::move(TUDeps.NamedModuleDeps);
+  NewInputDep.ClangModuleDeps = std::move(TUDeps.ClangModuleDeps);
+  assert(TUDeps.Commands.size() == 1 && "Expected exactly one command");
+  NewInputDep.BuildArgs = TUDeps.Commands.front().Arguments;
+
+  assert(ClangModuleGraphs[InputIndex].empty() &&
+         "Each slot should be written to at most once.");
+  ClangModuleGraphs[InputIndex] = std::move(TUDeps.ModuleGraph);
+}
+
+DependencyScanResult ScanResultCollector::takeScanResults() {
+  DependencyScanResult Out;
+
+  // Record each module only once, from its first importing input.
+  // This keeps the output deterministic.
+  llvm::DenseSet<deps::ModuleID> AlreadySeen;
+  for (auto &ModuleGraph : ClangModuleGraphs) {
+    for (auto &MD : ModuleGraph) {
+      auto [It, Inserted] = AlreadySeen.insert(MD.ID);
+      if (!Inserted)
+        continue;
+      Out.ClangModuleDeps.push_back(std::move(MD));
+    }
+  }
+
+  Out.InputDeps = std::move(InputDeps);
+  return Out;
+}
+
+namespace {
+
+/// Pool of reusable dependency scanning workers and their contexts, with RAII
+/// acquire/release semantics.
+class ScanningWorkerPool {
+public:
+  ScanningWorkerPool(size_t NumWorkers, deps::DependencyScanningService &S,
+                     llvm::vfs::FileSystem &FS);
+
+  /// Acquires a unique pointer to a dependency scanning worker and its
+  /// context.
+  ///
+  /// The worker bundle automatically released back to the pool when the
+  /// pointer is destroyed. The pool has to outlive the leased worker bundle.
+  [[nodiscard]] auto scopedAcquire();
+
+private:
+  /// Releases the worker bundle at \c Index back into the pool.
+  void release(size_t Index);
+
+  /// A scanning worker with its associated context.
+  struct WorkerBundle {
+    WorkerBundle(deps::DependencyScanningService &S, llvm::vfs::FileSystem &FS)
+        : Worker(std::make_unique<deps::DependencyScanningWorker>(S, &FS)) {}
+
+    std::unique_ptr<deps::DependencyScanningWorker> Worker = nullptr;
+    llvm::DenseSet<deps::ModuleID> SeenModules;
+  };
+
+  std::mutex Lock;
+  std::condition_variable CV;
+  SmallVector<size_t> AvailableSlots;
+  SmallVector<WorkerBundle, 0> Slots;
+};
+
+} // anonymous namespace
+
+ScanningWorkerPool::ScanningWorkerPool(size_t NumWorkers,
+                                       deps::DependencyScanningService &S,
+                                       llvm::vfs::FileSystem &FS) {
+  Slots.reserve(NumWorkers);
+  for (size_t I = 0; I < NumWorkers; ++I)
+    Slots.emplace_back(S, FS);
+
+  AvailableSlots.resize(NumWorkers);
+  std::iota(AvailableSlots.begin(), AvailableSlots.end(), 0);
+}
+
+[[nodiscard]] auto ScanningWorkerPool::scopedAcquire() {
+  std::unique_lock<std::mutex> UL(Lock);
+  CV.wait(UL, [&] { return !AvailableSlots.empty(); });
+  const size_t Index = AvailableSlots.pop_back_val();
+  auto ReleaseHandle = [&, Index](WorkerBundle *) { release(Index); };
+  return std::unique_ptr<WorkerBundle, decltype(ReleaseHandle)>(&Slots[Index],
+                                                                ReleaseHandle);
+}
+
+void ScanningWorkerPool::release(size_t Index) {
+  {
+    std::scoped_lock<std::mutex> SL(Lock);
+    AvailableSlots.push_back(Index);
+  }
+  CV.notify_one();
+}
+
+namespace {
+
+/// Thread-safe registry of system modules.
+///
+/// Records which system modules have been scheduled, and provides lookup for
+/// input indices of system modules that have not yet been seen.
+class SystemInputRegistry {
+public:
+  SystemInputRegistry(size_t FirstSystemInputIndex,
+                      const StdModuleManifest &Manifest);
+
+  /// Returns the indices of systems inputs that have not yet been seen.
+  SmallVector<size_t> getNewSystemInputs(ArrayRef<std::string> NamedDeps);
+
+private:
+  size_t FirstSystemInputIndex;
+  std::mutex Lock;
+  llvm::DenseMap<llvm::StringRef, size_t> NameToManifestIndex;
+  llvm::SmallBitVector ScheduledSystemModules;
+};
+
+} // anonymous namespace
+
+SystemInputRegistry::SystemInputRegistry(size_t FirstSystemInputIndex,
+                                         const StdModuleManifest &Manifest)
+    : FirstSystemInputIndex(FirstSystemInputIndex),
+      ScheduledSystemModules(Manifest.ModuleEntries.size(), false) {
+  // Build the mapping from module names to their manifest index.
+  NameToManifestIndex.reserve(Manifest.ModuleEntries.size());
+  for (const auto &[Index, M] : llvm::enumerate(Manifest.ModuleEntries))
+    NameToManifestIndex.try_emplace(M.LogicalName, Index);
+}
+
+SmallVector<size_t>
+SystemInputRegistry::getNewSystemInputs(ArrayRef<std::string> NamedDeps) {
+  SmallVector<size_t, 8> ToSchedule;
+  {
+    std::scoped_lock<std::mutex> SL(Lock);
+    for (const auto &ModuleName : NamedDeps) {
+      const auto It = NameToManifestIndex.find(ModuleName);
+      if (It == NameToManifestIndex.end())
+        continue;
+      const auto ManifestIndex = It->second;
+      if (ScheduledSystemModules[ManifestIndex])
+        continue;
+      ScheduledSystemModules[ManifestIndex] = true;
+      ToSchedule.push_back(FirstSystemInputIndex + ManifestIndex);
+    }
+  }
+  return ToSchedule;
+}
+
+/// Construct a path for the explicitly built PCM.
+static std::string constructPCMPath(deps::ModuleID ID, StringRef OutputDir) {
+  assert(!ID.ModuleName.empty() && !ID.ContextHash.empty() &&
+         "Invalid ModuleID");
+  SmallString<256> ExplicitPCMPath(OutputDir);
+  llvm::sys::path::append(ExplicitPCMPath, ID.ContextHash,
+                          ID.ModuleName + "-" + ID.ContextHash + ".pcm");
+  return std::string(ExplicitPCMPath);
+}
+
+namespace {
+
+/// A simple dependency action controller that only provides module lookup for
+/// Clang modules.
+class ModuleLookupController : public deps::DependencyActionController {
+public:
+  ModuleLookupController(StringRef OutputDir) : OutputDir(OutputDir) {}
+
+  std::string lookupModuleOutput(const deps::ModuleDeps &MD,
+                                 deps::ModuleOutputKind Kind) override {
+    if (Kind == deps::ModuleOutputKind::ModuleFile)
+      return constructPCMPath(MD.ID, OutputDir);
+
+    // Driver command lines that trigger lookups for unsupported
+    // ModuleOutputKinds are not supported by the modules driver. Those command
+    // lines should probably be adjusted or rejected in Driver::handleArguments
+    // or Driver::HandleImmediateArgs.
+    llvm::reportFatalInternalError(
+        "call to lookupModuleOutput with unexpected ModuleOutputKind");
+  }
+
+private:
+  std::string OutputDir;
+};
+
+} // anonymous namespace
+
+namespace {
+
+/// RAII utility to report StandaloneDiagnostics through a DiagnosticsEngine.
+///
+/// The driver's DiagnosticsEngine usually does not have a SourceManager at this
+/// point in building the compilation, in which case StandaloneDiagReporter
+/// supplies its own.
+class StandaloneDiagReporter {
+public:
+  explicit StandaloneDiagReporter(DiagnosticsEngine &Diags) : Diags(Diags) {
+    if (!Diags.hasSourceManager()) {
+      FileSystemOptions Opts;
+      Opts.WorkingDir = ".";
+      OwnedFileMgr = llvm::makeIntrusiveRefCnt<FileManager>(std::move(Opts));
+      OwnedSrcMgr =
+          llvm::makeIntrusiveRefCnt<SourceManager>(Diags, *OwnedFileMgr);
+    }
+  }
+
+  /// Emits all diagnostics in \c StandaloneDiags using the associated
+  /// DiagnosticsEngine.
+  void Report(SmallVectorImpl<StandaloneDiagnostic> &&StandaloneDiags) const {
+    llvm::StringMap<SourceLocation> SourceLocCache;
+    LangOptions LangOpts{};
+
+    for (auto &StandaloneDiag : StandaloneDiags) {
+      const auto StoredDiag = translateStandaloneDiag(
+          getFileManager(), getSourceManager(), StandaloneDiag, SourceLocCache);
+      Diags.getClient()->BeginSourceFile(LangOpts, nullptr);
+      Diags.Report(StoredDiag);
+      Diags.getClient()->EndSourceFile();
+    }
+  }
+
+private:
+  DiagnosticsEngine &Diags;
+  IntrusiveRefCntPtr<FileManager> OwnedFileMgr;
+  IntrusiveRefCntPtr<SourceManager> OwnedSrcMgr;
+
+  FileManager &getFileManager() const {
+    if (OwnedFileMgr)
+      return *OwnedFileMgr;
+    return Diags.getSourceManager().getFileManager();
+  }
+
+  SourceManager &getSourceManager() const {
+    if (OwnedSrcMgr)
+      return *OwnedSrcMgr;
+    return Diags.getSourceManager();
+  }
+};
+
+/// Collects diagnostics in a form that can be retained until after their
+/// associated SourceManager is destroyed.
+class StandaloneDiagCollector : public DiagnosticConsumer {
+public:
+  void BeginSourceFile(const LangOptions &LangOpts,
+                       const Preprocessor *PP = nullptr) override {
+    this->LangOpts = &LangOpts;
+  }
+
+  void HandleDiagnostic(DiagnosticsEngine::Level Level,
+                        const Diagnostic &Info) override {
+    StoredDiagnostic StoredDiag(Level, Info);
+    StandaloneDiags.emplace_back(*LangOpts, StoredDiag);
+    DiagnosticConsumer::HandleDiagnostic(Level, Info);
+  }
+
+  void EndSourceFile() override {}
+
+  StandaloneDiagList takeDiagnostics() { return std::move(StandaloneDiags); }
+
+private:
+  const LangOptions *LangOpts = nullptr;
+  StandaloneDiagList StandaloneDiags;
+};
+
+} // anonymous namespace
+
+/// Performs a full dependency scan of the given compilation inputs.
+///
+/// Diagnostics are emitted through the driver's diagnostic engine.
+///
+/// \returns A \c DependencyScanResult on success, or \c std::nullopt on
+/// failure. The returned \c DependencyScanResult is deterministic for the given
+/// compilation inputs.
+static std::optional<DependencyScanResult> scanDependencies(
+    const JobVector &ScanInputJobs, const StdModuleManifest &Manifest,
+    size_t FirstSystemInputIndex, Compilation &C, StringRef ModuleDir) {
+  llvm::PrettyStackTraceString CrashInfo("Performing module dependency scan.");
+
+  deps::DependencyScanningService ScanningService(
+      deps::ScanningMode::DependencyDirectivesScan,
+      deps::ScanningOutputFormat::Full);
+
+  const size_t NumInputs = ScanInputJobs.size();
+
+  // TODO: Benchmark: Determine the optimal number of worker threads for a given
+  // number of inputs. How many inputs are required for multi-threading to be
+  // beneficial? How many inputs should each thread scan?
+  std::unique_ptr<llvm::ThreadPoolInterface> ThreadPool;
+  size_t WorkerCount;
+
+#if LLVM_ENABLE_THREADS
+  const bool HasSystemInputs = !Manifest.ModuleEntries.empty();
+
+  if (NumInputs <= 2) {
+    auto S = llvm::optimal_concurrency(1);
+    ThreadPool = std::make_unique<llvm::SingleThreadExecutor>(std::move(S));
+    WorkerCount = 1;
+  } else {
+    auto S = llvm::optimal_concurrency(NumInputs -
+                                       static_cast<size_t>(HasSystemInputs));
+    ThreadPool = std::make_unique<llvm::DefaultThreadPool>(std::move(S));
+    const size_t MaxConcurrency = ThreadPool->getMaxConcurrency();
+    WorkerCount = std::min(
+        MaxConcurrency,
+        NumInputs - (HasSystemInputs && NumInputs < MaxConcurrency ? 1 : 0));
+  }
+#else
+  ThreadPool = std::make_unique<llvm::SingleThreadExecutor>();
+  WorkerCount = 1;
+#endif
+
+  ScanningWorkerPool WorkerPool(WorkerCount, ScanningService,
+                                C.getDriver().getVFS());
+
+  SystemInputRegistry SysInputRegistry(FirstSystemInputIndex, Manifest);
+  ModuleLookupController LookupController(ModuleDir);
+  ScanResultCollector ResultCollector(NumInputs);
+  SmallVector<StandaloneDiagList, 0> DiagLists(NumInputs);
+  std::atomic<bool> HasError = false;
+
+  std::function<void(size_t, bool)> ScanFn;
+  ScanFn = [&](size_t InputIndex, bool IsSystem) {
+    auto CC1CommandLine = buildCommandLine(*ScanInputJobs[InputIndex]);
+    StandaloneDiagCollector DiagConsumer;
+
+    std::optional<deps::TranslationUnitDeps> TUDeps;
+    {
+      auto WorkerHandle = WorkerPool.scopedAcquire();
+      deps::FullDependencyConsumer FullDepsConsumer(WorkerHandle->SeenModules);
+      if (WorkerHandle->Worker->computeDependencies(
+              ".", CC1CommandLine, FullDepsConsumer, LookupController,
+              DiagConsumer))
+        TUDeps = FullDepsConsumer.takeTranslationUnitDeps();
+    }
+
+    // Always capture diagnostics, since even successful scans may produce
+    // warnings or notes.
+    DiagLists[InputIndex] = DiagConsumer.takeDiagnostics();
+
+    if (!TUDeps) {
+      HasError.store(true, std::memory_order_relaxed);
+      return;
+    }
+
+    // Enqueue scans for newly seen system modules required by this TU.
+    for (auto SysInputIndex :
+         SysInputRegistry.getNewSystemInputs(TUDeps->NamedModuleDeps))
+      ThreadPool->async(
+          [&ScanFn, SysInputIndex]() { ScanFn(SysInputIndex, true); });
+
+    ResultCollector.handleTUResult(std::move(*TUDeps), IsSystem, InputIndex);
+  };
+
+  // Initiate the dependency scan with all user inputs.
+  for (size_t I = 0; I < FirstSystemInputIndex; ++I)
+    ThreadPool->async([&ScanFn, I]() { ScanFn(I, /*IsSystem*/ false); });
+  ThreadPool->wait();
+
+  // Report the diagnostics for each dependency scan.
+  StandaloneDiagReporter DiagReporter(C.getDriver().getDiags());
+  for (auto &DiagsList : DiagLists)
+    DiagReporter.Report(std::move(DiagsList));
+
+  if (HasError)
+    return std::nullopt;
+
+  return ResultCollector.takeScanResults();
+}
+
+namespace {
+
+class MDGNode;
+class MDGEdge;
+using MDGNodeBase = llvm::DGNode<MDGNode, MDGEdge>;
+using MDGEdgeBase = llvm::DGEdge<MDGNode, MDGEdge>;
+using ModuleDependencyGraphBase = llvm::DirectedGraph<MDGNode, MDGEdge>;
+
+/// Abstract base class for all node kinds in the module dependency graph.
+class MDGNode : public MDGNodeBase {
+public:
+  enum class NodeKind {
+    Root,
+    ClangModule,
+    NamedModule,
+    NonModule,
+  };
+
+  explicit MDGNode(NodeKind Kind) : Kind(Kind) {}
+  virtual ~MDGNode() = 0;
+
+  /// Returns this node's kind.
+  NodeKind getKind() const { return Kind; }
+
+  /// Returns this node's Clang module dependencies.
+  virtual ArrayRef<deps::ModuleID> getClangDeps() const { return {}; }
+
+  /// Returns this node's C++ named module dependencies.
+  virtual ArrayRef<std::string> getNamedDeps() const { return {}; }
+
+private:
+  const NodeKind Kind;
+};
+
+MDGNode::~MDGNode() {}
+
+/// Represents the root node of the module dependency graph.
+///
+/// The root node only serves as an entry point for graph traversal.
+/// It should have an edge to each node that would otherwise have no incoming
+/// edges, ensuring there is always a path from the root to any node in the
+/// graph.
+/// There should be exactly one such root node in a given graph.
+class RootMDGNode final : public MDGNode {
+public:
+  /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
+  static bool classof(const MDGNode *N) {
+    return N->getKind() == NodeKind::Root;
+  }
+
+private:
+  // Only allow the graph itself to creates its own single root node.
+  friend class ModuleDependencyGraph;
+
+  RootMDGNode() : MDGNode(NodeKind::Root) {}
+};
+
+class TranslationUnitMDGNode : public MDGNode {
+protected:
+  TranslationUnitMDGNode(NodeKind K, const InputDependencies &D)
+      : MDGNode(K), InputDeps(D) {}
+
+public:
+  StringRef getFilename() const {
+    assert(!InputDeps.FileDeps.empty() &&
+           "Expected input itself to be the first file dependency.");
+    return InputDeps.FileDeps.front();
+  }
+
+  ArrayRef<deps::ModuleID> getClangDeps() const final {
+    return InputDeps.ClangModuleDeps;
+  }
+
+  ArrayRef<std::string> getNamedDeps() const final {
+    return InputDeps.NamedModuleDeps;
+  }
+
+  const InputDependencies &InputDeps;
+};
+
+/// Subclass of MDGNode representing a translation unit that provides no
+/// module of any kind.
+class NonModuleMDGNode final : public TranslationUnitMDGNode {
+public:
+  explicit NonModuleMDGNode(const InputDependencies &InputDeps)
+      : TranslationUnitMDGNode(NodeKind::NonModule, InputDeps) {}
+
+  /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
+  static bool classof(const MDGNode *N) {
+    return N->getKind() == NodeKind::NonModule;
+  }
+};
+
+/// Subclass of MDGNode representing a translation unit that provides a C++20
+/// named module interface unit.
+class CXXNamedModuleMDGNode final : public TranslationUnitMDGNode {
+public:
+  explicit CXXNamedModuleMDGNode(const InputDependencies &InputDeps)
+      : TranslationUnitMDGNode(NodeKind::NamedModule, InputDeps) {}
+
+  const deps::ModuleID &getModuleID() const { return InputDeps.ID; };
+
+  /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
+  static bool classof(const MDGNode *N) {
+    return N->getKind() == NodeKind::NamedModule;
+  }
+};
+
+/// Subclass of MDGNode representing a Clang module unit.
+class ClangModuleMDGNode final : public MDGNode {
+public:
+  explicit ClangModuleMDGNode(const deps::ModuleDeps &ClangModuleDeps)
+      : MDGNode(NodeKind::ClangModule), ModuleDeps(ClangModuleDeps) {}
+
+  /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
+  static bool classof(const MDGNode *N) {
+    return N->getKind() == NodeKind::ClangModule;
+  }
+  const deps::ModuleID &getModuleID() const { return ModuleDeps.ID; }
+
+  ArrayRef<deps::ModuleID> getClangDeps() const override {
+    return ModuleDeps.ClangModuleDeps;
+  }
+
+  const deps::ModuleDeps &ModuleDeps;
+};
+
+/// Represents an import relation in the module dependency graph, directed
+/// from the importer to the imported module.
+class MDGEdge : public MDGEdgeBase {
+public:
+  explicit MDGEdge(MDGNode &N) : MDGEdgeBase(N) {}
+  MDGEdge() = delete;
+};
+
+/// A directed graph describing the full dependency relations of this
+/// compilation.
+///
+/// The graph owns all of its nodes and edges.
+/// The graph's root node is initialized on construction.
+class ModuleDependencyGraph : public ModuleDependencyGraphBase {
+public:
+  ModuleDependencyGraph() {
+    Root = new (Alloc.Allocate(sizeof(RootMDGNode), alignof(RootMDGNode)))
+        RootMDGNode();
+    addNode(*Root);
+  }
+
+  MDGNode *getRoot() { return Root; }
+  const MDGNode *getRoot() const { return Root; }
+
+  llvm::BumpPtrAllocator &getAllocator() { return Alloc; }
+
+private:
+  llvm::BumpPtrAllocator Alloc;
+  RootMDGNode *Root = nullptr;
+};
+
+} // anonymous namespace
+
+/// Allocation helper using the graph's allocator.
+template <typename MDGComponent, typename... Args>
+static MDGComponent *makeWithAlloc(llvm::BumpPtrAllocator &Alloc,
+                                   Args &&...args) {
+  return new (Alloc.Allocate(sizeof(MDGComponent), alignof(MDGComponent)))
+      MDGComponent(std::forward<Args>(args)...);
+}
+
+/// Builds all Clang module nodes from \c ClangModuleDeps for \c Graph and
+/// registers them in \c ClangModuleMap.
+static void buildClangModuleNodes(
+    ModuleDependencyGraph &Graph, ArrayRef<deps::ModuleDeps> ClangModuleDeps,
+    llvm::DenseMap<deps::ModuleID, ClangModuleMDGNode *> &ClangModuleMap) {
+  auto &Alloc = Graph.getAllocator();
+  for (auto &M : ClangModuleDeps) {
+    auto *Node = makeWithAlloc<ClangModuleMDGNode>(Alloc, M);
+    Graph.addNode(*Node);
+    const auto [It, Inserted] = ClangModuleMap.try_emplace(M.ID, Node);
+    assert(Inserted && "Duplicate Clang module in scan result.");
+  }
+}
+
+/// Builds translation unit nodes from \c InputDeps for \c Graph and registers
+/// all named module nodes in \c NamedModuleMap.
+///
+/// \returns true on success, if no duplicate modules are detected.
+static bool buildTranslationUnitNodes(
+    ModuleDependencyGraph &Graph,
+    ArrayRef<std::optional<InputDependencies>> InputDeps,
+    llvm::DenseMap<StringRef, CXXNamedModuleMDGNode *> &NamedModuleMap,
+    DiagnosticsEngine &Diags) {
+  auto &Alloc = Graph.getAllocator();
+  bool HasDuplicate = false;
+
+  for (auto &Dep : InputDeps) {
+    if (!Dep)
+      continue;
+
+    MDGNode *Node = nullptr;
+    if (Dep->ID.ModuleName.empty()) {
+      // If there is no module name, this is a regular non-module TU.
+      Node = makeWithAlloc<NonModuleMDGNode>(Alloc, *Dep);
+    } else {
+      // There is a module name; this is a named module interface unit.
+      Node = makeWithAlloc<CXXNamedModuleMDGNode>(Alloc, *Dep);
+      const auto [It, Inserted] = NamedModuleMap.try_emplace(
+          Dep->ID.ModuleName, static_cast<CXXNamedModuleMDGNode *>(Node));
+      if (!Inserted) {
+        // We have multiple source files which define the same module.
+        Diags.Report(diag::err_mod_graph_named_module_redefinition)
+            << Dep->ID.ModuleName << It->second->InputDeps.FileDeps.front()
+            << Dep->FileDeps.front();
+        HasDuplicate = true;
+      }
+    }
+
+    Graph.addNode(*Node);
+  }
+
+  return !HasDuplicate;
+}
+
+/// Adds edges from \c Importer to nodes referenced in \c Map for each
+/// dependency in \c Dependencies.
+template <typename DepTy, typename MapTy>
+static void addNodeEdges(MDGNode &Importer, ArrayRef<DepTy> Dependencies,
+                         MapTy &NodeMap,
+                         llvm::SmallPtrSetImpl<MDGNode *> &HasIncoming,
+                         llvm::BumpPtrAllocator &Alloc) {
+  for (const auto &Dep : Dependencies) {
+    if (auto It = NodeMap.find(Dep); It != NodeMap.end()) {
+      // TODO: For imports to unknown modules, check if a prebuilt module is
+      // provided via -fmodule-file.
+      // FIXME: TranslationUnitDeps::PrebuiltModuleDeps does currently not
+      // provide this information for named modules provided via
+      // -fmodule-file.
+      HasIncoming.insert(It->second);
+      auto *Edge = makeWithAlloc<MDGEdge>(Alloc, *It->second);
+      Importer.addEdge(*Edge);
+    }
+  }
+}
+
+/// Connects all nodes in \c Graph to their dependencies and links the root
+/// node to nodes with otherwise no incoming edges.
+static void connectGraphNodes(
+    ModuleDependencyGraph &Graph,
+    const llvm::DenseMap<deps::ModuleID, ClangModuleMDGNode *> &ClangModuleMap,
+    const llvm::DenseMap<StringRef, CXXNamedModuleMDGNode *> &NamedModuleMap) {
+  auto &Alloc = Graph.getAllocator();
+
+  llvm::SmallPtrSet<MDGNode *, 16> HasIncoming;
+  HasIncoming.reserve(Graph.size());
+
+  for (auto *Node : Graph) {
+    addNodeEdges(*Node, Node->getClangDeps(), ClangModuleMap, HasIncoming,
+                 Alloc);
+    addNodeEdges(*Node, Node->getNamedDeps(), NamedModuleMap, HasIncoming,
+                 Alloc);
+  }
+
+  // Link the root node to all other nodes with no incoming edges.
+  assert(*Graph.begin() == Graph.getRoot() &&
+         "Expected root node to be first in graph iteration order!");
+  auto NodesWithoutRoot = llvm::drop_begin(Graph);
+  for (auto *Node : NodesWithoutRoot) {
+    if (!HasIncoming.contains(Node)) {
+      auto *Edge = makeWithAlloc<MDGEdge>(Alloc, *Node);
+      Graph.getRoot()->addEdge(*Edge);
+    }
+  }
+}
+
+/// Construct a module dependency graph from the scan result.
+static std::optional<ModuleDependencyGraph>
+buildModuleDependencyGraph(DependencyScanResult &ScanResult,
+                           DiagnosticsEngine &Diags) {
+  ModuleDependencyGraph Graph;
+
+  // Lookup maps, used for connecting the nodes.
+  llvm::DenseMap<deps::ModuleID, ClangModuleMDGNode *> ClangModuleMap;
+  llvm::DenseMap<StringRef, CXXNamedModuleMDGNode *> NamedModuleMap;
+
+  buildClangModuleNodes(Graph, ScanResult.ClangModuleDeps, ClangModuleMap);
+  if (!buildTranslationUnitNodes(Graph, ScanResult.InputDeps, NamedModuleMap,
+                                 Diags))
+    return std::nullopt;
+  connectGraphNodes(Graph, ClangModuleMap, NamedModuleMap);
+
+  return Graph;
+}
+
+namespace llvm {
+
+/// Non-const versions of the GraphTraits specializations for ModuleDepGraph.
+template <> struct GraphTraits<MDGNode *> {
+  using NodeRef = MDGNode *;
+
+  static NodeRef MDGGetTargetNode(MDGEdgeBase *E) {
+    return &E->getTargetNode();
+  }
+
+  using ChildIteratorType =
+      mapped_iterator<MDGNode::iterator, decltype(&MDGGetTargetNode)>;
+  using ChildEdgeIteratorType = MDGNode::iterator;
+
+  static NodeRef getEntryNode(NodeRef N) { return N; }
+
+  static ChildIteratorType child_begin(NodeRef N) {
+    return ChildIteratorType(N->begin(), &MDGGetTargetNode);
+  }
+
+  static ChildIteratorType child_end(NodeRef N) {
+    return ChildIteratorType(N->end(), &MDGGetTargetNode);
+  }
+
+  static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
+    return N->begin();
+  }
+  static ChildEdgeIteratorType child_edge_end(NodeRef N) { return N->end(); }
+};
+
+template <>
+struct GraphTraits<ModuleDependencyGraph *> : GraphTraits<MDGNode *> {
+  using GraphRef = ModuleDependencyGraph *;
+  using NodeRef = MDGNode *;
+
+  using nodes_iterator = ModuleDependencyGraph::iterator;
+
+  static NodeRef getEntryNode(GraphRef G) { return G->getRoot(); }
+
+  static nodes_iterator nodes_begin(GraphRef G) { return G->begin(); }
+
+  static nodes_iterator nodes_end(GraphRef G) { return G->end(); }
+};
+
+/// Const versions of the GraphTraits specializations for ModuleDepGraph.
+template <> struct GraphTraits<const MDGNode *> {
+  using NodeRef = const MDGNode *;
+
+  static NodeRef MDGGetTargetNode(const MDGEdgeBase *E) {
+    return &E->getTargetNode();
+  }
+
+  using ChildIteratorType =
+      mapped_iterator<MDGNode::const_iterator, decltype(&MDGGetTargetNode)>;
+  using ChildEdgeIteratorType = MDGNode::const_iterator;
+
+  static NodeRef getEntryNode(NodeRef N) { return N; }
+
+  static ChildIteratorType child_begin(NodeRef N) {
+    return ChildIteratorType(N->begin(), &MDGGetTargetNode);
+  }
+
+  static ChildIteratorType child_end(NodeRef N) {
+    return ChildIteratorType(N->end(), &MDGGetTargetNode);
+  }
+
+  static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
+    return N->begin();
+  }
+
+  static ChildEdgeIteratorType child_edge_end(NodeRef N) { return N->end(); }
+};
+
+template <>
+struct GraphTraits<const ModuleDependencyGraph *>
+    : GraphTraits<const MDGNode *> {
+  using GraphRef = const ModuleDependencyGraph *;
+  using NodeRef = const MDGNode *;
+
+  using nodes_iterator = ModuleDependencyGraph::const_iterator;
+
+  static NodeRef getEntryNode(GraphRef G) { return G->getRoot(); }
+
+  static nodes_iterator nodes_begin(GraphRef G) { return G->begin(); }
+
+  static nodes_iterator nodes_end(GraphRef G) { return G->end(); }
+};
+
+template <>
+struct DOTGraphTraits<const ModuleDependencyGraph *> : DefaultDOTGraphTraits {
+  explicit DOTGraphTraits(bool IsSimple = false)
+      : DefaultDOTGraphTraits(IsSimple) {}
+
+  static std::string getGraphName(const ModuleDependencyGraph *) {
+    return "Module Dependency Graph";
+  }
+
+  static std::string getGraphProperties(const ModuleDependencyGraph *) {
+    return "\tnode [colorscheme=pastel13,style=filled,shape=Mrecord];\n\tedge "
+           "[dir=\"back\"];\n";
+  }
+
+  static bool isNodeHidden(const MDGNode *N, const ModuleDependencyGraph *G) {
+    assert(N && "Node must not be null");
+    return isa<RootMDGNode>(N);
+  }
+
+  static std::string getNodeIdentifier(const MDGNode *N,
+                                       const ModuleDependencyGraph *) {
+    assert(N && "Node must not be null");
+    return llvm::TypeSwitch<const MDGNode *, std::string>(N)
+        .Case<ClangModuleMDGNode>([](const ClangModuleMDGNode *Node) {
+          const auto &ID = Node->getModuleID();
+          return (Twine(ID.ModuleName) + ":" + ID.ContextHash).str();
+        })
+        .Case<CXXNamedModuleMDGNode>([](const CXXNamedModuleMDGNode *Node) {
+          return Node->getModuleID().ModuleName;
+        })
+        .Case<NonModuleMDGNode>(
+            [](const NonModuleMDGNode *Node) { return Node->getFilename(); });
+  }
+
+  static std::string getNodeLabel(const MDGNode *N,
+                                  const ModuleDependencyGraph *) {
+    assert(N && "Node must not be null");
+    SmallString<128> Buf;
+    raw_svector_ostream OS(Buf);
+
+    auto PrintModuleKind = [&](StringRef Kind) { OS << "Kind: " << Kind; };
+    auto PrintModuleName = [&](StringRef Name) {
+      OS << "Module name: " << Name;
+    };
+    auto PrintFilename = [&](StringRef Filename) {
+      OS << "Filename: " << Filename;
+    };
+    auto PrintInputOrigin = [&](bool IsSystem) {
+      OS << "Input origin: " << (IsSystem ? "System" : "User");
+    };
+    auto PrintContextHash = [&](StringRef Hash) { OS << "Hash: " << Hash; };
+
+    llvm::TypeSwitch<const MDGNode *>(N)
+        .Case<ClangModuleMDGNode>([&](const ClangModuleMDGNode *Node) {
+          PrintModuleKind("Clang module");
+          OS << " \\| ";
+          PrintModuleName(Node->getModuleID().ModuleName);
+          OS << " \\| ";
+          OS << "Modulemap file: " << Node->ModuleDeps.ClangModuleMapFile;
+          OS << " \\| ";
+          PrintInputOrigin(Node->ModuleDeps.IsSystem);
+          OS << " \\| ";
+          PrintContextHash(Node->getModuleID().ContextHash);
+        })
+        .Case<CXXNamedModuleMDGNode>([&](const CXXNamedModuleMDGNode *Node) {
+          PrintModuleKind("C++ named module");
+          OS << " \\| ";
+          PrintModuleName(Node->getModuleID().ModuleName);
+          OS << " \\| ";
+          PrintFilename(Node->getFilename());
+          OS << " \\| ";
+          PrintInputOrigin(Node->InputDeps.IsSystem);
+          OS << " \\| ";
+          PrintContextHash(Node->getModuleID().ContextHash);
+        })
+        .Case<NonModuleMDGNode>([&](const NonModuleMDGNode *Node) {
+          PrintModuleKind("Non-module");
+          OS << " \\| ";
+          PrintFilename(Node->getFilename());
+        });
+
+    return std::string(OS.str());
+  }
+
+  static std::string getNodeAttributes(const MDGNode *N,
+                                       const ModuleDependencyGraph *) {
+    assert(N && "Node must not be null");
+    return llvm::TypeSwitch<const MDGNode *, std::string>(N)
+        .Case<ClangModuleMDGNode>(
+            [&](const ClangModuleMDGNode *) { return "fillcolor=1"; })
+        .Case<CXXNamedModuleMDGNode>(
+            [&](const CXXNamedModuleMDGNode *) { return "fillcolor=2"; })
+        .Case<NonModuleMDGNode>(
+            [&](const NonModuleMDGNode *) { return "fillcolor=3"; });
+  }
+};
+
+/// GraphWriter specialization for ModuleDepGraph.
+///
+/// Uses human-readable identifiers instead of raw pointers and separates node
+/// definitions from import edges for a more remark-friendly output.
+template <>
+class GraphWriter<const ModuleDependencyGraph *>
+    : public GraphWriterBase<const ModuleDependencyGraph *,
+                             GraphWriter<const ModuleDependencyGraph *>> {
+public:
+  using GraphType = const ModuleDependencyGraph *;
+  using Base = GraphWriterBase<GraphType, GraphWriter<GraphType>>;
+
+  GraphWriter(llvm::raw_ostream &O, const GraphType &G, bool IsSimple)
+      : Base(O, G, IsSimple) {}
+
+  void writeNodes();
+
+private:
+  using Base::DOTTraits;
+  using Base::GTraits;
+  using Base::NodeRef;
+
+  DenseMap<NodeRef, std::string> NodeIDMap;
+
+  void writeNodeDefinitions(ArrayRef<NodeRef> Nodes);
+  void writeNodeRelations(ArrayRef<NodeRef> Nodes);
+};
+
+void llvm::GraphWriter<const ModuleDependencyGraph *>::writeNodes() {
+  auto IsNodeVisible = [&](NodeRef N) { return !DTraits.isNodeHidden(N, G); };
+  const auto VisibleNodeRange = make_filter_range(nodes(G), IsNodeVisible);
+  const SmallVector<NodeRef, 0> VisibleNodes(VisibleNodeRange);
+
+  writeNodeDefinitions(VisibleNodes);
+  writeNodeRelations(VisibleNodes);
+}
+
+void llvm::GraphWriter<const ModuleDependencyGraph *>::writeNodeDefinitions(
+    ArrayRef<NodeRef> Nodes) {
+  for (const auto *Node : Nodes) {
+    const auto NodeID = DTraits.getNodeIdentifier(Node, G);
+    const auto NodeLabel = DTraits.getNodeLabel(Node, G);
+    O << "\t\"" << DOT::EscapeString(NodeID) << "\" [ "
+      << DTraits.getNodeAttributes(Node, G) << ",label=\"{ "
+      << DOT::EscapeString(NodeLabel) << " }\"];\n";
+    NodeIDMap.try_emplace(Node, std::move(NodeID));
+  }
+  O << "\n";
+}
+
+void llvm::GraphWriter<const ModuleDependencyGraph *>::writeNodeRelations(
+    ArrayRef<NodeRef> Nodes) {
+  for (const auto *Node : Nodes) {
+    const auto &SourceNodeID = NodeIDMap.at(Node);
+    for (const auto *Edge : Node->getEdges()) {
+      const auto *TargetNode = GTraits::MDGGetTargetNode(Edge);
+      const auto &TargetNodeID = NodeIDMap.at(TargetNode);
+      O << "\t\"" << DOT::EscapeString(SourceNodeID) << "\" -> \""
+        << DOT::EscapeString(TargetNodeID) << "\";\n";
+    }
+  }
+}
+
+} // namespace llvm
+
+/// Adds each system include directory in \p SystemIncludeDirs to \p Job's
+/// arguments.
+static void
+addSystemIncludeDirsFromManifest(Compilation &C, Command &Job,
+                                 ArrayRef<std::string> SystemIncludeDirs) {
+  const auto &TC = Job.getCreator().getToolChain();
+  const auto &TCArgs = C.getArgsForToolChain(
+      &TC, /*BoundArch*/ "", Job.getSource().getOffloadingDeviceKind());
+  auto &CC1Args = Job.getArguments();
+
+  for (const auto &IncludeDir : SystemIncludeDirs)
+    TC.addSystemInclude(TCArgs, CC1Args, IncludeDir);
+}
+
+/// Applies local module arguments from the \c Manifest to the corresponding
+/// system input jobs in \c ScanJobs.
+static void applyLocalArgsFromManifest(Compilation &C, JobVector &ScanJobs,
+                                       size_t FirstSystemInputIndex,
+                                       const StdModuleManifest &Manifest) {
+  auto SystemInputJobs = ArrayRef(ScanJobs).slice(FirstSystemInputIndex);
+  for (auto &&[Job, ManifestEntry] :
+       llvm::zip_equal(SystemInputJobs, Manifest.ModuleEntries)) {
+    const auto &LocalArgs = ManifestEntry.LocalArgs;
+    if (LocalArgs)
+      addSystemIncludeDirsFromManifest(C, *Job, LocalArgs->SystemIncludeDirs);
+  }
+}
+
+/// Computes the -fmodule-cache-path for this compilation.
+static SmallString<128> getModuleCachePath(DerivedArgList &Args) {
+  SmallString<128> Path;
+  if (const auto *A = Args.getLastArg(options::OPT_fmodules_cache_path))
+    Path = A->getValue();
+  else
+    driver::Driver::getDefaultModuleCachePath(Path);
+  return Path;
+}
+
+void driver::modules::planDriverManagedModuleCompilation(
+    Compilation &C, const StdModuleManifest &Manifest) {
+  llvm::PrettyStackTraceString CrashInfo("Planning modules build.");
+  auto &Diags = C.getDriver().getDiags();
+
+  auto [ScanInputJobs, OtherJobs] =
+      splitCommandsByScanEligibility(C.getJobs().takeJobs());
+
+  const size_t SystemInputCount = Manifest.ModuleEntries.size();
+  const size_t FirstSystemInputIndex = ScanInputJobs.size() - SystemInputCount;
+
+#ifndef NDEBUG
+  // System module inputs are appended to the end of the compilation input list,
+  // in the same order as they appear in the standard module manifest.
+  // We assume these manifest-provided inputs are appended last.
+  // If this assumption ever breaks, explicitly partition the jobs by matching
+  // their inputs against the manifest paths.
+  const auto SysInputJobsForScan =
+      ArrayRef(ScanInputJobs).take_back(SystemInputCount);
+  for (const auto &[Job, ManifestEntry] :
+       llvm::zip_equal(SysInputJobsForScan, Manifest.ModuleEntries)) {
+    const auto &InputInfos = Job->getInputInfos();
+    assert(InputInfos.size() == 1 && "Expected exactly one dependency "
+                                     "scanning input for each system module");
+    assert(InputInfos.front().getFilename() == ManifestEntry.SourcePath &&
+           "System module input order should match order in manifest!");
+  }
+#endif
+
+  // Apply manifest-specified local arguments before scanning as they may affect
+  // the scan results.
+  applyLocalArgsFromManifest(C, ScanInputJobs, FirstSystemInputIndex, Manifest);
+
+  const auto ModuleCachePath = getModuleCachePath(C.getArgs());
+
+  // Run the dependency scan.
+  auto ScanResults = scanDependencies(
+      ScanInputJobs, Manifest, FirstSystemInputIndex, C, ModuleCachePath);
+  if (!ScanResults) {
+    Diags.Report(diag::err_failed_dependency_scan);
+    return;
+  }
+
+  // TODO: Remove driver jobs for module inputs generated from the standard
+  // library manifest that are unused in this compilation (i.e., each job
+  // corresponding to a std::nullopt in ScanResults).
+
+  // TODO: Generate driver jobs for each Clang module and update the other
+  // driver jobs with the scan-generated command lines.
+
+  // Construct the module dependency graph.
+  // TODO: Attach all jobs to the graph during construction.
+  auto MaybeModuleGraph = buildModuleDependencyGraph(*ScanResults, Diags);
+  if (!MaybeModuleGraph) {
+    Diags.Report(diag::err_building_dependency_graph);
+    return;
+  }
+  Diags.Report(diag::remark_printing_module_graph);
+  if (!Diags.isLastDiagnosticIgnored())
+    llvm::WriteGraph<const ModuleDependencyGraph *>(llvm::errs(),
+                                                    &(*MaybeModuleGraph));
+
+  // TODO: Detect cyclic dependencies in the module dependency graph.
+
+  // TODO: Update each driver job's command line to emit or pass-in the correct
+  // module files.
+
+  // Merge the jobs back into the compilation's job list.
+  for (auto &Job :
+       llvm::concat<std::unique_ptr<Command>>(ScanInputJobs, OtherJobs))
+    C.addCommand(std::move(Job));
+}
diff --git a/clang/test/Driver/modules-driver-dep-graph-with-system-inputs.cpp b/clang/test/Driver/modules-driver-dep-graph-with-system-inputs.cpp
new file mode 100644
index 0000000000000..09ead08302c78
--- /dev/null
+++ b/clang/test/Driver/modules-driver-dep-graph-with-system-inputs.cpp
@@ -0,0 +1,102 @@
+// This test checks the on-demand scanning of system inputs, in particular:
+// 1. System inputs are scanned only when needed.
+// 2. Imports between system modules are supported.
+
+// RUN: split-file %s %t
+
+// The standard library modules manifest (libc++.modules.json) is discovered
+// relative to the installed C++ standard library runtime libraries
+// We need to create them in order for Clang to find the manifest.
+// RUN: rm -rf %t && split-file %s %t && cd %t
+// RUN: mkdir -p %t/Inputs/usr/lib/x86_64-linux-gnu
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
+
+// RUN: sed "s|DIR|%/t|g" %t/libc++.modules.json.in > \
+// RUN:   %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json
+
+// RUN: mkdir -p %t/Inputs/usr/lib/share/libc++/v1
+// RUN: mkdir -p %t/Inputs/usr/lib/share/libc++/v2
+// RUN: cat %t/std.cppm > %t/Inputs/usr/lib/share/libc++/v1/std.cppm
+// RUN: cat %t/std.compat.cppm > %t/Inputs/usr/lib/share/libc++/v1/std.compat.cppm
+
+// RUN: %clang -std=c++20 \
+// RUN:   -fmodules-driver -Rmodules-driver \
+// RUN:   -stdlib=libc++ \
+// RUN:   -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
+// RUN:   --target=x86_64-linux-gnu \
+// RUN:   -fmodules-cache-path=%t/modules-cache \
+// RUN:   %t/main.cpp %t/foo.cpp \
+// RUN:   -### 2>&1 \
+// RUN:   | sed 's:\\\\\?:/:g' \
+// RUN:   | FileCheck %s -DPREFIX=%/t
+
+// CHECK:      remark: using standard modules manifest file '[[PREFIX]]/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json' [-Rmodules-driver]
+// CHECK-NOT:  remark: standard modules manifest file not found; import of standard library modules not supported [-Rmodules-driver]
+// CHECK:      remark: printing module dependency graph [-Rmodules-driver]
+// CHECK-NEXT: digraph "Module Dependency Graph" {
+// CHECK-NEXT:         label="Module Dependency Graph";
+
+// CHECK:              "[[PREFIX]]/main.cpp" [ fillcolor=[[COLOR1:[0-9]+]],label="{ Kind: Non-module | Filename: [[PREFIX]]/main.cpp }"];
+// CHECK-NEXT:         "[[PREFIX]]/foo.cpp" [ fillcolor=[[COLOR1]],label="{ Kind: Non-module | Filename: [[PREFIX]]/foo.cpp }"];
+// CHECK-NEXT:         "std" [ fillcolor=[[COLOR2:[0-9]+]],label="{ Kind: C++ named module | Module name: std | Filename: [[PREFIX]]/Inputs/usr/lib/share/libc++/v1/std.cppm | Input origin: System | Hash: {{.*}} }"];
+// CHECK-NEXT:         "std.compat" [ fillcolor=[[COLOR2]],label="{ Kind: C++ named module | Module name: std.compat | Filename: [[PREFIX]]/Inputs/usr/lib/share/libc++/v1/std.compat.cppm | Input origin: System | Hash: {{.*}} }"];
+// CHECK-NEXT:         "core" [ fillcolor=[[COLOR2]],label="{ Kind: C++ named module | Module name: core | Filename: [[PREFIX]]/core.cxxm | Input origin: System | Hash: {{.*}} }"];
+
+// CHECK:              "[[PREFIX]]/main.cpp" -> "std";
+// CHECK-NEXT:         "[[PREFIX]]/main.cpp" -> "std.compat";
+// CHECK-NEXT:         "[[PREFIX]]/foo.cpp" -> "core";
+// CHECK-NEXT:         "std.compat" -> "std";
+// CHECK-NEXT: }
+
+
+//--- main.cpp
+import std;
+import std.compat;
+
+//--- foo.cpp
+import core;
+
+//--- std.cppm
+export module std;
+
+//--- std.compat.cppm
+export module std.compat;
+import std;
+
+// The module 'core' is isn't really a system module in libc++ or libstdc++.
+// This is only to test that any module marked with '"is-std-library": true' can 
+// be imported on demand.
+//--- core.cxxm
+export module core;
+
+//--- unused.cppm
+export module unused;
+
+//--- libc++.modules.json.in
+{
+  "version": 1,
+  "revision": 1,
+  "modules": [
+    {
+      "logical-name": "std",
+      "source-path": "../share/libc++/v1/std.cppm",
+      "is-std-library": true
+    },
+    {
+      "logical-name": "std.compat",
+      "source-path": "../share/libc++/v1/std.compat.cppm",
+      "is-std-library": true
+    },
+    {
+      "logical-name": "core",
+      "source-path": "DIR/core.cxxm",
+      "is-std-library": true
+    },
+    {
+      "logical-name": "unused",
+      "source-path": "DIR/unused.cppm",
+      "is-std-library": true
+    }
+  ]
+}
diff --git a/clang/test/Driver/modules-driver-dep-graph.cpp b/clang/test/Driver/modules-driver-dep-graph.cpp
new file mode 100644
index 0000000000000..5f3862a28da5f
--- /dev/null
+++ b/clang/test/Driver/modules-driver-dep-graph.cpp
@@ -0,0 +1,95 @@
+// Tests that the module dependency scan and the module dependency graph
+// generation are correct.
+// This test does not make use of any system inputs.
+
+// RUN: split-file %s %t
+
+// RUN: %clang -std=c++23 -nostdlib -fmodules \
+// RUN:   -fmodules-driver -Rmodules-driver \
+// RUN:   -fmodule-map-file=%t/module.modulemap %t/main.cpp \
+// RUN:   -fmodules-cache-path=%t/modules-cache \
+// RUN:   %t/A.cpp %t/A-B.cpp %t/A-C.cpp %t/B.cpp -### 2>&1 \
+// RUN:   | sed 's:\\\\\?:/:g' \
+// RUN:   | FileCheck -DPREFIX=%/t --check-prefixes=CHECK %s
+
+// CHECK:      clang: remark: standard modules manifest file not found; import of standard library modules not supported [-Rmodules-driver]
+
+// CHECK:      clang: remark: printing module dependency graph [-Rmodules-driver]
+// CHECK-NEXT: digraph "Module Dependency Graph" {
+// CHECK-NEXT:         label="Module Dependency Graph";
+// CHECK-NEXT:         node [colorscheme={{.*}},style=filled,shape=Mrecord];
+// CHECK-NEXT:         edge [dir="back"];
+
+// CHECK:              "transitive1:[[HASH_TRANSITIVE1:.*]]" [ fillcolor=1,label="{ Kind: Clang module | Module name: transitive1 | Modulemap file: [[PREFIX]]/module.modulemap | Input origin: User | Hash: [[HASH_TRANSITIVE1]] }"];
+// CHECK-NEXT:         "transitive2:[[HASH_TRANSITIVE2:.*]]" [ fillcolor=1,label="{ Kind: Clang module | Module name: transitive2 | Modulemap file: [[PREFIX]]/module.modulemap | Input origin: User | Hash: [[HASH_TRANSITIVE2]] }"];
+// CHECK-NEXT:         "direct1:[[HASH_DIRECT1:.*]]" [ fillcolor=1,label="{ Kind: Clang module | Module name: direct1 | Modulemap file: [[PREFIX]]/module.modulemap | Input origin: User | Hash: [[HASH_DIRECT1]] }"];
+// CHECK-NEXT:         "direct2:[[HASH_DIRECT2:.*]]" [ fillcolor=1,label="{ Kind: Clang module | Module name: direct2 | Modulemap file: [[PREFIX]]/module.modulemap | Input origin: User | Hash: [[HASH_DIRECT2]] }"];
+// CHECK-NEXT:         "root:[[HASH_ROOT:.*]]" [ fillcolor=1,label="{ Kind: Clang module | Module name: root | Modulemap file: [[PREFIX]]/module.modulemap | Input origin: User | Hash: [[HASH_ROOT]] }"];
+// CHECK-NEXT:         "[[PREFIX]]/main.cpp" [ fillcolor=3,label="{ Kind: Non-module | Filename: [[PREFIX]]/main.cpp }"];
+// CHECK-NEXT:         "A" [ fillcolor=2,label="{ Kind: C++ named module | Module name: A | Filename: [[PREFIX]]/A.cpp | Input origin: User | Hash: {{.*}} }"];
+// CHECK-NEXT:         "A:B" [ fillcolor=2,label="{ Kind: C++ named module | Module name: A:B | Filename: [[PREFIX]]/A-B.cpp | Input origin: User | Hash: {{.*}} }"];
+// CHECK-NEXT:         "A:C" [ fillcolor=2,label="{ Kind: C++ named module | Module name: A:C | Filename: [[PREFIX]]/A-C.cpp | Input origin: User | Hash: {{.*}} }"];
+// CHECK-NEXT:         "B" [ fillcolor=2,label="{ Kind: C++ named module | Module name: B | Filename: [[PREFIX]]/B.cpp | Input origin: User | Hash: {{.*}} }"];
+
+// CHECK:              "direct1:[[HASH_DIRECT1]]" -> "transitive1:[[HASH_TRANSITIVE1]]";
+// CHECK-NEXT:         "direct1:[[HASH_DIRECT1]]" -> "transitive2:[[HASH_TRANSITIVE2]]";
+// CHECK-NEXT:         "direct2:[[HASH_DIRECT2]]" -> "transitive1:[[HASH_TRANSITIVE1]]";
+// CHECK-NEXT:         "root:[[HASH_ROOT]]" -> "direct1:[[HASH_DIRECT1]]";
+// CHECK-NEXT:         "root:[[HASH_ROOT]]" -> "direct2:[[HASH_DIRECT2]]";
+// CHECK-NEXT:         "[[PREFIX]]/main.cpp" -> "root:[[HASH_ROOT]]";
+// CHECK-NEXT:         "[[PREFIX]]/main.cpp" -> "A";
+// CHECK-NEXT:         "[[PREFIX]]/main.cpp" -> "B";
+// CHECK-NEXT:         "A" -> "A:B";
+// CHECK-NEXT:         "A" -> "A:C";
+// CHECK-NEXT:         "A:B" -> "direct1:[[HASH_DIRECT1]]";
+// CHECK-NEXT:         "B" -> "root:[[HASH_ROOT]]";
+// CHECK-NEXT:         "B" -> "A";
+// CHECK-NEXT: }
+
+//--- module.modulemap
+module root { header "root.h" }
+module direct1 { header "direct1.h" }
+module direct2 { header "direct2.h" }
+module transitive1 { header "transitive1.h" }
+module transitive2 { header "transitive2.h" }
+
+//--- root.h
+#include "direct1.h"
+#include "direct2.h"
+
+//--- direct1.h
+#include "transitive1.h"
+#include "transitive2.h"
+
+//--- direct2.h
+#include "transitive1.h"
+
+//--- transitive1.h
+// empty
+
+//--- transitive2.h
+// empty
+
+//--- A.cpp
+export module A;
+export import :B;
+import :C;
+
+//--- A-B.cpp
+module;
+#include "direct1.h"
+export module A:B;
+
+//--- A-C.cpp
+export module A:C;
+
+//--- B.cpp
+module;
+#include "root.h"
+export module B;
+import A;
+
+//--- main.cpp
+#include "root.h"
+import A;
+import B;
diff --git a/clang/test/Driver/modules-driver-dep-scan-diagnostics.cpp b/clang/test/Driver/modules-driver-dep-scan-diagnostics.cpp
new file mode 100644
index 0000000000000..ff141faf644eb
--- /dev/null
+++ b/clang/test/Driver/modules-driver-dep-scan-diagnostics.cpp
@@ -0,0 +1,25 @@
+// Tests that the module dependency scan properly outputs diagnostics which 
+// were collected during the dependency scan.
+
+// RUN: split-file %s %t
+
+// RUN: not %clang -### -fmodules -fmodules-driver -Rmodules-driver \
+// RUN:   -fmodule-map-file=%t/module.modulemap %t/main.cpp 2>&1 \
+// RUN:   -fmodules-cache-path=%t/modules-cache \
+// RUN:  | FileCheck --check-prefixes=CHECK %s
+
+//--- module.modulemap
+module a { header "a.h" }
+
+//--- a.h
+// Diagnostics collected during the dependency scan need to be translated to
+// and from a representation that can outlive the compiler invocation they
+// were generated by.
+// We test that the diagnostics source location is translated correctly:
+//----10|-------20|--------30|
+#include /*just some space*/ "doesnotexist.h"
+// CHECK: a.h:6:30: fatal error: 'doesnotexist.h' file not found
+
+//--- main.cpp
+#include "a.h"
+// CHECK: clang: error: failed to perform dependency scan
diff --git a/clang/test/Driver/modules-driver-duplicate-named-module.cpp b/clang/test/Driver/modules-driver-duplicate-named-module.cpp
new file mode 100644
index 0000000000000..15fe3894b9be8
--- /dev/null
+++ b/clang/test/Driver/modules-driver-duplicate-named-module.cpp
@@ -0,0 +1,20 @@
+// Verify that the modules driver rejects ambiguous module definitions.
+
+// RUN: split-file %s %t
+
+// RUN: not %clang -std=c++23 -fmodules -fmodules-driver -Rmodules-driver \
+// RUN:   %t/main.cpp %t/A1.cpp %t/A2.cpp 2>&1 \
+// RUN:   | sed 's:\\\\\?:/:g' \
+// RUN:   | FileCheck -DPREFIX=%/t --check-prefixes=CHECK %s
+
+/// CHECK: clang: error: duplicate definitions of C++20 named module 'A' in '[[PREFIX]]/A1.cpp' and '[[PREFIX]]/A2.cpp'
+/// CHECK: clang: error: failed to construct the module dependency graph
+
+//--- main.cpp
+import A;
+
+//--- A1.cpp
+export module A;
+
+//--- A2.cpp
+export module A;
diff --git a/clang/test/Driver/modules-driver-malformed-module-manifest.cpp b/clang/test/Driver/modules-driver-malformed-module-manifest.cpp
new file mode 100644
index 0000000000000..0a925db8089e5
--- /dev/null
+++ b/clang/test/Driver/modules-driver-malformed-module-manifest.cpp
@@ -0,0 +1,41 @@
+// Verify that a malformed standard modules manifest triggers an error.
+
+// RUN: split-file %s %t
+
+// The standard library modules manifest (libc++.modules.json) is discovered
+// relative to the installed C++ standard library runtime libraries
+// We need to create them in order for Clang to find the manifest.
+// RUN: rm -rf %t && split-file %s %t && cd %t
+// RUN: mkdir -p %t/Inputs/usr/lib/x86_64-linux-gnu
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
+
+// Add the standard module manifest itself.
+// RUN: cat %t/libc++.modules.json.in > \
+// RUN:   %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json
+
+// RUN: not %clang -std=c++20 \
+// RUN:   -fmodules-driver -Rmodules-driver \
+// RUN:   -stdlib=libc++ \
+// RUN:   -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
+// RUN:   --target=x86_64-linux-gnu \
+// RUN:   -fmodules-cache-path=%t/modules-cache \
+// RUN:   main.cpp \
+// RUN:   -### 2>&1 \
+// RUN:   | sed 's:\\\\\?:/:g' \
+// RUN:   | FileCheck %s -DPREFIX=%/t
+
+// CHECK: remark: using standard modules manifest file '[[PREFIX]]/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json' [-Rmodules-driver]
+// CHECK: error: failure while parsing standard modules manifest: '[5:7, byte=57]: Invalid JSON value (true?)'
+
+//--- main.cpp
+// empty
+
+//--- libc++.modules.json.in
+{
+  "version": 1,
+  "revision": 1,
+  "modules": [
+     this is malformed.
+  ]
+}
diff --git a/clang/test/Driver/modules-driver-manifest-local-system-includes.cpp b/clang/test/Driver/modules-driver-manifest-local-system-includes.cpp
new file mode 100644
index 0000000000000..55917b900b6c9
--- /dev/null
+++ b/clang/test/Driver/modules-driver-manifest-local-system-includes.cpp
@@ -0,0 +1,76 @@
+// Verifies that the local system include directories listed in the standard
+// module manifest are added to corresponding driver jobs.
+
+// RUN: split-file %s %t
+
+// The standard library modules manifest (libc++.modules.json) is discovered
+// relative to the installed C++ standard library runtime libraries
+// We need to create them in order for Clang to find the manifest.
+// RUN: rm -rf %t && split-file %s %t && cd %t
+// RUN: mkdir -p %t/Inputs/usr/lib/x86_64-linux-gnu
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
+
+// RUN: cat %t/libc++.modules.json.in > \
+// RUN:   %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json
+
+// RUN: mkdir -p %t/Inputs/usr/lib/share/libc++/v1
+// RUN: mkdir -p %t/Inputs/usr/lib/share/libc++/v2
+// RUN: cat %t/std.cppm > %t/Inputs/usr/lib/share/libc++/v1/std.cppm
+// RUN: cat %t/std.compat.cppm > %t/Inputs/usr/lib/share/libc++/v1/std.compat.cppm
+
+// RUN: %clang -std=c++20 \
+// RUN:   -fmodules-driver -Rmodules-driver \
+// RUN:   -stdlib=libc++ \
+// RUN:   -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
+// RUN:   --target=x86_64-linux-gnu \
+// RUN:   -fmodules-cache-path=%t/modules-cache \
+// RUN:   %t/main.cpp \
+// RUN:   -### 2>&1 \
+// RUN:   | sed 's:\\\\\?:/:g' \
+// RUN:   | FileCheck %s -DPREFIX=%/t
+
+// CHECK: "-cc1" {{.*}} "-main-file-name" "std.cppm" {{.*}} "-internal-isystem" "[[PREFIX]]/Inputs/usr/lib/share/libc++/v1"
+// CHECK: "-cc1" {{.*}} "-main-file-name" "std.compat.cppm" {{.*}} "-internal-isystem" "[[PREFIX]]/Inputs/usr/lib/share/libc++/v1" "-internal-isystem" "[[PREFIX]]/Inputs/usr/lib/share/libc++/v2"
+
+//--- main.cpp
+// Import the system modules to ensure that the corresponding jobs don't get
+// deleted.
+import std;
+import std.compat;
+
+//--- std.cppm
+export module std;
+
+//--- std.compat.cppm
+export module std.compat;
+import std;
+
+//--- libc++.modules.json.in
+{
+  "version": 1,
+  "revision": 1,
+  "modules": [
+    {
+      "logical-name": "std",
+      "source-path": "../share/libc++/v1/std.cppm",
+      "is-std-library": true,
+      "local-arguments": {
+        "system-include-directories": [
+          "../share/libc++/v1"
+        ]
+      }
+    },
+    {
+      "logical-name": "std.compat",
+      "source-path": "../share/libc++/v1/std.compat.cppm",
+      "is-std-library": true,
+      "local-arguments": {
+        "system-include-directories": [
+	  "../share/libc++/v1",
+          "../share/libc++/v2"
+        ]
+      }
+    }
+  ]
+}



More information about the cfe-commits mailing list