https://github.com/rmaz updated https://github.com/llvm/llvm-project/pull/239791

>From 193473ce619bf328da9fb1240b9ded9dc8d2e649 Mon Sep 17 00:00:00 2001
From: Richard Howell <[email protected]>
Date: Fri, 6 Nov 2026 12:03:45 -0800
Subject: [PATCH] [clang] Add -fpch-base-dir-is-cwd

Serialize PCH input paths relative to the current working directory, so a
build tree can be moved while preserving its relative layout. Reuse the
existing relocatable AST prefix stripping without storing a reader base
directory or enabling sysroot-based re-rooting.

This is the PCH equivalent of -fmodule-file-home-is-cwd.

Assisted-by: Muse
---
 clang/docs/ReleaseNotes.md                    |  6 ++
 clang/docs/UsersManual.md                     | 12 +++
 .../clang/Basic/DiagnosticFrontendKinds.td    |  4 +
 clang/include/clang/Lex/HeaderSearchOptions.h | 14 ++-
 clang/include/clang/Options/Options.td        |  5 ++
 clang/lib/Driver/ToolChains/Clang.cpp         |  1 +
 clang/lib/Frontend/FrontendActions.cpp        |  5 ++
 clang/lib/Serialization/ASTWriter.cpp         |  7 ++
 clang/test/PCH/pch-base-dir-is-cwd.c          | 88 +++++++++++++++++++
 9 files changed, 139 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/PCH/pch-base-dir-is-cwd.c

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index d0bc3b66453789..db1d10b149a8c3 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -360,6 +360,12 @@ documentation](CIR/index.md) for more information 
regarding ClangIR's status and
 
 ### New Compiler Flags
 
+- Added `-fpch-base-dir-is-cwd` to serialize precompiled header input paths
+  relative to the current working directory. Paths resolve against the
+  consumer's working directory when loading the PCH, allowing a build tree
+  to be moved without rewriting paths. Paths outside the working directory
+  remain absolute. This option cannot be combined with `--relocatable-pch`.
+
 - New option `-fmodules-validate-directory-dependencies` makes an implicitly
   built module out of date when a header is added to a directory it enumerated,
   such as an umbrella directory or the directory of an umbrella header, after 
it
diff --git a/clang/docs/UsersManual.md b/clang/docs/UsersManual.md
index 96d1c4e009c71a..9f1435152a029a 100644
--- a/clang/docs/UsersManual.md
+++ b/clang/docs/UsersManual.md
@@ -1582,6 +1582,18 @@ $ clang -include-pch test.h.pch -ignore-pch test.c -o 
test
 This option disables precompiled headers, overrides -emit-pch and -include-pch.
 test.h.pch is not generated and not used as a prefix header.
 
+#### Working-Directory-Relative PCH Files
+
+The `-fpch-base-dir-is-cwd` option serializes precompiled header input paths
+relative to the current working directory. This allows a build tree containing
+the PCH and its inputs to be moved, provided that the PCH is consumed from the
+corresponding working directory and the inputs retain the same relative layout.
+Paths outside the working directory remain absolute.
+
+Unlike `--relocatable-pch`, this option does not store a base directory or 
re-root
+paths using `-isysroot` when loading the PCH. The option is only needed when
+building the PCH and cannot be combined with `--relocatable-pch`.
+
 #### Relocatable PCH Files
 
 It is sometimes necessary to build a precompiled header from headers
diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index b51aa3ff0a0cb4..def00b10706e77 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -227,6 +227,10 @@ def warn_fixit_no_changes : Note<
 def err_relocatable_without_isysroot : Error<
     "must specify system root with -isysroot when building a relocatable "
     "PCH file">;
+def err_pch_base_dir_is_cwd_relocatable : Error<
+    "-fpch-base-dir-is-cwd cannot be used with -relocatable-pch when building "
+    "a PCH file; the two options select different base directories for input "
+    "paths">;
 
 def warn_unknown_diag_option : Warning<
     "unknown %select{warning|remark}0 option '%1'%select{|; did you mean 
