mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 16:58:37 +00:00
1129 lines
59 KiB
C++
1129 lines
59 KiB
C++
// Driver-level check of the translated corpus: vk_pipeline_check <spirv dir> [pipeline_cache.bin]
|
|
// Reads <spirv dir>/index.json (written by tools/rdna2spirv.py), creates a VkShaderModule for every entry and a real
|
|
// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash
|
|
// table 2; storage images 4, 7 and 8..19; push constants 144 bytes):
|
|
// - cs: compute pipeline via vkCreateComputePipelines
|
|
// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
|
|
// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
|
|
// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders
|
|
// whose required features or partner stubs are unavailable are reported as skipped rather than failed.
|
|
// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
|
|
// 10 minutes and at the end
|
|
// --jobs N compile on N threads (default: half the hardware threads)
|
|
// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation)
|
|
// --start I --count N check only index entries [I, I+N) (sorted by name)
|
|
// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running
|
|
// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip)
|
|
// --stage S which stages to check: all (default), cs, or graphics (aliases: --compute-only, --graphics-only)
|
|
// --stats FILE write the driver's statistics for each translated shader (VK_KHR_pipeline_executable_properties:
|
|
// instructions, registers, spills, scratch, waves...) as CSV rows name,stage,statistic,value. Only
|
|
// the executable that runs the translated shader is written, not the partner stub's. Use without
|
|
// cache.bin: a pipeline loaded from the cache may come without statistics.
|
|
// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and
|
|
// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a
|
|
// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count.
|
|
#include "vulkan_loader.h"
|
|
#include "vk_device_pick.h"
|
|
#include "pipeline_cache_file.h"
|
|
#include "pipeline_cache_snapshot.h"
|
|
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cctype>
|
|
#include <charconv>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <condition_variable>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <iterator>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <mutex>
|
|
#include <set>
|
|
#include <shared_mutex>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
static PFN_vkGetInstanceProcAddr gipa;
|
|
|
|
struct VertexInputMeta {
|
|
uint32_t location = 0;
|
|
std::string type = "float";
|
|
};
|
|
|
|
struct ShaderMeta {
|
|
std::string stage;
|
|
uint32_t subgroup_size = 0;
|
|
bool writes_depth = false;
|
|
bool needs_maintenance8 = false;
|
|
std::vector<std::string> features;
|
|
std::vector<uint32_t> inputs;
|
|
std::vector<uint32_t> outputs;
|
|
std::vector<uint32_t> params;
|
|
std::vector<uint32_t> gs_inputs;
|
|
std::vector<uint32_t> gs_outputs;
|
|
std::vector<uint32_t> gs_input_locations;
|
|
std::vector<uint32_t> gs_output_locations;
|
|
bool has_gs_input_locations = false;
|
|
bool has_gs_output_locations = false;
|
|
std::vector<VertexInputMeta> vertex_inputs;
|
|
};
|
|
|
|
// Minimal recursive-descent JSON reader for index.json (handles strings, numbers, bools, arrays, objects).
|
|
namespace {
|
|
|
|
struct JsonParser {
|
|
const std::string& s;
|
|
size_t i = 0;
|
|
bool error = false;
|
|
std::string error_msg;
|
|
|
|
void fail(const char* ctx) {
|
|
if (!error) {
|
|
error = true;
|
|
error_msg = std::string(ctx) + " at byte " + std::to_string(i);
|
|
}
|
|
}
|
|
void ws() {
|
|
while (i < s.size() && std::isspace(static_cast<unsigned char>(s[i]))) i++;
|
|
}
|
|
bool consume(char c) {
|
|
ws();
|
|
if (i < s.size() && s[i] == c) { i++; return true; }
|
|
return false;
|
|
}
|
|
std::string parse_string() {
|
|
ws();
|
|
if (i >= s.size() || s[i] != '"') { fail("expected string"); return {}; }
|
|
i++;
|
|
std::string out;
|
|
while (i < s.size() && s[i] != '"') {
|
|
if (s[i] == '\\' && i + 1 < s.size()) {
|
|
i++;
|
|
out.push_back(s[i++]);
|
|
} else {
|
|
out.push_back(s[i++]);
|
|
}
|
|
}
|
|
if (i >= s.size() || s[i] != '"') { fail("unterminated string"); return out; }
|
|
i++;
|
|
return out;
|
|
}
|
|
uint32_t parse_u32() {
|
|
ws();
|
|
const size_t start = i;
|
|
bool neg = false;
|
|
if (i < s.size() && s[i] == '-') { neg = true; i++; }
|
|
uint32_t v = 0;
|
|
const size_t digits_start = i;
|
|
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
|
|
v = v * 10 + uint32_t(s[i] - '0');
|
|
i++;
|
|
}
|
|
if (i == digits_start) { i = start; fail("expected unsigned integer"); return 0u; }
|
|
while (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E' || s[i] == '+' || s[i] == '-' ||
|
|
(s[i] >= '0' && s[i] <= '9'))) i++;
|
|
return neg ? 0u : v;
|
|
}
|
|
bool parse_bool() {
|
|
ws();
|
|
if (s.compare(i, 4, "true") == 0) { i += 4; return true; }
|
|
if (s.compare(i, 5, "false") == 0) { i += 5; return false; }
|
|
fail("expected boolean");
|
|
return false;
|
|
}
|
|
void skip_value() {
|
|
ws();
|
|
if (i >= s.size()) { fail("unexpected end of JSON"); return; }
|
|
char c = s[i];
|
|
if (c == '"') { parse_string(); return; }
|
|
if (c == '{') {
|
|
i++;
|
|
while (!error && i < s.size()) {
|
|
if (consume('}')) return;
|
|
const size_t before = i;
|
|
parse_string();
|
|
if (error) return;
|
|
if (!consume(':')) { fail("expected ':' in object"); return; }
|
|
skip_value();
|
|
if (error) return;
|
|
if (consume('}')) return;
|
|
if (!consume(',') || i == before) { fail("expected ',' or '}' in object"); return; }
|
|
}
|
|
if (!error) fail("unterminated object");
|
|
return;
|
|
}
|
|
if (c == '[') {
|
|
i++;
|
|
while (!error && i < s.size()) {
|
|
if (consume(']')) return;
|
|
const size_t before = i;
|
|
skip_value();
|
|
if (error) return;
|
|
if (consume(']')) return;
|
|
if (!consume(',') || i == before) { fail("expected ',' or ']' in array"); return; }
|
|
}
|
|
if (!error) fail("unterminated array");
|
|
return;
|
|
}
|
|
const size_t before = i;
|
|
while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' &&
|
|
!std::isspace(static_cast<unsigned char>(s[i]))) i++;
|
|
if (i == before) fail("unexpected token in value");
|
|
}
|
|
std::vector<uint32_t> parse_u32_array() {
|
|
std::vector<uint32_t> out;
|
|
if (!consume('[')) { skip_value(); return out; }
|
|
while (!error && i < s.size()) {
|
|
if (consume(']')) return out;
|
|
const size_t before = i;
|
|
out.push_back(parse_u32());
|
|
if (error) return out;
|
|
if (consume(']')) return out;
|
|
if (!consume(',') || i == before) { fail("expected ',' or ']' in u32 array"); return out; }
|
|
}
|
|
if (!error) fail("unterminated u32 array");
|
|
return out;
|
|
}
|
|
std::vector<std::string> parse_str_array() {
|
|
std::vector<std::string> out;
|
|
if (!consume('[')) { skip_value(); return out; }
|
|
while (!error && i < s.size()) {
|
|
if (consume(']')) return out;
|
|
const size_t before = i;
|
|
out.push_back(parse_string());
|
|
if (error) return out;
|
|
if (consume(']')) return out;
|
|
if (!consume(',') || i == before) { fail("expected ',' or ']' in string array"); return out; }
|
|
}
|
|
if (!error) fail("unterminated string array");
|
|
return out;
|
|
}
|
|
std::vector<VertexInputMeta> parse_vertex_inputs() {
|
|
std::vector<VertexInputMeta> out;
|
|
if (!consume('[')) { skip_value(); return out; }
|
|
while (!error && i < s.size()) {
|
|
if (consume(']')) return out;
|
|
const size_t before = i;
|
|
VertexInputMeta vi;
|
|
if (consume('{')) {
|
|
while (!error && i < s.size()) {
|
|
if (consume('}')) break;
|
|
const size_t obj_before = i;
|
|
std::string k = parse_string();
|
|
if (error) return out;
|
|
if (!consume(':')) { fail("expected ':' in vertex_inputs entry"); return out; }
|
|
if (k == "location") vi.location = parse_u32();
|
|
else if (k == "type") vi.type = parse_string();
|
|
else skip_value();
|
|
if (error) return out;
|
|
if (consume('}')) break;
|
|
if (!consume(',') || i == obj_before) { fail("expected ',' or '}' in vertex_inputs entry"); return out; }
|
|
}
|
|
if (error) return out;
|
|
out.push_back(std::move(vi));
|
|
} else {
|
|
skip_value();
|
|
if (error) return out;
|
|
}
|
|
if (consume(']')) return out;
|
|
if (!consume(',') || i == before) { fail("expected ',' or ']' in vertex_inputs"); return out; }
|
|
}
|
|
if (!error) fail("unterminated vertex_inputs array");
|
|
return out;
|
|
}
|
|
ShaderMeta parse_meta() {
|
|
ShaderMeta m;
|
|
if (!consume('{')) { skip_value(); return m; }
|
|
while (!error && i < s.size()) {
|
|
if (consume('}')) return m;
|
|
const size_t before = i;
|
|
std::string k = parse_string();
|
|
if (error) return m;
|
|
if (!consume(':')) { fail("expected ':' in shader metadata"); return m; }
|
|
if (k == "stage") m.stage = parse_string();
|
|
else if (k == "subgroup_size") {
|
|
// null: translated with --wave64-emulate, exact on any subgroup size, so request none (0)
|
|
ws();
|
|
if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; }
|
|
else m.subgroup_size = parse_u32();
|
|
}
|
|
else if (k == "writes_depth") m.writes_depth = parse_bool();
|
|
else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool();
|
|
else if (k == "features") m.features = parse_str_array();
|
|
else if (k == "inputs") m.inputs = parse_u32_array();
|
|
else if (k == "outputs") m.outputs = parse_u32_array();
|
|
else if (k == "params") m.params = parse_u32_array();
|
|
else if (k == "gs_inputs") m.gs_inputs = parse_u32_array();
|
|
else if (k == "gs_outputs") m.gs_outputs = parse_u32_array();
|
|
else if (k == "gs_input_locations") { m.gs_input_locations = parse_u32_array(); m.has_gs_input_locations = true; }
|
|
else if (k == "gs_output_locations") { m.gs_output_locations = parse_u32_array(); m.has_gs_output_locations = true; }
|
|
else if (k == "vertex_inputs") m.vertex_inputs = parse_vertex_inputs();
|
|
else skip_value();
|
|
if (error) return m;
|
|
if (consume('}')) return m;
|
|
if (!consume(',') || i == before) { fail("expected ',' or '}' in shader metadata"); return m; }
|
|
}
|
|
if (!error) fail("unterminated shader metadata object");
|
|
return m;
|
|
}
|
|
};
|
|
|
|
std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err) {
|
|
std::ifstream f(path, std::ios::binary);
|
|
std::string s((std::istreambuf_iterator<char>(f)), {});
|
|
std::map<std::string, ShaderMeta> out;
|
|
JsonParser p{s, 0};
|
|
p.ws();
|
|
if (p.i >= s.size()) return out;
|
|
if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; }
|
|
while (!p.error && p.i < s.size()) {
|
|
if (p.consume('}')) return out;
|
|
const size_t before = p.i;
|
|
std::string name = p.parse_string();
|
|
if (p.error) break;
|
|
if (!p.consume(':')) { p.fail("expected ':' after shader name"); break; }
|
|
out[name] = p.parse_meta();
|
|
if (p.error) break;
|
|
if (p.consume('}')) return out;
|
|
if (!p.consume(',') || p.i == before) { p.fail("expected ',' or '}' in index.json"); break; }
|
|
}
|
|
if (p.error) { err = p.error_msg; return {}; }
|
|
err = "unterminated top-level object at byte " + std::to_string(p.i);
|
|
return {};
|
|
}
|
|
|
|
std::string stub_filename(const char* kind, const std::vector<uint32_t>& raw_locs) {
|
|
std::vector<uint32_t> locs = raw_locs;
|
|
std::sort(locs.begin(), locs.end());
|
|
locs.erase(std::unique(locs.begin(), locs.end()), locs.end());
|
|
std::string out = std::string(kind) + "_";
|
|
if (locs.empty()) {
|
|
out += "empty";
|
|
} else {
|
|
for (size_t i = 0; i < locs.size(); i++) {
|
|
if (i) out += "_";
|
|
out += std::to_string(locs[i]);
|
|
}
|
|
}
|
|
out += ".spv";
|
|
return out;
|
|
}
|
|
|
|
bool is_graphics_stage(const std::string& st) {
|
|
return st == "ps" || st == "vs" || st == "ms" || st == "gs";
|
|
}
|
|
|
|
std::string upper_stage(const std::string& st) {
|
|
std::string u = st;
|
|
for (char& c : u) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
|
|
return u;
|
|
}
|
|
|
|
VkShaderStageFlagBits stage_bit(const std::string& st) {
|
|
if (st == "cs") return VK_SHADER_STAGE_COMPUTE_BIT;
|
|
if (st == "ps") return VK_SHADER_STAGE_FRAGMENT_BIT;
|
|
if (st == "vs") return VK_SHADER_STAGE_VERTEX_BIT;
|
|
if (st == "ms") return VK_SHADER_STAGE_MESH_BIT_EXT;
|
|
if (st == "gs") return VK_SHADER_STAGE_GEOMETRY_BIT;
|
|
return VkShaderStageFlagBits(0);
|
|
}
|
|
|
|
struct StageStats {
|
|
uint32_t pipes_ok = 0;
|
|
uint32_t pipes_bad = 0;
|
|
uint32_t pipes_skipped = 0;
|
|
uint32_t w32_ok = 0;
|
|
uint32_t w32_bad = 0;
|
|
uint32_t w32_unforced = 0;
|
|
uint32_t w64_ok = 0;
|
|
uint32_t w64_bad = 0;
|
|
uint32_t w64_unforced = 0;
|
|
uint32_t feedback[3] = {}; // --cache-feedback, successful pipelines only, indexed by feedback_outcome
|
|
double seconds = 0.0;
|
|
double max_sec = 0.0;
|
|
std::string max_name;
|
|
std::map<std::string, uint32_t> skip_reasons;
|
|
};
|
|
|
|
constexpr std::pair<size_t, size_t> shader_slice(size_t size, size_t start, size_t count) {
|
|
const size_t lo = std::min(start, size);
|
|
const size_t remaining = size - lo;
|
|
const size_t hi = count ? lo + std::min(count, remaining) : size;
|
|
return {lo, hi};
|
|
}
|
|
|
|
static_assert(shader_slice(7, 2, 3) == std::pair<size_t, size_t>{2, 5});
|
|
static_assert(shader_slice(7, 2, 0) == std::pair<size_t, size_t>{2, 7});
|
|
static_assert(shader_slice(7, 8, 3) == std::pair<size_t, size_t>{7, 7});
|
|
static_assert(shader_slice(7, 2, std::numeric_limits<size_t>::max()) == std::pair<size_t, size_t>{2, 7});
|
|
|
|
// --cache-feedback class of a successful pipeline: 0 hit, 1 no hit reported, 2 unavailable. A hit counts only with
|
|
// VALID; the duration and base-pipeline bits are not classified.
|
|
constexpr int feedback_outcome(VkPipelineCreationFeedbackFlags f) {
|
|
if (!(f & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT)) return 2;
|
|
return (f & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) ? 0 : 1;
|
|
}
|
|
|
|
static_assert(feedback_outcome(0) == 2);
|
|
static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 2);
|
|
static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) == 1);
|
|
static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT |
|
|
VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0);
|
|
|
|
} // namespace
|
|
|
|
int main(int argc, char** argv) {
|
|
if (argc < 2) {
|
|
std::fprintf(stderr,
|
|
"usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
|
|
"[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
|
|
"[--stats FILE] [--cache-feedback]\n");
|
|
return 2;
|
|
}
|
|
std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen
|
|
std::string dir = argv[1], cache_path, stats_path;
|
|
uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
|
|
size_t start = 0, count = 0, max_bytes = 0;
|
|
size_t large_module_bytes = 4 * 1024 * 1024;
|
|
double slow = 30.0;
|
|
std::string stage_filter = "all";
|
|
bool cache_feedback = false;
|
|
for (int i = 2; i < argc; i++) {
|
|
std::string a = argv[i];
|
|
auto value = [&]() -> std::string_view {
|
|
if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {};
|
|
return argv[++i];
|
|
};
|
|
auto number = [&](auto& dest) {
|
|
const auto text = value();
|
|
if (text.empty()) return false;
|
|
const auto end = text.data() + text.size();
|
|
const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
|
|
return ec == std::errc{} && ptr == end;
|
|
};
|
|
bool valid = true;
|
|
if (a == "--jobs") {
|
|
valid = number(jobs);
|
|
jobs = std::max(1u, jobs);
|
|
} else if (a == "--start") valid = number(start);
|
|
else if (a == "--count") valid = number(count);
|
|
else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0;
|
|
else if (a == "--stage") valid = !(stage_filter = value()).empty();
|
|
else if (a == "--compute-only") stage_filter = "cs";
|
|
else if (a == "--graphics-only") stage_filter = "graphics";
|
|
else if (a == "--max-bytes") valid = number(max_bytes);
|
|
else if (a == "--large-module-bytes") valid = number(large_module_bytes);
|
|
else if (a == "--stats") valid = !(stats_path = value()).empty();
|
|
else if (a == "--cache-feedback") cache_feedback = true;
|
|
else cache_path = a;
|
|
if (!valid) {
|
|
std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
|
|
return 2;
|
|
}
|
|
}
|
|
if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") {
|
|
std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str());
|
|
return 2;
|
|
}
|
|
|
|
std::string index_err;
|
|
auto index = read_index(dir + "/index.json", index_err);
|
|
if (!index_err.empty()) {
|
|
std::fprintf(stderr, "error: malformed JSON in %s/index.json: %s\n", dir.c_str(), index_err.c_str());
|
|
return 2;
|
|
}
|
|
std::fprintf(stderr, "%zu shaders in index\n", index.size());
|
|
|
|
// Build work list: index order (sorted by name), optionally filtered by stage, then [start, start + count).
|
|
using Item = std::pair<const std::string*, const ShaderMeta*>;
|
|
std::vector<Item> all;
|
|
for (auto& [name, meta] : index) {
|
|
if (stage_filter == "cs" && meta.stage != "cs") continue;
|
|
if (stage_filter == "graphics" && !is_graphics_stage(meta.stage)) continue;
|
|
all.push_back({&name, &meta});
|
|
}
|
|
const auto [lo, hi] = shader_slice(all.size(), start, count);
|
|
const std::vector<Item> work(all.begin() + lo, all.begin() + hi);
|
|
|
|
// Scan selected shaders to request only the optional extensions they actually use.
|
|
bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false;
|
|
for (auto& [_, meta] : work) {
|
|
if (meta->stage == "ms") want_mesh = true;
|
|
if (meta->needs_maintenance8) want_m8 = true;
|
|
for (const auto& feat : meta->features) {
|
|
if (feat == "meshShader") want_mesh = true;
|
|
else if (feat == "fragmentShaderBarycentric") want_bary = true;
|
|
else if (feat == "fragmentShaderPixelInterlock") want_lock = true;
|
|
else if (feat == "shaderFmaFloat32") want_fma = true; // OpFmaKHR (rdna2spirv.py --fma khr)
|
|
}
|
|
}
|
|
|
|
gipa = load_vulkan();
|
|
if (!gipa) return 1;
|
|
#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name))
|
|
VkInstance inst = VK_NULL_HANDLE;
|
|
LOADI(vkCreateInstance);
|
|
VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO};
|
|
app.apiVersion = VK_API_VERSION_1_3;
|
|
VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
|
|
ici.pApplicationInfo = &app;
|
|
if (vkCreateInstance(&ici, nullptr, &inst)) return 1;
|
|
LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); LOADI(vkCreateDevice);
|
|
LOADI(vkGetPhysicalDeviceProperties2);
|
|
LOADI(vkGetDeviceProcAddr); LOADI(vkEnumerateDeviceExtensionProperties); LOADI(vkGetPhysicalDeviceFeatures2);
|
|
uint32_t n = 0;
|
|
vkEnumeratePhysicalDevices(inst, &n, nullptr);
|
|
if (n == 0) { std::fprintf(stderr, "no Vulkan physical devices found\n"); return 1; }
|
|
std::vector<VkPhysicalDevice> pds(n);
|
|
vkEnumeratePhysicalDevices(inst, &n, pds.data());
|
|
std::vector<VkPhysicalDeviceProperties> candidates(pds.size());
|
|
for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]);
|
|
const std::size_t chosen = leonida::vk_test::pick_device(candidates);
|
|
VkPhysicalDevice pd = chosen < pds.size() ? pds[chosen] : VK_NULL_HANDLE;
|
|
if (!pd) {
|
|
leonida::vk_test::report_no_device();
|
|
return 1;
|
|
}
|
|
VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props);
|
|
VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES};
|
|
VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
|
|
props2.pNext = &sgProps;
|
|
vkGetPhysicalDeviceProperties2(pd, &props2);
|
|
std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize);
|
|
|
|
uint32_t en = 0;
|
|
vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, nullptr);
|
|
std::vector<VkExtensionProperties> exts(en);
|
|
vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, exts.data());
|
|
auto has = [&](const char* e) { for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; return false; };
|
|
std::vector<const char*> enable;
|
|
|
|
// Query what the GPU supports for core 1.2/1.3 and any optional extensions requested by `work`.
|
|
VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
|
|
VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
|
|
VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
|
|
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
|
|
VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR};
|
|
#endif
|
|
VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR exe{
|
|
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR};
|
|
VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
|
|
VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
|
|
void* chain = nullptr;
|
|
auto link = [&](void* s, VkBaseOutStructure* b, const char* ext, bool needed) -> bool {
|
|
if (!needed) return false;
|
|
if (ext && !has(ext)) return false;
|
|
if (ext) enable.push_back(ext);
|
|
b->pNext = static_cast<VkBaseOutStructure*>(chain); chain = s;
|
|
return true;
|
|
};
|
|
link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true);
|
|
link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true);
|
|
const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh);
|
|
const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary);
|
|
const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock);
|
|
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
|
|
const bool ext_m8 = link(&m8, reinterpret_cast<VkBaseOutStructure*>(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, want_m8);
|
|
#else
|
|
(void)want_m8;
|
|
#endif
|
|
#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
|
|
VkPhysicalDeviceShaderFmaFeaturesKHR fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR};
|
|
const bool ext_fma = link(&fma, reinterpret_cast<VkBaseOutStructure*>(&fma), VK_KHR_SHADER_FMA_EXTENSION_NAME, want_fma);
|
|
#else
|
|
const bool ext_fma = false;
|
|
(void)want_fma;
|
|
#endif
|
|
const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe),
|
|
VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty());
|
|
if (!stats_path.empty() && !ext_exe) {
|
|
std::fprintf(stderr, "--stats: the device has no %s\n", VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME);
|
|
return 1;
|
|
}
|
|
// --cache-feedback: core in Vulkan 1.3 (no feature bit). A pre-1.3 device needs VK_EXT_pipeline_creation_feedback;
|
|
// without it nothing is chained and every successful pipeline counts as unavailable.
|
|
const bool fb_ext = cache_feedback && props.apiVersion < VK_API_VERSION_1_3 &&
|
|
has(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
|
|
if (fb_ext) enable.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
|
|
const bool feedback = cache_feedback && (props.apiVersion >= VK_API_VERSION_1_3 || fb_ext);
|
|
if (cache_feedback && !feedback)
|
|
std::fprintf(stderr, "note: --cache-feedback: no Vulkan 1.3 or %s; every pipeline is counted unavailable\n",
|
|
VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
|
|
VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
|
|
f2.pNext = chain;
|
|
vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported
|
|
if (ext_mesh) {
|
|
mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = mesh.meshShaderQueries = VK_FALSE;
|
|
mesh.taskShader = VK_FALSE;
|
|
}
|
|
float prio = 1;
|
|
VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
|
|
qci.queueFamilyIndex = 0; qci.queueCount = 1; qci.pQueuePriorities = &prio;
|
|
VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
|
|
dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2;
|
|
dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data();
|
|
VkDevice dev;
|
|
if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; }
|
|
auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool {
|
|
return f13.subgroupSizeControl &&
|
|
sg >= sgProps.minSubgroupSize &&
|
|
sg <= sgProps.maxSubgroupSize &&
|
|
(sgProps.requiredSubgroupSizeStages & bit);
|
|
};
|
|
{
|
|
std::map<uint32_t, std::set<std::string>> unforced_by_sg;
|
|
for (const auto& [_, meta] : work) {
|
|
const VkShaderStageFlagBits bit = stage_bit(meta->stage);
|
|
if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) {
|
|
unforced_by_sg[meta->subgroup_size].insert(meta->stage);
|
|
}
|
|
}
|
|
for (const auto& [sg, stages] : unforced_by_sg) {
|
|
std::string list;
|
|
for (const auto& st : stages) {
|
|
if (!list.empty()) list += "/";
|
|
list += st;
|
|
}
|
|
std::fprintf(stderr,
|
|
"note: %u-wide subgroups not supported for %s; those pipelines are compiled without a required subgroup size\n",
|
|
sg, list.c_str());
|
|
}
|
|
}
|
|
#define LOADD(name) auto name = reinterpret_cast<PFN_##name>(vkGetDeviceProcAddr(dev, #name))
|
|
LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout);
|
|
LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines);
|
|
LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData);
|
|
LOADD(vkGetPipelineExecutablePropertiesKHR); LOADD(vkGetPipelineExecutableStatisticsKHR);
|
|
const VkPipelineCreateFlags capture = stats_path.empty() ? 0 : VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR;
|
|
|
|
// Map enabled device features for per-shader compatibility checks.
|
|
auto check_missing_feature = [&](const ShaderMeta& meta) -> std::string {
|
|
if (is_graphics_stage(meta.stage) && !f13.dynamicRendering) return "no dynamicRendering";
|
|
if (meta.stage == "ms" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader";
|
|
if (meta.stage == "gs" && !f2.features.geometryShader) return "no geometryShader";
|
|
if (meta.needs_maintenance8) {
|
|
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
|
|
if (!(ext_m8 && m8.maintenance8)) return "no VK_KHR_maintenance8";
|
|
#else
|
|
return "no VK_KHR_maintenance8";
|
|
#endif
|
|
}
|
|
for (const auto& feat : meta.features) {
|
|
if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader";
|
|
if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader";
|
|
if (feat == "fragmentShaderBarycentric" && !(ext_bary && bary.fragmentShaderBarycentric)) return "no fragmentShaderBarycentric";
|
|
if (feat == "fragmentShaderPixelInterlock" && !(ext_lock && lock.fragmentShaderPixelInterlock)) return "no fragmentShaderPixelInterlock";
|
|
if (feat == "shaderFmaFloat32") {
|
|
#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
|
|
if (!(ext_fma && fma.shaderFmaFloat32)) return "no VK_KHR_shader_fma (shaderFmaFloat32)";
|
|
#else
|
|
return "no VK_KHR_shader_fma (shaderFmaFloat32)";
|
|
#endif
|
|
}
|
|
if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64";
|
|
if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64";
|
|
if (feat == "bufferDeviceAddress" && !f12.bufferDeviceAddress) return "no bufferDeviceAddress";
|
|
if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray";
|
|
if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended";
|
|
if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod";
|
|
if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat)
|
|
return "no shaderStorageImageWriteWithoutFormat";
|
|
if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat)
|
|
return "no shaderStorageImageReadWithoutFormat";
|
|
}
|
|
return {};
|
|
};
|
|
|
|
// Resource contract (docs/design.md): set 0, runtime-sized arrays as large bindless arrays.
|
|
std::vector<VkDescriptorSetLayoutBinding> b;
|
|
auto add = [&](uint32_t bind, VkDescriptorType t, uint32_t cnt) {
|
|
b.push_back({bind, t, cnt, VK_SHADER_STAGE_ALL, nullptr});
|
|
};
|
|
add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024);
|
|
add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024);
|
|
add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256);
|
|
add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256);
|
|
for (uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256);
|
|
VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
|
|
dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data();
|
|
VkDescriptorSetLayout dsl;
|
|
if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; }
|
|
VkPushConstantRange pcr{VK_SHADER_STAGE_ALL, 0, 144};
|
|
VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
|
|
pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
|
|
VkPipelineLayout pl; vkCreatePipelineLayout(dev, &pli, nullptr, &pl);
|
|
VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
|
|
std::vector<char> seed;
|
|
if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly
|
|
std::ifstream cf(cache_path, std::ios::binary);
|
|
seed.assign(std::istreambuf_iterator<char>(cf), {});
|
|
if (!seed.empty()) std::fprintf(stderr, "seeded the pipeline cache with %zu bytes from %s\n", seed.size(), cache_path.c_str());
|
|
}
|
|
pci.initialDataSize = seed.size(); pci.pInitialData = seed.empty() ? nullptr : seed.data();
|
|
VkPipelineCache cache = VK_NULL_HANDLE;
|
|
if (vkCreatePipelineCache(dev, &pci, nullptr, &cache)) { // data from another driver: start empty
|
|
pci.initialDataSize = 0; pci.pInitialData = nullptr;
|
|
if (VkResult r = vkCreatePipelineCache(dev, &pci, nullptr, &cache)) {
|
|
std::fprintf(stderr, "vkCreatePipelineCache failed: %d\n", r);
|
|
return 1;
|
|
}
|
|
}
|
|
std::vector<char>().swap(seed); // the driver has copied the seed; it can be several GiB
|
|
auto save_cache = [&](bool final_save) {
|
|
if (cache_path.empty()) return true;
|
|
try {
|
|
const auto data = pipeline_cache_snapshot([&](size_t* size, void* dest) {
|
|
return vkGetPipelineCacheData(dev, cache, size, dest);
|
|
});
|
|
if (auto error = write_pipeline_cache_file(cache_path, data.data(), data.size()))
|
|
throw std::system_error(error);
|
|
if (final_save) std::printf("pipeline cache: %zu bytes -> %s\n", data.size(), cache_path.c_str());
|
|
return true;
|
|
} catch (const std::exception& e) {
|
|
std::fprintf(stderr, "%s pipeline cache save to %s failed: %s\n",
|
|
final_save ? "final" : "periodic", cache_path.c_str(), e.what());
|
|
return false;
|
|
}
|
|
};
|
|
|
|
std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n",
|
|
work.size(), lo, hi, stage_filter.c_str(), jobs);
|
|
|
|
std::mutex mu; // guards counters, stdout, stub cache and in-flight table
|
|
std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work
|
|
size_t isolated_modules = 0;
|
|
std::map<std::string, uint32_t> modules_ok, modules_bad, big_skipped;
|
|
std::map<std::string, StageStats> stats;
|
|
std::map<std::string, VkShaderModule> stub_cache;
|
|
std::atomic<size_t> next{0}, done{0};
|
|
std::atomic<uint32_t> total_pipes_done{0};
|
|
std::map<std::thread::id, std::pair<std::string, std::chrono::steady_clock::time_point>> inflight;
|
|
const auto t_start = std::chrono::steady_clock::now();
|
|
auto elapsed = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); };
|
|
|
|
auto load_stub = [&](const std::string& fname) -> VkShaderModule {
|
|
{
|
|
std::lock_guard<std::mutex> g(mu);
|
|
auto it = stub_cache.find(fname);
|
|
if (it != stub_cache.end()) return it->second;
|
|
}
|
|
std::ifstream f(dir + "/stubs/" + fname, std::ios::binary);
|
|
std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
|
|
VkShaderModule mod = VK_NULL_HANDLE;
|
|
if (!code.empty()) {
|
|
VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
|
|
smi.codeSize = code.size();
|
|
smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
|
|
if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE;
|
|
}
|
|
std::lock_guard<std::mutex> g(mu);
|
|
auto [it, inserted] = stub_cache.emplace(fname, mod);
|
|
if (!inserted && mod) vkDestroyShaderModule(dev, mod, nullptr);
|
|
return it->second;
|
|
};
|
|
|
|
auto record_skip = [&](const std::string& name, const std::string& stage, const std::string& reason) {
|
|
std::lock_guard<std::mutex> g(mu);
|
|
auto& st = stats[stage];
|
|
st.pipes_skipped++;
|
|
st.skip_reasons[reason]++;
|
|
std::printf("SKIPPED %s (%s)\n", name.c_str(), reason.c_str());
|
|
};
|
|
|
|
std::FILE* stats_out = stats_path.empty() ? nullptr : std::fopen(stats_path.c_str(), "w");
|
|
if (!stats_path.empty() && !stats_out) { std::fprintf(stderr, "cannot write %s\n", stats_path.c_str()); return 1; }
|
|
if (stats_out) std::fprintf(stats_out, "name,stage,statistic,value\n");
|
|
// --stats: one CSV row per statistic of the executable that runs the translated shader (stage bit `bit`).
|
|
auto write_stats = [&](const std::string& name, const std::string& stage, VkShaderStageFlagBits bit, VkPipeline p) {
|
|
if (!stats_out) return;
|
|
VkPipelineInfoKHR pi{VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR};
|
|
pi.pipeline = p;
|
|
uint32_t n = 0;
|
|
vkGetPipelineExecutablePropertiesKHR(dev, &pi, &n, nullptr);
|
|
std::vector<VkPipelineExecutablePropertiesKHR> exes(n, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_PROPERTIES_KHR});
|
|
vkGetPipelineExecutablePropertiesKHR(dev, &pi, &n, exes.data());
|
|
for (uint32_t e = 0; e < n; e++) {
|
|
if (!(exes[e].stages & bit)) continue;
|
|
VkPipelineExecutableInfoKHR ei{VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_INFO_KHR};
|
|
ei.pipeline = p; ei.executableIndex = e;
|
|
uint32_t m = 0;
|
|
vkGetPipelineExecutableStatisticsKHR(dev, &ei, &m, nullptr);
|
|
std::vector<VkPipelineExecutableStatisticKHR> st(m, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_STATISTIC_KHR});
|
|
vkGetPipelineExecutableStatisticsKHR(dev, &ei, &m, st.data());
|
|
std::lock_guard<std::mutex> g(mu);
|
|
for (auto& x : st) {
|
|
std::fprintf(stats_out, "%s,%s,%s,", name.c_str(), stage.c_str(), x.name);
|
|
switch (x.format) {
|
|
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR: std::fprintf(stats_out, "%u\n", x.value.b32); break;
|
|
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR: std::fprintf(stats_out, "%lld\n", (long long)x.value.i64); break;
|
|
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR: std::fprintf(stats_out, "%llu\n", (unsigned long long)x.value.u64); break;
|
|
default: std::fprintf(stats_out, "%g\n", x.value.f64); break;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
auto record_pipe = [&](const std::string& name, const std::string& stage, uint32_t sg, bool sg_forced,
|
|
VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) {
|
|
std::lock_guard<std::mutex> g(mu);
|
|
inflight.erase(std::this_thread::get_id());
|
|
auto& st = stats[stage];
|
|
st.seconds += sec;
|
|
if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; }
|
|
if (sec > slow) std::printf("SLOW %s %s (w%u, %.1fs)\n", upper_stage(stage).c_str(), name.c_str(), sg, sec);
|
|
if (sg > 0 && !sg_forced) {
|
|
if (sg == 64) st.w64_unforced++; else st.w32_unforced++;
|
|
}
|
|
if (r) {
|
|
st.pipes_bad++;
|
|
if (sg == 64) st.w64_bad++; else st.w32_bad++;
|
|
std::printf("PIPELINE FAIL %s (%s w%u, %d)\n", name.c_str(), stage.c_str(), sg, r);
|
|
} else {
|
|
st.pipes_ok++;
|
|
if (cache_feedback) st.feedback[feedback_outcome(fb_flags)]++;
|
|
if (sg == 64) st.w64_ok++; else st.w32_ok++;
|
|
}
|
|
uint32_t n_done = ++total_pipes_done;
|
|
if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed());
|
|
};
|
|
|
|
auto worker = [&] {
|
|
for (size_t k; (k = next++) < work.size();) {
|
|
const std::string& name = *work[k].first;
|
|
const ShaderMeta& meta = *work[k].second;
|
|
const std::string& stage = meta.stage;
|
|
std::ifstream f(dir + "/" + name + ".spv", std::ios::binary | std::ios::ate);
|
|
const std::streamoff file_size = f.tellg();
|
|
if (max_bytes && std::cmp_greater(file_size, max_bytes)) { // multi-MB ray-tracing shaders (#108)
|
|
{
|
|
std::lock_guard<std::mutex> g(mu);
|
|
big_skipped[stage]++;
|
|
std::printf("BIG SKIP %s (%lld bytes, limit %zu)\n",
|
|
name.c_str(), static_cast<long long>(file_size), max_bytes);
|
|
}
|
|
++done;
|
|
continue;
|
|
}
|
|
// Enter before reading the module: creation can also enter the driver. Hold until its pipeline and
|
|
// module have been destroyed, including on failure. The watchdog and cache writer don't take this lock.
|
|
const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes);
|
|
std::unique_lock exclusive(compile_gate, std::defer_lock);
|
|
std::shared_lock parallel(compile_gate, std::defer_lock);
|
|
if (isolated) exclusive.lock();
|
|
else if (large_module_bytes) parallel.lock();
|
|
|
|
f.seekg(0);
|
|
std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
|
|
VkShaderModule sm = VK_NULL_HANDLE;
|
|
bool mod_ok = false;
|
|
if (!code.empty()) {
|
|
VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
|
|
smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
|
|
mod_ok = vkCreateShaderModule(dev, &smi, nullptr, &sm) == VK_SUCCESS;
|
|
}
|
|
{
|
|
std::lock_guard<std::mutex> g(mu);
|
|
if (isolated) ++isolated_modules;
|
|
if (mod_ok) modules_ok[stage]++;
|
|
else { modules_bad[stage]++; std::printf("MODULE FAIL %s\n", name.c_str()); }
|
|
}
|
|
if (mod_ok && stage == "cs") {
|
|
const std::string miss = check_missing_feature(meta);
|
|
if (!miss.empty()) {
|
|
record_skip(name, stage, miss);
|
|
} else {
|
|
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{
|
|
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
|
|
reqSg.requiredSubgroupSize = meta.subgroup_size;
|
|
VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
|
|
cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
|
|
cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main";
|
|
const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT);
|
|
if (sg_forced) cpi.stage.pNext = &reqSg;
|
|
cpi.layout = pl;
|
|
cpi.flags = capture;
|
|
// Only whole-pipeline feedback is reported.
|
|
VkPipelineCreationFeedback fb{};
|
|
VkPipelineCreationFeedbackCreateInfo fci{
|
|
VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &fb, 0, nullptr};
|
|
if (feedback) cpi.pNext = &fci;
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
{ std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; }
|
|
VkPipeline p = VK_NULL_HANDLE;
|
|
VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p);
|
|
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
|
if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p);
|
|
if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr);
|
|
record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags);
|
|
}
|
|
} else if (mod_ok && is_graphics_stage(stage)) {
|
|
const std::string miss = check_missing_feature(meta);
|
|
if (!miss.empty()) {
|
|
record_skip(name, stage, miss);
|
|
} else {
|
|
std::vector<VkPipelineShaderStageCreateInfo> stages;
|
|
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{
|
|
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
|
|
reqSg.requiredSubgroupSize = meta.subgroup_size;
|
|
|
|
bool sg_forced = false;
|
|
auto make_stage = [&](VkShaderStageFlagBits bit, VkShaderModule mod, bool real) {
|
|
VkPipelineShaderStageCreateInfo si{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
|
|
si.stage = bit; si.module = mod; si.pName = "main";
|
|
if (real && can_require_sg(meta.subgroup_size, bit)) {
|
|
si.pNext = &reqSg;
|
|
sg_forced = true;
|
|
}
|
|
return si;
|
|
};
|
|
|
|
std::string skip_reason;
|
|
std::vector<VkFormat> color_formats;
|
|
VkFormat depth_format = VK_FORMAT_UNDEFINED;
|
|
bool use_vertex_input = true;
|
|
|
|
if (stage == "ps") {
|
|
std::string vs_fn = stub_filename("vs", meta.inputs);
|
|
VkShaderModule vs_mod = load_stub(vs_fn);
|
|
if (!vs_mod) {
|
|
skip_reason = "missing stub " + vs_fn;
|
|
} else {
|
|
uint32_t n_color = 0;
|
|
for (uint32_t loc : meta.outputs) n_color = std::max(n_color, loc + 1);
|
|
if (n_color > props.limits.maxColorAttachments) {
|
|
skip_reason = "exceeds maxColorAttachments";
|
|
} else {
|
|
color_formats.assign(n_color, VK_FORMAT_R32G32B32A32_SFLOAT);
|
|
if (meta.writes_depth) depth_format = VK_FORMAT_D32_SFLOAT;
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false));
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, sm, true));
|
|
}
|
|
}
|
|
} else if (stage == "vs") {
|
|
std::string ps_fn = stub_filename("ps", meta.outputs);
|
|
VkShaderModule ps_mod = load_stub(ps_fn);
|
|
if (!ps_mod) {
|
|
skip_reason = "missing stub " + ps_fn;
|
|
} else {
|
|
color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT);
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, sm, true));
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false));
|
|
}
|
|
} else if (stage == "ms") {
|
|
use_vertex_input = false;
|
|
std::string ps_fn = stub_filename("ps", meta.params);
|
|
VkShaderModule ps_mod = load_stub(ps_fn);
|
|
if (!ps_mod) {
|
|
skip_reason = "missing stub " + ps_fn;
|
|
} else {
|
|
color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT);
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_MESH_BIT_EXT, sm, true));
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false));
|
|
}
|
|
} else if (stage == "gs") {
|
|
const auto& gs_in = meta.has_gs_input_locations ? meta.gs_input_locations : meta.gs_inputs;
|
|
const auto& gs_out = meta.has_gs_output_locations ? meta.gs_output_locations : meta.gs_outputs;
|
|
std::string vs_fn = stub_filename("vs", gs_in);
|
|
std::string ps_fn = stub_filename("ps", gs_out);
|
|
VkShaderModule vs_mod = load_stub(vs_fn);
|
|
VkShaderModule ps_mod = load_stub(ps_fn);
|
|
if (!vs_mod) skip_reason = "missing stub " + vs_fn;
|
|
else if (!ps_mod) skip_reason = "missing stub " + ps_fn;
|
|
else {
|
|
color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT);
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false));
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_GEOMETRY_BIT, sm, true));
|
|
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false));
|
|
}
|
|
}
|
|
|
|
if (!skip_reason.empty()) {
|
|
record_skip(name, stage, skip_reason);
|
|
} else {
|
|
VkVertexInputBindingDescription vbind{0, 16, VK_VERTEX_INPUT_RATE_VERTEX};
|
|
std::vector<VkVertexInputAttributeDescription> vattrs;
|
|
if (stage == "vs") {
|
|
for (const auto& vi : meta.vertex_inputs) {
|
|
VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT;
|
|
if (vi.type == "uint") fmt = VK_FORMAT_R32G32B32A32_UINT;
|
|
else if (vi.type == "sint") fmt = VK_FORMAT_R32G32B32A32_SINT;
|
|
vattrs.push_back({vi.location, 0, fmt, 0});
|
|
}
|
|
}
|
|
VkPipelineVertexInputStateCreateInfo vi_state{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
|
|
if (!vattrs.empty()) {
|
|
vi_state.vertexBindingDescriptionCount = 1;
|
|
vi_state.pVertexBindingDescriptions = &vbind;
|
|
vi_state.vertexAttributeDescriptionCount = uint32_t(vattrs.size());
|
|
vi_state.pVertexAttributeDescriptions = vattrs.data();
|
|
}
|
|
VkPipelineInputAssemblyStateCreateInfo ia_state{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
|
|
ia_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
|
|
|
VkPipelineViewportStateCreateInfo vp_state{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
|
|
vp_state.viewportCount = 1;
|
|
vp_state.scissorCount = 1;
|
|
VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
|
|
VkPipelineDynamicStateCreateInfo dyn_state{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
|
|
dyn_state.dynamicStateCount = 2;
|
|
dyn_state.pDynamicStates = dyn_states;
|
|
|
|
VkPipelineRasterizationStateCreateInfo rast{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
|
|
rast.polygonMode = VK_POLYGON_MODE_FILL;
|
|
rast.cullMode = VK_CULL_MODE_NONE;
|
|
rast.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
|
|
rast.lineWidth = 1.0f;
|
|
|
|
VkPipelineMultisampleStateCreateInfo msaa{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
|
|
msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
|
|
|
|
VkPipelineDepthStencilStateCreateInfo ds{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
|
|
if (depth_format != VK_FORMAT_UNDEFINED) {
|
|
ds.depthTestEnable = VK_TRUE;
|
|
ds.depthWriteEnable = VK_TRUE;
|
|
ds.depthCompareOp = VK_COMPARE_OP_LESS;
|
|
}
|
|
|
|
std::vector<VkPipelineColorBlendAttachmentState> blend_atts(color_formats.size());
|
|
for (auto& ba : blend_atts) ba.colorWriteMask = 0xF;
|
|
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
|
|
blend.attachmentCount = uint32_t(blend_atts.size());
|
|
blend.pAttachments = blend_atts.empty() ? nullptr : blend_atts.data();
|
|
|
|
VkPipelineRenderingCreateInfo rend{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO};
|
|
rend.colorAttachmentCount = uint32_t(color_formats.size());
|
|
rend.pColorAttachmentFormats = color_formats.empty() ? nullptr : color_formats.data();
|
|
rend.depthAttachmentFormat = depth_format;
|
|
|
|
VkGraphicsPipelineCreateInfo gpci{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
|
|
gpci.pNext = &rend;
|
|
gpci.stageCount = uint32_t(stages.size());
|
|
gpci.pStages = stages.data();
|
|
gpci.pVertexInputState = use_vertex_input ? &vi_state : nullptr;
|
|
gpci.pInputAssemblyState = use_vertex_input ? &ia_state : nullptr;
|
|
gpci.pViewportState = &vp_state;
|
|
gpci.pRasterizationState = &rast;
|
|
gpci.pMultisampleState = &msaa;
|
|
gpci.pDepthStencilState = &ds;
|
|
gpci.pColorBlendState = &blend;
|
|
gpci.pDynamicState = &dyn_state;
|
|
gpci.layout = pl;
|
|
gpci.renderPass = VK_NULL_HANDLE;
|
|
gpci.flags = capture;
|
|
// Zeroed per call and read after it returns; per-stage entries are required but not reported.
|
|
VkPipelineCreationFeedback fb{};
|
|
VkPipelineCreationFeedbackCreateInfo fci{
|
|
VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, &rend, &fb, 0, nullptr};
|
|
if (feedback) gpci.pNext = &fci; // keeps rend chained behind it
|
|
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
{ std::lock_guard<std::mutex> g(mu); inflight[std::this_thread::get_id()] = {name, t0}; }
|
|
VkPipeline p = VK_NULL_HANDLE;
|
|
VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p);
|
|
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
|
if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p);
|
|
if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr);
|
|
record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags);
|
|
}
|
|
}
|
|
} else if (mod_ok) {
|
|
record_skip(name, stage, "unsupported stage " + stage);
|
|
}
|
|
if (sm) vkDestroyShaderModule(dev, sm, nullptr);
|
|
if (++done % 1000 == 0) {
|
|
std::lock_guard<std::mutex> g(mu);
|
|
std::fprintf(stderr, " %zu/%zu (%.0fs)\n", size_t(done), work.size(), elapsed());
|
|
}
|
|
}
|
|
};
|
|
std::vector<std::thread> pool;
|
|
for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker);
|
|
// Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes.
|
|
std::condition_variable watch_cv;
|
|
bool all_done = false;
|
|
std::thread watch([&] {
|
|
auto last_save = std::chrono::steady_clock::now();
|
|
std::unique_lock<std::mutex> g(mu);
|
|
while (!all_done) {
|
|
if (watch_cv.wait_for(g, std::chrono::seconds(5), [&] { return all_done; })) break;
|
|
const auto now = std::chrono::steady_clock::now();
|
|
for (auto& [tid, job] : inflight) {
|
|
const double s = std::chrono::duration<double>(now - job.second).count();
|
|
if (s > 60 && int(s) % 60 < 5) std::fprintf(stderr, " still compiling %s after %.0fs\n", job.first.c_str(), s);
|
|
}
|
|
if (now - last_save > std::chrono::minutes(10)) {
|
|
g.unlock();
|
|
save_cache(false);
|
|
g.lock();
|
|
last_save = now;
|
|
}
|
|
}
|
|
});
|
|
for (auto& t : pool) t.join();
|
|
{
|
|
std::lock_guard<std::mutex> g(mu);
|
|
all_done = true;
|
|
}
|
|
watch_cv.notify_one();
|
|
watch.join();
|
|
|
|
for (auto& [_, mod] : stub_cache) if (mod) vkDestroyShaderModule(dev, mod, nullptr);
|
|
|
|
std::set<std::string> all_stages;
|
|
for (auto& [st, _] : modules_ok) all_stages.insert(st);
|
|
for (auto& [st, _] : modules_bad) all_stages.insert(st);
|
|
for (auto& [st, _] : stats) all_stages.insert(st);
|
|
|
|
bool check_failed = false;
|
|
for (const auto& st : all_stages) {
|
|
std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]);
|
|
if (modules_bad[st]) check_failed = true;
|
|
const auto it = stats.find(st);
|
|
if (it != stats.end()) {
|
|
const auto& s = it->second;
|
|
if (s.pipes_bad) check_failed = true;
|
|
const uint32_t compiled = s.pipes_ok + s.pipes_bad;
|
|
std::printf("%s pipelines: %u ok, %u failed, %u skipped\n",
|
|
st.c_str(), s.pipes_ok, s.pipes_bad, s.pipes_skipped);
|
|
if (cache_feedback)
|
|
std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n",
|
|
st.c_str(), s.feedback[0], s.feedback[1], s.feedback[2]);
|
|
if (!s.skip_reasons.empty()) {
|
|
for (const auto& [reason, cnt] : s.skip_reasons)
|
|
std::printf(" %s skipped (%s): %u\n", st.c_str(), reason.c_str(), cnt);
|
|
}
|
|
if (compiled > 0) {
|
|
auto fmt_unforced = [](uint32_t cnt) -> std::string {
|
|
return cnt ? (" (" + std::to_string(cnt) + " without required subgroup size)") : "";
|
|
};
|
|
std::printf(" %s wave32: %u ok, %u failed%s; wave64: %u ok, %u failed%s\n",
|
|
st.c_str(),
|
|
s.w32_ok, s.w32_bad, fmt_unforced(s.w32_unforced).c_str(),
|
|
s.w64_ok, s.w64_bad, fmt_unforced(s.w64_unforced).c_str());
|
|
std::printf(" %s compile time: %.2fs total, %.3fs mean, slowest %s (%.2fs)\n",
|
|
st.c_str(), s.seconds, s.seconds / compiled, s.max_name.c_str(), s.max_sec);
|
|
}
|
|
}
|
|
}
|
|
uint32_t big_total = 0;
|
|
for (auto& [st, c] : big_skipped) big_total += c;
|
|
if (big_total) {
|
|
std::printf("big modules skipped: %u (limit %zu bytes)", big_total, max_bytes);
|
|
for (auto& [st, c] : big_skipped) std::printf(" %s=%u", st.c_str(), c);
|
|
std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size());
|
|
}
|
|
if (isolated_modules)
|
|
std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules,
|
|
large_module_bytes);
|
|
std::printf("wall time: %.1fs on %u threads\n", elapsed(), jobs);
|
|
const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed
|
|
if (stats_out) std::fclose(stats_out);
|
|
return (check_failed || !cache_saved) ? 1 : 0;
|
|
}
|