From 9bc6c30d97639a649ff04698d9a51a5e40ad6b80 Mon Sep 17 00:00:00 2001 From: Sergei Zimmerman Date: Tue, 22 Jul 2025 02:39:06 +0300 Subject: [PATCH] meson: Further optimize compile times with PCH template instantiations This is a follow-up to 6ec50ba73664838993d645dc78c936542eb2012c, which also almost halves the compile times on clang for subprojects that use PCH. `-fpch-instantiate-templates` is a clang-only option to force the instantiation of templates once in the PCH itself, not all of the translation units that it gets included to. This really cuts down on the overhead from nlohmann::json and std::format code: 48244 ms: nlohmann::basic_json<>::parse (76 times, avg 634 ms) 36193 ms: nlohmann::basic_json<>::basic_json (310 times, avg 116 ms) 28307 ms: nlohmann::detail::parser, nlohmann::detail::i... (76 times, avg 372 ms) 20334 ms: nlohmann::detail::parser, nlohmann::detail::i... (76 times, avg 267 ms) 17387 ms: nlohmann::basic_json<>::json_value::json_value (389 times, avg 44 ms) 16822 ms: std::vformat_to> (76 times, avg 221 ms) 16771 ms: std::__format::__do_vformat_to, char... (76 times, avg 220 ms) 12160 ms: std::vformat_to> (76 times, avg 160 ms) 12127 ms: std::__format::__do_vformat_to, w... (76 times, avg 159 ms) 10397 ms: nlohmann::detail::json_sax_dom_callback_parser::data::data (76 times, avg 119 ms) Initially done by Jade Lovelace in https://gerrit.lix.systems/c/lix/+/1842. We are doing basically the same, but unconditionally. It would be a huge pain to add a pch option for all subprojects to just support the usecase of using clangd in a gcc devshell. In total, this basically halves the frontend times for nix-util and nix-store to the point that the most expensive part of the build is linking. (nix-store before): ``` **** Time summary: Compilation (77 times): Parsing (frontend): 243.4 s Codegen & opts (backend): 140.3 s ``` (nix-store after): ``` **** Time summary: Compilation (77 times): Parsing (frontend): 120.2 s Codegen & opts (backend): 141.2 s ``` --- nix-meson-build-support/common/meson.build | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/nix-meson-build-support/common/meson.build b/nix-meson-build-support/common/meson.build index b9140256a..df8b958c0 100644 --- a/nix-meson-build-support/common/meson.build +++ b/nix-meson-build-support/common/meson.build @@ -18,3 +18,14 @@ add_project_arguments( '-Wno-deprecated-declarations', language : 'cpp', ) + +# This is a clang-only option for improving build times. +# It forces the instantiation of templates in the PCH itself and +# not every translation unit it's included in. +# It's available starting from clang 11, which is old enough to not +# bother checking the version. +# This feature helps in particular with the expensive nlohmann::json template +# instantiations in libutil and libstore. +if cxx.get_id() == 'clang' + add_project_arguments('-fpch-instantiate-templates', language : 'cpp') +endif