From 9c09a6749b246c3f86e9eba6dc4b6129444585cb Mon Sep 17 00:00:00 2001 From: hamdog0203 <360416966+hamdog0203@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:32:44 +0100 Subject: [PATCH] spirv_metal_set0: synthesize uint, retype helper calls, expand decoration groups, and capture spirv-as stderr (SHADER-METAL-SET0-FIX) --- tests/test_spirv_metal_set0.py | 281 +++++++++++++++++++++++++++++++++ tools/spirv_metal_set0.py | 190 +++++++++++++++++++--- 2 files changed, 447 insertions(+), 24 deletions(-) diff --git a/tests/test_spirv_metal_set0.py b/tests/test_spirv_metal_set0.py index 099298c15..cd22613ec 100644 --- a/tests/test_spirv_metal_set0.py +++ b/tests/test_spirv_metal_set0.py @@ -178,3 +178,284 @@ def test_cli_retypes_descriptor_array_copies(tmp_path, resource, binding, depth) foreign_type = definitions["%foreign_samplers"][1] assert definitions[definitions[foreign_type][2]][0] == "OpTypeRuntimeArray" assert definitions["%foreign_copy"] == ["OpCopyObject", foreign_type, "%foreign_samplers"] + + +def _assemble_rewrite_and_validate(tmp_path, assembly): + src, dst = tmp_path / "input.spv", tmp_path / "metal.spv" + target = ["--target-env", "vulkan1.2"] + subprocess.run(["spirv-as", *target, "-", "-o", str(src)], input=assembly, text=True, + encoding="utf-8", check=True) + subprocess.run(["spirv-val", *target, str(src)], check=True) + assert m.main(["spirv_metal_set0.py", str(src), str(dst)]) == 0 + subprocess.run(["spirv-val", *target, str(dst)], check=True) + return subprocess.check_output(["spirv-dis", str(dst)], text=True, encoding="utf-8") + + +@pytest.mark.skipif(not all(shutil.which(tool) for tool in ("spirv-as", "spirv-dis", "spirv-val")), + reason="needs SPIRV-Tools on PATH") +def test_synthesizes_uint_type_when_module_only_uses_signed_int(tmp_path): + signed_module = ( + SAMPLE_FRAGMENT + .replace("%uint = OpTypeInt 32 0", "%int = OpTypeInt 32 1") + .replace("%zero = OpConstant %uint 0", "%zero = OpConstant %int 0") + ) + text = _assemble_rewrite_and_validate(tmp_path, signed_module) + definitions = {parts[0]: parts[2:] for parts in map(str.split, text.splitlines()) + if len(parts) > 2 and parts[1] == "="} + arr_id = definitions[definitions["%images"][1]][2] + assert definitions[arr_id][0] == "OpTypeArray" + cap_id = definitions[arr_id][2] + assert definitions[definitions[cap_id][1]] == ["OpTypeInt", "32", "0"] + assert text.index("= OpTypeInt 32 0") < text.index(f"{cap_id} = OpConstant") + + +@pytest.mark.skipif(not all(shutil.which(tool) for tool in ("spirv-as", "spirv-dis", "spirv-val")), + reason="needs SPIRV-Tools on PATH") +def test_retypes_helper_function_parameters_and_nested_calls(tmp_path): + assembly = """\ +OpCapability Shader +OpCapability RuntimeDescriptorArray +OpExtension "SPV_EXT_descriptor_indexing" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %images %samplers %foreign_samplers %color +OpExecutionMode %main OriginUpperLeft +OpName %images "images" +OpName %samplers "samplers" +OpName %foreign_samplers "foreign_samplers" +OpName %loc_smp "loc_smp" +OpName %loc_smp_copy "loc_smp_copy" +OpName %in_sp_arr "in_sp_arr" +OpName %for_smp "for_smp" +OpDecorate %images DescriptorSet 0 +OpDecorate %images Binding 0 +OpDecorate %samplers DescriptorSet 0 +OpDecorate %samplers Binding 1 +OpDecorate %foreign_samplers DescriptorSet 1 +OpDecorate %foreign_samplers Binding 1 +OpDecorate %color Location 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%float = OpTypeFloat 32 +%v2f = OpTypeVector %float 2 +%v4f = OpTypeVector %float 4 +%image = OpTypeImage %float 2D 0 0 0 1 Unknown +%smp = OpTypeSampler +%sampled = OpTypeSampledImage %image +%image_array = OpTypeRuntimeArray %image +%sampler_array = OpTypeRuntimeArray %smp +%images_ptr = OpTypePointer UniformConstant %image_array +%samplers_ptr = OpTypePointer UniformConstant %sampler_array +%image_ptr = OpTypePointer UniformConstant %image +%sampler_ptr = OpTypePointer UniformConstant %smp +%color_ptr = OpTypePointer Output %v4f +%smp_helper_ty = OpTypeFunction %v4f %image_ptr %samplers_ptr +%helper_ty = OpTypeFunction %v4f %samplers_ptr +%zero = OpConstant %uint 0 +%half = OpConstant %float 0.5 +%uv = OpConstantComposite %v2f %half %half +%images = OpVariable %images_ptr UniformConstant +%samplers = OpVariable %samplers_ptr UniformConstant +%foreign_samplers = OpVariable %samplers_ptr UniformConstant +%color = OpVariable %color_ptr Output +%inner_sample = OpFunction %v4f None %smp_helper_ty +%in_ip = OpFunctionParameter %image_ptr +%in_sp_arr = OpFunctionParameter %samplers_ptr +%inner_bb = OpLabel +%i0 = OpLoad %image %in_ip +%sp0 = OpAccessChain %sampler_ptr %in_sp_arr %zero +%s0 = OpLoad %smp %sp0 +%tex0 = OpSampledImage %sampled %i0 %s0 +%r0 = OpImageSampleImplicitLod %v4f %tex0 %uv +OpReturnValue %r0 +OpFunctionEnd +%helper_local = OpFunction %v4f None %helper_ty +%loc_smp = OpFunctionParameter %samplers_ptr +%hl_bb = OpLabel +%loc_smp_copy = OpCopyObject %samplers_ptr %loc_smp +%loc_ip = OpAccessChain %image_ptr %images %zero +%r1 = OpFunctionCall %v4f %inner_sample %loc_ip %loc_smp_copy +OpReturnValue %r1 +OpFunctionEnd +%helper_foreign = OpFunction %v4f None %helper_ty +%for_smp = OpFunctionParameter %samplers_ptr +%hf_bb = OpLabel +%for_ip = OpAccessChain %image_ptr %images %zero +%for_sp = OpAccessChain %sampler_ptr %for_smp %zero +%i1 = OpLoad %image %for_ip +%s1 = OpLoad %smp %for_sp +%tex1 = OpSampledImage %sampled %i1 %s1 +%r2 = OpImageSampleImplicitLod %v4f %tex1 %uv +OpReturnValue %r2 +OpFunctionEnd +%main = OpFunction %void None %fn +%entry = OpLabel +%a = OpFunctionCall %v4f %helper_local %samplers +%b = OpFunctionCall %v4f %helper_foreign %foreign_samplers +%rgba = OpFAdd %v4f %a %b +OpStore %color %rgba +OpReturn +OpFunctionEnd +""" + text = _assemble_rewrite_and_validate(tmp_path, assembly) + definitions = {parts[0]: parts[2:] for parts in map(str.split, text.splitlines()) + if len(parts) > 2 and parts[1] == "="} + resized_smp_ptr = definitions["%samplers"][1] + assert definitions[definitions[resized_smp_ptr][2]][0] == "OpTypeArray" + assert definitions["%loc_smp"] == ["OpFunctionParameter", resized_smp_ptr] + assert definitions["%loc_smp_copy"] == ["OpCopyObject", resized_smp_ptr, "%loc_smp"] + assert definitions["%in_sp_arr"] == ["OpFunctionParameter", resized_smp_ptr] + foreign_smp_ptr = definitions["%foreign_samplers"][1] + assert definitions[definitions[foreign_smp_ptr][2]][0] == "OpTypeRuntimeArray" + assert definitions["%for_smp"] == ["OpFunctionParameter", foreign_smp_ptr] + + +def test_rejects_helper_called_with_conflicting_pointer_types(): + dis = """\ + OpDecorate %samplers DescriptorSet 0 + OpDecorate %samplers Binding 1 + OpDecorate %foreign_samplers DescriptorSet 1 + OpDecorate %foreign_samplers Binding 1 + %void = OpTypeVoid + %uint = OpTypeInt 32 0 + %float = OpTypeFloat 32 + %smp = OpTypeSampler + %rt_smp = OpTypeRuntimeArray %smp + %ptr_smp = OpTypePointer UniformConstant %rt_smp + %fn_ty = OpTypeFunction %void %ptr_smp + %samplers = OpVariable %ptr_smp UniformConstant +%foreign_samplers = OpVariable %ptr_smp UniformConstant + %helper = OpFunction %void None %fn_ty + %p_smp = OpFunctionParameter %ptr_smp + %bb = OpLabel + OpReturn + OpFunctionEnd + %main = OpFunction %void None %fn_ty + %entry = OpLabel + %c1 = OpFunctionCall %void %helper %samplers + %c2 = OpFunctionCall %void %helper %foreign_samplers + OpReturn + OpFunctionEnd +""" + with pytest.raises(SystemExit, match="conflicting descriptor array types"): + m.rewrite(dis, m.capacities()) + + +@pytest.mark.skipif(not all(shutil.which(tool) for tool in ("spirv-as", "spirv-dis", "spirv-val")), + reason="needs SPIRV-Tools on PATH") +def test_rewrites_set0_variables_decorated_via_decoration_group(tmp_path): + assembly = """\ +OpCapability Shader +OpCapability RuntimeDescriptorArray +OpExtension "SPV_EXT_descriptor_indexing" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %images %samplers %foreign_samplers %color +OpExecutionMode %main OriginUpperLeft +OpName %images "images" +OpName %samplers "samplers" +OpName %foreign_samplers "foreign_samplers" +OpDecorate %set0_grp DescriptorSet 0 +OpDecorate %shared_b1_grp Binding 1 +OpDecorate %images Binding 0 +OpDecorate %foreign_samplers DescriptorSet 1 +OpDecorate %color Location 0 +%set0_grp = OpDecorationGroup +%shared_b1_grp = OpDecorationGroup +OpGroupDecorate %set0_grp %images %samplers +OpGroupDecorate %shared_b1_grp %samplers %foreign_samplers +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%float = OpTypeFloat 32 +%v2f = OpTypeVector %float 2 +%v4f = OpTypeVector %float 4 +%image = OpTypeImage %float 2D 0 0 0 1 Unknown +%smp = OpTypeSampler +%sampled = OpTypeSampledImage %image +%image_array = OpTypeRuntimeArray %image +%sampler_array = OpTypeRuntimeArray %smp +%images_ptr = OpTypePointer UniformConstant %image_array +%samplers_ptr = OpTypePointer UniformConstant %sampler_array +%image_ptr = OpTypePointer UniformConstant %image +%sampler_ptr = OpTypePointer UniformConstant %smp +%color_ptr = OpTypePointer Output %v4f +%zero = OpConstant %uint 0 +%half = OpConstant %float 0.5 +%uv = OpConstantComposite %v2f %half %half +%images = OpVariable %images_ptr UniformConstant +%samplers = OpVariable %samplers_ptr UniformConstant +%foreign_samplers = OpVariable %samplers_ptr UniformConstant +%color = OpVariable %color_ptr Output +%main = OpFunction %void None %fn +%entry = OpLabel +%ip = OpAccessChain %image_ptr %images %zero +%sp = OpAccessChain %sampler_ptr %samplers %zero +%fp = OpAccessChain %sampler_ptr %foreign_samplers %zero +%i = OpLoad %image %ip +%s = OpLoad %smp %sp +%f = OpLoad %smp %fp +%t0 = OpSampledImage %sampled %i %s +%t1 = OpSampledImage %sampled %i %f +%a = OpImageSampleImplicitLod %v4f %t0 %uv +%b = OpImageSampleImplicitLod %v4f %t1 %uv +%rgba = OpFAdd %v4f %a %b +OpStore %color %rgba +OpReturn +OpFunctionEnd +""" + text = _assemble_rewrite_and_validate(tmp_path, assembly) + assert "OpDecorate %images Binding 0" in text + assert "OpDecorate %samplers Binding 4096" in text + assert "OpDecorate %foreign_samplers Binding 1" in text + definitions = {parts[0]: parts[2:] for parts in map(str.split, text.splitlines()) + if len(parts) > 2 and parts[1] == "="} + assert definitions[definitions[definitions["%images"][1]][2]][0] == "OpTypeArray" + assert definitions[definitions[definitions["%samplers"][1]][2]][0] == "OpTypeArray" + assert definitions[definitions[definitions["%foreign_samplers"][1]][2]][0] == "OpTypeRuntimeArray" + + +def test_rejects_retyped_pointer_in_phi_or_select(): + base = """\ + OpDecorate %samplers DescriptorSet 0 + OpDecorate %samplers Binding 1 + %bool = OpTypeBool + %void = OpTypeVoid + %uint = OpTypeInt 32 0 + %smp = OpTypeSampler + %rt_smp = OpTypeRuntimeArray %smp + %ptr_smp = OpTypePointer UniformConstant %rt_smp + %true = OpConstantTrue %bool + %samplers = OpVariable %ptr_smp UniformConstant +""" + phi_dis = base + " %phi = OpPhi %ptr_smp %samplers %entry\n" + sel_dis = base + " %sel = OpSelect %ptr_smp %true %samplers %samplers\n" + with pytest.raises(SystemExit, match="OpPhi"): + m.rewrite(phi_dis, m.capacities()) + with pytest.raises(SystemExit, match="OpSelect"): + m.rewrite(sel_dis, m.capacities()) + + +def test_cli_captures_spirv_as_stderr(tmp_path, capsys, monkeypatch): + src, dst = tmp_path / "in.spv", tmp_path / "out.spv" + src.write_bytes(b"") + + def fake_run(cmd, **kwargs): + if cmd[0] == "spirv-dis": + return subprocess.CompletedProcess(cmd, 0, stdout=MODULE, stderr="") + assert kwargs.get("capture_output") is True + assert kwargs.get("encoding") == "utf-8" + raise subprocess.CalledProcessError(1, cmd, stderr="error: line 9: mock spirv-as failure\n") + + monkeypatch.setattr(m, "_tools", lambda: ("spirv-dis", "spirv-as")) + monkeypatch.setattr(m, "_run", fake_run) + rc = m.cli(["spirv_metal_set0.py", str(src), str(dst)]) + assert rc == 1 + assert "mock spirv-as failure" in capsys.readouterr().err + + +@pytest.mark.skipif(not all(shutil.which(tool) for tool in ("spirv-as", "spirv-dis", "spirv-val")), + reason="needs SPIRV-Tools on PATH") +def test_cli_preserves_utf8_opnames(tmp_path): + assembly = SAMPLE_FRAGMENT.replace('OpName %images "images"', 'OpName %images "Schlüssel_αβγ"') + text = _assemble_rewrite_and_validate(tmp_path, assembly) + assert "Schlüssel_αβγ" in text diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py index 6d64b21dc..db331ab6d 100644 --- a/tools/spirv_metal_set0.py +++ b/tools/spirv_metal_set0.py @@ -63,19 +63,52 @@ def rewrite(text, counts): """Rewrite the disassembly (spirv-dis --raw-id is not needed; names are kept) of one module.""" ids = metal_ids(counts) lines = text.splitlines() - sets, binds = {}, {} + group_ids = set() + group_targets = {} + for ln in lines: + m = re.match(r"\s*(%\S+) = OpDecorationGroup$", ln) + if m: + group_ids.add(m.group(1)) + m = re.match(r"\s*OpGroupDecorate (%\S+)\s+(.+)$", ln) + if m: + group_targets.setdefault(m.group(1), []).extend(m.group(2).split()) + + direct_sets, direct_binds = {}, {} for ln in lines: m = re.match(r"\s*OpDecorate (%\S+) DescriptorSet (\d+)$", ln) if m: - sets[m.group(1)] = int(m.group(2)) + direct_sets[m.group(1)] = int(m.group(2)) m = re.match(r"\s*OpDecorate (%\S+) Binding (\d+)$", ln) if m: - binds[m.group(1)] = int(m.group(2)) + direct_binds[m.group(1)] = int(m.group(2)) + + sets = {k: v for k, v in direct_sets.items() if k not in group_ids} + binds = {k: v for k, v in direct_binds.items() if k not in group_ids} + for grp in group_ids: + for target in group_targets.get(grp, ()): + if grp in direct_sets: + sets[target] = direct_sets[grp] + if grp in direct_binds: + binds[target] = direct_binds[grp] + set0 = {v: b for v, b in binds.items() if sets.get(v) == 0} for v, b in set0.items(): if b >= len(counts): raise SystemExit(f"{v}: binding {b} isn't in vulkan_bindless.h") + all_set0_bind_groups = set() + split_bind_groups = set() + for grp in group_ids: + if grp not in direct_binds: + continue + targets = group_targets.get(grp, ()) + has_set0 = any(t in set0 for t in targets) + has_other = any(t not in set0 for t in targets) + if has_set0 and has_other: + split_bind_groups.add(grp) + elif has_set0: + all_set0_bind_groups.add(grp) + defs = {} # result id -> instruction text definition_positions: dict[str, int] = {} for idx, ln in enumerate(lines): @@ -97,20 +130,22 @@ def rewrite(text, counts): continue candidates.append((b, definition_positions[old_ptr], order, v, old_ptr, rt.group(1))) + used_ids = set(re.findall(r"%\S+", text)) if candidates: - if uint is None: - raise SystemExit("module has no 32-bit uint type for the array lengths") first_pointer = min(candidate[1] for candidate in candidates) - uint_position = definition_positions[uint] - if uint_position > first_pointer: - # The generated length may precede an original declaration of its integer type. - lines.insert(first_pointer, lines.pop(uint_position)) + if uint is None: + uint = _fresh_id("%msl_uint", used_ids) + lines.insert(first_pointer, f"{uint} = OpTypeInt 32 0") + else: + uint_position = definition_positions[uint] + if uint_position > first_pointer: + # The generated length may precede an original declaration of its integer type. + lines.insert(first_pointer, lines.pop(uint_position)) - used_ids = set(defs) | set(sets) | set(binds) cap_by_bind = {} # binding -> OpConstant id (emitted once per binding) ptr_by_key = {} # (binding, elem_type) -> new OpTypePointer id new_types = [] # inserted right after the variable's pointer type is declared - retype = {} # resized variable or copied pointer ID -> new pointer type + retype = {} # resized variable, copy, or helper param ID -> new pointer type for b, _, _, v, old_ptr, elem in sorted(candidates): if (b, elem) in ptr_by_key: retype[v] = ptr_by_key[(b, elem)] @@ -131,26 +166,132 @@ def rewrite(text, counts): ptr_by_key[(b, elem)] = nptr retype[v] = nptr + fn_type_defs = {} + for tid, body in defs.items(): + m = re.match(r"OpTypeFunction\s+(%\S+)(.*)$", body) + if m: + fn_type_defs[tid] = (m.group(1), tuple(m.group(2).split())) + + fn_info = {} + cur_fn = None + for ln in lines: + m = re.match(r"\s*(%\S+) = OpFunction (%\S+) (\S+) (%\S+)$", ln) + if m: + fn_id, ret_ty, ctrl, fn_ty = m.groups() + cur_fn = fn_id + fn_info[fn_id] = {"ret": ret_ty, "ctrl": ctrl, "fn_ty": fn_ty, "params": []} + continue + m = re.match(r"\s*(%\S+) = OpFunctionParameter (%\S+)$", ln) + if m and cur_fn is not None: + fn_info[cur_fn]["params"].append((m.group(1), m.group(2))) + continue + if cur_fn is not None and not ln.strip().startswith(";"): + cur_fn = None + + copies = [] + calls = [] + for ln in lines: + m = re.match(r"\s*(%\S+) = OpCopyObject (%\S+) (%\S+)$", ln) + if m: + copies.append(m.groups()) + continue + m = re.match(r"\s*(%\S+) = OpFunctionCall (%\S+) (%\S+)(.*)$", ln) + if m: + res_id, ret_ty, callee_id, rest_args = m.groups() + calls.append((res_id, ret_ty, callee_id, rest_args.split())) + + # Phase 1: converge retyped pointer IDs across OpCopyObject and OpFunctionCall. + changed = True + while changed: + changed = False + for res_id, _, src_id in copies: + if src_id in retype and res_id not in retype: + retype[res_id] = retype[src_id] + changed = True + for _, _, callee_id, args in calls: + info = fn_info.get(callee_id) + if not info: + continue + for (p_id, _), arg_id in zip(info["params"], args): + if arg_id in retype and p_id not in retype: + retype[p_id] = retype[arg_id] + changed = True + + # Phase 2: ensure every call site passes a consistent pointer type for each parameter. + for _, _, callee_id, args in calls: + info = fn_info.get(callee_id) + if not info: + continue + for idx, ((p_id, p_ty), arg_id) in enumerate(zip(info["params"], args)): + expected_ty = retype.get(p_id, p_ty) + actual_ty = retype.get(arg_id, p_ty) + if actual_ty != expected_ty: + raise SystemExit( + f"{callee_id}: parameter {idx} ({p_id}) called with conflicting descriptor array types" + ) + + for ln in lines: + m = re.match(r"\s*(%\S+) = (OpPhi|OpSelect)\s+(%\S+)\s+(.+)$", ln) + if m: + res_id, opname, _, operands_str = m.groups() + if res_id in retype or any(tok in retype for tok in operands_str.split()): + raise SystemExit(f"{res_id}: {opname} of resized descriptor pointer is not supported") + + fn_retype = {} + fn_type_by_key = {} + new_fn_types = [] + for fn_id, info in fn_info.items(): + if not any(p_id in retype for p_id, _ in info["params"]): + continue + old_fn_ty = info["fn_ty"] + ret_ty, _ = fn_type_defs[old_fn_ty] + new_param_tys = tuple(retype.get(p_id, p_ty) for p_id, p_ty in info["params"]) + key = (old_fn_ty, new_param_tys) + new_fn_ty = fn_type_by_key.get(key) + if new_fn_ty is None: + new_fn_ty = _fresh_id(f"%msl_fn_{fn_id.lstrip('%')}", used_ids) + fn_type_by_key[key] = new_fn_ty + ops = " ".join((ret_ty, *new_param_tys)) + new_fn_types.append((old_fn_ty, f"{new_fn_ty} = OpTypeFunction {ops}")) + fn_retype[fn_id] = new_fn_ty + out = [] for ln in lines: - m = re.match(r"(\s*OpDecorate (%\S+) Binding )(\d+)$", ln) - if m and m.group(2) in set0: - ln = f"{m.group(1)}{ids[int(m.group(3))]}" + m = re.match(r"^(\s*)OpDecorate (%\S+) Binding (\d+)$", ln) + if m: + indent, target, b_str = m.groups() + if target in split_bind_groups: + b_val = int(b_str) + for grp_target in group_targets[target]: + mapped = ids[b_val] if grp_target in set0 else b_val + out.append(f"{indent}OpDecorate {grp_target} Binding {mapped}") + continue + if target in set0 or target in all_set0_bind_groups: + ln = f"{indent}OpDecorate {target} Binding {ids[int(b_str)]}" m = re.match(r"(\s*(%\S+) = OpVariable )(%\S+)( UniformConstant)$", ln) if m and m.group(2) in retype: ln = f"{m.group(1)}{retype[m.group(2)]}{m.group(4)}" - # Retype copies by source ID so arrays sharing a type in other sets are unaffected. - m = re.match(r"(\s*(%\S+) = OpCopyObject )%\S+ (%\S+)$", ln) - if m and m.group(3) in retype: - ptr = retype[m.group(3)] - retype[m.group(2)] = ptr - ln = f"{m.group(1)}{ptr} {m.group(3)}" + # Retype copies by precomputed result ID so out-of-order blocks and helpers stay consistent. + m = re.match(r"(\s*(%\S+) = OpCopyObject )%\S+( %\S+)$", ln) + if m and m.group(2) in retype: + ln = f"{m.group(1)}{retype[m.group(2)]}{m.group(3)}" + m = re.match(r"(\s*(%\S+) = OpFunction %\S+ \S+ )%\S+$", ln) + if m and m.group(2) in fn_retype: + ln = f"{m.group(1)}{fn_retype[m.group(2)]}" + m = re.match(r"(\s*(%\S+) = OpFunctionParameter )%\S+$", ln) + if m and m.group(2) in retype: + ln = f"{m.group(1)}{retype[m.group(2)]}" out.append(ln) m = re.match(r"\s*(%\S+) = OpTypePointer", ln) if m: for after, decl in new_types: if after == m.group(1): out.extend(decl) + m = re.match(r"\s*(%\S+) = OpTypeFunction", ln) + if m: + for after, decl_line in new_fn_types: + if after == m.group(1): + out.append(decl_line) return "\n".join(out) + "\n" @@ -169,12 +310,13 @@ def main(argv): print(__doc__.strip().splitlines()[-2], file=sys.stderr) return 2 dis, asm = _tools() - # errors="replace": on Windows text=True decodes with the ANSI code page, and a program that answers in UTF-8 - # (a path with non-ASCII letters in its error message) would otherwise kill the reader thread and lose stderr. - text = _run([dis, argv[1]], capture_output=True, text=True, errors="replace").stdout + # encoding="utf-8", errors="replace": keep non-ASCII OpNames intact across Windows code pages while + # staying safe on unexpected invalid bytes from external tools. + text = _run([dis, argv[1]], capture_output=True, text=True, encoding="utf-8", errors="replace").stdout env = re.search(r"; Version: (\d+)\.(\d+)", text) target = f"spv{env.group(1)}.{env.group(2)}" if env else "vulkan1.2" - _run([asm, "--target-env", target, "-", "-o", argv[2]], input=rewrite(text, counts), text=True) + _run([asm, "--target-env", target, "-", "-o", argv[2]], input=rewrite(text, counts), + capture_output=True, text=True, encoding="utf-8", errors="replace") return 0