"""A draw's program by a wider memo in front of program_for (gpu/vk/pickwide.h; vk_shader.cpp program_for_wide, vk_draw.cpp draw and dry_draw_program; no game, no GPU). (Triforce, 11-26, the GPU audit's C02.) program_for's pair of last picks compares ub_generation(), which every inline uniform update moves, and holds two programs; a draw that misses hashes its inputs, finds its pick, reads every answer's handle and, where one differs, reads them all again with their types compared. The memo in front of it holds 32 programs a thread, lets a program whose answers are all in c2 of their own stages stand across uniform updates, and asks a program whose textures moved in one pass over its answers. program_for itself is in the translation stamp and is not touched. Compiles a driver against the header: - the switch's values (a number other than 0 on, any word but check off), the lab's phase, the rules RX_VK_PICK_BIND_GEN and RX_VK_DEFERRED_LATE leave; - A, B, C, A with their textures unchanged and a buffer bound between them: the fourth stands (a pair held two); A, B, A of handle programs: A is kept and takes one pass; - a uniform update between two draws of a c2-only program: stands; of a handle program (mask ~0): does not; nor with the pair's old rule or with deferred binds; - a stage outside the mask rebound: stands; one inside it: does not; a slot registered anew: does not; - other vertex inputs, colour types or stage words: another entry; - one pass: every handle read once; a slot seen and checked at its version is not asked again; a slot rebound to a texture of the same type costs one compare; another type, or a version moved to another type, fails; an unbound slot takes any and is asked once it is bound; the verdict is still_valid's on a random walk of binds, registrations and types; - the table: one entry for one program object and inputs, the way not used last replaced; - a program only noted (program_for's, at a draw that went to it) does not stand and has nothing of it read; found by its first pass, it stands. Runs a model of the hook over the real rule, in the default mode's shape (the full pick asked only where the memo has no answer, its program noted and walked at its next draw), against a model of program_for's full pick asked at every draw in a world of its own (its kept program while it is of the bound textures' types, else the first variant that is): the same variant at every draw of a random stream. And the cost the review of the first version found: three programs of one set drawn in turn, every draw program_for's, read no answer at all in the memo (the first version walked each of them at every draw, a third walk on top of the full pick's two); two programs in turn are walked once each, at their second draw. And one program object drawn with three sets of vertex inputs in turn: every draw program_for's (the set is by the serial alone). Compiles the hook itself (vk_shader.cpp, its counters to program_wide_stats, cut out by its text) over stubs, with RX_VK_PICK_WIDE=check: program_for's program drawn at every draw; a helper thread's differences and wrong variants reach the frame line's totals at once, its compares with them, although it records nothing more (they waited for its next 256th pick before); a nopickwide phase's first pick adds what the thread held; no program from program_for is logged as such. Reads the source: program_for_wide in a part of vk_shader.cpp outside the translation stamp, nothing of it inside (the stamp's text, as nx2/build.py takes it, does not name it); the switch read once and logged, the lab's knob, the two older switches; the memo's program used only ready and not failed; a full pick's program only noted where it is picked (no pass, no mask, no canonical types there) and kept once its first pass, at its next draw, found it valid; check mode returns program_for's; draw() and dry_draw_program ask it for graphics programs, and nothing else does; the status line, with check mode's totals shown once a difference or a compare is counted; the switches table's row. python -I -B tests/test_pickwide.py [--cxx clang++] """ import argparse import ast import hashlib import json import os import subprocess import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] RUN_ALL_ARGS = ["--cxx", "{cxx}"] OUT_MARK = "// ---- (Triforce) Outside the translation stamp" IN_MARK = "// ---- (Triforce) Inside the translation stamp again" DRIVER = r''' #include "pickwide.h" #include #include #include #include using namespace mkwvk::pickwide; static int checks, fails; static void want(const char* what, bool ok) { checks++; if (!ok) fails++, printf("FAIL %s\n", what); } // A state as the hook reads it struct State { uint64_t serial = 1, sig = 11, bind = 100, reg = 5, ub = 9; int nvattr = 2; uint32_t vattr[16]{}; uint8_t ct[8]{}; uint64_t tex_gen[kStages]{}; Now now() const { return {serial, sig, bind, reg, ub, nvattr, vattr, ct, tex_gen}; } }; // The world one_pass asks: the handle each answer reads, the slots' versions and types struct World { std::vector handle; // (an answer's) std::map version; // (a slot's) std::map type; // (a slot's) int reads = 0, asked = 0; bool valid(const std::vector& canon) const { // (still_valid: every bound answer of the variant's type) for (size_t i = 0; i < handle.size(); i++) if (handle[i] && type.at(handle[i] & kSlotBits) != canon[i]) return false; return true; } }; static bool pass(Entry& e, World& w, Walk* walk = nullptr) { return one_pass(e, w.handle.size(), [&](size_t i) { return w.reads++, w.handle[i]; }, [&](uint32_t id) { return w.version[id]; }, [&](size_t i, uint32_t h) { return w.asked++, w.type[h & kSlotBits] == e.canon[i]; }, walk); } int main() { want("the switch: unset on, 1 on, 0 off, check", mode(nullptr) == Mode::On && mode("1") == Mode::On && mode("0") == Mode::Off && mode("check") == Mode::Check); want("a number other than 0 is on, any word but check off", mode("2") == Mode::On && mode("on") == Mode::Off && mode("Check") == Mode::Off && mode("") == Mode::Off); want("the lab's phase is off", in_phase(Mode::On, true) == Mode::Off && in_phase(Mode::Check, true) == Mode::Off && in_phase(Mode::On, false) == Mode::On && in_phase(Mode::Check, false) == Mode::Check && in_phase(Mode::Off, false) == Mode::Off); const Rules all = rules(false, false), old_pair = rules(true, false), late = rules(false, true); want("the rules", all.by_tex && all.free_ub && !old_pair.by_tex && !old_pair.free_ub && late.by_tex && !late.free_ub); { // A, B, C, A: three programs, a buffer bound and a uniform updated between them, the textures as they were Table t; State s; int pa = 0, pb = 0, pc = 0; const void* progs[3] = {&pa, &pb, &pc}; for (int k = 0; k < 3; k++) { s.serial = 100 + k, s.sig = 1000 + k, s.bind++, s.ub++; want("first sight: no entry", find(t, s.now()) == nullptr); take(place(t, s.now()), s.now(), progs[k], 1u << 1); } s.serial = 100, s.sig = 1000, s.bind++, s.ub++; Entry* e = find(t, s.now()); want("A after B and C is still kept", e && e->p == &pa); want("and stands past the binds and the update", e && stands(*e, s.now(), all) == Stand::PastUpdate); want("the pair's old rule: it does not", e && stands(*e, s.now(), old_pair) == Stand::No); want("deferred binds: it does not", e && stands(*e, s.now(), late) == Stand::No); } { // A, B, A, two handle programs (mask ~0): A is kept, but binding B and A again moved bind_gen, so A takes one pass Table t; State s; World w; // (A's two answers, their textures as they were throughout) w.handle = {5, 6}; for (uint32_t id : {5u, 6u}) w.version[id] = 1, w.type[id] = 1; int pa = 0, pb = 0; Entry& a = place(t, s.now()); take(a, s.now(), &pa, kNotC2); a.canon = {1, 1}; pass(a, w); // (the pass it was found by) s.serial = 200, s.sig = 2000, s.bind++; take(place(t, s.now()), s.now(), &pb, kNotC2); s.serial = 1, s.sig = 11, s.bind++; Entry* e = find(t, s.now()); want("a handle program drawn after another one: kept, and does not stand", e && e->p == &pa && stands(*e, s.now(), all) == Stand::No); w.reads = w.asked = 0; want("its one pass: valid, each handle read once, no type compared again", e && pass(*e, w) && w.reads == 2 && w.asked == 0); if (e) restamp(*e, s.now()); want("and it stands from there", e && stands(*e, s.now(), all) == Stand::Bound); } { // the three ways an entry stands, and what ends each Table t; State s; int p = 0; s.tex_gen[1] = 40, s.tex_gen[0] = 30; Entry& e = place(t, s.now()); take(e, s.now(), &p, 1u << 1); want("nothing bound, nothing updated", stands(e, s.now(), all) == Stand::Bound && stands(e, s.now(), old_pair) == Stand::Bound); s.bind++; want("bound anew, its stage's textures the same", stands(e, s.now(), all) == Stand::Textures && stands(e, s.now(), late) == Stand::Textures); want("the pair's old rule: not across a bind", stands(e, s.now(), old_pair) == Stand::No); s.ub++; want("a uniform updated: a c2-only program stands", stands(e, s.now(), all) == Stand::PastUpdate); State same_bind = s; same_bind.bind = e.bind; want("a uniform updated and nothing bound: stands by its textures", stands(e, same_bind.now(), all) == Stand::PastUpdate); s.tex_gen[0] = ++s.bind; want("a stage outside its mask rebound: stands", stands(e, s.now(), all) == Stand::PastUpdate); s.tex_gen[1] = ++s.bind; want("a stage of its mask rebound: does not", stands(e, s.now(), all) == Stand::No); want("but it is of these inputs: one pass", same_inputs(e, s.now()) && find(t, s.now()) == &e); restamp(e, s.now()); want("found valid: stands from here", stands(e, s.now(), all) == Stand::Bound); s.reg++; want("a slot registered anew: does not stand", stands(e, s.now(), all) == Stand::No && same_inputs(e, s.now())); restamp(e, s.now()); Entry handles = e; handles.amask = kNotC2; want("a handle program: nothing bound, nothing updated", stands(handles, s.now(), all) == Stand::Bound); s.ub++; want("a handle program does not stand past a uniform update", stands(handles, s.now(), all) == Stand::No); want("the c2-only one does", stands(e, s.now(), all) == Stand::PastUpdate); s.ub--, s.bind++; want("a handle program does not stand past a bind", stands(handles, s.now(), all) == Stand::No); Entry none = e; none.amask = 0; s.ub++, s.tex_gen[1] = ++s.bind; want("a program that asks nothing stands whatever is bound", stands(none, s.now(), all) == Stand::PastUpdate); State o = s; o.vattr[3] = 7; want("other vertex inputs: another entry", !same_inputs(e, o.now()) && find(t, o.now()) == nullptr && stands(e, o.now(), all) == Stand::No); o = s, o.ct[0] = 2; want("other colour types: another entry", !same_inputs(e, o.now()) && stands(e, o.now(), all) == Stand::No); o = s, o.nvattr = 3; want("another count of vertex inputs: another entry", !same_inputs(e, o.now())); o = s, o.sig++; want("other stage words: another entry", !same_inputs(e, o.now())); drop(e); want("dropped: nothing kept", !same_inputs(e, s.now()) && find(t, s.now()) == nullptr); } { // noted, then found: a program program_for gave is not walked where it is picked Table t; State s; int p = 0, q = 0; Entry& e = place(t, s.now()); e.canon = {7, 7}, e.stamps = {1, 1, 2, 2}, e.ok = {1, 1}, e.amask = 1u << 1, e.walked = true; // (what an older program left) note(e, s.now(), &p); want("noted: of these inputs, found again", same_inputs(e, s.now()) && find(t, s.now()) == &e && e.p == &p); want("noted: not walked, no mask, its next pass asks every answer", !e.walked && e.amask == kNotC2 && e.stamps.empty() && e.ok.empty()); want("a noted program does not stand, nothing bound or updated since", stands(e, s.now(), all) == Stand::No && stands(e, s.now(), old_pair) == Stand::No); s.bind++, s.ub++, s.tex_gen[1] = s.bind; found(e, s.now(), 1u << 1); want("found by its first pass: it stands from there", e.walked && e.amask == 1u << 1 && stands(e, s.now(), all) == Stand::Bound); s.ub++; want("and past a uniform update", stands(e, s.now(), all) == Stand::PastUpdate); note(e, s.now(), &q); want("noted anew (program_for gave another): it does not stand", e.p == &q && stands(e, s.now(), all) == Stand::No); Entry both; take(both, s.now(), &p, 1u << 1); want("take is note and found", both.walked && both.p == &p && stands(both, s.now(), all) == Stand::Bound); } { // one pass World w; w.handle = {5, 6 | 3u << 20, 0, 7}; for (uint32_t id : {0u, 5u, 6u, 7u, 8u, 9u}) w.version[id] = 1, w.type[id] = 1; w.type[9] = 0x81; // (an integer texture) Entry e; e.canon = {1, 1, 1, 1}; Walk k; want("a fresh entry: valid", pass(e, w, &k)); want("every handle read once, every bound answer asked", w.reads == 4 && w.asked == 3 && k.answers == 4 && k.moved == 4 && k.checked == 3); w.reads = w.asked = 0; want("the same textures again: valid", pass(e, w, &k)); want("each handle read once, none asked again", w.reads == 4 && w.asked == 0 && k.moved == 0 && k.checked == 0); w.handle[0] = 8, w.reads = w.asked = 0; want("a slot rebound to a texture of the same type: valid", pass(e, w, &k)); want("one read an answer, one compare", w.reads == 4 && w.asked == 1 && k.moved == 1 && k.checked == 1); w.handle[1] = 6 | 9u << 20, w.reads = w.asked = 0; want("another sampler, the same slot: valid, nothing asked", pass(e, w, &k) && w.asked == 0 && k.moved == 0); w.handle[2] = 7, w.reads = w.asked = 0; want("the unbound answer bound: asked once", pass(e, w, &k) && w.asked == 1); w.handle[2] = 0; want("unbound again: takes any", pass(e, w, &k)); w.handle[3] = 9, w.reads = w.asked = 0; want("an integer texture where the variant has a float one: not valid", !pass(e, w, &k) && k.checked == 1); want("and not valid again (nothing is taken on trust after a failure)", !pass(e, w)); w.handle[3] = 7; want("back to the float one: valid", pass(e, w)); w.version[7] = 2, w.type[7] = 0x81, w.asked = 0; want("its slot registered anew as an integer one: not valid", !pass(e, w) && w.asked == 1); w.version[7] = 3, w.type[7] = 1, w.asked = 0; want("and anew as a float one: valid, asked once", pass(e, w) && w.asked == 1); // (slot 0 with a sampler is a bound handle: it is asked although an unbound answer left slot 0's stamp there) w.handle[2] = 0; pass(e, w); w.type[0] = 0x81, w.handle[2] = 1u << 20, w.asked = 0; want("slot 0 named with a sampler after the answer was unbound: asked, not valid", !pass(e, w) && w.asked == 1); w.handle[2] = 0; fresh(e); w.reads = w.asked = 0; want("fresh: every bound answer asked again", pass(e, w) && w.reads == 4 && w.asked == 3); Entry empty; World nothing; want("a program that asks nothing is valid", pass(empty, nothing) && nothing.reads == 0); // the verdict is still_valid's, over a random walk of binds, registrations and types std::mt19937 rng(20261126); World r; r.handle.assign(6, 0); for (uint32_t id = 0; id < 12; id++) r.version[id] = 1, r.type[id] = (uint8_t)(rng() % 3 ? 1 : 0x81); Entry m; m.canon.assign(6, 1); int agree = 0, valid_n = 0, reads_ok = 1; for (int step = 0; step < 20000; step++) { const unsigned what = rng() % 10; if (what < 6) r.handle[rng() % 6] = rng() % 5 ? (rng() % 12) | (rng() % 4) << 20 : 0; else if (what < 8) { const uint32_t id = rng() % 12; r.version[id]++, r.type[id] = (uint8_t)(rng() % 3 ? 1 : 0x81); } else if (what == 8) fresh(m); r.reads = 0; const bool got = pass(m, r), should = r.valid(m.canon); agree += got == should, valid_n += should; if (got && r.reads != 6) reads_ok = 0; } want("one pass says what still_valid says, 20000 steps", agree == 20000 && valid_n > 500 && valid_n < 19500); want("a valid pass reads each handle exactly once", reads_ok == 1); } { // the table Table t; State s; int p[40]; std::vector in_set0; for (uint64_t serial = 1; in_set0.size() < 3; serial++) if (set_of(serial) == set_of(1)) in_set0.push_back(serial); for (int k = 0; k < 2; k++) { s.serial = in_set0[k]; take(place(t, s.now()), s.now(), &p[k], 0); } s.serial = in_set0[0]; want("two programs of one set are both kept", find(t, s.now()) && find(t, s.now())->p == &p[0]); s.serial = in_set0[2]; take(place(t, s.now()), s.now(), &p[2], 0); s.serial = in_set0[0]; want("a third replaces the one not used last", find(t, s.now()) && find(t, s.now())->p == &p[0]); s.serial = in_set0[1]; want("which is gone", find(t, s.now()) == nullptr); s.serial = in_set0[0]; Entry& again = place(t, s.now()); want("the same inputs are kept in the entry they have", again.p == &p[0]); take(again, s.now(), &p[5], 0); int n = 0; for (auto& set : t.e) for (Entry& e : set) n += same_inputs(e, s.now()); want("one entry for one program object and inputs", n == 1 && find(t, s.now())->p == &p[5]); drop(*find(t, s.now())); s.serial = in_set0[1]; take(place(t, s.now()), s.now(), &p[6], 0); s.serial = in_set0[2]; want("an empty way is taken before a kept program is replaced", find(t, s.now()) && find(t, s.now())->p == &p[2]); int sets[kSets] = {}; for (uint64_t serial = 0x5000; serial < 0x5000 + 64; serial++) sets[set_of(serial)]++; int used = 0; for (int k : sets) used += k > 0; want("serials spread over the sets", used >= 12 && set_of(~0ull) < (unsigned)kSets); clear(t); n = 0; for (auto& set : t.e) for (Entry& e : set) n += e.p != nullptr; want("cleared", n == 0); } { // The hook's model, in the default mode's shape (the full pick asked only where the memo has no answer), against the // full pick asked at every draw in a world of its own (RX_VK_PICK_WIDE=0): the same variant at every draw. // A program object has variants by its answers' types; the full pick keeps one for its key and returns it while it is // of the bound textures' types, else the first variant that is (made when there is none). struct Variant { std::vector canon; }; struct Object { uint64_t serial; size_t nanswers; uint32_t amask; std::vector variants; Variant* kept; // (the full pick's Pick::p) }; struct Scene { uint32_t slot_of[4] = {1, 2, 3, 4}; // (stage 1's bound textures, one an answer) std::map version; std::map type; State s; }; struct Counts { int memo = 0, first = 0, by_pass = 0, full = 0, unkept = 0, reads = 0; }; auto valid = [](Scene& sc, const Object& o, const Variant& v) { for (size_t i = 0; i < o.nanswers; i++) if (sc.slot_of[i] && sc.type[sc.slot_of[i]] != v.canon[i]) return false; return true; }; auto full_pick = [&](Scene& sc, Object& o) { // (program_for past its pair) if (!o.kept || !valid(sc, o, *o.kept)) { o.kept = nullptr; for (Variant* v : o.variants) if (!o.kept && valid(sc, o, *v)) o.kept = v; if (!o.kept) { Variant* v = new Variant; for (size_t i = 0; i < o.nanswers; i++) v->canon.push_back(sc.slot_of[i] ? sc.type[sc.slot_of[i]] : 1); o.variants.push_back(v), o.kept = v; } } return o.kept; }; auto wide = [&](Scene& sc, Table& t, Object& o, Counts& c) -> const Variant* { // (program_for_wide, RX_VK_PICK_WIDE unset) const Now now = sc.s.now(); auto walk = [&](Entry& e) { return one_pass(e, o.nanswers, [&](size_t i) { return c.reads++, sc.slot_of[i]; }, [&](uint32_t id) { return sc.version[id]; }, [&](size_t i, uint32_t h) { return sc.type[h] == e.canon[i]; }); }; Entry* e = find(t, now); if (e) { const Variant* const p = static_cast(e->p); if (!e->walked) { // (noted at its last draw: its first pass) e->canon = p->canon; if (walk(*e)) return found(*e, now, o.amask), c.first++, p; drop(*e), e = nullptr, c.unkept++; } else if (stands(*e, now, all) != Stand::No) { return c.memo++, p; } else if (walk(*e)) { return restamp(*e, now), c.by_pass++, p; } } c.full++; const Variant* const v = full_pick(sc, o); note(e ? *e : place(t, now), now, v); // (nothing of it read here) return v; }; auto index_of = [](const Object& o, const Variant* v) { for (size_t i = 0; i < o.variants.size(); i++) if (o.variants[i] == v) return (int)i; return -1; }; std::mt19937 rng(8303); std::vector olds, news; // (the same program objects in the two worlds: each world's picks are its own) for (int k = 0; k < 9; k++) olds.push_back({(uint64_t)(0x7000 + k * 13), (size_t)(k % 4), k % 3 == 2 ? kNotC2 : 1u << 1, {}, nullptr}); news = olds; Scene sc; for (uint32_t id = 0; id < 10; id++) sc.version[id] = 1, sc.type[id] = (uint8_t)(id % 3 ? 1 : 0x81); Table t; Counts c; int differ = 0, unbound = 0; for (int step = 0; step < 60000; step++) { State& s = sc.s; const unsigned what = rng() % 16; if (what < 3) s.bind++; // (a buffer bound) else if (what < 7) s.ub++; // (a uniform updated) else if (what < 9) sc.slot_of[rng() % 4] = rng() % 10, s.tex_gen[1] = ++s.bind; // (a texture bound in stage 1, or none) else if (what == 9) s.tex_gen[0] = ++s.bind; // (one in a stage no answer reads) else if (what == 10) { const uint32_t id = rng() % 10; sc.version[id]++, sc.type[id] = (uint8_t)(rng() % 3 ? 1 : 0x81), s.reg++; } const size_t k = rng() % olds.size(); s.serial = olds[k].serial, s.sig = olds[k].serial * 3; for (size_t i = 0; i < olds[k].nanswers; i++) unbound += sc.slot_of[i] == 0; const Variant* const mine = wide(sc, t, news[k], c); // (before the old world's pick: neither sees the other's) const Variant* const theirs = full_pick(sc, olds[k]); const int a = index_of(news[k], mine), b = index_of(olds[k], theirs); differ += a < 0 || a != b || mine->canon != theirs->canon || !valid(sc, news[k], *mine); } want("the memo's variant is the full pick's, and of the bound textures' types, at every draw of 60000", differ == 0); want("with answers unbound among them (more than one variant can be valid)", unbound > 1000); want("and most draws never reach the full pick", c.memo > 10000 && c.by_pass > 5000 && c.memo + c.by_pass + c.first > 50000 && c.full > 100); want("a noted program is walked at its next draw, once", c.first > 50 && c.first + c.unkept <= c.full); printf("model: %d by the memo, %d by one pass, %d by a first pass, %d full, %d noted and not kept\n", c.memo, c.by_pass, c.first, c.full, c.unkept); // programs drawn once before their entries are replaced: program_for's, and no answer read in the memo std::vector one_set; for (uint64_t serial = 0x9000; one_set.size() < 3; serial++) if (set_of(serial) == set_of(0x9000)) one_set.push_back(serial); for (int n = 2; n <= 3; n++) { std::vector o; for (int k = 0; k < n; k++) o.push_back({one_set[k], 3, 1u << 1, {}, nullptr}); Scene still; for (uint32_t id = 0; id < 10; id++) still.version[id] = 1, still.type[id] = 1; Table tt; Counts cc; for (int draw = 0; draw < 300; draw++) { Object& x = o[draw % n]; still.s.serial = x.serial, still.s.sig = x.serial * 3, still.s.ub++; // (a uniform updated before every draw) wide(still, tt, x, cc); } if (n == 3) want("three programs of one set in turn: every draw program_for's, and no answer read in the memo", cc.full == 300 && cc.reads == 0 && cc.first == 0 && cc.memo == 0 && cc.by_pass == 0); else want("two in turn: each noted once, walked once at its second draw, then the memo's", cc.full == 2 && cc.first == 2 && cc.reads == 6 && cc.memo == 296 && cc.by_pass == 0 && cc.unkept == 0); } { // one program object drawn with three sets of vertex inputs in turn: the set is by the serial alone, so the three take // its two ways in turn and none is answered by the memo (what pickwide.h says of it) Object x{0x9100, 3, 1u << 1, {}, nullptr}; Scene still; for (uint32_t id = 0; id < 10; id++) still.version[id] = 1, still.type[id] = 1; Table tt; Counts cc; for (int draw = 0; draw < 300; draw++) { still.s.serial = x.serial, still.s.sig = x.serial * 3, still.s.vattr[0] = (uint32_t)(draw % 3), still.s.ub++; wide(still, tt, x, cc); } want("one program object with three sets of vertex inputs in turn: every draw program_for's", cc.full == 300 && cc.memo == 0 && cc.first == 0 && cc.by_pass == 0); } } if (fails) printf("pickwide: FAILED (%d of %d checks)\n", fails, checks); else printf("pickwide: all %d checks passed\n", checks); return fails != 0; } ''' # The hook itself (vk_shader.cpp's part from the counters to program_wide_stats, cut out by its text) over stubs of what it # reads of the stamp's side, run with RX_VK_PICK_WIDE=check: what reaches the frame line's totals, and when HOOK_STUBS = r''' #include #include #include #include #include #include #include #include #include "lab_ab.h" #include "pickwide.h" namespace mkwvk { constexpr int kNvnStages = 8; inline constexpr int kProgramWideStats = 10; enum class ProgramKind { Graphics, Compute, Mesh }; struct ProgramObject { uint64_t serial = 1; }; struct NvnState { bool has_prog = true; ProgramObject prog; uint64_t bind_gen = 100; int nvattr = 2; uint32_t vattr[16]{}; uint64_t tex_gen[kNvnStages]{}; }; struct Program { struct Answer { uint8_t type; bool image; int at; }; std::atomic ready{true}; bool failed = false; std::vector answers; uint64_t key = 0, variant = 0; }; // (the world: an answer's handle, a slot's type, program_for's program, the last line logged) uint32_t handle_of[4]; uint8_t type_of[16]; const Program* full_pick; char last_log[512]; uint64_t prog_stage_sig(const ProgramObject& p) { return p.serial * 3; } uint64_t registrations_generation() { return 5; } uint64_t ub_generation() { return 9; } uint32_t answer_stage_mask(const Program&) { return 1u << 1; } uint32_t answer_handle(const NvnState&, const Program&, const Program::Answer& a) { return handle_of[a.at]; } uint32_t texture_slot_version(int) { return 1; } uint8_t answer_of(uint32_t handle, bool) { return type_of[handle & 15]; } uint8_t canonical_answer(const Program&, const Program::Answer&, uint8_t type) { return type; } const Program* program_for(const NvnState&, ProgramKind, const uint8_t*) { return full_pick; } void logf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(last_log, sizeof last_log, fmt, ap); va_end(ap); } } // namespace mkwvk ''' HOOK_MAIN = r''' using namespace mkwvk; static int checks, fails; static void want(const char* what, bool ok) { checks++; if (!ok) fails++, printf("FAIL %s\n", what); } struct Totals { // (what the frame line reads) int64_t n[kProgramWideStats]; Totals() { program_wide_stats(n); } int64_t since(const Totals& was, int k) const { return n[k] - was.n[k]; } }; int main() { std::strcpy(lab_ab::knobs[0].name, "nopickwide"); lab_ab::n_knobs = 1; Program p1, p2, p3; for (Program* p : {&p1, &p2, &p3}) p->answers = {{1, false, 0}}, p->key = 0x77; // (one answer, a float texture's) p1.variant = 1, p2.variant = 2, p3.variant = 3, p3.answers[0].type = 0x81; handle_of[0] = 3, type_of[3] = 1; const uint8_t ct[8] = {}; { // a helper thread finds a difference and a wrong variant, then records nothing more (the tuner keeps to the replay // thread, or the run ends): its counts are in the totals all the same, its compares with them const Totals was; const Program* got[5] = {}; std::thread([&] { NvnState s; full_pick = &p1; got[0] = program_for_wide(s, ct); // (no entry: program_for's, noted) got[1] = program_for_wide(s, ct); // (its first pass: kept; program_for's is the same) full_pick = &p2; got[2] = program_for_wide(s, ct); // (the memo's stands; program_for gives another variant, of the same types) got[3] = program_for_wide(s, ct); // (that one noted in its place: its first pass, the same) type_of[3] = 0x81, full_pick = &p3; // (an integer texture in the slot, no generation moved: what check mode is for) got[4] = program_for_wide(s, ct); // (the memo's stands, and is not of the bound texture's type) }).join(); const Totals now; want("check mode draws program_for's at every draw", got[0] == &p1 && got[1] == &p1 && got[2] == &p2 && got[3] == &p2 && got[4] == &p3); want("a thread's differences reach the totals at once", now.since(was, PW_DIFFER) == 2 && now.since(was, PW_WRONG) == 1); want("and its compares with them", now.since(was, PW_COMPARED) == 4); printf("hook: %lld compared, %lld differences, %lld not of the types\n", (long long)now.since(was, PW_COMPARED), (long long)now.since(was, PW_DIFFER), (long long)now.since(was, PW_WRONG)); } { // a nopickwide phase begins: what the thread counted before it reaches the totals at its first pick in the phase type_of[3] = 1, full_pick = &p1; const Totals was; std::thread([&] { NvnState s; s.prog.serial = 2; for (int k = 0; k < 4; k++) program_for_wide(s, ct); // (noted, kept, the memo's twice: three compared, the same) lab_ab::active.store(1); program_for_wide(s, ct); lab_ab::active.store(0); }).join(); const Totals now; want("a change of mode adds what the thread held", now.since(was, PW_COMPARED) == 3 && now.since(was, PW_FULL) == 1 && now.since(was, PW_DIFFER) == 0); } { // program_for gives no program where the memo has one: the draw is left out, and the log says so type_of[3] = 1; const Totals was; std::thread([&] { NvnState s; s.prog.serial = 3; full_pick = &p1; program_for_wide(s, ct), program_for_wide(s, ct); full_pick = nullptr; want("no program from program_for: none drawn", program_for_wide(s, ct) == nullptr); }).join(); const Totals now; want("counted as a difference, not as a wrong variant", now.since(was, PW_DIFFER) == 1 && now.since(was, PW_WRONG) == 0); want("logged as no program, not as one not ready", std::strstr(last_log, "no program") && !std::strstr(last_log, "not ready")); } if (fails) printf("pickwide hook: FAILED (%d of %d checks)\n", fails, checks); else printf("pickwide hook: all %d checks passed\n", checks); return fails != 0; } ''' def block(text, marker): start = text.index(marker) at = text.index("{", start) + 1 depth = 1 while depth: depth += (text[at] == "{") - (text[at] == "}") at += 1 return text[start:at] def need(ok, why): if not ok: raise SystemExit("FAIL: " + why) def ordered(text, parts, why): last = 0 for p in parts: k = text.find(p, last) need(k >= 0, why + " (missing, or out of order: " + p + ")") last = k + len(p) def stamp_text(rel, data): """A file as the translation stamp takes it (nx2/build.py translation_text)""" build = ROOT / "nx2" / "build.py" tree = ast.parse(build.read_text(encoding="utf-8"), filename=str(build)) functions = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ("strip_comments", "translation_text")] need(len(functions) == 2, "nx2/build.py: strip_comments and translation_text are not there to run") ns = {"os": os, "hashlib": hashlib, "json": json, "__file__": str(build)} exec(compile(ast.Module(body=functions, type_ignores=[]), str(build), "exec"), ns) return ns["translation_text"](rel, data).decode("utf-8") def check_source(): raw = (ROOT / "gpu/vk/vk_shader.cpp").read_bytes() shader = raw.decode("utf-8").replace("\r\n", "\n") # (outside the translation stamp: between the last "Outside" mark and its "Inside again", and nothing of it in the stamp's text) at = shader.find("const Program* program_for_wide(const NvnState& s, const uint8_t color_types[8]) {") need(at >= 0, "vk_shader.cpp: program_for_wide is missing") need(shader.rfind(OUT_MARK, 0, at) > shader.rfind(IN_MARK, 0, at) and shader.find(IN_MARK, at) > 0, "vk_shader.cpp: program_for_wide is inside the translation stamp: every player's program and pipeline caches would start again") stamped = stamp_text("vk_shader.cpp", raw) for name in ("pickwide", "program_for_wide", "program_wide_stats", "pw_", "RX_VK_PICK_WIDE", "lab_ab"): need(name not in stamped, "vk_shader.cpp: the translation stamp's text names %s" % name) need("const Program* program_for(const NvnState& s, ProgramKind kind, const uint8_t color_types[8]) {" in stamped and "thread_local ProgFast prog_fast[2];" in stamped and "if (still_valid(s, *pk.p)) {" in stamped, "vk_shader.cpp: program_for, its pair and its two walks are no longer what RX_VK_PICK_WIDE=0 goes back to") part = shader[shader.rfind(OUT_MARK, 0, at):shader.find(IN_MARK, at)] need('#include "pickwide.h"' in part and '#include "lab_ab.h"' in part, "vk_shader.cpp: pickwide.h and lab_ab.h are not included outside the stamp") mode = block(part, "pickwide::Mode pw_mode() {") need('static const pickwide::Mode env = [] {' in mode and 'pickwide::mode(getenv("RX_VK_PICK_WIDE"))' in mode and 'return pickwide::in_phase(env, lab_ab::on("nopickwide"));' in mode and "logf(" in mode and "if (m != pickwide::Mode::On)" in mode, "the switch is not RX_VK_PICK_WIDE read once and logged when not the default, with the lab's nopickwide knob") walk = block(part, "bool pw_pass(") need("pickwide::one_pass(" in walk and "answer_handle(s, p, p.answers[i])" in walk and "texture_slot_version((int)id)" in walk and "canonical_answer(p, a, answer_of(h, a.image)) == e.canon[i]" in walk and walk.count("answer_handle(") == 1, "pw_pass does not read each answer's handle once and compare canonical types, as still_valid does") canon = block(part, "void pw_canon(") need("e.canon[i] = canonical_answer(p, p.answers[i], p.answers[i].type);" in canon and "e.canon.resize(p.answers.size());" in canon, "pw_canon does not keep the variant's own types canonical, as still_valid compares them") wide = block(part, "const Program* program_for_wide(") need('pickwide::rules(getenv("RX_VK_PICK_BIND_GEN") != nullptr, getenv("RX_VK_DEFERRED_LATE") != nullptr)' in wide, "RX_VK_PICK_BIND_GEN and RX_VK_DEFERRED_LATE do not keep ub_generation in the rule") need("static_assert(pickwide::kStages == kNvnStages" in wide, "the header's stages are not asserted to be NvnState's") ordered(wide, ["const pickwide::Mode mode = pw_mode();", "if (mode == pickwide::Mode::Off || !s.has_prog) return program_for(s, ProgramKind::Graphics, color_types);", "const pickwide::Now now{s.prog.serial, prog_stage_sig(s.prog), s.bind_gen, registrations_generation(), ub_generation(), s.nvattr,", "s.vattr, color_types, s.tex_gen};", "pickwide::find(t, now)", "if (!p->ready.load(std::memory_order_acquire) || p->failed) {", "} else if (!e->walked) {", "pw_canon(*p, *e);", "const bool ok = pw_pass(s, *p, *e, &w);", "if (ok) pickwide::found(*e, now, answer_stage_mask(*p)), mine = p,", "else pickwide::drop(*e), e = nullptr, pw_mine[PW_UNKEPT]++;", "pickwide::stands(*e, now, rules)", "pw_pass(s, *p, *e, &w)", "pickwide::restamp(*e, now)", "if (mine && mode == pickwide::Mode::On) return mine;", "const Program* const full = program_for(s, ProgramKind::Graphics, color_types);", "if (full && full->ready.load(std::memory_order_acquire) && !full->failed) {", "pickwide::note(e ? *e : pickwide::place(t, now), now, full);", "return full;"], "program_for_wide does not ask the memo, then one pass, then program_for, and keep only a program a pass found valid") # (a draw that went to program_for only notes its program: the pass, the mask and the canonical types are its next draw's. # Walked where it is picked, a program drawn once before its entry is replaced pays a third walk on top of the full pick's two) tail = wide[wide.index("const Program* const full = program_for("):] noted = tail[tail.index("if (full && full->ready.load(std::memory_order_acquire) && !full->failed) {"):] need("pw_pass(" not in noted and "pw_canon(" not in noted and "answer_stage_mask(" not in noted and "pickwide::take(" not in wide, "program_for_wide walks a program where program_for picked it: the miss path is dearer than the pick it stands in front of") need(wide.count("answer_stage_mask(") == 1 and wide.count("pw_pass(") == 3 and tail.count("pw_pass(") == 1, "program_for_wide: the passes are no longer a noted entry's first, a kept entry's, and check mode's probe") rule = (ROOT / "gpu/vk/pickwide.h").read_text(encoding="utf-8").replace("\r\n", "\n") need("if (!same_inputs(e, n) || !e.walked || e.reg != n.reg) return Stand::No;" in rule, "pickwide.h: a program only noted stands without a pass ever having found it of the bound textures' types") need(wide.count("return mine;") == 1 and wide.count("program_for(s, ProgramKind::Graphics, color_types)") == 2, "program_for_wide returns the memo's program somewhere else than in the mode that is on (check mode draws program_for's)") need("pickwide::clear(" in wide and "pw_mode_was" in wide, "a thread's memo is not cleared when the mode changes (a lab phase)") header = (ROOT / "gpu/vk/vk_shader.h").read_text(encoding="utf-8") need("const Program* program_for_wide(const NvnState& s, const uint8_t color_types[8]);" in header, "vk_shader.h does not declare program_for_wide") draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8").replace("\r\n", "\n") body = block(draw, "void draw(VkCommandBuffer cmd, NvnState& s, const DrawArgs& d) {") ordered(body, ["PROF_HOT(PROF_PROGRAM);", "if (d.mesh) cp = program_for(s, ProgramKind::Mesh, types);", "else cp = program_for_wide(s, types);"], "draw() does not ask the wide memo for its graphics program") dry = block(draw, "uint64_t dry_draw_program(void* ctx) {") need("q.mesh ? program_for(*q.s, ProgramKind::Mesh, types) : program_for_wide(*q.s, types)" in dry, "the dry pass picks its graphics programs past the memo: the picks' kept programs would move behind it") need(draw.count("program_for_wide(") == 2, "the memo is asked somewhere else than draw()'s and the dry pass's graphics picks") replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8").replace("\r\n", "\n") need("program_wide_stats(" in replay and "program picks by the wide memo" in replay and "past a uniform update" in replay and "a noted program's first" in replay and "RX_VK_PICK_WIDE=check" in replay, "vk_replay.cpp: the status line does not count the memo's picks and check mode's differences") line = replay[replay.index("program_wide_stats(pw);"):] line = line[:line.index("std::memcpy(l_pw, pw, sizeof l_pw);")] need("if (pw[6] || pw[7])" in line, "vk_replay.cpp: check mode's totals are shown only once a compare reached them, not at a difference") docs = (ROOT / "docs/development.md").read_text(encoding="utf-8") row = [l for l in docs.splitlines() if l.startswith("| `RX_VK_PICK_WIDE=0` or `check`")] need(len(row) == 1 and "`gpu/vk/pickwide.h`" in row[0] and "`nopickwide`" in row[0] and "program picks by the wide memo" in row[0] and "only noted" in row[0], "docs/development.md: the switches table has no RX_VK_PICK_WIDE row with its knob and its counter line") def hook_source(): """The hook's part of vk_shader.cpp, from its counters to program_wide_stats, over HOOK_STUBS""" shader = (ROOT / "gpu/vk/vk_shader.cpp").read_text(encoding="utf-8").replace("\r\n", "\n") at = shader.index("const Program* program_for_wide(const NvnState& s, const uint8_t color_types[8]) {") part = shader[shader.rfind(OUT_MARK, 0, at):shader.find(IN_MARK, at)] start = part.rindex("namespace {", 0, part.index("enum PwCount")) return HOOK_STUBS + "namespace mkwvk {\n" + part[start:] + "} // namespace mkwvk\n" + HOOK_MAIN def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--cxx", default="clang++") args = parser.parse_args() need((ROOT / "gpu/vk/pickwide.h").is_file(), "gpu/vk/pickwide.h is missing (the wide memo's rule)") with tempfile.TemporaryDirectory(prefix="pickwide-") as tmp: cpp, exe = Path(tmp) / "pickwide_test.cpp", Path(tmp) / "pickwide.exe" cpp.write_text(DRIVER, encoding="utf-8") subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)], check=True) r = subprocess.run([str(exe)], capture_output=True, text=True) print(r.stdout.rstrip()) if r.returncode: raise SystemExit("FAIL: the wide memo's checks failed") cpp, exe = Path(tmp) / "pickwide_hook.cpp", Path(tmp) / "pickwide_hook.exe" cpp.write_text(hook_source(), encoding="utf-8") subprocess.run([args.cxx, "-std=c++20", "-O1", "-pthread", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)], check=True) r = subprocess.run([str(exe)], capture_output=True, text=True, env=dict(os.environ, RX_VK_PICK_WIDE="check")) print(r.stdout.rstrip()) if r.returncode: raise SystemExit("FAIL: the hook's checks failed") check_source() print("PASS: a draw's program comes from the wide memo in front of program_for, outside the translation stamp; RX_VK_PICK_WIDE=0 as before") if __name__ == "__main__": main()