feat(build): run a build's steps on one worker per hardware thread
Build() started a thread for every stale shader, asset, C, CUDA and C++
unit, and Module::Compile one more for every stale partition, and
nothing bounded how many of them ran their step at once. Jorijn asked
for the amount of parallelism to be limited by the amount of threads
instead of just starting one per file; the threads are taken here to be
the machine's hardware threads.
The new :Jobs partition holds the two pieces. JobPool is worker threads
behind one queue, started as jobs need them up to a fixed number, and
JobPool::Process() is the pool of the process: at most a worker per
hardware thread, one where std:🧵:hardware_concurrency does not
know. JobGroup is the jobs of one build on a pool. A job starts once
the jobs it was added after have finished; the first job to fail keeps
the ones that have not started from starting, and Wait() returns its
error. No job waits for another job, and a JobGroup made on a worker of
its own pool throws: a worker that waited for a job still in the queue
would hold the thread that job needs.
Build() adds what it did on those threads to a JobGroup instead, and
the group's first error replaces the buildCancelled and buildError pair
the threads set. The module units no longer block on the `compiled`
flag of the units they import: Schedule() replaces Compile() on Module,
ModulePartition and Implementation and adds a unit's jobs after the jobs
that write the BMIs it imports. An interface unit is two jobs, its BMI
and then its object from the BMI, so the units importing it start when
the first is done, as they did when one thread ran both commands and
raised the flag in between. A primary interface now waits for the BMIs
of its partitions and no longer for their objects. Each of the two jobs
has a progress line, "Precompiling X.cppm" and "Compiling X.cppm" for
every interface unit, where a module and its partitions shared one
"Compiling interface X".
RunBuildCommand runs its command on a worker of the process's pool: on
the calling thread when that is one, otherwise it waits for one. A link,
an archive, the std module's precompile and project.cpp's compile are
steps under the limit that way. The threads Build() starts per
dependency and per external dependency stay: one of the first runs the
dependency's own Build(), or waits for the thread that does, and one of
the second runs git and cmake.
With the BMI and the object as two jobs, a build that fails between them
has written the BMI and skips the object, and Check, which reads
staleness off the BMI, would call the unit built from then on.
Schedule() therefore adds the object job alone for a unit whose BMI is
up to date and whose object is missing or older than the BMI. A build
interrupted between the two commands, or one whose second command
failed, left the same behind before, and it stayed: the link took the
object of the source before the edit, or failed on the missing one.
ImportCycleError is now what keeps Schedule() from following a round of
imports without end.
The limit is on steps. Outside it, as AGENTS.template.md lists: an
ExternalDependency's cmake --build, which keeps its own --parallel of
as many jobs as there are hardware threads; the tests RunTests runs,
--jobs= of them at once as before; the Crafter.Build modules
EnsureCrafterBuildPcms precompiles one after another; and the threads a
step starts for itself, which lld does for a link and Crafter.Asset's
GDeflate compressor for an asset. The pool is one process's. The --help
text says what a build runs at once and that test --jobs= counts tests.
ConcurrentDependencyReset read the `compiled` flag, which is gone. It
asserts on `checked` and `scheduled` instead, the state a reset from
another build's thread would clear now, with a unit scheduled twice as
the result, and the comment in its fixture says what the implementation
unit comes after now. TransitiveInterfaceChange's comment names
Schedule() where it named Compile() as what honours a partition's
imports. Two comments in :Platform that spoke of worker threads, a word
that now means the pool's, name the threads they mean. The bug-prover
lens's section said shaders compile on a thread of their own each, and
describes the pool now.
This commit is contained in:
parent
eff9868b68
commit
913310da86
19 changed files with 726 additions and 377 deletions
|
|
@ -17,6 +17,7 @@ import :Agents;
|
|||
import :Progress;
|
||||
import :Asset;
|
||||
import :Flatpak;
|
||||
import :Jobs;
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Crafter;
|
||||
|
||||
|
|
@ -148,8 +149,8 @@ void Configuration::GetInterfacesAndImplementations(std::span<fs::path> interfac
|
|||
|
||||
// Primary interface unit: record only its module imports. Its
|
||||
// `[export] import :Part;` lines need no edge — Module::Check walks
|
||||
// every partition it owns and Module::Compile builds them all before
|
||||
// precompiling itself, so partitions are covered wholesale.
|
||||
// every partition it owns and Module::Schedule puts the primary
|
||||
// interface after all of them, so partitions are covered wholesale.
|
||||
if (partition == nullptr) {
|
||||
std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)");
|
||||
std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern);
|
||||
|
|
@ -537,9 +538,10 @@ namespace {
|
|||
// to the first again: partitions that import each other, a partition that
|
||||
// imports its own module, sibling modules that import each other. Empty
|
||||
// when there are none, otherwise the error naming the round. No order
|
||||
// builds such units: each is compiled on a thread that first waits for
|
||||
// the units it imports, a primary interface for the partitions of its
|
||||
// module as well, so such a build hung with no compiler running.
|
||||
// builds such units. Schedule() works the order out before it adds a
|
||||
// unit's jobs, by following the imports, and would follow a round of
|
||||
// them without end. When each unit had a thread that waited for the
|
||||
// units it imports, such a build hung with no compiler running.
|
||||
//
|
||||
// The imports are the scanner's, which reads one in a string literal, in
|
||||
// a comment that spans lines or under `#if 0` as it reads any other
|
||||
|
|
@ -767,22 +769,26 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
// (diamond deps point at the same Configuration*), and every config in the
|
||||
// tree gets its own Build() call: the per-PcmDir builder registered in
|
||||
// depResults resets its own state here, at the top of its own Build(),
|
||||
// sequenced before that config's compile threads spawn. Recursing into
|
||||
// dependencies from here would re-clear a shared dependency's `compiled`
|
||||
// atomic from a parent/sibling thread *while that dependency's own Build()
|
||||
// is concurrently compiling it* — after its module-compile thread set the
|
||||
// flag true and exited but before its impl/partition waiter ran
|
||||
// compiled.wait(false). The waiter would then block forever on a flag
|
||||
// nothing re-signals: the build freezes mid-compile, idle, with no compiler
|
||||
// sequenced before that config's units are checked and scheduled.
|
||||
// Recursing into dependencies from here would clear a shared dependency's
|
||||
// state from a parent/sibling thread *while that dependency's own Build()
|
||||
// is using it*: a unit whose `scheduled` is cleared between two of that
|
||||
// build's Schedule() calls is scheduled a second time, and two compilers
|
||||
// write one BMI. When every unit had a thread of its own that waited on a
|
||||
// `compiled` flag of each unit it imports, the reset cleared that flag
|
||||
// under a waiter, which then blocked forever on a flag nothing
|
||||
// re-signalled: the build froze mid-compile, idle, with no compiler
|
||||
// process alive (issue #16). Cross-config module state is consulted only via
|
||||
// PCM file mtimes and the depResults futures, never via these flags, so the
|
||||
// PCM file mtimes and the depResults futures, never via this state, so the
|
||||
// narrower reset is correct.
|
||||
for (auto& iface : config.interfaces) {
|
||||
iface->checked = false;
|
||||
iface->compiled.store(false);
|
||||
iface->scheduled = false;
|
||||
iface->precompileJob.reset();
|
||||
for (auto& part : iface->partitions) {
|
||||
part->checked = false;
|
||||
part->compiled.store(false);
|
||||
part->scheduled = false;
|
||||
part->precompileJob.reset();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -874,7 +880,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
// glslang #include search paths for every shader compiled in this
|
||||
// configuration: each transitive (incl. self) buildFiles entry's parent
|
||||
// dir, or the entry itself if it points at a directory. Collected once
|
||||
// up front so the per-shader threads can capture the resulting span by
|
||||
// up front so the per-shader jobs can capture the resulting span by
|
||||
// reference. No file copy involved — glslang reads the includes in
|
||||
// place from the dep's source tree.
|
||||
std::vector<fs::path> shaderIncludeDirs;
|
||||
|
|
@ -894,11 +900,23 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
collect(&config);
|
||||
}
|
||||
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(config.shaders.size() + 1 + config.interfaces.size() + config.implementations.size());
|
||||
// A stale shader, asset to compress, C, CUDA or C++ unit is a job of this
|
||||
// group; each used to get a thread of its own the moment it was found
|
||||
// stale. The copies of cfg.files and of the other files of an asset
|
||||
// directory are jobs as well. The jobs run on the workers every build of
|
||||
// the process shares, so no more of them run at once than the machine
|
||||
// has hardware threads.
|
||||
//
|
||||
// The group also holds the first error among its jobs and what this
|
||||
// build reports to it (Fail), the dependency and external builds below
|
||||
// among it, and none of its jobs starts after one. What goes wrong once
|
||||
// the jobs are done, at the link, is not the group's.
|
||||
//
|
||||
// Declared after everything its jobs use by reference: leaving Build()
|
||||
// waits for them before any of that is destroyed. A job gets a copy of
|
||||
// whatever it uses that is declared below here.
|
||||
JobGroup jobs;
|
||||
|
||||
std::string buildError;
|
||||
std::atomic<bool> buildCancelled{false};
|
||||
// Two entries with the same output name would compile in parallel into
|
||||
// one file: whichever finished last won, the build reported success, and
|
||||
// Check() then called both up to date. The usual way in is one source
|
||||
|
|
@ -909,28 +927,18 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
for (const Shader& shader : config.shaders) {
|
||||
const auto [existing, inserted] = outputs.emplace(shader.OutputName().string(), &shader);
|
||||
if (inserted) continue;
|
||||
buildError = std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first);
|
||||
buildCancelled.store(true);
|
||||
jobs.Fail(std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first));
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (const Shader& shader : config.shaders) {
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) break;
|
||||
if (jobs.Failed()) break;
|
||||
place(outputDir / shader.OutputName(), {});
|
||||
if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue;
|
||||
threads.emplace_back([&shader, &outputDir, &buildDir, &shaderIncludeDirs, &buildError, &buildCancelled]() {
|
||||
// A source registered more than once shows up once per variant;
|
||||
// name the variant so the lines can be told apart.
|
||||
Progress::Task task(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant));
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
|
||||
std::string result = shader.Compile(outputDir, buildDir, shaderIncludeDirs);
|
||||
if (result.empty()) return;
|
||||
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
}
|
||||
// A source registered more than once shows up once per variant;
|
||||
// name the variant so the lines can be told apart.
|
||||
jobs.Add(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant), [&shader, &outputDir, &buildDir, &shaderIncludeDirs] {
|
||||
return shader.Compile(outputDir, buildDir, shaderIncludeDirs);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -942,23 +950,19 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
// trees keep their nested layout so mod.json paths like
|
||||
// "cannon/base.cmesh" resolve correctly at runtime.
|
||||
// Skipped per-file if the output is newer than the source. Each
|
||||
// compress runs in its own thread; passthrough copies are bundled into
|
||||
// a single thread to match the cfg.files pattern.
|
||||
// compress is a job of its own; passthrough copies are bundled into
|
||||
// a single job to match the cfg.files pattern.
|
||||
auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) {
|
||||
place(outputDir / outRelative, {});
|
||||
fs::path out = outputDir / outRelative;
|
||||
if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return;
|
||||
threads.emplace_back([sourcePath = std::move(sourcePath), out = std::move(out), &buildError, &buildCancelled]() {
|
||||
Progress::Task task(std::format("Compressing asset {}", sourcePath.filename().string()));
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
// Named before the job takes the path: the arguments of one call
|
||||
// are evaluated in no particular order.
|
||||
std::string label = std::format("Compressing asset {}", sourcePath.filename().string());
|
||||
jobs.Add(std::move(label), [sourcePath = std::move(sourcePath), out = std::move(out)] {
|
||||
std::error_code ec;
|
||||
fs::create_directories(out.parent_path(), ec);
|
||||
std::string result = CompressAsset(sourcePath, out);
|
||||
if (result.empty()) return;
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
}
|
||||
return CompressAsset(sourcePath, out);
|
||||
});
|
||||
};
|
||||
std::vector<std::pair<fs::path, fs::path>> assetPassthroughs;
|
||||
|
|
@ -978,73 +982,58 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
} else {
|
||||
std::optional<fs::path> outName = CompressedAssetName(asset);
|
||||
if (!outName) {
|
||||
buildCancelled.store(true);
|
||||
buildError = std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string());
|
||||
jobs.Fail(std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string()));
|
||||
break;
|
||||
}
|
||||
submitCompress(asset, *outName);
|
||||
}
|
||||
}
|
||||
if (!assetPassthroughs.empty()) {
|
||||
threads.emplace_back([passthroughs = std::move(assetPassthroughs), &outputDir, &buildCancelled, &buildError]() {
|
||||
Progress::Task task("Copying asset passthrough files");
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
try {
|
||||
for (const auto& [src, rel] : passthroughs) {
|
||||
fs::path dst = outputDir / rel;
|
||||
fs::create_directories(dst.parent_path());
|
||||
if (!fs::exists(dst)) {
|
||||
fs::copy_file(src, dst);
|
||||
} else if (fs::last_write_time(src) > fs::last_write_time(dst)) {
|
||||
fs::copy_file(src, dst, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = e.what();
|
||||
// What a copy throws is the job's error (JobGroup::Add), here and
|
||||
// for cfg.files below.
|
||||
jobs.Add("Copying asset passthrough files", [passthroughs = std::move(assetPassthroughs), &outputDir]() -> std::string {
|
||||
for (const auto& [src, rel] : passthroughs) {
|
||||
fs::path dst = outputDir / rel;
|
||||
fs::create_directories(dst.parent_path());
|
||||
if (!fs::exists(dst)) {
|
||||
fs::copy_file(src, dst);
|
||||
} else if (fs::last_write_time(src) > fs::last_write_time(dst)) {
|
||||
fs::copy_file(src, dst, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile);
|
||||
threads.emplace_back([&config, &outputDir, &buildCancelled, &buildError]() {
|
||||
Progress::Task task(std::format("Copying files for {}", config.name));
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
try {
|
||||
for (const fs::path& additionalFile : config.files) {
|
||||
fs::path destination = outputDir / additionalFile.filename();
|
||||
if (fs::is_directory(additionalFile)) {
|
||||
for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) {
|
||||
const fs::path& sourcePath = entry.path();
|
||||
fs::path relativePath = fs::relative(sourcePath, additionalFile);
|
||||
fs::path destPath = destination / relativePath;
|
||||
if (entry.is_directory()) {
|
||||
if (!fs::exists(destPath)) fs::create_directories(destPath);
|
||||
} else if (entry.is_regular_file()) {
|
||||
fs::create_directories(destPath.parent_path());
|
||||
if (!fs::exists(destPath)) {
|
||||
fs::copy_file(sourcePath, destPath);
|
||||
} else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) {
|
||||
fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
jobs.Add(std::format("Copying files for {}", config.name), [&config, &outputDir]() -> std::string {
|
||||
for (const fs::path& additionalFile : config.files) {
|
||||
fs::path destination = outputDir / additionalFile.filename();
|
||||
if (fs::is_directory(additionalFile)) {
|
||||
for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) {
|
||||
const fs::path& sourcePath = entry.path();
|
||||
fs::path relativePath = fs::relative(sourcePath, additionalFile);
|
||||
fs::path destPath = destination / relativePath;
|
||||
if (entry.is_directory()) {
|
||||
if (!fs::exists(destPath)) fs::create_directories(destPath);
|
||||
} else if (entry.is_regular_file()) {
|
||||
fs::create_directories(destPath.parent_path());
|
||||
if (!fs::exists(destPath)) {
|
||||
fs::copy_file(sourcePath, destPath);
|
||||
} else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) {
|
||||
fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!fs::exists(destination)) {
|
||||
fs::copy_file(additionalFile, destination);
|
||||
} else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) {
|
||||
fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!fs::exists(destination)) {
|
||||
fs::copy_file(additionalFile, destination);
|
||||
} else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) {
|
||||
fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
}
|
||||
} catch(std::exception& e) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = e.what();
|
||||
}
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
std::vector<ExternalBuildResult> externalResults(config.externalDependencies.size());
|
||||
|
|
@ -1054,7 +1043,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
externalThreads.emplace_back([&, i]() {
|
||||
const ExternalDependency& dep = config.externalDependencies[i];
|
||||
Progress::Task task(std::format("Building external dep {}", dep.name));
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
if (jobs.Failed()) return;
|
||||
std::string error;
|
||||
try {
|
||||
// Every configuration of the pass that declares this
|
||||
|
|
@ -1072,11 +1061,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
} catch (const std::exception& e) {
|
||||
error = std::format("external dep {} threw: {}", dep.name, e.what());
|
||||
}
|
||||
if (error.empty()) return;
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(error);
|
||||
}
|
||||
if (!error.empty()) jobs.Fail(std::move(error));
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -1089,8 +1074,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
std::string stdPcmResult;
|
||||
{
|
||||
Progress::Task task(std::format("Building std PCM ({}-{})", config.target, config.march));
|
||||
// The shader and external threads are running: an exception leaving
|
||||
// here would destroy them joinable, which terminates the process.
|
||||
// The external threads are running: an exception leaving here would
|
||||
// destroy them joinable, which terminates the process.
|
||||
try {
|
||||
stdPcmResult = BuildStdPcm(config, stdPcmDir/"std.pcm");
|
||||
} catch (const std::exception& e) {
|
||||
|
|
@ -1098,9 +1083,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
}
|
||||
}
|
||||
if(!stdPcmResult.empty()) {
|
||||
buildCancelled.store(true);
|
||||
for(std::thread& thread : threads) thread.join();
|
||||
jobs.Fail(stdPcmResult);
|
||||
for(std::thread& thread : externalThreads) thread.join();
|
||||
jobs.Wait();
|
||||
return {stdPcmResult, false, {}};
|
||||
}
|
||||
|
||||
|
|
@ -1136,7 +1121,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
for(Configuration* dep : config.dependencies) {
|
||||
depThreads.emplace_back([&, dep](){
|
||||
try {
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
if (jobs.Failed()) return;
|
||||
|
||||
const std::shared_future<BuildResult> built = OncePerPass(depResults, depMutex, dep->PcmDir(), [&] { return Build(*dep, depResults, depMutex); });
|
||||
const BuildResult& result = built.get();
|
||||
|
|
@ -1146,20 +1131,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
for (const std::string& f : result.publicCompileFlags) publicFlagSet.insert(f);
|
||||
for (const std::string& dir : result.runPaths) runPathSet.insert(dir);
|
||||
fileMutex.unlock();
|
||||
if (!result.result.empty()) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = result.result;
|
||||
}
|
||||
}
|
||||
if (!result.result.empty()) jobs.Fail(result.result);
|
||||
if (result.repack) {
|
||||
repack = true;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::format("dep build for {} threw: {}", dep->path.string(), e.what());
|
||||
}
|
||||
jobs.Fail(std::format("dep build for {} threw: {}", dep->path.string(), e.what()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -1196,17 +1173,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
// depfile the compile below writes is the whole record of what this
|
||||
// object was built from beyond the .c itself.
|
||||
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) {
|
||||
threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled, &config, &includeFlags, &defineFlags, &userFlags, &cArchFlags, <oCompileFlags]() {
|
||||
Progress::Task task(std::format("Compiling {}.c", cFile.filename().string()));
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
|
||||
std::string result = RunBuildCommand(std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string()));
|
||||
if (result.empty()) return;
|
||||
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
}
|
||||
jobs.Add(std::format("Compiling {}.c", cFile.filename().string()), [command = std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())] {
|
||||
return RunBuildCommand(command);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1225,23 +1193,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) {
|
||||
const Toolchain& toolchain = GetToolchain();
|
||||
if (toolchain.nvcc.empty()) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError);
|
||||
}
|
||||
jobs.Fail(std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError));
|
||||
break;
|
||||
}
|
||||
threads.emplace_back([&cFile, &buildError, &buildCancelled, &config, &toolchain, srcPath, objPath]() {
|
||||
Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string()));
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) return;
|
||||
|
||||
std::string result = RunBuildCommand(std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch)));
|
||||
if (result.empty()) return;
|
||||
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
}
|
||||
jobs.Add(std::format("Compiling {}.cu", cFile.filename().string()), [command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] {
|
||||
return RunBuildCommand(command);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1253,9 +1209,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
thread.join();
|
||||
}
|
||||
|
||||
if(buildCancelled.load()) {
|
||||
for(std::thread& thread : threads) thread.join();
|
||||
return {buildError, false, {}};
|
||||
if (jobs.Failed()) {
|
||||
return {jobs.Wait(), false, {}};
|
||||
}
|
||||
|
||||
// Ship runtime artifacts from transitive deps' bin dirs alongside the
|
||||
|
|
@ -1334,7 +1289,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
};
|
||||
for (Configuration* dep : config.dependencies) forwardDepArtifacts(dep);
|
||||
} catch (const fs::filesystem_error& e) {
|
||||
for(std::thread& thread : threads) thread.join();
|
||||
jobs.Fail(e.what());
|
||||
jobs.Wait();
|
||||
return {e.what(), false, {}};
|
||||
}
|
||||
}
|
||||
|
|
@ -1389,15 +1345,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
if (ext.latestArtifact > externalFloor) externalFloor = ext.latestArtifact;
|
||||
}
|
||||
|
||||
// Check every interface before compiling any of them. Module::Compile waits
|
||||
// on the `compiled` flag of each sibling module it imports, and that flag is
|
||||
// set either by a Compile that runs or by the Check that decides none is
|
||||
// needed — so a Check still pending while another module's thread is already
|
||||
// waiting would block on a flag nothing goes on to raise.
|
||||
std::vector<Module*> staleInterfaces;
|
||||
// Check every interface before scheduling any of them. Schedule() puts a
|
||||
// unit after the stale units it imports and reads their needsRecompiling
|
||||
// for that, which a unit's own Check need not have set: a partition's
|
||||
// returns at the first stale import it finds.
|
||||
for(std::unique_ptr<Module>& interface : config.interfaces) {
|
||||
if(interface->Check(pcmDir, externalFloor)) {
|
||||
staleInterfaces.push_back(interface.get());
|
||||
buildResult.repack = true;
|
||||
}
|
||||
files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string());
|
||||
|
|
@ -1406,45 +1359,24 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
}
|
||||
}
|
||||
|
||||
for(Module* mod : staleInterfaces) {
|
||||
threads.emplace_back([mod, &command, &pcmDir, &buildDir, &buildCancelled, &buildError]() {
|
||||
Progress::Task task(std::format("Compiling interface {}", mod->path.filename().string()));
|
||||
try {
|
||||
mod->Compile(command, pcmDir, buildDir, buildCancelled, buildError);
|
||||
} catch (const std::exception& e) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::format("Module::Compile threw: {}", e.what());
|
||||
}
|
||||
}
|
||||
});
|
||||
// Every interface, and with each its partitions, not only the stale
|
||||
// ones: a unit whose BMI is up to date can still be without the object
|
||||
// made from it, which Schedule() then adds alone. No repack for that
|
||||
// here: the link below runs again for an object newer than its output.
|
||||
for(std::unique_ptr<Module>& interface : config.interfaces) {
|
||||
interface->Schedule(jobs, command, pcmDir, buildDir);
|
||||
}
|
||||
|
||||
for(Implementation& implementation : config.implementations) {
|
||||
if(implementation.Check(buildDir, pcmDir, externalFloor)) {
|
||||
buildResult.repack = true;
|
||||
Implementation* impl = &implementation;
|
||||
threads.emplace_back([impl, &command, &buildDir, &buildCancelled, &buildError]() {
|
||||
Progress::Task task(std::format("Compiling {}.cpp", impl->path.filename().string()));
|
||||
try {
|
||||
impl->Compile(command, buildDir, buildCancelled, buildError);
|
||||
} catch (const std::exception& e) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::format("Implementation::Compile threw: {}", e.what());
|
||||
}
|
||||
}
|
||||
});
|
||||
implementation.Schedule(jobs, command, pcmDir, buildDir);
|
||||
}
|
||||
files += std::format(" {}/{}_impl.o", buildDir.string(), implementation.path.filename().string());
|
||||
}
|
||||
|
||||
for(std::thread& thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
|
||||
if(buildCancelled.load()) {
|
||||
return {buildError, false, {}};
|
||||
if (std::string failed = jobs.Wait(); !failed.empty()) {
|
||||
return {std::move(failed), false, {}};
|
||||
}
|
||||
|
||||
std::string linkExtras;
|
||||
|
|
@ -2228,6 +2160,13 @@ object, and invokes its CrafterBuildProject() to obtain a Configuration that
|
|||
drives the build. Outputs land at bin/<name>-<target>-<march>/, intermediates
|
||||
at build/<name>-<target>-<march>/.
|
||||
|
||||
A build runs at most as many of its steps at once as the machine has hardware
|
||||
threads: the compiles of its sources, its shaders and assets, and its links
|
||||
and archives, counted together for the project and the dependencies it is
|
||||
built on. An external dependency's CMake build is not among them, nor are the
|
||||
tests `test` runs. A step counts as one whatever threads it starts for itself,
|
||||
as a link and the compression of an asset do.
|
||||
|
||||
Build options:
|
||||
-r Run the produced executable after a successful build:
|
||||
one for the host in its own directory, a wasm32 one
|
||||
|
|
@ -2244,7 +2183,9 @@ Build options:
|
|||
|
||||
Test options (after the `test` subcommand):
|
||||
--list Enumerate matching tests without running them.
|
||||
--jobs=<N> Parallel job count (default: hardware_concurrency).
|
||||
--jobs=<N> Tests built and run at once (default: one per
|
||||
hardware thread). The steps of their builds share
|
||||
the one limit a build has.
|
||||
--timeout=<seconds> Per-test timeout override.
|
||||
--runner=<spec> Override the test runner for this run. Specs:
|
||||
local
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ module Crafter.Build:Implementation_impl;
|
|||
import std;
|
||||
import :Implementation;
|
||||
import :Interface;
|
||||
import :Jobs;
|
||||
import :Platform;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
|
|
@ -35,33 +36,22 @@ namespace Crafter {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
void Implementation::Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const {
|
||||
void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const {
|
||||
std::vector<JobGroup::Job> after;
|
||||
for(ModulePartition* dependency : partitionDependencies) {
|
||||
if(!dependency->compiled.load()) {
|
||||
dependency->compiled.wait(false);
|
||||
}
|
||||
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
|
||||
}
|
||||
for(Module* dependency : moduleDependencies) {
|
||||
if(!dependency->compiled.load()) {
|
||||
dependency->compiled.wait(false);
|
||||
}
|
||||
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
|
||||
}
|
||||
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// -MD leaves <name>_impl.o.d beside the object for Check to read, and
|
||||
// -fmodule-file-deps puts the BMIs the unit imported in it with the
|
||||
// headers. The driver adds that for --precompile only, so a std
|
||||
// module rebuilt in place, for a mingw-w64 or libc++ update under
|
||||
// the same compiler, left the objects importing it as they were, and
|
||||
// the next build only relinked them.
|
||||
std::string result = RunBuildCommand(std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string()));
|
||||
|
||||
bool expected = false;
|
||||
if(!result.empty() && buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
}
|
||||
jobs.Add(std::format("Compiling {}.cpp", path.filename().string()), [command = std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())] {
|
||||
return RunBuildCommand(command);
|
||||
}, after);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,55 @@
|
|||
module Crafter.Build:Interface_impl;
|
||||
import std;
|
||||
import :Interface;
|
||||
import :Jobs;
|
||||
import :Platform;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
// The job that makes an interface unit's object from its BMI, once the
|
||||
// jobs in `after` have finished. The command is put together here, as in
|
||||
// the functions below, so the job owns the one it runs.
|
||||
void AddObjectJob(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
|
||||
jobs.Add(std::format("Compiling {}.cppm", path.filename().string()), [command = std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())] {
|
||||
return Crafter::RunBuildCommand(command);
|
||||
}, after);
|
||||
}
|
||||
|
||||
// The two compiler runs of a stale interface unit, as jobs of `jobs`: its
|
||||
// BMI once the jobs in `after` have finished, then its object from that
|
||||
// BMI. Returns the first, the one the units importing this one come
|
||||
// after: the object is the link's alone to wait for.
|
||||
Crafter::JobGroup::Job AddInterfaceJobs(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
|
||||
// -MD records every header the preamble pulled in, next to the BMI as
|
||||
// <name>.pcm.d, so the next Check can see an edit to one of them.
|
||||
const Crafter::JobGroup::Job precompile = jobs.Add(std::format("Precompiling {}.cppm", path.filename().string()), [command = std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())] {
|
||||
return Crafter::RunBuildCommand(command);
|
||||
}, after);
|
||||
const std::array<Crafter::JobGroup::Job, 1> precompiled = {precompile};
|
||||
AddObjectJob(jobs, clang, path, pcmDir, buildDir, precompiled);
|
||||
return precompile;
|
||||
}
|
||||
|
||||
// For a unit whose BMI is up to date: the object job alone, when the
|
||||
// object is missing or older than the BMI it is made from. The two are
|
||||
// written by two commands, and a build can end between them: by an error
|
||||
// elsewhere, which keeps the second from starting, by the second failing,
|
||||
// or by being interrupted. An object written in the same tick of the
|
||||
// file system's clock as its BMI is taken to be the later of the two,
|
||||
// which it is whenever the command that writes it ran.
|
||||
void AddObjectJobIfStale(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir) {
|
||||
std::error_code ec;
|
||||
const fs::file_time_type pcmTime = fs::last_write_time(std::format("{}.pcm", (pcmDir/path.filename()).string()), ec);
|
||||
// No BMI to make it from; Check does not call such a unit up to date.
|
||||
if (ec) return;
|
||||
const fs::file_time_type objectTime = fs::last_write_time(std::format("{}.o", (buildDir/path.filename()).string()), ec);
|
||||
if (!ec && objectTime >= pcmTime) return;
|
||||
AddObjectJob(jobs, clang, path, pcmDir, buildDir, {});
|
||||
}
|
||||
}
|
||||
|
||||
namespace Crafter {
|
||||
ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {}
|
||||
ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
|
||||
|
||||
bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
|
||||
if(!checked) {
|
||||
|
|
@ -44,11 +88,6 @@ namespace Crafter {
|
|||
}
|
||||
}
|
||||
needsRecompiling = false;
|
||||
compiled.store(true);
|
||||
// Nothing waits on `compiled` until the compile threads start,
|
||||
// which is after every Check has run — but notify anyway so the
|
||||
// flag is never left set without a wake-up behind it.
|
||||
compiled.notify_all();
|
||||
return false;
|
||||
} else {
|
||||
needsRecompiling = true;
|
||||
|
|
@ -59,52 +98,25 @@ namespace Crafter {
|
|||
}
|
||||
}
|
||||
|
||||
void ModulePartition::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) {
|
||||
for(ModulePartition* dependency : partitionDependencies) {
|
||||
if(!dependency->compiled.load()) {
|
||||
dependency->compiled.wait(false);
|
||||
std::optional<JobGroup::Job> ModulePartition::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
|
||||
if (scheduled) return precompileJob;
|
||||
if (needsRecompiling) {
|
||||
std::vector<JobGroup::Job> after;
|
||||
for (ModulePartition* dependency : partitionDependencies) {
|
||||
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
|
||||
}
|
||||
}
|
||||
for(Module* dependency : moduleDependencies) {
|
||||
if(!dependency->compiled.load()) {
|
||||
dependency->compiled.wait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) {
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
return;
|
||||
}
|
||||
|
||||
// -MD records every header the preamble pulled in, next to the BMI as
|
||||
// <name>.pcm.d, so the next Check can see an edit to one of them.
|
||||
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
|
||||
|
||||
if (!result.empty()) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
|
||||
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
|
||||
|
||||
if (!result.empty()) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
for (Module* dependency : moduleDependencies) {
|
||||
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
|
||||
}
|
||||
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
|
||||
} else {
|
||||
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
|
||||
}
|
||||
scheduled = true;
|
||||
return precompileJob;
|
||||
}
|
||||
|
||||
Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {}
|
||||
Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
|
||||
|
||||
bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
|
||||
if(!checked) {
|
||||
|
|
@ -116,7 +128,7 @@ namespace Crafter {
|
|||
if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) {
|
||||
fs::file_time_type pcmTime = fs::last_write_time(pcmPath);
|
||||
// Every partition gets Check()ed even once one is known stale:
|
||||
// Compile() drives partition rebuilds off their own
|
||||
// Schedule() drives partition rebuilds off their own
|
||||
// needsRecompiling flags, so short-circuiting here would leave
|
||||
// the later ones unevaluated and silently unbuilt.
|
||||
bool depCheck = false;
|
||||
|
|
@ -149,14 +161,12 @@ namespace Crafter {
|
|||
return true;
|
||||
} else {
|
||||
needsRecompiling = false;
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Already known stale, but the dependencies still need
|
||||
// evaluating: an unchecked local module would never get built,
|
||||
// and Compile() below waits on its `compiled` flag.
|
||||
// evaluating: Schedule() below reads their needsRecompiling,
|
||||
// and an unchecked local module would never get built.
|
||||
for(std::unique_ptr<ModulePartition>& partition : partitions) {
|
||||
partition->Check(pcmDir, sourceFloor);
|
||||
}
|
||||
|
|
@ -171,60 +181,29 @@ namespace Crafter {
|
|||
}
|
||||
}
|
||||
|
||||
void Module::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) {
|
||||
// A sibling module in the same Configuration that this interface unit
|
||||
// imports has to have its PCM on disk before we precompile against it.
|
||||
// Safe to block here: Build() Checks every interface before it spawns
|
||||
// any compile thread, so a dependency that needs no rebuild already has
|
||||
// `compiled` set and this returns immediately.
|
||||
for(Module* dependency : moduleDependencies) {
|
||||
if(!dependency->compiled.load()) {
|
||||
dependency->compiled.wait(false);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(partitions.size());
|
||||
for(std::unique_ptr<ModulePartition>& part : partitions) {
|
||||
if(part->needsRecompiling) {
|
||||
threads.emplace_back(&ModulePartition::Compile, part.get(), clang, pcmDir, buildDir, std::ref(buildCancelled), std::ref(buildError));
|
||||
}
|
||||
}
|
||||
|
||||
for(std::thread& thread : threads){
|
||||
thread.join();
|
||||
}
|
||||
|
||||
if (buildCancelled.load(std::memory_order_relaxed)) {
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
return;
|
||||
}
|
||||
|
||||
// -MD records every header the preamble pulled in, next to the BMI as
|
||||
// <name>.pcm.d, so the next Check can see an edit to one of them.
|
||||
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
|
||||
|
||||
if (!result.empty()) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
compiled.store(true);
|
||||
compiled.notify_all();
|
||||
|
||||
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
|
||||
|
||||
if (!result.empty()) {
|
||||
bool expected = false;
|
||||
if (buildCancelled.compare_exchange_strong(expected, true)) {
|
||||
buildError = std::move(result);
|
||||
std::optional<JobGroup::Job> Module::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
|
||||
if (scheduled) return precompileJob;
|
||||
std::vector<JobGroup::Job> after;
|
||||
// All of the module's partitions, not the ones the primary interface
|
||||
// names: the scanner records no edge for its `import :Part;` lines
|
||||
// (see GetInterfacesAndImplementations). And of a module that is up
|
||||
// to date as well: this is where its partitions are scheduled, and
|
||||
// one of them may be without its object.
|
||||
for (const std::unique_ptr<ModulePartition>& partition : partitions) {
|
||||
if (const std::optional<JobGroup::Job> job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
|
||||
}
|
||||
if (needsRecompiling) {
|
||||
// A sibling module in the same Configuration that this interface
|
||||
// unit imports has to have its PCM on disk before we precompile
|
||||
// against it.
|
||||
for (Module* dependency : moduleDependencies) {
|
||||
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
|
||||
}
|
||||
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
|
||||
} else {
|
||||
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
|
||||
}
|
||||
scheduled = true;
|
||||
return precompileJob;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
218
implementations/Crafter.Build-Jobs.cpp
Normal file
218
implementations/Crafter.Build-Jobs.cpp
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Build:Jobs_impl;
|
||||
import std;
|
||||
import :Jobs;
|
||||
import :Progress;
|
||||
|
||||
namespace {
|
||||
// The pool this thread is a worker of; null on every other thread.
|
||||
thread_local const Crafter::JobPool* WorkerOf = nullptr;
|
||||
}
|
||||
|
||||
namespace Crafter {
|
||||
JobPool::JobPool(std::uint32_t workers) : limit(std::max(workers, 1u)) {}
|
||||
|
||||
JobPool::~JobPool() {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
stopping = true;
|
||||
}
|
||||
wake.notify_all();
|
||||
for (std::thread& thread : threads) thread.join();
|
||||
}
|
||||
|
||||
JobPool& JobPool::Process() {
|
||||
static JobPool* const pool = new JobPool(std::thread::hardware_concurrency());
|
||||
return *pool;
|
||||
}
|
||||
|
||||
std::uint32_t JobPool::Workers() const {
|
||||
return limit;
|
||||
}
|
||||
|
||||
void JobPool::Submit(std::function<void()> job) {
|
||||
std::lock_guard lock(mutex);
|
||||
queue.push_back(std::move(job));
|
||||
if (queue.size() <= idle || threads.size() >= limit) {
|
||||
wake.notify_one();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
threads.emplace_back([this] { Work(); });
|
||||
} catch (...) {
|
||||
// The system has no thread to give. The workers there are take
|
||||
// the job when they get to it. With none it would stay queued
|
||||
// for good, and whoever waits for it with it.
|
||||
if (!threads.empty()) return;
|
||||
queue.pop_back();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void JobPool::Work() {
|
||||
WorkerOf = this;
|
||||
std::unique_lock lock(mutex);
|
||||
for (;;) {
|
||||
while (queue.empty() && !stopping) {
|
||||
++idle;
|
||||
wake.wait(lock);
|
||||
--idle;
|
||||
}
|
||||
if (queue.empty()) return;
|
||||
std::function<void()> job = std::move(queue.front());
|
||||
queue.pop_front();
|
||||
lock.unlock();
|
||||
job();
|
||||
// Before the lock is taken again: what the job captured is
|
||||
// released without holding up the queue.
|
||||
job = nullptr;
|
||||
lock.lock();
|
||||
}
|
||||
}
|
||||
|
||||
void JobPool::Run(const std::function<void()>& work) {
|
||||
if (WorkerOf == this) {
|
||||
work();
|
||||
return;
|
||||
}
|
||||
// Shared with the job, not a local of this function: this thread
|
||||
// goes on as soon as the value is set, which is before set_value has
|
||||
// returned on the worker.
|
||||
const std::shared_ptr<std::promise<void>> done = std::make_shared<std::promise<void>>();
|
||||
std::future<void> finished = done->get_future();
|
||||
Submit([&work, done] {
|
||||
try {
|
||||
work();
|
||||
done->set_value();
|
||||
} catch (...) {
|
||||
done->set_exception(std::current_exception());
|
||||
}
|
||||
});
|
||||
finished.get();
|
||||
}
|
||||
|
||||
struct JobGroup::Node {
|
||||
std::string label;
|
||||
std::function<std::string()> work;
|
||||
std::unique_ptr<Progress::Task> task;
|
||||
// The jobs added after this one that it has yet to release, and how
|
||||
// many jobs this one still waits for. Both under the group's mutex;
|
||||
// the members above belong to whoever runs the job.
|
||||
std::vector<Node*> dependents;
|
||||
std::size_t waiting = 0;
|
||||
bool finished = false;
|
||||
};
|
||||
|
||||
JobGroup::JobGroup(JobPool& pool) : pool(pool) {
|
||||
if (WorkerOf == &pool) throw std::logic_error("a JobGroup cannot be made on a worker of its own pool: it would wait there for jobs that need that worker");
|
||||
}
|
||||
|
||||
JobGroup::~JobGroup() {
|
||||
std::unique_lock lock(mutex);
|
||||
failed = true;
|
||||
settled.wait(lock, [this] { return unfinished == 0; });
|
||||
}
|
||||
|
||||
JobGroup::Job JobGroup::Add(std::string label, std::function<std::string()> work, std::span<const Job> after) {
|
||||
std::unique_ptr<Node> made = std::make_unique<Node>();
|
||||
// Counted from here on, not from when it starts: the total a build
|
||||
// shows is then what it has queued, and not only what the workers
|
||||
// have got to.
|
||||
made->task = std::make_unique<Progress::Task>(label);
|
||||
made->label = std::move(label);
|
||||
made->work = std::move(work);
|
||||
|
||||
std::lock_guard lock(mutex);
|
||||
// Room for the new job in each list it may join, made before the
|
||||
// group knows of it: from there to the count below nothing can throw,
|
||||
// so no job is ever waited on by half of what it comes after.
|
||||
for (const Job job : after) {
|
||||
if (job >= nodes.size()) throw std::out_of_range("JobGroup::Add: a job can only come after jobs added before it");
|
||||
std::vector<Node*>& dependents = nodes[job]->dependents;
|
||||
dependents.reserve(dependents.size() + after.size());
|
||||
}
|
||||
const Job id = nodes.size();
|
||||
Node& node = *nodes.emplace_back(std::move(made));
|
||||
for (const Job job : after) {
|
||||
Node& before = *nodes[job];
|
||||
if (before.finished) continue;
|
||||
before.dependents.push_back(&node);
|
||||
++node.waiting;
|
||||
}
|
||||
++unfinished;
|
||||
if (node.waiting != 0) return id;
|
||||
try {
|
||||
Start(node);
|
||||
} catch (...) {
|
||||
// Not queued (JobPool::Submit), so nothing will ever finish it:
|
||||
// it is taken back, or Wait() would never return.
|
||||
node.work = nullptr;
|
||||
node.task.reset();
|
||||
node.finished = true;
|
||||
if (--unfinished == 0) settled.notify_all();
|
||||
throw;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
void JobGroup::Start(Node& node) {
|
||||
pool.Submit([this, &node] { Execute(node); });
|
||||
}
|
||||
|
||||
void JobGroup::Execute(Node& node) {
|
||||
bool skipped = false;
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
skipped = failed;
|
||||
}
|
||||
std::string result;
|
||||
if (!skipped) {
|
||||
try {
|
||||
result = node.work();
|
||||
} catch (const std::exception& e) {
|
||||
result = std::format("{}: {}", node.label, e.what());
|
||||
} catch (...) {
|
||||
result = std::format("{}: threw something that isn't a std::exception", node.label);
|
||||
}
|
||||
}
|
||||
// Both before the group hears of it: what the work captured is gone,
|
||||
// and the step counted as done, by the time Wait() returns.
|
||||
node.work = nullptr;
|
||||
node.task.reset();
|
||||
|
||||
// Nothing of the group is touched once this lock is released: with
|
||||
// the last job finished, whoever waited may destroy it.
|
||||
std::lock_guard lock(mutex);
|
||||
if (!result.empty() && !failed) {
|
||||
failed = true;
|
||||
error = std::move(result);
|
||||
}
|
||||
node.finished = true;
|
||||
// Released after a failure as well: they are skipped when they run,
|
||||
// which is what counts them as finished.
|
||||
for (Node* dependent : node.dependents) {
|
||||
if (--dependent->waiting == 0) Start(*dependent);
|
||||
}
|
||||
if (--unfinished == 0) settled.notify_all();
|
||||
}
|
||||
|
||||
void JobGroup::Fail(std::string why) {
|
||||
std::lock_guard lock(mutex);
|
||||
if (failed) return;
|
||||
failed = true;
|
||||
error = std::move(why);
|
||||
}
|
||||
|
||||
bool JobGroup::Failed() const {
|
||||
std::lock_guard lock(mutex);
|
||||
return failed;
|
||||
}
|
||||
|
||||
std::string JobGroup::Wait() {
|
||||
std::unique_lock lock(mutex);
|
||||
settled.wait(lock, [this] { return unfinished == 0; });
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
|
@ -18,6 +18,7 @@ import :Toolchain;
|
|||
import :Clang;
|
||||
import :Interface;
|
||||
import :External;
|
||||
import :Jobs;
|
||||
import :Progress;
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Crafter;
|
||||
|
|
@ -25,7 +26,7 @@ using namespace Crafter;
|
|||
namespace {
|
||||
// Exclusive advisory lock over one PCM cache dir (`<cache>/<target>-<march>/`),
|
||||
// held for the duration of a (re)build. Concurrent crafter-build invocations —
|
||||
// and the worker threads inside a single invocation — that share a cache
|
||||
// and the threads of a single invocation that build at once — that share a cache
|
||||
// serialize their builds through it: the first builder to acquire the lock
|
||||
// precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else
|
||||
// blocks, then re-checks freshness and reuses the finished file instead of
|
||||
|
|
@ -276,34 +277,46 @@ bool Crafter::MatchAny(std::span<const std::string> globs, std::string_view name
|
|||
return false;
|
||||
}
|
||||
|
||||
// See the declaration in Crafter.Build-Platform.cppm for why this branches on
|
||||
// the exit code rather than on whether the command said anything.
|
||||
namespace {
|
||||
// RunBuildCommand's command, run on the thread that calls. See the
|
||||
// declaration in Crafter.Build-Platform.cppm for why this branches on the
|
||||
// exit code rather than on whether the command said anything.
|
||||
std::string RunBuildStep(std::string_view cmd) {
|
||||
Progress::EchoCommand(cmd);
|
||||
CommandResult r = RunCommandChecked(cmd);
|
||||
// A mingw build against a system prefix sees mingw-w64 through a view in
|
||||
// the cache, and clang names every header by the path it found it at.
|
||||
r.output = MingwViewToPrefix(std::move(r.output));
|
||||
|
||||
if (r.exitCode == 0) {
|
||||
// Warnings from a step that succeeded. Show them — until now they were
|
||||
// invisible on an incremental build and fatal on a cold one.
|
||||
if (!r.output.empty()) Progress::Diagnostic(r.output);
|
||||
return "";
|
||||
}
|
||||
|
||||
// A compiler killed outright (the OOM killer is the common one) prints
|
||||
// nothing, so the old "output means failure" rule read it as success and
|
||||
// let the build carry on with a missing object. Say what happened instead.
|
||||
if (r.output.empty()) {
|
||||
return r.crashed
|
||||
? std::format("terminated by signal {}: {}", r.signal, cmd)
|
||||
: std::format("exited with code {}: {}", r.exitCode, cmd);
|
||||
}
|
||||
if (r.crashed) {
|
||||
return std::format("{}\nterminated by signal {}", r.output, r.signal);
|
||||
}
|
||||
return r.output;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Crafter::RunBuildCommand(std::string_view cmd) {
|
||||
Progress::EchoCommand(cmd);
|
||||
CommandResult r = RunCommandChecked(cmd);
|
||||
// A mingw build against a system prefix sees mingw-w64 through a view in
|
||||
// the cache, and clang names every header by the path it found it at.
|
||||
r.output = MingwViewToPrefix(std::move(r.output));
|
||||
|
||||
if (r.exitCode == 0) {
|
||||
// Warnings from a step that succeeded. Show them — until now they were
|
||||
// invisible on an incremental build and fatal on a cold one.
|
||||
if (!r.output.empty()) Progress::Diagnostic(r.output);
|
||||
return "";
|
||||
}
|
||||
|
||||
// A compiler killed outright (the OOM killer is the common one) prints
|
||||
// nothing, so the old "output means failure" rule read it as success and
|
||||
// let the build carry on with a missing object. Say what happened instead.
|
||||
if (r.output.empty()) {
|
||||
return r.crashed
|
||||
? std::format("terminated by signal {}: {}", r.signal, cmd)
|
||||
: std::format("exited with code {}: {}", r.exitCode, cmd);
|
||||
}
|
||||
if (r.crashed) {
|
||||
return std::format("{}\nterminated by signal {}", r.output, r.signal);
|
||||
}
|
||||
return r.output;
|
||||
// A job is on a worker already and runs the command where it is. A link,
|
||||
// or the precompile of the std module, comes from the thread of a Build()
|
||||
// or a LoadProject and waits here for its turn among the jobs.
|
||||
std::string result;
|
||||
JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); });
|
||||
return result;
|
||||
}
|
||||
|
||||
// --- Dependencies of project.cpp itself -------------------------------------
|
||||
|
|
@ -874,7 +887,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
|
|||
// and, when clang finds no gcc directory, an empty entry that would
|
||||
// name a manifest in the working directory. A toolchain that isn't
|
||||
// there is a build error, not an exception: Build() runs this with
|
||||
// its worker threads started.
|
||||
// the threads of its external dependencies started.
|
||||
const Toolchain& tc = GetToolchain();
|
||||
const std::string where = tc.mingwPrefix.empty()
|
||||
? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH")
|
||||
|
|
@ -995,11 +1008,12 @@ std::string Crafter::GetBaseCommand(const Configuration& config) {
|
|||
}
|
||||
|
||||
namespace {
|
||||
constexpr std::array<std::string_view, 15> CrafterBuildModules = {
|
||||
constexpr std::array<std::string_view, 16> CrafterBuildModules = {
|
||||
"Crafter.Build-Toolchain",
|
||||
"Crafter.Build-Shader",
|
||||
"Crafter.Build-Platform",
|
||||
"Crafter.Build-Flatpak",
|
||||
"Crafter.Build-Jobs",
|
||||
"Crafter.Build-Interface",
|
||||
"Crafter.Build-Implementation",
|
||||
"Crafter.Build-External",
|
||||
|
|
|
|||
Loading…
Reference in a new issue