// Driver-level check of the translated corpus: vk_pipeline_check [pipeline_cache.bin] // Reads /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 /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) // --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) #include "vulkan_loader.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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 features; std::vector inputs; std::vector outputs; std::vector params; std::vector gs_inputs; std::vector gs_outputs; std::vector gs_input_locations; std::vector gs_output_locations; bool has_gs_input_locations = false; bool has_gs_output_locations = false; std::vector 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(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(s[i]))) i++; if (i == before) fail("unexpected token in value"); } std::vector parse_u32_array() { std::vector 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 parse_str_array() { std::vector 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 parse_vertex_inputs() { std::vector 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 read_index(const std::string& path, std::string& err) { std::ifstream f(path, std::ios::binary); std::string s((std::istreambuf_iterator(f)), {}); std::map 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& raw_locs) { std::vector 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(std::toupper(static_cast(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; double seconds = 0.0; double max_sec = 0.0; std::string max_name; std::map skip_reasons; }; } // namespace int main(int argc, char** argv) { if (argc < 2) { std::fprintf(stderr, "usage: vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " "[--max-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only]\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; uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); size_t start = 0, count = 0, max_bytes = 0; double slow = 30.0; std::string stage_filter = "all"; for (int i = 2; i < argc; i++) { std::string a = argv[i]; auto val = [&] { return i + 1 < argc ? std::string(argv[++i]) : std::string("0"); }; if (a == "--jobs") jobs = std::max(1u, uint32_t(std::stoul(val()))); else if (a == "--start") start = std::stoull(val()); else if (a == "--count") count = std::stoull(val()); else if (a == "--slow") slow = std::stod(val()); else if (a == "--stage") stage_filter = val(); else if (a == "--compute-only") stage_filter = "cs"; else if (a == "--graphics-only") stage_filter = "graphics"; else if (a == "--max-bytes") max_bytes = std::stoull(val()); else cache_path = a; } 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; std::vector 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 size_t lo = std::min(start, all.size()), hi = std::min(all.size(), count ? lo + count : all.size()); const std::vector 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; 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; } } gipa = load_vulkan(); if (!gipa) return 1; #define LOADI(name) auto name = reinterpret_cast(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 pds(n); vkEnumeratePhysicalDevices(inst, &n, pds.data()); VkPhysicalDevice pd = VK_NULL_HANDLE; for (auto d : pds) { VkPhysicalDeviceProperties p; vkGetPhysicalDeviceProperties(d, &p); if (p.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU || !pd) pd = d; } 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 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 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 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(chain); chain = s; return true; }; link(&f12, reinterpret_cast(&f12), nullptr, true); link(&f13, reinterpret_cast(&f13), nullptr, true); const bool ext_mesh = link(&mesh, reinterpret_cast(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh); const bool ext_bary = link(&bary, reinterpret_cast(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); const bool ext_lock = link(&lock, reinterpret_cast(&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(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, want_m8); #else (void)want_m8; #endif 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> 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(vkGetDeviceProcAddr(dev, #name)) LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout); LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines); LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData); // 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 == "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 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 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(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; if (vkCreatePipelineCache(dev, &pci, nullptr, &cache)) { // data from another driver: start empty pci.initialDataSize = 0; pci.pInitialData = nullptr; vkCreatePipelineCache(dev, &pci, nullptr, &cache); } auto save_cache = [&](bool final_save) { if (cache_path.empty()) return; size_t sz = 0; vkGetPipelineCacheData(dev, cache, &sz, nullptr); std::vector data(sz); vkGetPipelineCacheData(dev, cache, &sz, data.data()); const std::string tmp = cache_path + ".partial"; std::ofstream(tmp, std::ios::binary).write(data.data(), std::streamsize(sz)); std::remove(cache_path.c_str()); std::rename(tmp.c_str(), cache_path.c_str()); if (final_save) std::printf("pipeline cache: %zu bytes -> %s\n", sz, cache_path.c_str()); }; 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::map modules_ok, modules_bad, big_skipped; std::map stats; std::map stub_cache; std::atomic next{0}, done{0}; std::atomic total_pipes_done{0}; std::map> inflight; const auto t_start = std::chrono::steady_clock::now(); auto elapsed = [&] { return std::chrono::duration(std::chrono::steady_clock::now() - t_start).count(); }; auto load_stub = [&](const std::string& fname) -> VkShaderModule { { std::lock_guard 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 code((std::istreambuf_iterator(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(code.data()); if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE; } std::lock_guard 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 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()); }; auto record_pipe = [&](const std::string& name, const std::string& stage, uint32_t sg, bool sg_forced, VkResult r, double sec) { std::lock_guard 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 (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 && file_size > std::streamoff(max_bytes)) { // multi-MB ray-tracing shaders (#108) { std::lock_guard g(mu); big_skipped[stage]++; std::printf("BIG SKIP %s (%lld bytes, limit %zu)\n", name.c_str(), static_cast(file_size), max_bytes); } ++done; continue; } f.seekg(0); std::vector code((std::istreambuf_iterator(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(code.data()); mod_ok = vkCreateShaderModule(dev, &smi, nullptr, &sm) == VK_SUCCESS; } { std::lock_guard g(mu); 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; const auto t0 = std::chrono::steady_clock::now(); { std::lock_guard 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(std::chrono::steady_clock::now() - t0).count(); if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec); } } 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 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 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 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 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; const auto t0 = std::chrono::steady_clock::now(); { std::lock_guard 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(std::chrono::steady_clock::now() - t0).count(); if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec); } } } else if (mod_ok) { record_skip(name, stage, "unsupported stage " + stage); } if (sm) vkDestroyShaderModule(dev, sm, nullptr); if (++done % 1000 == 0) { std::lock_guard g(mu); std::fprintf(stderr, " %zu/%zu (%.0fs)\n", size_t(done), work.size(), elapsed()); } } }; std::vector 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 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(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 g(mu); all_done = true; } watch_cv.notify_one(); watch.join(); for (auto& [_, mod] : stub_cache) if (mod) vkDestroyShaderModule(dev, mod, nullptr); std::set 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); for (const auto& st : all_stages) { std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]); const auto it = stats.find(st); if (it != stats.end()) { const auto& s = it->second; 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 (!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()); } std::printf("wall time: %.1fs on %u threads\n", elapsed(), jobs); save_cache(true); return 0; }