diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl index 0ee9bd2fc..7258a5fa3 100644 --- a/src/gfx1013_direct_graphics.inl +++ b/src/gfx1013_direct_graphics.inl @@ -545,6 +545,8 @@ struct GraphicsMaskRegions { std::set scalar_mask_selects; std::map then_fallthroughs; std::set scalar_tail_merges; + // One-armed pixel CMPX restores that return EXEC to the coverage saved before s_wqm_b64. + std::set coverage_restores; static unsigned scalar_width(const Inst &i) { if (i.enc == Encoding::Smem) return memory_count(i); if (i.enc == Encoding::Vopc) return 2; @@ -828,12 +830,24 @@ struct GraphicsMaskRegions { if (!compare) continue; } unsigned record_anchor=UINT_MAX; + // The pair may instead be the coverage saved just before s_wqm_b64 exec, exec: the + // restore then also leaves whole-quad mode. Without an ELSE, a helper lane runs the + // THEN arm exactly when its guest copy does, so nothing differs once helpers stop. + bool to_coverage=false; if (cmpx) { size_t anchor=k; while (anchor && !entries.count(code[anchor].pc)) { const auto &op=code[--anchor]; if ((op.name=="s_mov_b64" && op.src[0]==126 && op.dst==parent) || (op.name=="s_mov_b64" && op.src[0]==parent && op.dst==126)) break; + if (!else_skip && op.name=="s_wqm_b64" && op.dst==126 && op.src[0]==126 && anchor && + !entries.count(op.pc) && + code[anchor-1].name=="s_mov_b64" && code[anchor-1].dst==parent && + code[anchor-1].src[0]==126) { + --anchor; + to_coverage=true; + break; + } if (op.branch() || clobbers(op,126) || clobbers(op,parent) || carry_destination(op) || op.name.find("exec")!=Name::npos) { anchor=k; @@ -843,7 +857,8 @@ struct GraphicsMaskRegions { const auto &op=code[anchor]; if (op.name!="s_mov_b64" || !((op.src[0]==126 && op.dst==parent) || (op.src[0]==parent && op.dst==126))) continue; - if (op.dst==parent) record_anchor=op.pc; + // The coverage save keeps its entry tag; the restore proves it when lowered. + if (op.dst==parent && !to_coverage) record_anchor=op.pc; } bool closed=true; for (auto it=entries.upper_bound(mask.pc);it!=entries.end() && it->first<=restore.pc;++it) @@ -893,8 +908,9 @@ struct GraphicsMaskRegions { if (scalar) for (unsigned r=op.dst;rpc); mask_inputs.emplace(intersection->pc,1024+compare->pc); @@ -1428,6 +1444,143 @@ struct GraphicsMaskRegions { } } }; +// A wave64 pixel CMPX outside every recognised EXEC region is an alpha-test kill when no later +// EXEC write can return its lanes. The lowering discards a failing lane where the compare stands. +// In DXIL that lane stays a helper; the guest lane stops. They agree while nothing later reads +// another lane (derivatives, DPP, LDS, lane and wave operations), stores, reads EXEC as a value +// or writes EXEC other than by narrowing it or restoring a pair saved after the kill. An export +// before the kill has already delivered its lane. Every rule here only accepts or ignores a +// shape; an ignored CMPX or skip keeps its existing refusal. +struct PixelLaneKills { + std::set kills, uncut; + // Sample and gather forms whose level of detail comes from the quad's coordinates. + static bool implicit_lod(const Inst &i) { + if (i.enc != Encoding::Image || i.op < 0x20) return false; + if (i.op >= 0x60) return true; + const unsigned form = i.op & 7; // 0 plain, 1 CL, 5 B, 6 B_CL; 2/3 D, 4 L and 7 LZ are explicit + return form == 0 || form == 1 || form == 5 || form == 6; + } + static bool cmpx(const Inst &i) { + return i.enc == Encoding::Vopc && i.dst == 126 && i.name.substr(0,7) == "v_cmpx_"; + } + void find(Program &p, const GraphicsMaskRegions ®ions, const std::set &claimed) { + auto &code = p.code; + // A loop could carry a killed lane back above its compare. + if (std::any_of(code.begin(), code.end(), [](const Inst &i) { return i.branch() && i.target() <= i.pc; })) + return; + std::multimap entries; + for (const auto &i : code) + if (i.branch()) entries.emplace(i.target(), i.pc); + auto entered = [&](unsigned after, unsigned through) { + auto e = entries.upper_bound(after); + return e != entries.end() && e->first <= through; + }; + auto overlaps = [](const Inst &op, unsigned reg) { + const unsigned width = GraphicsMaskRegions::scalar_width(op); + const auto carry = carry_destination(op); + return (width && op.dst < reg + 2 && reg < op.dst + width) || (carry && *carry < reg + 2 && reg < *carry + 2); + }; + // The pair's only reaching definition is a save of EXEC made after the kill. + auto saved_after = [&](size_t kill, size_t at, unsigned reg) { + if (reg > 104 || (reg & 1)) return false; + for (size_t j = at; j-- > kill + 1;) { + const auto &op = code[j]; + if (!overlaps(op, reg)) continue; + if (op.dst != reg || !((op.name == "s_mov_b64" && op.src[0] == 126) || op.name == "s_and_saveexec_b64")) + return false; + for (auto e = entries.upper_bound(op.pc); e != entries.end() && e->first <= code[at].pc; ++e) + if (e->second < op.pc) return false; + return true; + } + return false; + }; + auto lane_local_after = [&](size_t k) { + for (size_t j = k + 1; j < code.size(); ++j) { + const auto &op = code[j]; + if (op.branch()) continue; // the CFG refuses a branch it cannot structure + if (op.dpp_control || op.dpp8_selectors || op.enc == Encoding::Lds || op.enc == Encoding::QuadCompare || + (op.enc == Encoding::Image && op.op >= 0x08 && op.op < 0x20) || + implicit_lod(op) || (op.name.find("lane") != Name::npos && op.name != "v_readfirstlane_b32") || + op.name.find("mbcnt") != Name::npos || op.name.find("wqm") != Name::npos || + op.name.find("quadmask") != Name::npos || + op.name.find("store") != Name::npos || op.name.find("sendmsg") != Name::npos || + op.name.find("barrier") != Name::npos || + (op.name.find("atomic") != Name::npos && op.name != "buffer_atomic_add")) + return false; + const bool reads = std::any_of(op.src.begin(), op.src.end(), + [](unsigned r) { return r == 126 || r == 127 || r == 252; }); + if (!reads && !overlaps(op, 126) && op.name.find("exec") == Name::npos) continue; + // Narrowing EXEC never returns a lane. + if (cmpx(op) || op.name == "s_and_saveexec_b64" || + (op.name == "s_and_b64" && op.dst == 126 && (op.src[0] == 126) != (op.src[1] == 126))) + continue; + // A save that only anchors a recognised arm is never read as a number. + if (op.name == "s_mov_b64" && op.src[0] == 126 && regions.vertex_anchors.count(op.pc)) continue; + if (op.dst == 126 && (op.name == "s_mov_b64" || (op.name == "s_andn2_b64" && op.src[1] == 126)) && + saved_after(k, j, op.src[0])) + continue; + return false; + } + return true; + }; + auto quiet = [](const Inst &op) { + return GraphicsMaskRegions::local_alu(op) || op.name == "s_waitcnt" || op.name == "s_nop" || + op.name == "s_clause" || (op.enc == Encoding::Smem && op.dst + memory_count(op) <= 106) || + (op.enc == Encoding::Vopc && op.dst <= 106 && op.name.substr(0,6) == "v_cmp_" && !op.dpp_control); + }; + std::vector candidates, null_skips; + const size_t null = code.size() >= 3 ? code.size() - 2 : 0; + const bool null_block = null && code[null].enc == Encoding::Export && (code[null].a & 0x1fff) == 0x1890 && + code[null - 1].name == "s_endpgm" && code.back().name == "s_endpgm"; + for (size_t k = 0; k < code.size(); ++k) { + const auto &cmp = code[k]; + if (!cmpx(cmp) || cmp.name.find("class") != Name::npos || cmp.subword || cmp.scale || cmp.clamp || + cmp.dpp_control || claimed.count(cmp.pc) || regions.cmpx_starts.count(cmp.pc) || + regions.branch_saves.count(cmp.pc) || regions.mask_inputs.count(cmp.pc) || + std::any_of(code.begin(), code.begin() + k, [](const Inst &i) { return i.enc == Encoding::Export; }) || + !lane_local_after(k)) + continue; + candidates.push_back(k); + // EXEC at a following EXECZ is the surviving lanes. The guest takes it only when none + // of its lanes survive, and every DXIL lane that is still covered falls through. + size_t s = k + 1; + while (s < code.size() && quiet(code[s])) ++s; + if (s == code.size() || !code[s].branch() || code[s].op != 8 || code[s].target() <= code[s].next || + entered(cmp.pc, code[s].pc)) + continue; + const size_t target = p.at.at(code[s].target()); + if (null_block && target == null) { + null_skips.push_back(s); + } else if (code[target - 1].name != "s_endpgm" && !(code[target - 1].branch() && code[target - 1].op == 2)) { + GraphicsMaskRegions::skip_proven(code[s]); + } + } + // The EXP_NULL block goes only if every branch to it is such a skip. + if (!null_skips.empty()) { + const unsigned output = code[null].pc; + const auto into = std::count_if(code.begin(), code.end(), [&](const Inst &i) { + return i.branch() && i.target() == output; + }); + if (static_cast(into) == null_skips.size()) { + for (auto s : null_skips) GraphicsMaskRegions::skip_proven(code[s]); + p.at.erase(output); + p.at.erase(code.back().pc); + code.resize(null); + } + } + // The discard must lie on every path to the code after it: no remaining branch may cross + // the compare, and no earlier block may end the program. + for (auto k : candidates) { + const unsigned pc = code[k].pc; + const bool cut = std::none_of(code.begin(), code.end(), [&](const Inst &i) { + return i.branch() && i.pc < pc && i.target() > pc; + }) && std::none_of(regions.then_fallthroughs.begin(), regions.then_fallthroughs.end(), [&](const auto &e) { + return e.first < pc && e.second > pc; + }) && std::none_of(code.begin(), code.begin() + k, [](const Inst &i) { return i.name == "s_endpgm"; }); + (cut ? kills : uncut).insert(pc); + } + } +}; std::map graphics_blocks(const Program &program, const GraphicsMaskRegions ®ions) { std::set leaders{0}; for (auto edge : regions.then_fallthroughs) leaders.insert(edge.second); @@ -1997,6 +2150,25 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = wqm.numeric_guards(program,stage.wave32); } GraphicsMaskRegions regions(program, stage.wave32, !pixel); + PixelLaneKills lane_kills; + if (pixel && !stage.wave32) + lane_kills.find(program, regions, {kill_pc, wqm.kill_compare}); + // From this pc on, code has a single entry and no branch: every earlier block flows here + // (no earlier s_endpgm and no backward branch), so it is emitted last in topological order. + // EXEC may leave whole-quad mode here even after a branch. + unsigned exact_tail = 0; + for (const auto &i : program.code) { + if (i.branch()) { + if (i.target() <= i.pc) { exact_tail = UINT_MAX; break; } + exact_tail = (std::max)({exact_tail, i.next, i.target()}); + } else if (i.name == "s_endpgm" && &i != &program.code.back()) { + exact_tail = UINT_MAX; + break; + } + } + if (exact_tail != UINT_MAX) + for (const auto &edge : regions.then_fallthroughs) + exact_tail = (std::max)(exact_tail, edge.second); const auto first_branch = std::find_if(program.code.begin(), program.code.end(), [](const auto &i) { return i.branch(); }); const bool straight = first_branch == program.code.end(); @@ -2089,6 +2261,11 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = std::string covered; string discard_lane; string killed_coverage_lane; + // The lanes still alive after every lane kill so far. A kill dominates the code after it, so + // this value does too. Coverage tests use it rather than relying on a discarded lane's helper bit. + string lane_alive; + // Exact mode was entered at or after exact_tail, so it holds on the only path from there. + bool exact_in_tail = false; std::string parent_predicate, arm_condition, inner_parent; bool scalar_entry = true; std::set uniform_vector_values; @@ -2107,7 +2284,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = auto covered_lane = [&] { auto helper = alu.ir.invoke("i1","isHelperLane.i1",221,{},"nounwind readonly"); alu.ir.dependencies[helper].set(128); - return alu.ir.value("xor i1 " + helper + ", true"); + auto exact = alu.ir.value("xor i1 " + helper + ", true"); + return lane_alive.empty() ? exact : alu.ir.value("and i1 " + exact + ", " + lane_alive); }; GraphicsFullWave full_wave{alu, stage.wave32 ? 32u : 64u}; // A two-SGPR compare and the combines made from it. The bit is the lane's @@ -2128,6 +2306,30 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = auto in_compare_tail = [&] { return pixel && (whole_quad || exact_after_wqm); }; + // EXEC returns from whole quads to the covered lanes. If nothing after this reads a helper + // result, leave whole-quad mode; otherwise later writes keep the covered lanes only. + auto enter_exact = [&](unsigned at) { + exact_after_wqm = true; + if (!entry_backedge && last_observer != program.code.rend() && at == last_observer->pc) { + while (!alu.guarded_ij.empty()) { + auto it = alu.guarded_ij.begin(); + if (!covered.empty() && it->second.first == covered) { + alu.graphics_registers[it->first] = it->second.second; + alu.guarded_ij.erase(it); + } else { + alu.materialize_ij(it->first); + } + } + whole_quad = false; + exact_after_wqm = false; + alu.exact_pixel_entry = false; + alu.graphics_predicate.clear(); + return; + } + if (covered.empty()) covered = covered_lane(); + alu.graphics_predicate = covered; + alu.exact_pixel_entry = true; + }; auto instruction = [&](const Inst &i, const State &state) { const auto pc = alu.graphics_pc = graphics.pc = i.pc; if (alu.pixel_heap_slot_map && pcsecond == "0"))) + refuse(pc, "CMPX arm restore to coverage requires whole-quad EXEC, saved entry coverage and no later branch"); + exact_in_tail = true; + enter_exact(pc); + return; + } if (regions.branch_merges.count(pc) && !regions.scalar_tail_merges.count(pc) && !regions.restores.count(pc)) return; const bool cmpx = regions.cmpx_starts.count(pc) != 0; if (cmpx || regions.compares.count(pc)) { @@ -2531,6 +2759,29 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = return; } } + if (intersect_coverage && !exact_sample_region) { + // EXEC & saved coverage. In whole-quad mode it leaves for exact coverage, and lanes a + // kill removed stay out of both. In exact mode, or with no whole-quad entry, EXEC is + // already within the coverage. A pair tagged "0" holds the covered lanes when it was + // saved, a superset of the lanes alive now. + const unsigned source = i.src[i.src[0] == 126 ? 1 : 0]; + const auto tag = alu.graphics_registers.find(512 + source); + const bool entry = invariant_entry_masks.count(source) || + (tag != alu.graphics_registers.end() && tag->second == "0"); + const bool exact = exact_after_wqm && !covered.empty() && alu.graphics_predicate == covered && + (straight || pc < prologue_end || exact_in_tail); + const bool tail = straight || pc < prologue_end || pc >= exact_tail; + if (entry && whole_quad && !exact_after_wqm && alu.graphics_predicate.empty() && tail) { + exact_in_tail = !straight && pc >= prologue_end; + enter_exact(pc); + alu.write(128,{}); + return; + } + if (entry && (exact || (!whole_quad && alu.graphics_predicate.empty()))) { + alu.write(128,{}); + return; + } + } if (move_exec && i.dst == 126 && pc >= prologue_end && !entry_backedge && whole_quad && alu.graphics_predicate.empty() && terminal_mask != program.code.rend() && terminal_mask->pc == pc) { const auto tag = alu.graphics_registers.find(512 + i.src[0]); @@ -2552,7 +2803,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = } else alu.graphics_predicate.clear(); return; } - if (!straight && pc >= prologue_end && exact_after_wqm && !exact_sample_region) + if (!straight && pc >= prologue_end && exact_after_wqm && !exact_sample_region && !exact_in_tail) refuse(pc, "exact pixel mask crosses a control-flow edge"); if (move_exec && (short_mask ? i.dst <= 105 : i.dst <= 104 && !(i.dst & 1)) && i.src[0] == 126 && (pc < prologue_end || waterfalls.saves.count(pc))) { @@ -2580,29 +2831,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = if (move_exec && i.dst == 126 && pc < prologue_end && saved_exec.count(i.src[0]) && alu.graphics_registers.count(512 + i.src[0])) { exact_after_wqm = whole_quad && !saved_exec.at(i.src[0]); - if (whole_quad && exact_after_wqm && !entry_backedge && - last_observer != program.code.rend() && pc == last_observer->pc) { - while (!alu.guarded_ij.empty()) { - auto it = alu.guarded_ij.begin(); - if (!covered.empty() && it->second.first == covered) { - alu.graphics_registers[it->first] = it->second.second; - alu.guarded_ij.erase(it); - } else { - alu.materialize_ij(it->first); - } - } - whole_quad = false; - exact_after_wqm = false; - alu.exact_pixel_entry = false; - alu.graphics_predicate.clear(); - return; - } if (exact_after_wqm) { - if (covered.empty()) { - covered = covered_lane(); - } - alu.graphics_predicate = covered; - alu.exact_pixel_entry = true; + enter_exact(pc); } else { alu.graphics_predicate.clear(); alu.exact_pixel_entry = false; diff --git a/tests/cmake/native_pixel_alpha_kill.cmake b/tests/cmake/native_pixel_alpha_kill.cmake new file mode 100644 index 000000000..a2b751aa5 --- /dev/null +++ b/tests/cmake/native_pixel_alpha_kill.cmake @@ -0,0 +1,17 @@ +# Wave64 pixel alpha-test kills (a CMPX with no saved EXEC), coverage re-application (s_and_b64 exec, exec, sN) +# and one-armed CMPX skips followed by it, alone and combined (Part of #3814). +# _controls checks the DXIL and the refusals; _warp and _hardware draw every accepted shape and check each pixel. +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_pixel_alpha_kill_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pixel_alpha_kill_check.py" "$" + - "${DXC_BIN_DIR}" controls) + set_tests_properties(native_pixel_alpha_kill_controls PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_pixel_alpha_kill_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pixel_alpha_kill_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_pixel_alpha_kill_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() +endif() diff --git a/tests/native_pixel_alpha_kill_check.py b/tests/native_pixel_alpha_kill_check.py new file mode 100644 index 000000000..3fa323c8e --- /dev/null +++ b/tests/native_pixel_alpha_kill_check.py @@ -0,0 +1,259 @@ +"""Wave64 pixel alpha-test kills and coverage re-application (Part of #3814). + +The guest programs are source-built gfx1013 words in a synthetic pixel container (v0 = SV_Position.x, v2 is the +exported colour). Three shapes, alone and combined: + + kill v_cmpx__f32 limit, v0 ; EXEC write with no saved EXEC to restore: an alpha test. + ; Failing lanes never come back, so they are discarded. + [s_cbranch_execz EXP_NULL or a later instruction] ; taken only when the guest wave is empty + coverage s_mov_b64 s[4:5], exec ; entry coverage + s_wqm_b64 exec, exec + ... + s_and_b64 exec, exec, s[4:5] ; or exec = s[4:5] & exec: leave whole-quad mode + arm s_mov_b64 s[6:7], exec + v_cmpx_lt_f32 3.0, v0 + s_cbranch_execz L + + L: s_mov_b64 exec, s[6:7] ; then the coverage AND, or the arm restores s[4:5] itself + +The draw covers an 8x2 target. A killed pixel keeps the clear value; every other pixel shows the colour its own +lane computed. Each draw is repeated with references that must differ: no pixel killed, the opposite pixels killed, +and, with an arm, the arm's values swapped. + +Refused: an export before the kill, a quad, DPP or EXEC read after it, s_wqm_b64 after it, an EXEC restore that +would bring killed lanes back, a branch into the kill or around it, a class or clamped compare, and coverage +re-application from a pair that is not the saved entry coverage or whose saved half was overwritten. + +Modes: controls (DXIL shape and refusals) and warp/hardware (the draws as well). +""" +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import patched_pixel, signature +from native_graphics_wqm_check import VERTEX +from native_scalar_lds_check import sop1, vmove + +CLEAR = (-1.0,) * 4 +ONE, HALF, TWO = 242, 240, 244 # inline 1.0, 0.5, 2.0 +NULL_DONE_VM = (0xF8001890, 0x80808080, 0xBF810000) +LT, EQ, LE, GT, GE = 0x11, 0x12, 0x13, 0x14, 0x16 # v_cmpx_*_f32 +WQM = sop1(10, 126, 126) # s_wqm_b64 exec, exec +ENTRY = (sop1(4, 4, 126), WQM) # s_mov_b64 s[4:5], exec; s_wqm_b64 exec, exec +UNIFORM_TRUE = 0xBF068080 # s_cmp_eq_u32 0, 0 + + +def bits(value): + return struct.unpack("_f32 limit, v0 + + +def and_exec(pair, exec_first=True): + return sop2(15, 126, 126, pair) if exec_first else sop2(15, 126, pair, 126) + + +def arm(body, save=6, restore=6): + """One-armed CMPX skip on 3.0 < x. save=None leaves the save to the entry coverage.""" + pre = [sop1(4, save, 126)] if save is not None else [] + return [*pre, *cmpx(LT, 3.0), ("execz", "join"), *body, ("label", "join"), sop1(4, 126, restore)] + + +def program(seq): + """"null" is an EXECZ to EXP_NULL, ("execz"|"scc1", name) a branch to ("label", name).""" + labels, words, branches = {}, [], [] + for item in seq: + if isinstance(item, tuple) and item[0] == "label": + labels[item[1]] = len(words) + elif item == "null" or isinstance(item, tuple): + branches.append((len(words), item)) + words.append(0) + else: + words.append(item) + for at, item in branches: + # The colour export (two words) and s_endpgm follow the program; EXP_NULL comes after them. + target = len(words) + 3 if item == "null" else labels[item[1]] + opcode = 0xBF850000 if item != "null" and item[0] == "scc1" else 0xBF880000 + words[at] = opcode | (target - (at + 1)) + return patched_pixel(len(words), words, input_address=1 << 8, + input_signature=((b"ISG1", signature(b"SV_Position", 1)), + (b"OSG1", signature(b"SV_Target", 64))), + export=(0xF800180F, 0x02020202), tail=NULL_DONE_VM if "null" in seq else ()) + + +def armed(x, value=1.0, otherwise=2.0): + return value if 3.0 < x else otherwise + + +# (label, guest words, colour(x), kept(x) or None, colour with the arm's values swapped or None) +CASES = ( + ("kill-lt", program([*cmpx(LT, 3.0), vmove(2, ONE)]), lambda x: 1.0, lambda x: 3.0 < x, None), + ("kill-gt-execz-null", program([*cmpx(GT, 6.0), "null", vmove(2, ONE)]), lambda x: 1.0, lambda x: x < 6.0, None), + # VOP3 v_cmpx_gt_f32 -4.0, -v0 keeps 4 < x. + ("kill-e64-neg", program([0xD414007E, 247 | 256 << 9 | 2 << 29, vmove(2, ONE)]), + lambda x: 1.0, lambda x: 4.0 < x, None), + # A #3815 if/else first, then the kill and its skip: the shader has three branches. + ("if-else-then-kill-ge", program([vmove(2, TWO), sop1(4, 4, 126), *cmpx(LT, 3.0), ("execz", "else"), vmove(2, ONE), + ("label", "else"), sop2(21, 126, 4, 126), ("execz", "join"), vmove(2, HALF), + ("label", "join"), sop1(4, 126, 4), *cmpx(GE, 6.0), "null"]), + lambda x: armed(x, 1.0, 0.5), lambda x: x <= 6.0, lambda x: armed(x, 0.5, 1.0)), + ("coverage-exec-first", program([*ENTRY, vmove(2, ONE), and_exec(4)]), lambda x: 1.0, None, None), + ("coverage-pair-first", program([*ENTRY, vmove(2, ONE), and_exec(4, False)]), lambda x: 1.0, None, None), + # Exact coverage, then the kill; a compare and select after it still follow the lane's own bit. + ("coverage-then-kill", program([*ENTRY, vmove(2, ONE), and_exec(4), *cmpx(GT, 6.0), 0x7C0200FF, bits(5.0), + vmove(3, HALF), 0x02000000 | 2 << 17 | 3 << 9 | 258]), + lambda x: 0.5 if 5.0 < x else 1.0, lambda x: x < 6.0, None), + ("coverage-pair-first-then-kill-eq", program([*ENTRY, vmove(2, ONE), and_exec(4, False), *cmpx(EQ, 2.5)]), + lambda x: 1.0, lambda x: x == 2.5, None), + # A uniform branch (taken: 0 == 0) before the coverage AND; the AND is where every path meets. + ("uniform-branch-then-coverage-kill", program([*ENTRY, vmove(2, TWO), UNIFORM_TRUE, ("scc1", "end"), + vmove(2, HALF), ("label", "end"), and_exec(4), *cmpx(GT, 6.0)]), + lambda x: 2.0, lambda x: x < 6.0, None), + ("wqm-kill-then-coverage", program([*ENTRY, vmove(2, ONE), *cmpx(GT, 6.0), "null", and_exec(4)]), + lambda x: 1.0, lambda x: x < 6.0, None), + ("wqm-kill-skips-to-coverage", program([*ENTRY, vmove(2, TWO), *cmpx(LE, 5.5), ("execz", "exact"), vmove(2, ONE), + ("label", "exact"), and_exec(4)]), + lambda x: 1.0, lambda x: x >= 5.5, None), + ("arm-then-coverage", program([*ENTRY, vmove(2, TWO), *arm([vmove(2, ONE)]), and_exec(4)]), + armed, None, lambda x: armed(x, 2.0, 1.0)), + ("arm-restores-coverage", program([*ENTRY, vmove(2, TWO), *arm([vmove(2, ONE)], save=None, restore=4)]), + armed, None, lambda x: armed(x, 2.0, 1.0)), + ("kill-arm-coverage", program([*ENTRY, vmove(2, TWO), *cmpx(GT, 6.0), "null", *arm([vmove(2, ONE)]), + and_exec(4)]), + armed, lambda x: x < 6.0, lambda x: armed(x, 2.0, 1.0)), + ("arm-coverage-kill", program([*ENTRY, vmove(2, TWO), *arm([vmove(2, ONE)]), and_exec(4), *cmpx(GT, 6.0), + "null"]), + armed, lambda x: x < 6.0, lambda x: armed(x, 2.0, 1.0)), + ("arm-restores-coverage-kill", program([*ENTRY, vmove(2, TWO), *arm([vmove(2, ONE)], save=None, restore=4), + *cmpx(GT, 6.0), "null"]), + armed, lambda x: x < 6.0, lambda x: armed(x, 2.0, 1.0)), +) + +KILL_REFUSAL = "graphics wave or control-flow instruction" +BRANCH_REFUSAL = "graphics branch on a wave mask" +REFUSALS = ( + # A valid-mask export before the compare has already delivered the lane. + ("export-before-kill", program([vmove(2, ONE), 0xF800100F, 0x02020202, *cmpx(LT, 3.0), vmove(2, HALF)]), + KILL_REFUSAL), + # After the kill a DXIL helper keeps computing where the guest lane stopped: no lane may read another. + ("dpp-after-kill", program([*ENTRY, *cmpx(GT, 6.0), vmove(3, 250), 0xFF00B100, vmove(2, 3), and_exec(4)]), + KILL_REFUSAL), + ("quad-swizzle-after-kill", program([*ENTRY, *cmpx(GT, 6.0), 0xD8D480B1, 0x03000000, vmove(2, 3), and_exec(4)]), + KILL_REFUSAL), + ("exec-read-after-kill", program([*cmpx(LT, 3.0), sop1(4, 20, 126), vmove(2, ONE)]), KILL_REFUSAL), + ("wqm-after-kill", program([sop1(4, 4, 126), *cmpx(GT, 6.0), WQM, vmove(2, ONE), and_exec(4)]), KILL_REFUSAL), + # Restoring a pair saved before the kill brings the killed lanes back. + ("restore-revives-killed-lanes", program([sop1(4, 6, 126), *cmpx(GT, 6.0), "null", vmove(2, ONE), + sop1(4, 126, 6)]), BRANCH_REFUSAL), + # A uniform branch into the kill's skip, or around the kill itself. + ("branch-into-kill", program([UNIFORM_TRUE, ("scc1", "skip"), *cmpx(GT, 6.0), ("label", "skip"), "null", + vmove(2, ONE)]), BRANCH_REFUSAL), + ("kill-under-uniform-branch", program([UNIFORM_TRUE, ("scc1", "after"), *cmpx(GT, 6.0), ("label", "after"), + vmove(2, ONE)]), "pixel lane kill is not on every path to the code after it"), + ("class-compare", program([*ENTRY, 0x7C000000 | 0x98 << 17 | 1 << 9 | 256, vmove(2, ONE), and_exec(4)]), + KILL_REFUSAL), + ("clamped-compare", program([0xD411807E, 246 | 256 << 9, vmove(2, ONE)]), KILL_REFUSAL), + # Coverage re-application needs the saved entry coverage, intact. + ("coverage-from-other-pair", program([*ENTRY, sop1(4, 8, 193), vmove(2, ONE), and_exec(8), *cmpx(GT, 6.0)]), + KILL_REFUSAL), + ("coverage-half-overwritten", program([*ENTRY, sop1(3, 5, 128), vmove(2, ONE), and_exec(4), *cmpx(GT, 6.0)]), + KILL_REFUSAL), + ("arm-restores-overwritten-coverage", program([*ENTRY, vmove(2, TWO), sop1(3, 4, 128), + *arm([vmove(2, ONE)], save=None, restore=4)]), BRANCH_REFUSAL), + # Exact coverage reached through the arm, then another branch: the exact mask would cross it. + ("arm-restores-coverage-before-branch", program([*ENTRY, vmove(2, TWO), *arm([vmove(2, ONE)], save=None, restore=4), + UNIFORM_TRUE, ("scc1", "end"), vmove(2, HALF), ("label", "end")]), + "CMPX arm restore to coverage requires"), + # Inside a uniform branch's arm the AND would leave whole-quad mode on one path only. + ("coverage-inside-uniform-branch", program([*ENTRY, vmove(2, TWO), UNIFORM_TRUE, ("scc1", "end"), and_exec(4), + vmove(2, HALF), ("label", "end"), *cmpx(GT, 6.0)]), KILL_REFUSAL), + # With an earlier s_endpgm, the second exit arm is not a unique post-dominating tail: leaving WQM there + # could run before the first arm in topological order and leak exact-mode state across sibling blocks. + ("coverage-after-early-endpgm", program([*ENTRY, vmove(2, TWO), UNIFORM_TRUE, ("scc1", "arm2"), + 0xF800180F, 0x02020202, 0xBF810000, ("label", "arm2"), + and_exec(4), vmove(2, ONE), *cmpx(GT, 6.0)]), KILL_REFUSAL), +) + + +def reference(colour, kept=None): + return [(colour(x + 0.5),) * 4 if kept is None or kept(x + 0.5) else CLEAR for _ in range(2) for x in range(8)] + + +def main(cli, raster, sdk, backend="controls"): + with TemporaryDirectory() as tmp: + work = Path(tmp) + source, vs, ps = work / "source", work / "vs.cso", work / "ps.cso" + + def compile_guest(blob): + ps.unlink(missing_ok=True) + source.write_bytes(blob) + return subprocess.run([cli, sdk, work / "cache", "gfx1013-container-ps", source, ps], + capture_output=True, text=True) + + for label, blob, _, kept, swapped in CASES: + result = compile_guest(blob) + assert result.returncode == 0, (label, result.stdout, result.stderr) + dump = subprocess.check_output([Path(sdk) / "dxc.exe", "-dumpbin", ps], text=True) + # A kill is one discard of the failing lanes. Every EXECZ shortcut is gone: only an arm or the + # uniform branch still branches. + assert dump.count("call void @dx.op.discard(i32 82") == (kept is not None), (label, dump) + assert ("br i1" in dump) == (swapped is not None or label.startswith("uniform-")), (label, dump) + assert "@dx.op.wave" not in dump and "@dx.op.quadOp" not in dump, (label, dump) + print(f"translated: {label}: ok") + for label, blob, reason in REFUSALS: + result = compile_guest(blob) + assert result.returncode and reason in result.stderr and not ps.exists(), \ + (label, result.stdout, result.stderr) + print(f"refused: {label}: ok") + if backend == "controls": + return + + source.write_text(VERTEX["full"]) + subprocess.run([Path(sdk) / "dxc.exe", "-T", "vs_6_6", "-Fo", vs, source], check=True) + + def draw(blob, pixels): + result = compile_guest(blob) + assert not result.returncode, result.stderr + expected = work / "expected.bin" + expected.write_bytes(b"".join(struct.pack("<4f", *pixel) for pixel in pixels)) + result = subprocess.run([raster, backend, "--startup-pixel-words", vs, ps, "8", "2", expected], + capture_output=True, text=True) + if result.returncode == 77: + sys.exit(77) + return result + + for label, blob, colour, kept, swapped in CASES: + result = draw(blob, reference(colour, kept)) + assert result.returncode == 0, (label, result.stdout, result.stderr) + wrong = [] + if kept is not None: + wrong += [("nothing-killed", reference(colour)), + ("opposite-killed", reference(colour, lambda x, k=kept: not k(x)))] + if swapped is not None: + wrong.append(("arm-swapped", reference(swapped, kept))) + if not wrong: + wrong.append(("all-clear", reference(colour, lambda x: False))) + for name, pixels in wrong: + result = draw(blob, pixels) + assert result.returncode not in (0, 77), (label, name, result.stdout, result.stderr) + print(f"draw: {label}: ok ({', '.join(name for name, _ in wrong)} differ)") + + # Every lane fails the kill: the whole target keeps the clear value, with and without the skip. + for label, blob in (("all-killed", program([*cmpx(GT, -100.0), vmove(2, ONE)])), + ("all-killed-wqm-execz-null", program([*ENTRY, vmove(2, ONE), *cmpx(GT, -100.0), "null", + and_exec(4)]))): + result = draw(blob, reference(lambda x: 1.0, lambda x: False)) + assert result.returncode == 0, (label, result.stdout, result.stderr) + print(f"draw: {label}: ok") + + +if __name__ == "__main__": + main(*sys.argv[1:])