'%3'?}2">,
diff --git a/clang/include/clang/Lex/HeaderSearchOptions.h 
b/clang/include/clang/Lex/HeaderSearchOptions.h
index 4bee6a83e61a7c..49ff8b82f63e4e 100644
--- a/clang/include/clang/Lex/HeaderSearchOptions.h
+++ b/clang/include/clang/Lex/HeaderSearchOptions.h
@@ -151,6 +151,13 @@ class HeaderSearchOptions {
   LLVM_PREFERRED_TYPE(bool)
   unsigned ModuleFileHomeIsCwd : 1;
 
+  /// Serialize precompiled header input paths relative to the current working
+  /// directory. Relative paths resolve against the consumer's working
+  /// directory; unlike relocatable PCHs, no base directory is stored or
+  /// re-rooted at load.
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned PCHBaseDirIsCwd : 1;
+
   /// Also search for prebuilt implicit modules in the prebuilt module cache
   /// path.
   LLVM_PREFERRED_TYPE(bool)
@@ -299,9 +306,10 @@ class HeaderSearchOptions {
   HeaderSearchOptions(StringRef _Sysroot = "/")
       : Sysroot(_Sysroot), ModuleFormat("raw"), DisableModuleHash(false),
         ImplicitModuleMaps(false), ModuleMapFileHomeIsCwd(false),
-        ModuleFileHomeIsCwd(false), EnablePrebuiltImplicitModules(false),
-        UseBuiltinIncludes(true), UseStandardSystemIncludes(true),
-        UseStandardCXXIncludes(true), UseLibcxx(false), Verbose(false),
+        ModuleFileHomeIsCwd(false), PCHBaseDirIsCwd(false),
+        EnablePrebuiltImplicitModules(false), UseBuiltinIncludes(true),
+        UseStandardSystemIncludes(true), UseStandardCXXIncludes(true),
+        UseLibcxx(false), Verbose(false),
         ModulesValidateOncePerBuildSession(false),
         ModulesValidateSystemHeaders(false),
         ModulesForceValidateUserHeaders(true),
diff --git a/clang/include/clang/Options/Options.td 
b/clang/include/clang/Options/Options.td
index d9abc9b6e37d01..651ed3e9d13ebc 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -3915,6 +3915,11 @@ def fmodules_validate_input_files_content:
 def fno_modules_validate_input_files_content:
   Flag <["-"], "fno_modules-validate-input-files-content">,
   Group<f_Group>;
+def fpch_base_dir_is_cwd : Flag<["-"], "fpch-base-dir-is-cwd">,
+  Group<f_Group>, Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Serialize precompiled header input paths relative to the current "
+           "working directory">,
+  MarshallingInfoFlag<HeaderSearchOpts<"PCHBaseDirIsCwd">>;
 def fpch_validate_input_files_content:
   Flag <["-"], "fpch-validate-input-files-content">,
   Group<f_Group>,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index d8819c952e5add..bd840ccb985e0a 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6955,6 +6955,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 
   if (Args.hasArg(options::OPT_relocatable_pch))
     CmdArgs.push_back("-relocatable-pch");
+  Args.AddLastArg(CmdArgs, options::OPT_fpch_base_dir_is_cwd);
 
   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
     static const char *kCFABIs[] = {
diff --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index 3fa12ef62be828..60bc3332b32248 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -137,6 +137,11 @@ GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, 
StringRef InFile) {
 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
                                                     std::string &Sysroot) {
   Sysroot = CI.getHeaderSearchOpts().Sysroot;
+  if (CI.getFrontendOpts().RelocatablePCH &&
+      CI.getHeaderSearchOpts().PCHBaseDirIsCwd) {
+    CI.getDiagnostics().Report(diag::err_pch_base_dir_is_cwd_relocatable);
+    return false;
+  }
   if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
     CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
     return false;
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index de1c2449138e58..ad218305039f67 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1534,6 +1534,13 @@ void ASTWriter::WriteControlBlock(Preprocessor &PP, 
StringRef isysroot) {
     SmallString<128> CleanedSysroot(isysroot);
     PP.getFileManager().makeAbsolutePath(CleanedSysroot, 
/*Canonicalize=*/true);
     BaseDirectory.assign(CleanedSysroot.begin(), CleanedSysroot.end());
+  } else if (PP.getHeaderSearchInfo().getHeaderSearchOpts().PCHBaseDirIsCwd) {
+    // Reuse relocatable PCH prefix stripping, but leave the reader's base
+    // directory empty so relative paths resolve against the consumer's cwd.
+    // GeneratePCHAction rejects combining this with -relocatable-pch.
+    SmallString<128> BaseDir(".");
+    FileMgr.makeAbsolutePath(BaseDir, /*Canonicalize=*/true);
+    BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
   }
 
   // Module map file
diff --git a/clang/test/PCH/pch-base-dir-is-cwd.c 
b/clang/test/PCH/pch-base-dir-is-cwd.c
new file mode 100644
index 00000000000000..435640463a812b
--- /dev/null
+++ b/clang/test/PCH/pch-base-dir-is-cwd.c
@@ -0,0 +1,88 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: mkdir %t/original/pch
+
+// The PCH option does not change the base directory of a module file.
+// RUN: cd %t/original && %clang_cc1 -emit-module -x c 
modules/module.modulemap -fmodule-name=ExplicitTypes -o pch/isolated.pcm 
-fmodules -fno-implicit-modules -fpch-base-dir-is-cwd
+// RUN: llvm-bcanalyzer -dump -disable-histogram %t/original/pch/isolated.pcm 
| FileCheck %s --check-prefix=MODULE
+// MODULE: <MODULE_DIRECTORY{{.*}}> blob data = 
'{{(/|[A-Za-z]:).*[/\\]}}original{{[/\\]}}modules'
+// MODULE: <INPUT_FILE{{.*}}> blob data = 'explicit.h'
+
+// Default PCH generation still stores absolute input paths.
+// RUN: cd %t/original && %clang_cc1 -emit-pch -x c-header forced.h -o 
pch/default.pch
+// RUN: llvm-bcanalyzer -dump -disable-histogram %t/original/pch/default.pch | 
FileCheck %s --check-prefix=DEFAULT
+// DEFAULT: <ORIGINAL_FILE{{.*}}> blob data = 
'{{(/|[A-Za-z]:).*[/\\]}}original{{[/\\]}}forced.h'
+// DEFAULT: <INPUT_FILE{{.*}}> blob data = 
'{{(/|[A-Za-z]:).*[/\\]}}original{{[/\\]}}forced.h'
+
+// Paths under the cwd are relative; paths outside it remain absolute.
+// RUN: cd %t/original && %clang_cc1 -emit-module -x c 
modules/module.modulemap -fmodule-name=ExplicitTypes -o pch/ExplicitTypes.pcm 
-fmodules -fno-implicit-modules -fmodule-file-home-is-cwd
+// RUN: cd %t/original && %clang_cc1 -emit-pch -x c-header headers/bridge.h -o 
pch/bridge.pch -fpch-base-dir-is-cwd -isysroot %t/original -fmodules 
-fno-implicit-modules -fmodule-map-file=modules/module.modulemap 
-fmodule-file=ExplicitTypes=pch/ExplicitTypes.pcm -I modules -I %t/shared 
-include ./forced.h -imacros ./macros.h
+// RUN: llvm-bcanalyzer -dump -disable-histogram -show-binary-blobs 
%t/original/pch/bridge.pch > %t/bridge.dump
+// RUN: FileCheck %s --check-prefix=PATHS --input-file=%t/bridge.dump
+// PATHS: <IMPORT {{.*}}> blob data = 
'ExplicitTypes{{.*}}pch{{[/\\]+}}ExplicitTypes.pcm'
+// PATHS: <ORIGINAL_FILE{{.*}}> blob data = 'headers{{[/\\]+}}bridge.h'
+// PATHS-DAG: <INPUT_FILE{{.*}}> blob data = 'forced.h'
+// PATHS-DAG: <INPUT_FILE{{.*}}> blob data = 'headers{{[/\\]+}}bridge.h'
+// PATHS-DAG: <INPUT_FILE{{.*}}> blob data = 'macros.h'
+// PATHS-DAG: <INPUT_FILE{{.*}}> blob data = 
'{{(/|[A-Za-z]:).*[/\\]}}shared{{[/\\]+}}types.h'
+
+// Reuse the dump, but check it separately so the negative checks cover the 
whole
+// file rather than only the gaps between positive checks. The summary footer
+// includes the PCH filename, so only reject record blobs.
+// RUN: FileCheck %s --check-prefix=NO-ABSOLUTE --input-file=%t/bridge.dump
+// NO-ABSOLUTE-NOT: blob data = '{{.*[/\\]}}original{{[/\\]}}
+// NO-ABSOLUTE-NOT: <MODULE_DIRECTORY
+
+// The two options select different base directories, with or without a 
sysroot.
+// RUN: not %clang_cc1 -emit-pch -x c-header %t/original/headers/bridge.h -o 
%t/error.pch -fpch-base-dir-is-cwd -relocatable-pch -isysroot %t/original 2>&1 
| FileCheck %s --check-prefix=ERROR
+// RUN: not %clang_cc1 -emit-pch -x c-header %t/original/headers/bridge.h -o 
%t/error.pch -fpch-base-dir-is-cwd -relocatable-pch 2>&1 | FileCheck %s 
--check-prefix=ERROR
+// ERROR: -fpch-base-dir-is-cwd cannot be used with -relocatable-pch
+
+// PCHs built in different working directories are bit-identical when all their
+// inputs are inside those directories. Preserve input timestamps when copying.
+// RUN: cd %t/original && %clang_cc1 -emit-pch -x c-header headers/identical.h 
-o pch/identical.pch -fpch-base-dir-is-cwd
+// RUN: cp -pR %t/original %t/relocated
+// RUN: cd %t/relocated && %clang_cc1 -emit-pch -x c-header 
headers/identical.h -o pch/identical.pch -fpch-base-dir-is-cwd
+// RUN: cmp %t/original/pch/identical.pch %t/relocated/pch/identical.pch
+
+// Consume the original PCH from the relocated tree after removing the 
original.
+// RUN: rm -rf %t/original
+// RUN: cd %t/relocated && %clang_cc1 -fsyntax-only main.c -include-pch 
pch/bridge.pch -fmodules -fno-implicit-modules 
-fmodule-map-file=modules/module.modulemap 
-fmodule-file=ExplicitTypes=pch/ExplicitTypes.pcm -I modules -I %t/shared 
-include ./forced.h -imacros ./macros.h
+
+// PCH generation also works when the working directory does not exist.
+// RUN: %clang_cc1 -emit-pch -x c-header %t/relocated/forced.h -o 
%t/no-cwd.pch -fpch-base-dir-is-cwd -working-directory %t/does-not-exist
+
+// The driver forwards the flag to -cc1.
+// RUN: %clang -### -x c-header %s -fpch-base-dir-is-cwd -o %t/driver.pch 2>&1 
| FileCheck %s --check-prefix=DRIVER
+// DRIVER: "-cc1"
+// DRIVER-SAME: "-fpch-base-dir-is-cwd"
+
+//--- original/headers/bridge.h
+#include "explicit.h"
+#include "types.h"
+
+//--- original/headers/identical.h
+#include "../forced.h"
+#include "../macros.h"
+#include "../modules/explicit.h"
+
+//--- original/modules/module.modulemap
+module ExplicitTypes { header "explicit.h" export * }
+
+//--- original/modules/explicit.h
+typedef int ExplicitValue;
+
+//--- shared/types.h
+typedef struct { int x; } BridgePoint;
+
+//--- original/forced.h
+// Leave this unguarded to catch re-including the file after loading the PCH.
+typedef struct { int x; } ForcedPoint;
+
+//--- original/macros.h
+#define BRIDGE_VALUE 42
+
+//--- original/main.c
+int getX(BridgePoint point, ForcedPoint forced, ExplicitValue value) {
+  return point.x + forced.x + value + BRIDGE_VALUE;
+}

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

Reply via email to