A pixel shader's readable-tile version is cut from its one compile, and every extra entry point calls main0's one body: Mario Kart 8 Deluxe's cold Mac shader build 22:46 to 14:47 and Super Mario Odyssey's 30:02 to 22:23 on an M2 (PR #1520)

The readable-tile version <key>_bf was a source and a Metal compile of its own (13,666 of Mario Kart 8 Deluxe's 29,651 shaders), and main0_u / main0_m (fs_uint) and main0_d (fs_dual) were each a copy of main0's body, built again for each (4,990 of Pokémon Legends: Arceus's 6,160 pixel shaders have main0_u).

- dmsh_side.shared_body makes main0's body one always_inline dm_body_main0; main0, main0_u, main0_m and main0_d call it.
- dmsh_fetch.fold rewrites the samples in that body alone, with fx_i and fb0-fb7 as its parameters, and adds main0_f; every other caller passes -1 and zeros, which the inlined body folds back, so main0 declares no function constants. Rewriting a copy elsewhere would not build (no fb_k there).
- ps_libraries cuts <key>_b, <key>_bx and <key>_bf from the one compile (dmsh_side.cut with groups, compile_split with a list). A folded unit that does not build is compiled again without main0_f, so its alpha test and logic operation entry points stay; each step down prints a red line.
- The host's bf_fn specializes main0_f.
- metal and metallib are found once and run with -isysroot: the same .air and .metallib bytes as xcrun -sdk macosx. MAC_RECORD and the Metal cache format are unchanged, so unchanged MSL keeps its cached compiles.
- dmsh_side.py is in the shader cache key (CODE_FP); Metal cache prefill skips libraries cut with a _bf; the separate variant cache is gone.

Measured: Metal CPU on 60 of Odyssey's pixel shaders 0.53x (readable-tile) and 0.64x (integer only), main0's bitcode 5.7% smaller at the median. Partial cold builds of the same shaders on chain 3ee493b2c3a4 and this one: Arceus 239 in 24 to 18 s, Metroid Prime Remastered 182 in 26 to 19 s, every shader with the same libraries, entry points and reflections (MPR's ab809a7456f59614 has main0_d and main0_f). check_t_feedback, check_t_alpha, check_t_logic and the gfx run pass. No game run: a boot needs both chains' full libraries.

Also: test_shader_toolchain_cache lists partner_inputs, which vs_pad calls since main's vs_pad change.

Chain 1d619d0f520b.

Co-authored-by: Alexandre Melo <[email protected]>
This commit is contained in:
seeddsandAlexandre Melo committed 2026-11-07 19:59:55 +08:00
1 parent 2bd920a9ef
commit c8bfa161b6
18 files changed
+435 -232

No files matched your search

+1
View File
@@ -83,6 +83,7 @@ General host and tool changes first needed here; each applies to every game:
- **Small host segments for small grants** (`hostseg_size`): [Host-lent command memory segments](../../../docs/reference/nvn-objects.md#host-lent-command-memory-segments).
- **Shorter state and single texture bind records** (`bind_state`, `p_bind_tex1`): [Model heaps sized by the host's command record sizes](../../../docs/reference/memory.md#model-heaps-sized-by-the-hosts-command-record-sizes); the null-pool grants they caused: [Host-lent command memory segments](../../../docs/reference/nvn-objects.md#host-lent-command-memory-segments).
- **Same-pass feedback snapshots without a per-game list** (a draw that writes the attachment it samples; one snapshot until the game's next barrier): [Same-pass feedback read through a snapshot](../../../docs/reference/rendering.md#same-pass-feedback-read-through-a-snapshot).
- **Cold Mac Metal shader builds:** [Cold Mac shader builds compile each pixel shader more than once](../../../docs/reference/shaders.md#cold-mac-shader-builds-compile-each-pixel-shader-more-than-once). Apple M2, `J=8`, no keys, `own_compilers`: 30:02 (1802 s) to 22:23 (1343.26 s), 1.34×.
## Open
+1
View File
@@ -76,6 +76,7 @@ General host changes first needed here; each applies to every game:
- **The Mii database and the MiiModel stand-in** (`hle_mii.c`, `dm_mii_standin`, `MountSystemData`), **the add-on content cache sized as Horizon's RomFS working memory** (`romfs_work_size`), **device save data as a save of its own** for a game that mounts account save data too (`<DM_SAVE>_device`) and **SDK 4's DeviceSink** (`g_sink4`): [Mii database answered by the host](../../../docs/reference/services.md#mii-database-answered-by-the-host), [System data stand-in for the MiiModel archive](../../../docs/reference/services.md#system-data-stand-in-for-the-miimodel-archive), [Add-on content mount cache sized as RomFS working memory](../../../docs/reference/services.md#add-on-content-mount-cache-sized-as-romfs-working-memory), [Device and account save data as two saves](../../../docs/reference/services.md#device-and-account-save-data-as-two-saves), [SDK 4: DeviceSink is command 0xf of 0x130 bytes](../../../docs/reference/audio.md#sdk-4-devicesink-is-command-0xf-of-0x130-bytes).
- **The audio renderer's update lock read off each SDK's `Update`** (`update_lock`): [The renderer's update lock (`update_lock`)](../../../docs/reference/audio.md#the-renderers-update-lock-update_lock).
- **The zero cube for a 2D array of fewer than six layers in a cube slot** (`tex_fit`): [A 2D texture in a cube slot binds the zero cube](../../../docs/reference/rendering.md#a-2d-texture-in-a-cube-slot-binds-the-zero-cube).
- **Cold Mac Metal shader builds:** [Cold Mac shader builds compile each pixel shader more than once](../../../docs/reference/shaders.md#cold-mac-shader-builds-compile-each-pixel-shader-more-than-once). Apple M2, `J=8`, no keys, `own_compilers`: 22:46 (1366 s) to 14:47 (886.86 s), 1.54×.
## Open
+1 -1
View File
@@ -1,3 +1,3 @@
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
#define DMSH_CHAIN "3ee493b2c3a4"
#define DMSH_CHAIN "1d619d0f520b"
+1 -1
View File
@@ -10901,7 +10901,7 @@ static id<MTLFunction> bf_fn(NvShader *fs, const int *fx, uint8_t fbmask, const
for (int i = 0; i < nfc; i++) { int v = fx[i]; [cv setConstantValue:&v type:MTLDataTypeInt atIndex:(NSUInteger)i]; }
for (int q = 0; q < 8; q++) { bool b = fbmask >> q & 1; [cv setConstantValue:&b type:MTLDataTypeBool atIndex:(NSUInteger)(32 + q)]; }
for (int j = 0; j < fs->rf.nfo; j++) for (int q = 0; q < 8; q++) { bool b = lmap[q] == fs->rf.fo_color[j]; [cv setConstantValue:&b type:MTLDataTypeBool atIndex:(NSUInteger)(64 + 8 * j + q)]; }
NSError *e = nil; id<MTLFunction> f = fn4_note([lib newFunctionWithName:@"main0" constantValues:cv error:&e], lib, @"main0", cv);
NSError *e = nil; id<MTLFunction> f = fn4_note([lib newFunctionWithName:@"main0_f" constantValues:cv error:&e], lib, @"main0_f", cv);
if (!f) MLOG("[RED] readable-tile version specialization failed %s (mask %02x): %s", fs->key, fbmask, e.localizedDescription.UTF8String);
NvBfFn *s = [NvBfFn new]; s->k = k; s->fn = f;
if (!fs->bffn) fs->bffn = [NSMutableArray array];
+72 -3
View File
@@ -1,5 +1,5 @@
// Feedback snapshots and their per-draw argument substitution include separate texture slots and read-only fragment images; a snapshot is reused until the game's next barrier,
// and a draw that only samples an attachment nothing in its pass has written reads it directly. With the directory test_dmsh_fetch.py --fixture writes, a draw that samples the
// and a draw that only samples an attachment nothing in its pass has written reads it directly. With the directory test_dmsh_fetch.py --fixture writes (folded readable-tile library, entry main0_f), a draw that samples the
// attachment at its own pixel through a projective sample reads it from the tile (fb_tile_plan): a snapshot while its pipeline builds, then none after a barrier, the pass stays
// open, and the GPU reads what an earlier draw of the pass wrote; not with a viewport smaller than the target. The same for a sample at the draw's pixel position times a uniform
// 1 / the target's size, set by an inline update (Splatoon Raiders' ink stamps), on an RG8 attachment sampled through (red, green, zero, one): the tile read fills the missing
@@ -231,12 +231,15 @@ static id<MTLLibrary> lib_file(NSString *path) {
// writes the sample's channels rotated (green from blue, blue from red, red from green): red where it read green, blue where it read red
static void tile_case(const char *dir) {
int before = failed, tid = 660; NSString *d = @(dir);
g_msl_dir = d; // bf_fn loads <key>_bf.metallib from here
g_msl_dir = d; // bf_fn loads <key>_bf.metallib from here and specializes @"main0_f"
NSData *fj = [NSData dataWithContentsOfFile:[d stringByAppendingPathComponent:@"facts.json"]];
NSDictionary *facts = fj ? [NSJSONSerialization JSONObjectWithData:fj options:0 error:nil] : nil;
id<MTLLibrary> vl = lib_file([d stringByAppendingPathComponent:@"fb_vs.metal"]), fl = lib_file([d stringByAppendingPathComponent:@"fb_fs.metal"]);
CHECK(facts && vl && fl, "the fixture's shaders compile");
if (!facts || !vl || !fl) return;
NSError *bfe = nil;
id<MTLLibrary> bfl = lib_from_file([d stringByAppendingPathComponent:@"fedcba9876543210_bf.metallib"], &bfe);
CHECK(bfl && [bfl.functionNames containsObject:@"main0_f"], "the folded tile-read library exposes main0_f");
NvProg *pr = [NvProg new]; NvShader *vs = [NvShader new], *fs = [NvShader new]; pr->sh[0] = vs; pr->sh[1] = fs;
vs->stage = 0; strcpy(vs->key, "0123456789abcdef_b"); vs->fn = [vl newFunctionWithName:@"main0"]; vs->rf.pos_attr = -1;
for (NSNumber *k in facts[@"screen"]) vs->rf.scr_locn |= 1u << k.intValue;
@@ -329,6 +332,9 @@ static void fpos_case(const char *dir) {
id<MTLLibrary> vl = lib_file([d stringByAppendingPathComponent:@"fb_vs.metal"]), fl = lib_file([d stringByAppendingPathComponent:@"fb_pos.metal"]);
CHECK(facts && vl && fl, "the pixel-position fixture compiles");
if (!facts || !vl || !fl) return;
NSError *bfe = nil;
id<MTLLibrary> bfl = lib_from_file([d stringByAppendingPathComponent:@"fedcba9876543211_bf.metallib"], &bfe);
CHECK(bfl && [bfl.functionNames containsObject:@"main0_f"], "the folded pixel-position library exposes main0_f");
NvProg *pr = [NvProg new]; NvShader *vs = [NvShader new], *fs = [NvShader new]; pr->sh[0] = vs; pr->sh[1] = fs;
vs->stage = 0; strcpy(vs->key, "0123456789abcdee_b"); vs->fn = [vl newFunctionWithName:@"main0"]; vs->rf.pos_attr = -1;
fs->stage = 1; strcpy(fs->key, "fedcba9876543211_b"); fs->fn = [fl newFunctionWithName:@"main0"];
@@ -491,6 +497,69 @@ static void cut_boundary_case(void) {
uint64_t r0[2], r1[2]; memcpy(r0, rep.contents, 16); memcpy(r1, (uint8_t *)rep.contents + 16, 16);
CHECK(r0[1] && r1[1] > r0[1], "two reports in one command buffer read two times");
}
// Output-mapping-only fixture (no rewritable sample): main0 writes magenta to color(0); main0_f remaps
// that output through OM_0_k. Specialized with OM_0_1, attachment 1 is magenta and attachment 0 stays the clear colour.
static void om_case(const char *dir) {
int before = failed; NSString *d = @(dir);
NSData *oj = [NSData dataWithContentsOfFile:[d stringByAppendingPathComponent:@"om.json"]];
NSDictionary *facts = oj ? [NSJSONSerialization JSONObjectWithData:oj options:0 error:nil] : nil;
CHECK(facts && [facts[@"calls"] count] == 0 && [facts[@"outputs"] count] == 1, "the om-only fixture has no samples and one colour output");
NSError *e = nil;
id<MTLLibrary> bfl = lib_from_file([d stringByAppendingPathComponent:@"fedcba9876543212_bf.metallib"], &e);
CHECK(bfl && [bfl.functionNames containsObject:@"main0_f"], "the folded om-only library exposes main0_f");
if (!bfl) { printf("feedback output-mapping-only: %s\n", before == failed ? "PASS" : "FAIL"); return; }
MTLFunctionConstantValues *cv = [MTLFunctionConstantValues new];
bool no = false;
for (int k = 0; k < 8; k++) {
[cv setConstantValue:&no type:MTLDataTypeBool atIndex:32 + k];
bool om = (k == 1);
[cv setConstantValue:&om type:MTLDataTypeBool atIndex:64 + k];
}
id<MTLFunction> ff = [bfl newFunctionWithName:@"main0_f" constantValues:cv error:&e];
CHECK(ff != nil, "main0_f specializes with OM_0_1");
if (!ff) { fprintf(stderr, "om specialize: %s\n", e.localizedDescription.UTF8String); printf("feedback output-mapping-only: FAIL\n"); return; }
id<MTLLibrary> vl = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
"vertex float4 v(uint i[[vertex_id]]) { return float4(i == 1 ? 3.0 : -1.0, i == 2 ? 3.0 : -1.0, 0, 1); }\n"
options:nil error:&e];
CHECK(vl != nil, "the om-only vertex shader compiles");
MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
pd.vertexFunction = [vl newFunctionWithName:@"v"]; pd.fragmentFunction = ff;
pd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
pd.colorAttachments[1].pixelFormat = MTLPixelFormatRGBA8Unorm;
id<MTLRenderPipelineState> ps = vl ? [g_dev newRenderPipelineStateWithDescriptor:pd error:&e] : nil;
CHECK(ps != nil, "the om-only remap pipeline compiles");
if (!ps) { fprintf(stderr, "om pipeline: %s\n", e.localizedDescription.UTF8String); printf("feedback output-mapping-only: FAIL\n"); return; }
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:4 height:4 mipmapped:NO];
td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
td.storageMode = MTLStorageModeShared;
id<MTLTexture> t0 = [g_dev newTextureWithDescriptor:td], t1 = [g_dev newTextureWithDescriptor:td];
id<MTLCommandQueue> q = [g_dev newCommandQueue];
id<MTLCommandBuffer> cb = [q commandBuffer];
MTLRenderPassDescriptor *rpd = [MTLRenderPassDescriptor renderPassDescriptor];
rpd.colorAttachments[0].texture = t0; rpd.colorAttachments[0].loadAction = MTLLoadActionClear; rpd.colorAttachments[0].storeAction = MTLStoreActionStore;
rpd.colorAttachments[0].clearColor = MTLClearColorMake(0, 1, 0, 1);
rpd.colorAttachments[1].texture = t1; rpd.colorAttachments[1].loadAction = MTLLoadActionClear; rpd.colorAttachments[1].storeAction = MTLStoreActionStore;
rpd.colorAttachments[1].clearColor = MTLClearColorMake(0, 1, 0, 1);
id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rpd];
[enc setRenderPipelineState:ps];
[enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[enc endEncoding];
[cb commit]; [cb waitUntilCompleted];
CHECK(cb.error == nil, "om-only GPU submission has no error");
uint8_t px0[64], px1[64];
[t0 getBytes:px0 bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0];
[t1 getBytes:px1 bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0];
int att0 = 1, att1 = 1;
for (int i = 0; i < 16; i++) {
const uint8_t *a = px0 + i * 4, *b = px1 + i * 4;
att0 &= a[0] == 0 && a[1] == 255 && a[2] == 0 && a[3] == 255;
att1 &= b[0] == 255 && b[1] == 0 && b[2] == 255 && b[3] == 255;
}
CHECK(att0, "attachment 0 stays the clear green; output 0 did not write there");
CHECK(att1, "attachment 1 is magenta: OM_0_1 moved colour 0");
printf("feedback output-mapping-only: %s\n", before == failed ? "PASS" : "FAIL");
}
int main(int argc, char **argv) { @autoreleasepool {
setenv("DM_NVN_TBDR", "0", 1); setenv("DM_NVN_GPU_TS", "segment", 1);
mtl_init(); NSError *error = nil;
@@ -527,7 +596,7 @@ int main(int argc, char **argv) { @autoreleasepool {
if (pipeline) slot_case(pr, pipeline, 3, 3);
image_view_case(pr);
swizzle_case();
if (argc == 2) { tile_case(argv[1]); fpos_case(argv[1]); }
if (argc == 2) { tile_case(argv[1]); fpos_case(argv[1]); om_case(argv[1]); }
pool_depth_case();
reuse_tables_case();
cut_boundary_case();
+2 -2
View File
@@ -148,11 +148,11 @@ class Rewrite(unittest.TestCase):
plain = re.sub(r' float4 _50 = .*\n', ' float4 _50 = float4(0.0);\n', GRASS.replace(', center_no_perspective', '')) # a plain interpolated input, one sample left
src = border_emu(plain)
refl = reflect('k', 'ps', src, {'sbufs': []})
fv, meta = dmsh_fetch.variant(src, refl)
fv, meta = dmsh_fetch.fold(src, refl)
self.assertIsNotNone(fv, meta)
self.assertEqual(len(meta['calls']), 1)
self.assertEqual(meta['mixed_regs'], [])
self.assertRegex(fv, r'\(FX_0 == 0 \? fb0 : [^;]*FX_0 == 7 \? fb7 : dm_bs\(spvDescriptorSet0\.fp_t_tcb_8\.sample\(', 'a tile read replaces the corrected sample')
self.assertRegex(fv, r'\(fx0 == 0 \? fb0 : [^;]*fx0 == 7 \? fb7 : dm_bs\(spvDescriptorSet0\.fp_t_tcb_8\.sample\(','a tile read replaces the corrected sample')
@unittest.skipUnless(shutil.which('xcrun'), 'requires Metal compilers')
def test_compiles(self):
+122 -19
View File
@@ -2,12 +2,13 @@
spellings (a product with 1.0 / w either way round, a quotient) and not when a name is assigned twice or the components come from different outputs; screen_varyings finds the
clip → screen varying ((x + w) / 2, (w − y) / 2, ·, w) of gl_Position in every vertex entry point, after branches, and not with a flipped y, another w, an assignment in a branch,
an early return or a uniform coefficient; a sample at gl_FragCoord.xy [/ render scale] times a uniform is marked 'frag_pos' with its uniform references, and not at another
position, scale or uniform; the variants compile for the Mac and the iPhone. With --fixture <dir>, writes t_feedback.m's tile-read shaders: fb_vs.metal, fb_fs.metal, the variant
library fedcba9876543210_bf.metallib and facts.json (the vertex shader's screen varyings and the fragment shader's calls), and the pixel-position shader fb_pos.metal with its
variant fedcba9876543211_bf.metallib and pos.json"""
position, scale or uniform; the readable-tile version main0_f compiles for the Mac and the iPhone, beside the other entry points calling main0's body (main0_d, a compile unit's), with
only the body rewritten and main0 without function constants. With --fixture <dir>, writes t_feedback.m's tile-read shaders: fb_vs.metal, fb_fs.metal, the readable-tile library
fedcba9876543210_bf.metallib (main0_f, cut from the shader's compile as the build cuts it) and facts.json (the vertex shader's screen varyings and the fragment shader's calls), the
pixel-position shader fb_pos.metal with fedcba9876543211_bf.metallib and pos.json, and the output-mapping-only fedcba9876543212_bf.metallib with om.json"""
import json, pathlib, subprocess, sys, tempfile, unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / 'tools'))
import dmsh_abi, dmsh_fetch
import dmsh_abi, dmsh_fetch, dmsh_side, pso_offline
# Breath of the Wild's decal vertex shader 095cd6ad97fd779a as spirv-cross writes it, cut down (a full-screen triangle with w = 2 in place of the decal box), and a branch first,
# as Tears of the Kingdom's bb19fab2f950e587 has
@@ -149,6 +150,26 @@ fragment main0_out main0(constant spvDescriptorSetBuffer0& spvDescriptorSet0 [[b
"""
POS_KEY = 'fedcba9876543211'
# Output-mapping-only: no rewritable sample, but the host still needs a readable-tile version so colour
# outputs can move (bf_want.tsv / om_only_ok). Magenta on color(0); main0_f remaps it through OM_0_k.
FS_OM = """#include <metal_stdlib>
using namespace metal;
struct main0_out
{
float4 m_46 [[color(0)]];
};
fragment main0_out main0()
{
main0_out out = {};
out.m_46 = float4(1.0, 0.0, 1.0, 1.0);
return out;
}
"""
OM_KEY = 'fedcba9876543212'
def compile_lib(src, root, name, sdk='macosx'): # → the library path; CalledProcessError with the compiler's message
msl = root / (name + '.metal'); msl.write_text(src); air = root / (name + '.' + sdk + '.air'); lib = root / (name + '.metallib')
@@ -160,7 +181,7 @@ def compile_lib(src, root, name, sdk='macosx'): # → the library path; Called
class ProjectiveSample(unittest.TestCase):
def calls(self, src):
v, meta = dmsh_fetch.variant(src, BINDINGS)
v, meta = dmsh_fetch.fold(src, BINDINGS)
return meta if v is None else meta['calls']
def test_product_with_reciprocal(self):
@@ -171,9 +192,11 @@ class ProjectiveSample(unittest.TestCase):
self.assertEqual(self.calls(FS.replace('float _69 = _59 * _67;', 'float _69 = _59 / _57;').replace('float _71 = _61 * _67;', 'float _71 = _61 / _57;'))[0].get('proj'), 1)
def test_rewritten_like_a_plain_sample(self):
v, _ = dmsh_fetch.variant(FS, BINDINGS)
self.assertIn('(FX_0 == 0 ? fb0 : ', v)
v, _ = dmsh_fetch.fold(FS, BINDINGS)
self.assertIn('(fx0 == 0 ? fb0 : ', v)
self.assertIn('float4 fb0 [[color(0), function_constant(FB_0)]]', v)
self.assertIn('fragment main0_out_f main0_f(', v)
self.assertIn('static __attribute__((always_inline)) main0_out dm_body_main0(', v)
def test_not_rewritten(self):
for why, src in (('a name assigned twice', FS.replace(' float2 _309', ' _69 = 0.5;\n float2 _309')),
@@ -183,7 +206,7 @@ class ProjectiveSample(unittest.TestCase):
with self.subTest(why=why): self.assertEqual(self.calls(src), 'no rewritable sample')
def test_compiles_on_both_platforms(self):
v, _ = dmsh_fetch.variant(FS, BINDINGS)
v, _ = dmsh_fetch.fold(FS, BINDINGS)
with tempfile.TemporaryDirectory() as d:
for sdk in ('macosx', 'iphoneos'):
with self.subTest(sdk=sdk):
@@ -193,7 +216,7 @@ class ProjectiveSample(unittest.TestCase):
class PixelPositionSample(unittest.TestCase):
def calls(self, src):
v, meta = dmsh_fetch.variant(src, BINDINGS)
v, meta = dmsh_fetch.fold(src, BINDINGS)
return meta if v is None else meta['calls']
def test_over_the_render_scale(self):
@@ -213,7 +236,7 @@ class PixelPositionSample(unittest.TestCase):
with self.subTest(why=why): self.assertEqual(self.calls(src), 'no rewritable sample')
def test_compiles_on_both_platforms(self):
v, _ = dmsh_fetch.variant(FS_POS, BINDINGS)
v, _ = dmsh_fetch.fold(FS_POS, BINDINGS)
with tempfile.TemporaryDirectory() as d:
for sdk in ('macosx', 'iphoneos'):
with self.subTest(sdk=sdk):
@@ -240,17 +263,97 @@ class ScreenVaryings(unittest.TestCase):
self.assertEqual(dmsh_fetch.screen_varyings(early), [], 'an early return')
class OutputMappingOnly(unittest.TestCase):
def test_refused_without_the_flag(self):
v, meta = dmsh_fetch.fold(FS_OM, [])
self.assertIsNone(v)
self.assertEqual(meta, 'no rewritable sample')
def test_folded_with_the_flag(self):
v, meta = dmsh_fetch.fold(FS_OM, [], om_only_ok=True)
self.assertIsNotNone(v)
self.assertEqual(meta['calls'], [])
self.assertEqual(meta['outputs'], [{'color': 0, 'type': 'float4'}])
self.assertIn('fragment main0_out_f main0_f(', v)
self.assertIn('static __attribute__((always_inline)) main0_out dm_body_main0(', v)
self.assertIn('constant bool OM_0_0 [[function_constant(64)]]', v)
self.assertIn('constant bool OM_0_1 [[function_constant(65)]]', v)
self.assertIn('if (OM_0_1) out.m_46_at1 = r.m_46;', v)
self.assertNotIn('constant int FX_0', v)
def test_compiles_on_both_platforms(self):
v, _ = dmsh_fetch.fold(FS_OM, [], om_only_ok=True)
with tempfile.TemporaryDirectory() as d:
for sdk in ('macosx', 'iphoneos'):
with self.subTest(sdk=sdk):
try: compile_lib(v, pathlib.Path(d), 'om_' + sdk, sdk)
except subprocess.CalledProcessError as e: self.fail(e.stderr)
def tile_library(src, root, name, side=frozenset(), sdk='macosx'):
"""The libraries ps_libraries cuts from a folded source: (base, side..., main0_f) as files root/<name>_<i>.metallib; raises AssertionError unless main0_f, alone in the last, declares
function constants and the base's entry points none (the logic operation entry points have their own)"""
lib = compile_lib(src, root, name, sdk); libs = []
for i, piece in enumerate(dmsh_side.cut(lib.read_bytes(), *([side] if side else []), {'main0_f'})):
libs.append(root / f'{name}_{i}.metallib'); libs[-1].write_bytes(piece)
base, tile = pso_offline.functions(libs[0]), pso_offline.functions(libs[-1])
assert list(tile) == ['main0_f'] and tile['main0_f'], f'{name}: the readable-tile library {tile}'
assert 'main0' in base and not any(base.values()), f'{name}: the base library {base}'
return libs
# A pixel shader with two outputs, as the dual-source entry point main0_d wants (dmsh_build.py fs_dual), with FS's projective sample
FS2 = FS.replace(' float4 m_46 [[color(0)]];\n', ' float4 m_46 [[color(0)]];\n float4 m_47 [[color(1)]];\n').replace(' return out;', ' out.m_47 = _84;\n return out;')
class OtherEntryPoints(unittest.TestCase):
def dual(self): # as dmsh_build.py finish writes it: main0's body shared, main0_d calling it
e = dmsh_side.entry(FS2, 'main0')
return dmsh_side.shared_body(FS2) + '\nstruct main0_out_d\n{\n float4 m_46 [[color(0)]];\n float4 m_47 [[color(0), index(1)]];\n};\n\n' + \
dmsh_side.calling(e, 'main0_d', 'main0_out_d', 'return main0_out_d{out.m_46, out.m_47};')
def test_only_the_body_is_rewritten(self):
v, meta = dmsh_fetch.fold(self.dual(), BINDINGS)
self.assertIsNotNone(v, meta)
self.assertEqual(len(meta['calls']), 1)
self.assertEqual(v.count('fx0 == 0 ? fb0 : '), 1)
self.assertEqual(v.count('dm_body_main0(in, spvDescriptorSet0, -1, float4(0.0)'), 2) # main0 and main0_d turn the tile read off
def test_a_copy_of_the_body_is_left_alone(self): # main0_d as a copy of main0 (fs_dual before it called the body): its sample has no fb0 to read
copy = FS2 + '\nstruct main0_out_d\n{\n float4 m_46 [[color(0)]];\n float4 m_47 [[color(0), index(1)]];\n};\n\n' + \
FS2[FS2.index('fragment main0_out main0('):].replace('fragment main0_out main0(', 'fragment main0_out_d main0_d(').replace('return out;', 'return main0_out_d{out.m_46, out.m_47};')
v, meta = dmsh_fetch.fold(copy, BINDINGS)
self.assertEqual((len(meta['calls']), v.count('fx0 == 0 ? fb0 : ')), (1, 1))
with tempfile.TemporaryDirectory() as d:
try: tile_library(v, pathlib.Path(d), 'copy')
except subprocess.CalledProcessError as e: self.fail(e.stderr)
def test_builds_beside_a_dual_source_entry_point(self):
v, _ = dmsh_fetch.fold(self.dual(), BINDINGS)
with tempfile.TemporaryDirectory() as d:
try: tile_library(v, pathlib.Path(d), 'dual')
except subprocess.CalledProcessError as e: self.fail(e.stderr)
def test_builds_in_a_compile_unit(self): # the base, the alpha test and logic operation entry points and main0_f from one compile
for name, src in (('unit', FS), ('unit_dual', self.dual())):
with self.subTest(name):
u, info = dmsh_side.unit(src)
self.assertIsNotNone(u, info)
v, meta = dmsh_fetch.fold(u, BINDINGS)
self.assertIsNotNone(v, meta)
with tempfile.TemporaryDirectory() as d:
for sdk in ('macosx', 'iphoneos'):
try: tile_library(v, pathlib.Path(d), name + sdk, set(info['alpha'] + info['logic']), sdk)
except subprocess.CalledProcessError as e: self.fail(e.stderr)
def fixture(out):
out = pathlib.Path(out); out.mkdir(parents=True, exist_ok=True)
v, meta = dmsh_fetch.variant(FS, BINDINGS)
(out / 'fb_vs.metal').write_text(VS); (out / 'fb_fs.metal').write_text(FS)
compile_lib(v, out, 'v').rename(out / f'{FS_KEY}_bf.metallib')
(out / 'facts.json').write_text(json.dumps({'screen': dmsh_fetch.screen_varyings(VS), 'calls': meta['calls'], 'outputs': meta['outputs']}))
v, meta = dmsh_fetch.variant(FS_POS, BINDINGS)
(out / 'fb_pos.metal').write_text(FS_POS)
compile_lib(v, out, 'vp').rename(out / f'{POS_KEY}_bf.metallib')
(out / 'pos.json').write_text(json.dumps({'calls': meta['calls'], 'outputs': meta['outputs']}))
(out / 'fb_vs.metal').write_text(VS); (out / 'fb_fs.metal').write_text(FS); (out / 'fb_pos.metal').write_text(FS_POS)
for src, key, name, facts, om in ((FS, FS_KEY, 'v', 'facts.json', False), (FS_POS, POS_KEY, 'vp', 'pos.json', False), (FS_OM, OM_KEY, 'vom', 'om.json', True)):
v, meta = dmsh_fetch.fold(src, BINDINGS if not om else [], om_only_ok=om)
tile_library(v, out, name)[-1].rename(out / f'{key}_bf.metallib')
(out / facts).write_text(json.dumps({**({'screen': dmsh_fetch.screen_varyings(VS)} if src is FS else {}), 'calls': meta['calls'], 'outputs': meta['outputs']}))
if __name__ == '__main__':
if len(sys.argv) == 3 and sys.argv[1] == '--fixture': fixture(sys.argv[2])
+2 -1
View File
@@ -241,7 +241,8 @@ fragment main0_out main0(main0_in in [[stage_in]])
import ast, re
tools = Path(__file__).resolve().parents[1] / 'tools'
tree = ast.parse((tools / 'dmsh_build.py').read_text())
scope = {'re': re, 'collections': __import__('collections')}
sys.path.insert(0, str(tools)); import dmsh_side # fs_uint's entry points call main0's shared body
scope = {'re': re, 'collections': __import__('collections'), 'dmsh_side': dmsh_side}
exec(compile(ast.Module(body=[n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ('fs_uint', 'int_outputs', 'in_word')], type_ignores=[]), 'dmsh_build.py', 'exec'), scope)
cls.fs_uint = staticmethod(scope['fs_uint'])
+69 -115
View File
@@ -365,16 +365,21 @@ PRE_STATS = collections.Counter()
# Odyssey's alRenderMaterialUber took 25 minutes and 17.3 MB of GPU code, 31 s and 1.3 MB at -O1. Ordinary shaders come out within a few percent either way (the backend optimizes again)
MAC_METAL = ['xcrun', '-sdk', 'macosx', 'metal', '-c', '-O1', '-fpreserve-invariance']
MAC_RECORD = ' '.join(MAC_METAL) + '; xcrun -sdk macosx metallib'
# The compiles run the tools xcrun names, found once: each xcrun launch looks them up again, about 4 ms of a compile's two launches (8 ms a shader). -isysroot is what xcrun -sdk passes
# (as SDKROOT), and the outputs are the same bytes (.air and .metallib, checked on Odyssey's shaders); without it the driver targets the running macOS, not the SDK, and they differ.
# MAC_RECORD names the xcrun command, which runs the same compiler
def xcrun_out(*args): return subprocess.run(['xcrun', '-sdk', 'macosx', *args], capture_output=True, text=True, check=True).stdout.strip()
MAC_RUN = [xcrun_out('-f', 'metal'), '-isysroot', xcrun_out('--show-sdk-path'), *MAC_METAL[4:]]
MAC_LINK = [xcrun_out('-f', 'metallib')]
# -fbracket-depth: the front end stops at 256 nested brackets ("bracket nesting level exceeded maximum of 256"). Ocarina of Time's compute shaders 1f78730053feb036 and e172bd7ec218ab8e
# (3.5 MB of MSL each) nest 259 deep in one expression and were left out. A source within the default limit compiles to the same bytes with it (checked on macOS and iOS), so, like the
# precompiled header, the records do not name it and the Metal cache keeps its libraries. ios_metal.DEPTH is the same
METAL_DEPTH = ['-fbracket-depth=1024']
# The outer shader and fetch-variant caches restore compiled libraries directly,
# before the MSL compile cache can check their compiler. Keep override builds separate there too.
# The outer shader cache restores compiled libraries directly, before the MSL compile cache can check their compiler. Keep override builds separate there too.
METAL_FP = dmsh_mtlcache.compiler_id('macosx') + ('\0iphoneos\0' + dmsh_mtlcache.compiler_id('iphoneos') if IOSOUT else '')
def mac_compile(msl, air, lib): # same interface as ios_metal.compile; the precompiled header and METAL_DEPTH change no output, so MAC_RECORD does not name them (dmsh_pch.py)
dmsh_pch.compile(MAC_METAL + METAL_DEPTH, msl, air)
subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', air, '-o', lib], check=True)
dmsh_pch.compile(MAC_RUN + METAL_DEPTH, msl, air)
subprocess.run([*MAC_LINK, air, '-o', lib], check=True)
# The NVN driver's constant segments have one layout in every game, which dm/gfx/nvn/dmsh_abi.h holds for the host and this build (through dmsh_abi.py); nvn_mtl.m fills them the same way at run time.
# c2 C2_TEX + 8 r: handles bound with nvnCommandBufferBindTexture (combined texture and sampler), slot r. The driver has 32 such slots, but a game may bind higher ones, whose words lie in the
# image table (Hades II binds slot 34, and no image), so a texture instruction's handle anywhere below the separate texture table names a combined slot. In the image
@@ -545,91 +550,19 @@ def publish_cache(key, digest, rule_fp, code_fp):
for name in names:
src = os.path.join(out if label == 'mac' else IOSOUT, name)
if name.endswith('.json'):
value = json.load(open(src)); value.pop('fetch', None); value.pop('vin', None); value.pop('pull', None); value.pop('alpha', None); value.pop('logic', None) # the side libraries are made again from the restored MSL (fetch_finish, vin_finish, pull_finish, alpha_finish, logic_finish)
value = json.load(open(src)); value.pop('fetch', None); value.pop('vin', None); value.pop('pull', None); value.pop('alpha', None); value.pop('logic', None) # the side libraries are made again from the restored MSL (ps_libraries, vin_finish, pull_finish)
STORE.put(f'{root}/{label}/{name}', json.dumps(value, ensure_ascii=False, indent=1).encode())
else: STORE.put_file(f'{root}/{label}/{name}', src)
STORE.put(cache_meta_path(key), json.dumps({'digest': digest, 'rule_fp': rule_fp, 'code_fp': code_fp}).encode())
BF_STATS = collections.Counter()
def bf_digest(msl, key):
h = hashlib.sha256()
h.update(msl.encode())
h.update(b'\0mac\0' + MAC_RECORD.encode())
h.update(b'\0ios\0' + (ios_metal.RECORD if IOSOUT else '').encode())
h.update(b'\0metal\0' + METAL_FP.encode())
h.update(b'\0bf-want\0' + (b'1' if key in BF_WANT else b'0'))
return h.hexdigest()
def bf_cache_root(digest): return f'variant/{digest}'
def bf_cache_restore(key, digest, fmeta, fmsl):
root = bf_cache_root(digest)
names = ['metal'] + (['mac.metallib'] if 'mac' in TARGETS else []) + (['ios.metallib'] if IOSOUT else [])
if not all(STORE.has(f'{root}/{n}') for n in names): return False
STORE.to_file(f'{root}/metal', fmsl)
if 'mac' in TARGETS: STORE.to_file(f'{root}/mac.metallib', os.path.join(out, key + '_bf.metallib'))
if IOSOUT: STORE.to_file(f'{root}/ios.metallib', os.path.join(IOSOUT, key + '_bf.metallib'))
BF_STATS['hit'] += 1
return True
def bf_cache_publish(digest, fmsl, maclib, ioslib, fmeta):
root = bf_cache_root(digest)
with STORE.batch():
STORE.put_file(f'{root}/metal', fmsl)
if maclib: STORE.put_file(f'{root}/mac.metallib', maclib)
if IOSOUT: STORE.put_file(f'{root}/ios.metallib', ioslib)
STORE.put(f'{root}/fetch.json', json.dumps(fmeta, ensure_ascii=False, indent=1).encode())
def write_refl(key, refl):
for target, d in (('mac', out),) + ((('ios', IOSOUT),) if IOSOUT else ()):
atomic_json(os.path.join(d, key + '_b.json'), MTL.with_compiler(target, refl))
def fetch_finish(key, src, refl):
if refl['stage'] != 'ps': return refl
# Those with rewritable samples get variants as before; those without get an output-mapping-only variant, and only for keys in the list (bf_want.tsv, produced by the host planner)
fv, fmeta = dmsh_fetch.variant(src, refl['bindings'], om_only_ok=key in BF_WANT)
if not fv:
for path in (os.path.join(out, key + '_bf.metallib'), os.path.join(out, key + '_bf.metal')) + ((os.path.join(IOSOUT, key + '_bf.metallib'),) if IOSOUT else ()):
try: os.unlink(path)
except FileNotFoundError: pass
write_refl(key, refl)
return refl
BF_STATS['generated'] += 1
fmsl = os.path.join(out, key + '_bf.metal')
digest = bf_digest(fv, key)
with CAS_LOCKS_GUARD: lock = CAS_LOCKS.setdefault(('variant', digest), threading.Lock())
with lock:
try:
if not bf_cache_restore(key, digest, fmeta, fmsl):
BF_STATS['miss'] += 1
open(fmsl, 'w').write(fv)
fair = fmsl[:-6] + '.air'; flib = os.path.join(out, key + '_bf.metallib') if 'mac' in TARGETS else None
try:
if flib:
tmp_flib = flib + '.tmp-' + str(os.getpid())
mac_compile(fmsl, fair, tmp_flib)
os.replace(tmp_flib, flib)
ilib = None
if IOSOUT:
ilib = os.path.join(IOSOUT, key + '_bf.metallib')
ios_metal.compile(fmsl, fmsl[:-6] + '.ios.air', ilib + '.tmp')
os.replace(ilib + '.tmp', ilib)
except subprocess.CalledProcessError:
return refl
BF_STATS['compile'] += 1
bf_cache_publish(digest, fmsl, flib, ilib, fmeta)
finally:
for path in (fmsl, fmsl[:-6] + '.air', fmsl[:-6] + '.ios.air'):
try: os.unlink(path)
except FileNotFoundError: pass
refl['fetch'] = fmeta
write_refl(key, refl)
return refl
VIN_STATS = collections.Counter()
PULL_STATS = collections.Counter()
SIDE_STATS = collections.Counter()
BF_STATS = collections.Counter()
def pull_finish(key, full, refl):
"""The pulling library <key>_bp of a vertex shader with stage inputs (dmsh_pull.py: no [[stage_in]], the inputs read through the per-draw layout block), compiled through the
@@ -690,28 +623,41 @@ def vin_finish(key, full, refl):
VIN_STATS['inputs'] += len(shadows); VIN_STATS['float only'] += sum(1 for s in shadows if 'sint' not in s and 'uint' not in s)
return refl
def ps_libraries(key, msl, full):
"""A pixel shader's libraries: <key>_b, and <key>_bx with its alpha test and logic operation entry points, cut from one compile through the MSL-keyed Metal cache (dmsh_side.py). msl: the file of
its plain source, full. A shader none of them apply to, or whose compile unit does not build, gets <key>_b from the plain source and no <key>_bx (a stale one removed): the host draws it
without. → what the reflection says of them. Raises CalledProcessError when the plain source does not compile"""
def ps_libraries(key, msl, full, bindings):
"""A pixel shader's libraries, cut from one compile through the MSL-keyed Metal cache (dmsh_side.cut): <key>_b with its own entry points, <key>_bx with its alpha test and logic
operation ones (dmsh_side.unit), <key>_bf with its readable-tile version main0_f (dmsh_fetch.fold; a shader without a rewritable sample only when bf_want.tsv lists it). The readable-tile
version was a source and a Metal compile of its own (13,666 of Mario Kart 8 Deluxe's 29,651 shaders). msl: the file of its plain source, full; bindings: its reflection's.
What does not build is left out, and only that: a unit whose readable-tile version does not build is compiled again without it, one that does not build at all gives <key>_b from the
plain source, each with a red line. A library a shader does not get is removed (a stale one of an earlier build), and the host draws without it. → what the reflection says of them.
Raises CalledProcessError when the plain source does not compile"""
targets = [(t, d) for t, d in (('mac', out), ('ios', IOSOUT)) if d and t in TARGETS]
def drop(*suffixes):
for _, d in targets:
for s in suffixes:
try: os.unlink(os.path.join(d, key + s + '.metallib'))
except FileNotFoundError: pass
src, info = dmsh_side.unit(full)
if src:
u = os.path.join(w, key + '_bu.metal'); open(u, 'w').write(src)
side = set(info['alpha'] + info['logic']) if src else set()
folded, fmeta = dmsh_fetch.fold(src or full, bindings, om_only_ok=key in BF_WANT) # also without side entry points: main0_f then shares the compile with main0 alone
for unit, fetch in ([(folded, fmeta)] if folded else []) + ([(src, None)] if src else []):
names = ['_b'] + (['_bx'] if side else []) + (['_bf'] if fetch else [])
groups = ([side] if side else []) + ([{'main0_f'}] if fetch else [])
u = os.path.join(w, key + '_bu.metal'); open(u, 'w').write(unit)
try:
for t, d in targets: MTL.compile_split(t, u, os.path.join(d, key + '_b.metallib'), os.path.join(d, key + '_bx.metallib'), lambda lib: dmsh_side.cut(lib, set(info['alpha'] + info['logic'])))
SIDE_STATS['generated'] += 1
return {f: {'entries': info[f]} for f in ('alpha', 'logic') if info[f]}
for t, d in targets: MTL.compile_split(t, u, [os.path.join(d, key + n + '.metallib') for n in names], lambda lib, groups=groups: dmsh_side.cut(lib, *groups))
except (subprocess.CalledProcessError, ValueError) as e:
SIDE_STATS['failed'] += 1; print(f'[RED] {key}: the alpha test and logic operation entry points do not build ({str(e)[:120]}): its draws go without them', flush=True)
if fetch: BF_STATS['failed'] += 1; print(f'[RED] {key}: the readable-tile version does not build ({str(e)[:120]}): its draws go without the tile read', flush=True)
else: SIDE_STATS['failed'] += 1; print(f'[RED] {key}: the alpha test and logic operation entry points do not build ({str(e)[:120]}): its draws go without them', flush=True)
continue
finally:
try: os.unlink(u)
except FileNotFoundError: pass
else: SIDE_STATS['not generated'] += 1
for t, d in targets:
try: os.unlink(os.path.join(d, key + '_bx.metallib'))
except FileNotFoundError: pass
MTL.compile(t, msl, os.path.join(d, key + '_b.metallib'))
drop(*{'_bx', '_bf'} - set(names))
SIDE_STATS['generated'] += bool(side); BF_STATS['generated'] += bool(fetch)
return {**{f: {'entries': info[f]} for f in ('alpha', 'logic') if side and info[f]}, **({'fetch': fetch} if fetch else {})}
SIDE_STATS['not generated'] += not src
drop('_bx', '_bf')
for t, d in targets: MTL.compile(t, msl, os.path.join(d, key + '_b.metallib'))
return {}
pc_of, loc = {}, {}
@@ -1165,9 +1111,10 @@ def unfillable(dr, stage):
RULES = [] # MSL rewrite rules attached by shader name (function, applicability test); the former dark-range remap toe has been removed (back to the original Switch brightness)
# CODE_FP hashes the code form of this file and its helper modules (dmsh_chain.code_form): editing a comment, a docstring or the layout does not change any shader's key.
# The library ABI enters as its values (dmsh_abi.VALUES), so a comment in dmsh_abi.h does not change a key either.
# It covers what runs only when a shader misses the cache, since a hit restores the output and skips it. dmsh_fetch.py is not in it, but for screen_varyings (raster_facts): readable-tile variants get a
# separate second-stage cache keyed on the generated MSL. Nor are the other side libraries' modules, made again from the restored MSL on every build (test_dmsh_code_fp.py checks this list).
CODE_FP = hashlib.sha256(source_without_rule_bodies() + b''.join(b'\0' + dmsh_chain.code_form(open(m.__file__, 'r').read()) for m in (dmsh_chain, dmsh_geometry, dmsh_atomic, dmsh_wide, dmsh_meshstage, dmsh_ampere, abi) + ((ios_metal,) if IOSOUT else ()))
# It covers what runs only when a shader misses the cache, since a hit restores the output and skips it. dmsh_side.py is in it: fs_uint and fs_dual write main0's shared body (shared_body).
# dmsh_fetch.py is not, but for screen_varyings (raster_facts), nor are the other side libraries' modules: they are made again from the restored MSL on every build (ps_libraries;
# test_dmsh_code_fp.py checks this list).
CODE_FP = hashlib.sha256(source_without_rule_bodies() + b''.join(b'\0' + dmsh_chain.code_form(open(m.__file__, 'r').read()) for m in (dmsh_chain, dmsh_geometry, dmsh_atomic, dmsh_wide, dmsh_meshstage, dmsh_ampere, dmsh_side, abi) + ((ios_metal,) if IOSOUT else ()))
+ b'\0' + inspect.getsource(dmsh_fetch.screen_varyings).encode()
+ b'\0abi\0' + repr(sorted(abi.VALUES.items())).encode()).hexdigest()
TOOL_FP = tool_fingerprint().encode()
@@ -1413,7 +1360,7 @@ def fs_uint(src):
A G-buffer may mix the two: Pokémon Sword's scene shaders write colour 0 and 2 as floats and colour 1 from integer bits into an RGBA16Uint target. A shader whose outputs include both
gets a third entry point, main0_m, that returns only the outputs written from integer bits as unsigned integers (their colour indices: the mask); the host takes it for a pipeline whose
integer attachments are exactly those; which outputs those are comes from how their values are computed (int_outputs), as nearly every float output is written as integer bits too.
→ (the source with main0_u (and main0_m) added, the main0_m mask or 0), or (None, 0)"""
Both call main0's body (dmsh_side.shared_body) instead of copying it. → (main0_u (and main0_m), to append to the source with its body shared, the main0_m mask or 0), or (None, 0)"""
m = re.search(r'^.*\bfragment\s+main0_out\s+main0\s*\(', src, re.M); st = re.search(r'struct main0_out\s*\{(.*?)\};', src, re.S)
if not m or not st: return None, 0
mem = re.findall(r'^\s*(\w+)\s+(\w+)\s*(\[\[[^\]]*\]\])?;', st.group(1), re.M)
@@ -1433,11 +1380,14 @@ def fs_uint(src):
ints = int_outputs(src, body, cols)
if not from_int and not ints and not (writes and (all(re.fullmatch(r'-?[0-9.]+f?|float\d\([-0-9., ]*\)', w.strip()) for w in writes) or all(passed(w) for w in writes))): return None, 0
uty = lambda ty: 'u' + ty.replace('float', 'int') # float4 → uint4, float → uint
def entry(sfx, as_uint): # main0 again as main0_<sfx>, returning the outputs in as_uint as the unsigned integer vectors of their bits (dmsh_fetch.py cuts the source at main0_out_u)
try: e = dmsh_side.entry(src, 'main0')
except ValueError: e = None
if not e: return None, 0
def entry(sfx, as_uint): # main0_<sfx>: main0's body (dmsh_side.shared_body), its outputs in as_uint returned as the unsigned integer vectors of their bits
struct = f'struct main0_out_{sfx}\n{{\n' + ''.join(f' {uty(cols[nm]) if nm in as_uint else ty} {nm} {at};\n' for ty, nm, at in mem) + '};\n\n'
ret = f'return main0_out_{sfx}{{' + ', '.join(f'as_type<{uty(cols[nm])}>(out.{nm})' if nm in as_uint else f'out.{nm}' for _, nm, _ in mem) + '};'
return '\n' + struct + re.sub(r'\bfragment\s+main0_out\s+main0\s*\(', f'fragment main0_out_{sfx} main0_{sfx}(', src[m.start():], count=1).replace('return out;', ret)
out, mask = src + entry('u', set(cols)), 0
conv = f'return main0_out_{sfx}{{' + ', '.join(f'as_type<{uty(cols[nm])}>(out.{nm})' if nm in as_uint else f'out.{nm}' for _, nm, _ in mem) + '};'
return '\n' + struct + dmsh_side.calling(e, f'main0_{sfx}', f'main0_out_{sfx}', conv)
out, mask = entry('u', set(cols)), 0
as_int = ints or from_int
if as_int and set(cols) - as_int: # some outputs from integer bits, some not: the mixed entry point
out += entry('m', as_int)
@@ -1449,14 +1399,17 @@ def fs_dual(src):
output [[color(1)]]; Metal reads the second source only from [[color(0), index(1)]], and its compiler crashes building a pipeline that blends with an absent one (Pokémon Legends:
Arceus's ha_post_effects, f4f36a03b0c6691d). A shader in the profile's dual_want.tsv that writes exactly colours 0 and 1 gets a second entry point, main0_d, the same body with
output 1 as index 1 of colour 0; the host takes it for a pipeline whose target 0 blends with a SRC1 factor (nvn_mtl.m pso_desc). Not every such shader gets one: most write a
second render target (5,474 of Arceus's 6,156 pixel shaders write exactly colours 0 and 1). → main0_d, to append to the source (with its other entry points), or None"""
m = re.search(r'^.*\bfragment\s+main0_out\s+main0\s*\(', src, re.M); st = re.search(r'struct main0_out\s*\{(.*?)\};', src, re.S)
if not m or not st: return None
second render target (5,474 of Arceus's 6,156 pixel shaders write exactly colours 0 and 1). It calls main0's body (dmsh_side.shared_body): a copy of the body was compiled again, and
a readable-tile rewrite of its samples would not build there (dmsh_fetch.fold). → main0_d, to append to the source with its body shared (with its other entry points), or None"""
st = re.search(r'struct main0_out\s*\{(.*?)\};', src, re.S)
if not st: return None
try: e = dmsh_side.entry(src, 'main0')
except ValueError: e = None
if not e: return None
mem = re.findall(r'^\s*(\w+)\s+(\w+)\s*(\[\[[^\]]*\]\])?;', st.group(1), re.M)
if sorted(at for _, _, at in mem if 'color(' in at) != ['[[color(0)]]', '[[color(1)]]']: return None
struct = 'struct main0_out_d\n{\n' + ''.join(f' {ty} {nm} {"[[color(0), index(1)]]" if at == "[[color(1)]]" else at};\n' for ty, nm, at in mem) + '};\n\n'
ret = 'return main0_out_d{' + ', '.join(f'out.{nm}' for _, nm, _ in mem) + '};'
return '\n' + struct + re.sub(r'\bfragment\s+main0_out\s+main0\s*\(', 'fragment main0_out_d main0_d(', src[m.start():], count=1).replace('return out;', ret)
return '\n' + struct + dmsh_side.calling(e, 'main0_d', 'main0_out_d', 'return main0_out_d{' + ', '.join(f'out.{nm}' for _, nm, _ in mem) + '};')
SG_OPS = {333: 'true', 334: 'pred', 335: 'pred', 336: 'true', 337: 'value', 338: 'value', 339: 'ballot', 345: 'value', 346: 'value', 347: 'value', 348: 'value'} # OpGroupNonUniform* → its one-lane value
SG_BUILTINS = {36: 'one', 41: 'zero', 4416: 'one4', 4417: 'one4', 4418: 'zero4', 4419: 'one4', 4420: 'zero4'} # SubgroupSize, SubgroupLocalInvocationId, Eq / Ge / Gt / Le / Lt masks
@@ -1651,10 +1604,14 @@ def finish(key, w, j, c1):
open(msl, 'w').write(full)
fu, fmask = fs_uint(src) if j['stage'] == 'ps' else (None, 0) # the integer-output entry points (see fs_uint); the analysis below uses the source with only main0
fd = fs_dual(src) if j['stage'] == 'ps' and key in DUAL_WANT else None # the dual-source entry point (see fs_dual), from the source with only main0
if fu or fd: plain = src; open(msl, 'w').write((fu or src) + (fd or ''))
shared = dmsh_side.shared_body(src) if fu or fd else None # they call main0's body; fs_uint and fs_dual give none for a main0 whose shape it does not know
if shared: plain = src; open(msl, 'w').write(shared + (fu or '') + (fd or ''))
else: fu = fd = None
try: binds = reflect(key, mesh['kind'] if mesh else j['stage'], src, res) # before the compile: a pixel shader's readable-tile version needs its texture slots (ps_libraries)
except ValueError as e: return 'reflection failed', str(e)[:160], None
side, lost = {}, []
def compile_targets(): # the selected targets from the same MSL (MSL identical to one compiled before takes that library, dmsh_mtlcache.py)
if j['stage'] == 'ps': side.clear(); side.update(ps_libraries(key, msl, open(msl).read())); return
if j['stage'] == 'ps': side.clear(); side.update(ps_libraries(key, msl, open(msl).read(), binds)); return
if 'mac' in TARGETS: MTL.compile('mac', msl, lib)
if 'ios' in TARGETS and IOSOUT: MTL.compile('ios', msl, os.path.join(IOSOUT, key + '_b.metallib'))
try: compile_targets()
@@ -1667,8 +1624,6 @@ def finish(key, w, j, c1):
clone(msl, os.path.join(out, key + '_b.metal'))
entry = re.search(r'(vertex|fragment|kernel)\s+\S+\s+(\w+)\s*\(', src)
dr = drv_reads(src)
try: binds = reflect(key, mesh['kind'] if mesh else j['stage'], src, res)
except ValueError as e: return 'reflection failed', str(e)[:160], None
refl = {'key': key + '_b', 'route': 'B', 'chain': CHAIN, 'dm_ctl': key, 'source': f'{name}#{k}', 'pc_paired': pc_of[key], 'stage': mesh['kind'] if mesh else j['stage'],
**({'mesh_stage': {'kind': mesh['kind'], 'threads': mesh['threads'], 'payload': mesh['payload'], 'task': mesh.get('task', True)}, **({'entry_z': 'main0_z'} if mesh['kind'] == 'ms' else {})} if mesh else {}),
'entry': entry.group(2) if entry else 'main0', 'msl_entry_kind': entry.group(1) if entry else None, **({'entry_z': 'main0_z', 'entry_geometry_capture': 'main0_gs'} if j['stage'] == 'vs' else {}),
@@ -1682,9 +1637,8 @@ def finish(key, w, j, c1):
'vertex_inputs': [{'location': int(m.group(3)), 'msl_type': m.group(1)} for m in attributes(src)],
'raster': raster_facts(j['stage'], src), 'vs_pad': pad}
if j['stage'] == 'vs': full = open(msl).read(); vin_finish(key, full, refl); pull_finish(key, full, refl) # the shadow-input and pulling libraries (dmsh_vin.py, dmsh_pull.py), from the source with every entry point
refl.update(side) # the alpha test and logic operation entry points (ps_libraries)
refl.update(side) # the alpha test and logic operation entry points and the readable-tile version (ps_libraries)
write_refl(key, refl)
fetch_finish(key, src, refl)
return 'ok', '', refl
keys = build_keys(want, loc, PAIRS)
@@ -1805,8 +1759,8 @@ def fin(key, wb):
refl = json.loads(output_of('mac', key + '_b.json'))
src = output_of('mac', key + '_b.metal').decode() if refl['stage'] in ('ps', 'vs') else ''
if refl['stage'] == 'vs': write_refl(key, pull_finish(key, src, vin_finish(key, src, refl)))
if refl['stage'] == 'ps': refl.update(ps_libraries(key, os.path.join(out, key + '_b.metal'), src))
return key, 'ok', '', fetch_finish(key, src, refl)
if refl['stage'] == 'ps': refl.update(ps_libraries(key, os.path.join(out, key + '_b.metal'), src, refl['bindings'])); write_refl(key, refl) # stored without them (publish_cache)
return key, 'ok', '', refl
if key in xerr or not os.path.exists(os.path.join(wb, key + '.spv')): return key, 'translation failed', xerr.get(key, 'no spv'), None
result = (key,) + finish(key, wb, jobs[key], c1s[key])
if result[1] == 'ok': publish_cache(key, digests[key], rule_fps[key], CODE_FP)
@@ -1859,7 +1813,7 @@ print(f'shaders {len(res)}: ok {st["ok"]}, ' + ', '.join(f'{k} {v}' for k, v in
print(f'shader cache: hit {PRE_STATS["hit"]}, rebuilt {PRE_STATS["miss"]}')
for reason in ('new key', 'rule changed', 'code fingerprint changed: all rebuilt'):
if PRE_STATS[reason]: print(f' {reason} {PRE_STATS[reason]}')
print(f'variant cache: generated {BF_STATS["generated"]}, hit {BF_STATS["hit"]}, rebuilt {BF_STATS["miss"]}, compiled {BF_STATS["compile"]}')
print(f'readable-tile versions (<key>_bf, dmsh_fetch.py): {BF_STATS["generated"]} generated, {BF_STATS["failed"]} failed to compile')
print(f'shadow-input libraries (<key>_bv, dmsh_vin.py): {VIN_STATS["generated"]} generated, {VIN_STATS["failed"]} failed to compile, {VIN_STATS["not generated"]} not generated; '
f'{VIN_STATS["inputs"]} integer inputs shadowed, {VIN_STATS["float only"]} of them with no other-sign shadow (attribute indices ran out)')
print(f'alpha test and logic operation libraries (<key>_bx, dmsh_side.py): {SIDE_STATS["generated"]} generated, {SIDE_STATS["failed"]} failed to compile, {SIDE_STATS["not generated"]} pixel shaders without either')
+51 -37
View File
@@ -1,6 +1,7 @@
# "Readable-tile" version of a fragment shader (merge B step 2): within one pass, when a later draw samples, at its own pixel, a color attachment written by an earlier draw,
# it is changed to read the color directly from the tile (framebuffer fetch); the two render passes become one, and the intermediate attachment need not be stored to main memory and loaded back just to be sampled.
# Built offline; at runtime only function-constant specialization is done (no source compilation). Usage: variant(msl, bindings, om_only_ok=False) → (new MSL, metadata) or (None, reason)
# Built offline, as the entry point main0_f of the shader's own compile (fold); at runtime only function-constant specialization is done (no source compilation).
# Usage: fold(msl, bindings, om_only_ok=False) → (the source with main0_f, metadata) or (None, reason)
# Function constant numbering: FX_i (which color index the i-th rewritable sample reads, -1 = sample as usual) = i; FB_k (enable color input k) = 32 + k;
# OM_j_k (the j-th output writes to attachment k) = 64 + 8 j + k
# Rewritable samples: .sample(sampler, select(_N, float2(0.0), isnan(_N))) on a 2D float texture, where _N = float2(in.m_X.x, in.m_X.y) (interpolated output unchanged),
@@ -12,6 +13,7 @@
import collections
import re
import dmsh_abi as abi
import dmsh_side
NFB = 8
@@ -182,63 +184,75 @@ def screen_varyings(msl):
for e in entries: got &= _entry_screen(e.group(1), locn)
return sorted(got)
def variant(msl, bindings, om_only_ok=False):
# main0_u (dmsh_build.py int_outputs: integer colour targets) is appended to the source after main0; the host takes it from the shader's own library, never from this variant.
# Its body reads main0's output struct, whose members the variant renames, and its samples were rewritten to fb0–fb7, which only main0 declares: 483 of Breath of the
# Wild's variants failed to compile once their cached copies were gone (use of undeclared identifier 'fb0'). The variant is built from the source without it
cut = msl.find('\nstruct main0_out_u\n')
if cut >= 0: msl = msl[:cut + 1]
tex = {m.group(1) for m in re.finditer(r'texture2d<float> (\w+) \[\[id\(\d+\)\]\];', msl)}
locn = {m.group(1): int(m.group(2)) for m in re.finditer(r'float4 (m_\d+) \[\[user\(locn(\d+)\)\]\];', msl.split('struct main0_in', 1)[-1].split('};', 1)[0])}
def fold(msl, bindings, om_only_ok=False):
"""The readable-tile version main0_f added to msl (a pixel shader's source, or the compile unit dmsh_side.unit made of it), to be cut from the one compile of the shader's other entry
points (dmsh_build.py ps_libraries); it was a source and a compile of its own. main0's body is dm_body_main0 (dmsh_side.shared_body), and each rewritable sample in it becomes
(fx_i == k ? fb_k : the sample), fx_i and fb0-fb7 parameters of the body: main0_f passes its function constants FX_i and the tile's colours, every other caller -1 and zeros, which
the always-inline body folds back to the plain sample, so main0 and the side entry points stay functions without function constants. main0_f writes each output to the
attachments its OM_j_k name. Only the body is read and rewritten: a copy of a sample in another function would have no fb_k (483 of Breath of the Wild's variants once failed to
compile on main0_u's copy: use of undeclared identifier 'fb0'). → (the source with main0_f, {'calls', 'mixed_regs', 'outputs'}), or (None, why)"""
src = dmsh_side.shared_body(msl)
if src is None: return None, 'main function signature not recognized'
try: where, e = dmsh_side.body(src), dmsh_side.entry(src, 'main0')
except ValueError as x: return None, str(x)
if not where or not e: return None, 'main function signature not recognized'
start, head, end = where; text = src[head:end]
tex = {m.group(1) for m in re.finditer(r'texture2d<float> (\w+) \[\[id\(\d+\)\]\];', src)}
locn = {m.group(1): int(m.group(2)) for m in re.finditer(r'float4 (m_\d+) \[\[user\(locn(\d+)\)\]\];', src.split('struct main0_in', 1)[-1].split('};', 1)[0])}
reg = {b['msl_name']: b['reg'] for b in bindings if b.get('kind') == abi.KIND_TEX and b.get('msl_name') and b.get('reg') is not None}
# A sample the border colour correction wrapped (dmsh_build.py border_emu) is taken whole: a tile read replaces the corrected sample, never feeds the correction
pat = re.compile(r'(dm_bs\()?spvDescriptorSet0\.(\w+)\.sample\(spvDescriptorSet0\.(\w+)Smplr, select\((_\d+), float2\(0\.0\), isnan\(\4\)\)\)'
r'(?(1), spvDescriptorSet0\.%s, \d+u, spvDescriptorSet0\.\2, spvDescriptorSet0\.\3Smplr%s, select\(\4, float2\(0\.0\), isnan\(\4\)\)\))' % (abi.BORDER_MEMBER, abi.BORDER_TWIN))
calls, out_parts, pos = [], [], 0
for m in pat.finditer(msl):
for m in pat.finditer(text):
member, var = m.group(2), m.group(4)
if member not in tex or member != m.group(3) or member not in reg: continue
d = re.search(r'float2 %s = float2\((_\d+), (_\d+)\);' % var, msl)
a = d and re.search(r'float %s = in\.(m_\d+)\.x;' % d.group(1), msl); b = d and re.search(r'float %s = in\.(m_\d+)\.y;' % d.group(2), msl)
d = re.search(r'float2 %s = float2\((_\d+), (_\d+)\);' % var, text)
a = d and re.search(r'float %s = in\.(m_\d+)\.x;' % d.group(1), text); b = d and re.search(r'float %s = in\.(m_\d+)\.y;' % d.group(2), text)
if a and b and a.group(1) == b.group(1) and a.group(1) in locn: how = {'varying_locn': locn[a.group(1)]}
else:
pa, pb = (_proj(msl, d.group(1), 'x', locn), _proj(msl, d.group(2), 'y', locn)) if d else (None, None)
fx, fy = (_frag_pos(msl, d.group(1), 'x'), _frag_pos(msl, d.group(2), 'y')) if d else (None, None)
pa, pb = (_proj(text, d.group(1), 'x', locn), _proj(text, d.group(2), 'y', locn)) if d else (None, None)
fx, fy = (_frag_pos(text, d.group(1), 'x'), _frag_pos(text, d.group(2), 'y')) if d else (None, None)
if pa and pa == pb: how = {'varying_locn': locn[pa], 'proj': 1}
elif fx and fy: how = {'frag_pos': [fx, fy]}
else: continue
i = len(calls)
if i >= 32: break
sel = ''.join(f'FX_{i} == {k} ? fb{k} : ' for k in range(NFB))
out_parts.append(msl[pos:m.start()]); out_parts.append(f'({sel}{m.group(0)})'); pos = m.end()
sel = ''.join(f'fx{i} == {k} ? fb{k} : ' for k in range(NFB))
out_parts.append(text[pos:m.start()]); out_parts.append(f'({sel}{m.group(0)})'); pos = m.end()
calls.append({'fc': i, 'tex_reg': reg[member], **how})
if not calls and not om_only_ok:
return None, 'no rewritable sample'
# Mixed-use slots: the same texture also has other (non-rewritable) uses - at runtime this texture must not be switched to tile reads (the rewritten reads and the unrewritten ones would not see the same data)
conv = {}
for c in calls: conv[c['tex_reg']] = conv.get(c['tex_reg'], 0) + 1
mixed = sorted({reg[mb] for mb in reg if mb in tex and msl.count(f'spvDescriptorSet0.{mb}.') > conv.get(reg[mb], 0)})
body = ''.join(out_parts) + msl[pos:]
om = re.search(r'struct main0_out\s*\{(.*?)\};', body, re.S)
conv = collections.Counter(c['tex_reg'] for c in calls)
mixed = sorted({reg[mb] for mb in reg if mb in tex and text.count(f'spvDescriptorSet0.{mb}.') > conv[reg[mb]]})
om = re.search(r'struct main0_out\s*\{(.*?)\};', src, re.S)
if not om: return None, 'no output struct'
outs = [(t, n, int(c)) for t, n, c in re.findall(r'(\w+) (m_\d+) \[\[color\((\d+)\)\]\];', om.group(1))]
if not outs or len(outs) > 4 or re.sub(r'\w+ m_\d+ \[\[color\(\d+\)\]\];', '', om.group(1)).strip(): return None, 'the output struct is not plain color outputs (or has more than 4)'
members = ''.join(f' {t} {n}_at{k} [[color({k}), function_constant(OM_{j}_{k})]];\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB))
body = body[:om.start(1)] + '\n' + members + body[om.end(1):]
rest = src[end:]
if calls: # the body's new parameters, and every call of it (the definition comes first) passing what turns the tile read off
params = [f'int fx{i}' for i in range(len(calls))] + [f'float4 fb{k}' for k in range(NFB)]
off = ', '.join(['-1'] * len(calls) + ['float4(0.0)'] * NFB)
sig = src[start:head - 1]; sig += (', ' if not sig.endswith('(') else '') + ', '.join(params) + ')'
parts, at = [], 0
for m in re.finditer(r'\bdm_body_main0\(', rest):
close = dmsh_side._close(rest, m.end(), '(', ')') - 1
parts += [rest[at:close], (', ' if rest[m.end():close].strip() else '') + off]; at = close
rest = ''.join(parts) + rest[at:]
else: sig = src[start:head]
consts = ''.join(f'constant int FX_{c["fc"]} [[function_constant({c["fc"]})]];\n' for c in calls) + \
''.join(f'constant bool FB_{k} [[function_constant({32 + k})]];\n' for k in range(NFB)) + \
''.join(f'constant bool OM_{j}_{k} [[function_constant({64 + 8 * j + k})]];\n' for j in range(len(outs)) for k in range(NFB))
body = body.replace('using namespace metal;\n', 'using namespace metal;\n\n' + consts, 1)
i0 = body.find('fragment main0_out main0(')
i1 = body.find(')\n{', i0) if i0 >= 0 else -1 # end of signature: closing parenthesis immediately followed by a newline and an opening brace (parameter attributes contain brackets such as [[buffer(0)]])
if i0 < 0 or i1 < 0: return None, 'main function signature not recognized'
fbs = ''.join(f', float4 fb{k} [[color({k}), function_constant(FB_{k})]]' for k in range(NFB))
if body[i1 - 1] == '(': fbs = fbs[2:] # main0() with no parameters at all: no leading comma (30 of Breath of the Wild's output-mapping-only variants)
body = body[:i1] + fbs + body[i1:]
decl = ''.join(f' {t} spv_o_{n} = {t}(0);\n' for t, n, c in outs)
body = body.replace(' main0_out out = {};\n', ' main0_out out = {};\n' + decl, 1)
for t, n, c in outs: body = body.replace(f'out.{n}', f'spv_o_{n}')
put = ''.join(f' if (OM_{j}_{k}) out.{n}_at{k} = spv_o_{n};\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB))
if body.count(' return out;\n') < 1: return None, 'return out not found'
body = body.replace(' return out;\n', put + ' return out;\n')
return body, {'calls': calls, 'mixed_regs': mixed, 'outputs': [{'color': c, 'type': t} for t, n, c in outs]}
lead = src[:start]
if 'using namespace metal;\n' not in lead: return None, 'no using namespace metal'
lead = lead.replace('using namespace metal;\n', 'using namespace metal;\n\n' + consts, 1)
# main0_f: main0's parameters and the tile's colours; a colour the pipeline does not read (FB_k false) is not passed to the body
members = ''.join(f' {t} {n}_at{k} [[color({k}), function_constant(OM_{j}_{k})]];\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB))
fbs = [f'float4 fb{k} [[color({k}), function_constant(FB_{k})]]' for k in range(NFB)]
args = ', '.join(([e['args']] if e['args'] else []) + ([f'FX_{i}' for i in range(len(calls))] + [f'_fb{k}' for k in range(NFB)] if calls else []))
load = ''.join(f' float4 _fb{k} = float4(0.0);\n if (FB_{k}) _fb{k} = fb{k};\n' for k in range(NFB)) if calls else ''
put = ''.join(f' if (OM_{j}_{k}) out.{n}_at{k} = r.{n};\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB))
main0_f = (f'\nstruct main0_out_f\n{{\n{members}}};\n\n{e["attr"]}fragment main0_out_f main0_f({", ".join(e["params"] + fbs)})\n{{\n'
f'{load} main0_out r = dm_body_main0({args});\n main0_out_f out = {{}};\n{put} return out;\n}}\n')
return lead + sig + ''.join(out_parts) + text[pos:] + rest + main0_f, {'calls': calls, 'mixed_regs': mixed, 'outputs': [{'color': c, 'type': t} for t, n, c in outs]}
+16 -11
View File
@@ -62,21 +62,26 @@ class Cache:
os.replace(tmp, lib)
self.store.put_file(p, lib); self.count((target, 'compiled'))
def compile_split(self, target, msl, a, b, split):
"""msl → two libraries cut from its one compile, split(the library's bytes) → (a's bytes, b's bytes): clones of what the same source gave before, or a compile (then both kept, not the whole
library, so an output stays a clone as compile's are). Raises CalledProcessError as the compile does, and what split raises"""
p = self.path(target, open(msl, 'rb').read()); q = p[:-len('.metallib')] + '_x.metallib'
if self.store.has(p) and self.store.has(q):
self.store.to_file(p, a); self.store.to_file(q, b); self.count((target, 'reused')); return
whole = f'{a}.tmp-{os.getpid()}-{threading.get_ident()}'
def compile_split(self, target, msl, libs, split):
"""msl → the libraries libs cut from its one compile, split(the library's bytes) → their bytes, in order: clones of what the same source gave before, or a compile (then the pieces
kept, not the whole library, so an output stays a clone as compile's are). The pieces are cached by their place (<digest>.metallib, <digest>_x.metallib, <digest>_x2.metallib):
one source always splits the same way. Raises CalledProcessError as the compile does, and what split raises"""
p = self.path(target, open(msl, 'rb').read())
paths = [p] + [f'{p[:-len(".metallib")]}_x{i if i > 1 else ""}.metallib' for i in range(1, len(libs))]
if all(self.store.has(x) for x in paths):
for src, dst in zip(paths, libs): self.store.to_file(src, dst)
self.count((target, 'reused')); return
whole = f'{libs[0]}.tmp-{os.getpid()}-{threading.get_ident()}'
self._compile(target, msl, whole)
try:
with open(whole, 'rb') as f: pieces = split(f.read())
finally: os.unlink(whole)
for lib, data in zip((a, b), pieces):
if len(pieces) != len(libs): raise ValueError(f'the split gave {len(pieces)} libraries, not {len(libs)}')
for lib, data in zip(libs, pieces):
with open(whole, 'wb') as f: f.write(data)
os.replace(whole, lib)
with self.store.batch(): self.store.put_file(q, b); self.store.put_file(p, a)
with self.store.batch():
for path, lib in zip(paths, libs): self.store.put_file(path, lib)
self.count((target, 'compiled'))
def _check(self, target, d, stems, mac_dir):
@@ -109,8 +114,8 @@ class Cache:
if not romfs.os.path.isdir(mac_dir): return [] # a stopped pack's .part beside the libraries
try: stamps = json.loads(self.store.get(STAMPS) or b'{}')
except ValueError: stamps = {}
names = set(romfs.os.listdir(mac_dir)) # a library with a side library was cut from another source than its .metal (compile_split, dmsh_side.py), and a compile of that source is never asked for
stems = sorted(n[:-6] for n in names if OUTPUT.fullmatch(n) and n[:-6] + 'x.metallib' not in names) # not an AppleDouble ._<name> (exFAT / FAT drives)
names = set(romfs.os.listdir(mac_dir)) # a library with a side or readable-tile library was cut from another source than its .metal (compile_split, dmsh_side.py), and a compile of that source is never asked for
stems = sorted(n[:-6] for n in names if OUTPUT.fullmatch(n) and n[:-6] + 'x.metallib' not in names and n[:-6] + 'f.metallib' not in names) # not an AppleDouble ._<name> (exFAT / FAT drives)
todo, notes = {}, []
for target, d in (('mac', mac_dir), ('ios', ios_dir)):
if targets is not None and target not in targets: continue # checking an earlier build compiles samples too
+62 -22
View File
@@ -5,9 +5,11 @@
# metallib gives every entry point a complete module, whether or not the body is shared, and two things in the host's path grow with what one file holds: metal-tt compiles every unspecialized
# entry point of a library, so a base library with them made the pipeline archive twice as large, and the base library is what every shader loads. So the compile's one library is
# cut in two: <key>_b with the plain entry points, <key>_bx with the others, which the host loads on first need (nvn_mtl.m at_fn, lo_fn). <key>_b.metal stays the plain source, which is
# what every other tool reads. cut() takes functions out of the file as `metallib --function-name` does (byte-identical for one function), and unlike that option takes several. The Metal cache
# keeps the cut libraries, not the whole one: a change to cut() changes what the cache holds, so it needs a new dmsh_mtlcache.FORMAT.
# Usage: unit(msl) → (the compile unit, {'alpha': entry point names, 'logic': entry point names}), or (None, {'why': why}); cut(library bytes, names of the side library's functions) → (base bytes, side bytes)
# what every other tool reads. cut() takes functions out of the file as `metallib --function-name` does (byte-identical for one function), and unlike that option takes several, in groups:
# the readable-tile version main0_f (dmsh_fetch.fold) is a third library, <key>_bf, of the same compile. The Metal cache keeps the cut libraries, not the whole one: a change to what cut()
# gives for the same groups changes what the cache holds, so it needs a new dmsh_mtlcache.FORMAT.
# Usage: unit(msl) → (the compile unit, {'alpha': entry point names, 'logic': entry point names}), or (None, {'why': why}); cut(library bytes, names of each further library's functions...)
# → (base bytes, each further library's bytes...); shared_body(msl) → msl with main0's body as dm_body_main0 (None on an unknown shape), calling(e, name, ret, tail) → an entry point calling it
import re, struct
import dmsh_alpha, dmsh_logic
@@ -31,23 +33,57 @@ def _params(s): # a parameter list's parameters: commas inside <>, () or [] do
return out + ([s[at:].strip()] if s[at:].strip() else [])
def _entry(msl, m):
attr, ret, name = m.groups()
head = _close(msl, m.end(), '(', ')')
body = msl.find('{', head) if head >= 0 else -1
end = _close(msl, body + 1, '{', '}') if body >= 0 else -1
if end < 0: raise ValueError(f'no body for {name}')
params = _params(msl[m.end():head - 1]); decl, args = [], []
for p in params:
d = re.sub(r'\s*\[\[.*\]\]$', '', p); a = re.search(r'(\w+)$', d)
if not a or 'function_constant' in p: raise ValueError(f'a parameter of {name}: {p[:80]}')
decl.append(d); args.append(a.group(1))
return {'attr': attr, 'ret': ret, 'name': name, 'params': params, 'decl': ', '.join(decl), 'args': ', '.join(args), 'start': m.start(), 'head': head, 'end': end}
def entries(msl):
"""The fragment entry points in source order: attr (the text before `fragment`), ret, name, params, decl (the parameters without attributes), args, start (of the entry point), head (after its
parameter list), end (after its body). Raises ValueError on a shape it does not know"""
out = []
for m in _ENTRY.finditer(msl):
attr, ret, name = m.groups()
head = _close(msl, m.end(), '(', ')')
body = msl.find('{', head) if head >= 0 else -1
end = _close(msl, body + 1, '{', '}') if body >= 0 else -1
if end < 0: raise ValueError(f'no body for {name}')
params = _params(msl[m.end():head - 1]); decl, args = [], []
for p in params:
d = re.sub(r'\s*\[\[.*\]\]$', '', p); a = re.search(r'(\w+)$', d)
if not a or 'function_constant' in p: raise ValueError(f'a parameter of {name}: {p[:80]}')
decl.append(d); args.append(a.group(1))
out.append({'attr': attr, 'ret': ret, 'name': name, 'params': params, 'decl': ', '.join(decl), 'args': ', '.join(args), 'start': m.start(), 'head': head, 'end': end})
return out
return [_entry(msl, m) for m in _ENTRY.finditer(msl)]
def entry(msl, name): # one entry point as entries() gives it, None when there is none; the others are not read (a unit's _a and _l take function constants)
return next((_entry(msl, m) for m in _ENTRY.finditer(msl) if m.group(3) == name), None)
# main0's body once, as a function the entry points that return what it computes call: main0 itself, main0_u / main0_m (dmsh_build.py fs_uint), main0_d (fs_dual) and main0_f (dmsh_fetch.fold).
# Each of them used to be a copy of the body, which the compiler built again for each. always_inline: a caller that passes constants (main0's literals for main0_f's tile read) gets them folded,
# and each entry point is a module of its own in the library anyway (metallib)
_BODY = re.compile(r'static (__attribute__\(\(always_inline\)\) )?main0_out dm_body_main0\(')
BODY = 'static __attribute__((always_inline)) main0_out dm_body_main0('
def body(msl): # dm_body_main0's definition: (its start, the end of its parameter list, the end of its body), None when there is none
m = _BODY.search(msl)
if not m: return None
head = _close(msl, m.end(), '(', ')'); end = _close(msl, msl.find('{', head) + 1, '{', '}')
return (m.start(), head, end) if head >= 0 and end >= 0 else None
def shared_body(msl):
"""msl with main0's body as dm_body_main0 and main0 calling it (unit's static body made always_inline), unchanged when it has that already; None when main0 is not of a shape entries()
knows"""
m = _BODY.search(msl)
if m: return msl if m.group(1) else msl[:m.start()] + BODY + msl[m.end():]
try: e = entry(msl, 'main0')
except ValueError: return None
if not e or e['ret'] != 'main0_out': return None
return msl[:e['start']] + f'{BODY}{e["decl"]})' + msl[e['head']:e['end']] + '\n' + calling(e, 'main0', 'main0_out', 'return out;') + msl[e['end']:]
def calling(e, name, ret, tail): # entry point name, with main0's (e) attributes and parameters, returning ret: the body's result as out, then tail
return f'{e["attr"]}fragment {ret} {name}({", ".join(e["params"])})\n{{\n main0_out out = dm_body_main0({e["args"]});\n {tail}\n}}\n'
def unit(msl) -> tuple[str | None, dict]:
@@ -61,8 +97,9 @@ def unit(msl) -> tuple[str | None, dict]:
if not alpha and not logic: return None, {'why': no_alpha or no_logic or 'no colour output'}
thin = [a for a in alpha.values() if a] + [o[0] for o in logic.values()]; targets = set().union(*(o[1] for o in logic.values()))
src, at = [], es[0]['start']
shared = bool(_BODY.search(msl)) # main0 already calls dm_body_main0 (shared_body): it is made again below as it is
for e in es:
src += [msl[at:e['start']], f'static {e["ret"]} dm_body_{e["name"]}({e["decl"]})', msl[e['head']:e['end']]]; at = e['end']
src += [msl[at:e['start']]] + ([] if shared and e['name'] == 'main0' else [f'static {e["ret"]} dm_body_{e["name"]}({e["decl"]})', msl[e['head']:e['end']]]); at = e['end']
plain = [f'{e["attr"]}fragment {e["ret"]} {e["name"]}({", ".join(e["params"])})\n{{\n return dm_body_{e["name"]}({e["args"]});\n}}\n' for e in es]
return msl[:es[0]['start']] + dmsh_alpha.HELPER + dmsh_logic.HELPER + dmsh_logic.constants(targets) + ''.join(src) + msl[at:] + '\n' + ''.join(plain + thin), {'alpha': list(alpha), 'logic': list(logic)}
@@ -102,8 +139,9 @@ def _take(b, keep, fns, tail, sections):
return bytes(head) + listing + tail + newpub + newpriv + code
def cut(lib, side):
"""(the library without the functions named in side, the library of those), from the layout pso_offline.functions reads. Raises ValueError on a file it does not know"""
def cut(lib, *groups):
"""(the library without the functions named in groups, then the library of each group's), from the layout pso_offline.functions reads: cut(lib, side) gives the base and the side library,
cut(lib, side, {'main0_f'}) the readable-tile one too. Raises ValueError on a file it does not know, a name it does not hold or a name in two groups"""
try:
if lib[:4] != b'MTLB' or struct.unpack_from('<Q', lib, 0x10)[0] != len(lib): raise ValueError('not a whole Metal library')
sections = struct.unpack_from('<QQQQQQQQ', lib, 0x18); fo = sections[0]; po = sections[2]; bo, bs = sections[6:8]
@@ -111,8 +149,10 @@ def cut(lib, side):
n = struct.unpack_from('<I', lib, fo)[0]; p = fo + 4; fns, names = [], []
for _ in range(n):
size = struct.unpack_from('<I', lib, p)[0]; t = _tags(lib, p + 4, p + size); fns.append(t); names.append(dict(t)[b'NAME'].rstrip(b'\0').decode()); p += size
missing = set(side) - set(names)
groups = [set(g) for g in groups]; named = set().union(*groups)
missing = named - set(names)
if missing: raise ValueError(f'no function {sorted(missing)[0]}')
if sum(map(len, groups)) != len(named): raise ValueError('a function in two groups')
tail = lib[p:po] # what lies between the function list and the public metadata stays
return tuple(_take(lib, keep, fns, tail, sections) for keep in ([i for i, x in enumerate(names) if x not in side], [i for i, x in enumerate(names) if x in side]))
return tuple(_take(lib, [i for i, x in enumerate(names) if keep(x)], fns, tail, sections) for keep in [lambda x: x not in named] + [g.__contains__ for g in groups])
except (struct.error, KeyError) as e: raise ValueError(f'an unreadable library ({e})') from e
+2 -1
View File
@@ -60,7 +60,7 @@ dm/gfx/tools/dmsh_build.py:vs_layer|vs_layer_entry shader:layer_output layer out
dm/gfx/tools/dmsh_build.py:fs_uint shader:integer_outputs integer fragment outputs
dm/gfx/tools/dmsh_build.py:int_inputs|vin_finish shader:integer_vertex_inputs integer vertex inputs
dm/gfx/tools/dmsh_build.py:pull_finish shader:pulling_vertex_inputs pulling vertex inputs
dm/gfx/tools/dmsh_build.py:fetch_finish|bf_ shader:readable_tile readable tiles
dm/gfx/tools/dmsh_build.py:ps_libraries shader:readable_tile readable tiles (cut from the pixel shader's one compile)
dm/gfx/tools/dmsh_build.py:vs_pad shader:vs_pad padded vertex outputs
dm/gfx/tools/dmsh_build.py:drv_reads|unfillable|DRV_FILL shader:driver_read_* driver constant segments
dm/gfx/tools/dmsh_build.py:spv_single_lane|SG_ shader:simd subgroup operations
@@ -72,6 +72,7 @@ dm/gfx/tools/dmsh_pull.* shader:pulling_vertex_inputs pulling vertex inputs
dm/gfx/tools/dmsh_fetch.py shader:readable_tile readable tiles
dm/gfx/tools/dmsh_alpha.py nvn:nvnColorStateSetAlphaTest the alpha test entry points
dm/gfx/tools/dmsh_logic.py nvn:nvnColorStateSetLogicOp the logic operation entry points
dm/gfx/tools/dmsh_side.py shader:stage:ps every pixel shader's compile unit and main0's shared body (side, integer, dual-source and readable-tile entry points)
dm/gfx/tools/dmsh_geometry.py shader:stage:gs geometry shaders
dm/gfx/tools/dmsh_facts.py shader:stage:* the translator's answer table
dm/gfx/tools/dmsh_chain.* shader:stage:* the chain version: every NVN game's libraries are rebuilt
Can't render this file because it contains an unexpected character in line 4 and column 54.
+3 -2
View File
@@ -87,8 +87,9 @@ class Coverage(unittest.TestCase):
self.assertEqual({m for m in self.imported if m + '.py' not in chain} - NO_OUTPUT, set())
def test_in_the_shader_key(self):
# made again from the restored MSL on every build, a hit too: dmsh_fetch (but for screen_varyings), dmsh_vin, dmsh_pull, dmsh_side (with dmsh_alpha, dmsh_logic), dmsh_mesh. dmsh_facts: its row is in the key
self.assertEqual(self.imported - self.keyed - NO_OUTPUT - {'dmsh_fetch', 'dmsh_vin', 'dmsh_pull', 'dmsh_side', 'dmsh_mesh', 'dmsh_facts'}, set())
# made again from the restored MSL on every build, a hit too: dmsh_fetch (but for screen_varyings), dmsh_vin, dmsh_pull, dmsh_mesh (and dmsh_side's dmsh_alpha, dmsh_logic, which
# only its unit calls). dmsh_side is keyed: fs_uint and fs_dual write main0's shared body. dmsh_facts: its row is in the key
self.assertEqual(self.imported - self.keyed - NO_OUTPUT - {'dmsh_fetch', 'dmsh_vin', 'dmsh_pull', 'dmsh_mesh', 'dmsh_facts'}, set())
def test_screen_varyings_in_the_shader_key(self): # raster_facts takes it when a shader misses the cache, and a hit restores what it gave from the reflection
self.assertIn('screen_varyings', {n.attr for n in ast.walk(self.code_fp) if isinstance(n, ast.Attribute)})
+1 -1
View File
@@ -18,7 +18,7 @@ import dmsh_atomic # noqa: E402
import dmsh_fetch # noqa: E402
import dmsh_side # noqa: E402
ns: dict[str, Any] = {'re': re, 'collections': collections} # dmsh_build.py is a script that runs a build when imported
ns: dict[str, Any] = {'re': re, 'collections': collections, 'dmsh_side': dmsh_side} # dmsh_build.py is a script that runs a build when imported
exec(compile(ast.Module(body=[n for n in ast.parse((TOOLS / 'dmsh_build.py').read_text()).body if isinstance(n, ast.FunctionDef) and n.name in {'attributes', 'in_word', 'has_word', 'int_outputs', 'fs_uint'}], type_ignores=[]), 'dmsh_build', 'exec'), ns)
attributes, has_word, fs_uint = ns['attributes'], ns['has_word'], ns['fs_uint']
+18 -15
View File
@@ -44,13 +44,13 @@ class ShaderCache(unittest.TestCase):
XC=['--msl'], MAC_RECORD='mac flags', IOSOUT=None, TARGETS={'mac'},
ios_metal=types.SimpleNamespace(RECORD='ios flags'), METAL_FP='tested Metal and SDK',
FACTS={}, MAP_ROWS={}, MAP_CONFLICT_ROWS={}, CODE_FP='source', PROFILE_ROWS=b'', PAIRS={},
DUAL_WANT=set(), BF_WANT=set(), BF_STATS=collections.Counter(), STORE=shader_cache.Store(root / 'cas.db'), out=str(root / 'out'),
DUAL_WANT=set(), BF_WANT=set(), STORE=shader_cache.Store(root / 'cas.db'), out=str(root / 'out'),
CHAIN='test-chain', clone=shutil.copyfile, shader_rule_source=lambda name: b'',
STAGE='stage/test', want=set(), OUT_KEY=re.compile(r'([0-9a-f]{16})_b'), OLD_IMAGE={}, shader_lib=shader_lib, romfs=romfs, shutil=shutil,
STAMP_BEFORE=None, INPUTS='inputs')
(root / 'out').mkdir()
names = {'tool_fingerprint', 'shader_key', 'cache_path', 'cache_outputs', 'restore_cache', 'publish_cache', 'atomic_json', 'cache_meta_path',
'bf_digest', 'bf_cache_root', 'bf_cache_restore', 'vs_pad', 'label_dir', 'output', 'commit', 'publish_library'}
'vs_pad', 'partner_inputs', 'label_dir', 'output', 'commit', 'publish_library'}
tree = ast.parse((TOOLS / 'dmsh_build.py').read_text())
self.tree = tree
nodes: list[ast.stmt] = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]
@@ -116,15 +116,6 @@ class ShaderCache(unittest.TestCase):
self.ns['DUAL_WANT'] = set()
self.assertEqual(self.digest(), original)
def test_fetch_variants_do_not_restore_override_libraries(self):
self.ns['METAL_FP'] = 'override Metal and SDK'
old = self.ns['bf_digest']('same fetch MSL', 'key')
d = self.ns['bf_cache_root'](old)
self.ns['STORE'].put(d + '/metal', b'same fetch MSL'); self.ns['STORE'].put(d + '/mac.metallib', b'untested variant')
self.ns['METAL_FP'] = 'tested Metal and SDK'
current = self.ns['bf_digest']('same fetch MSL', 'key')
self.assertFalse(self.ns['bf_cache_restore']('key', current, {}, str(Path(self.tmp.name) / 'fetch.metal')))
def test_unchanged_compiler_reuses_key(self):
self.assertEqual(self.digest(), self.digest())
@@ -440,21 +431,33 @@ class MetalPrefill(unittest.TestCase):
notes = self.cache.fill(str(self.old))
self.assertEqual(self.cache.stats['mac', 'filled'], 2, notes)
def test_compile_split_keeps_both_pieces(self):
def test_a_library_cut_with_a_readable_tile_version_does_not_prefill(self): # main0_f came from the same compile as its base (dmsh_fetch.fold)
self.earlier_libraries(self.cache.ident['mac'].hex())
(self.old / f'{2:016x}_b.metallib').write_bytes(b'CUT FROM ANOTHER SOURCE'); (self.old / f'{2:016x}_bf.metallib').write_bytes(b'TILE')
notes = self.cache.fill(str(self.old))
self.assertEqual(self.cache.stats['mac', 'filled'], 2, notes)
def test_compile_split_keeps_every_piece(self):
msl = self.root / 'unit.metal'; msl.write_bytes(b'UNIT'); a, b = self.root / 'a.metallib', self.root / 'b.metallib'
split = lambda lib: (lib[:6], lib[6:])
self.cache.compile_split('mac', str(msl), str(a), str(b), split)
self.cache.compile_split('mac', str(msl), [str(a), str(b)], split)
self.assertEqual((a.read_bytes(), b.read_bytes()), (b'TESTED', b' UNIT'))
self.assertEqual(self.cache.stats['mac', 'compiled'], 1)
a.unlink(); b.unlink()
self.cache.compile_split('mac', str(msl), str(a), str(b), lambda lib: self.fail('a second compile'))
self.cache.compile_split('mac', str(msl), [str(a), str(b)], lambda lib: self.fail('a second compile'))
self.assertEqual((a.read_bytes(), b.read_bytes()), (b'TESTED', b' UNIT'))
self.assertEqual(self.cache.stats['mac', 'reused'], 1)
c = self.root / 'c.metallib'; msl.write_bytes(b'FOLDED UNIT') # three pieces: base, side and readable-tile libraries
self.cache.compile_split('mac', str(msl), [str(a), str(b), str(c)], lambda lib: (lib[:6], lib[6:13], lib[13:]))
a.unlink(); b.unlink(); c.unlink()
self.cache.compile_split('mac', str(msl), [str(a), str(b), str(c)], lambda lib: self.fail('a second compile'))
self.assertEqual((a.read_bytes(), b.read_bytes(), c.read_bytes()), (b'TESTED', b' FOLDED', b' UNIT'))
def test_compile_split_failure_leaves_nothing(self):
msl = self.root / 'unit.metal'; msl.write_bytes(b'UNIT'); a, b = self.root / 'a.metallib', self.root / 'b.metallib'
def refuse(lib): raise ValueError('not a library')
with self.assertRaises(ValueError): self.cache.compile_split('mac', str(msl), str(a), str(b), refuse)
with self.assertRaises(ValueError): self.cache.compile_split('mac', str(msl), [str(a), str(b)], refuse)
with self.assertRaises(ValueError): self.cache.compile_split('mac', str(msl), [str(a), str(b)], lambda lib: (lib,)) # fewer pieces than libraries
self.assertEqual(sorted(p.name for p in self.root.glob('a.metallib*')), [])
self.assertFalse(b.exists()); self.assertEqual(self.cache.stats['mac', 'compiled'], 0)
+1
View File
@@ -991,6 +991,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- the shader step of a game with large translated sources has fewer Metal compiles running than `J` asks for, and `dmsh_build.py`'s own process stays busy on one core between them. Pokémon Pokopia's sources average 220 KB, and the builder spent about 0.12 s of Python on each shader, all but its system calls under the GIL, which alone would have come to about 4.2 hours of its full build. → [Rewrites that try every character of a large source](../reference/shaders.md#rewrites-that-try-every-character-of-a-large-source)
- two builds of the same shaders give different `_bl` or `_bf` libraries for some keys, of the same size, 46 bytes apart, while their MSL is the same. A byte comparison of two library folders reports them, and `regress.py` can report them as changed variants. → [A library that depends on its source's file name](../reference/shaders.md#a-library-that-depends-on-its-sources-file-name)
- the Mac or iOS shader step of a game with many pixel shaders spends most of its Metal compiles on libraries that few draws load: Pokémon Pokopia's whole map took 366,805 compiles, about 57% of them for `_ba` and `_bl`, and its runs opened none of the 5,775 of each. → [One compile for a pixel shader's side entry points](../reference/shaders.md#one-compile-for-a-pixel-shaders-side-entry-points)
- the first Mac shader build of a title, with an empty output directory and CAS and no keys, takes tens of minutes while `J` Metal workers stay busy. On an Apple M2 MacBook Pro at `J=8`, Mario Kart 8 Deluxe took 22:46 (1366 s) and Super Mario Odyssey 30:02 (1802 s). → [Cold Mac shader builds compile each pixel shader more than once](../reference/shaders.md#cold-mac-shader-builds-compile-each-pixel-shader-more-than-once)
- startup tasks can prepare the same shader more than once, even though only one object enters the warm dictionary. A measured Tears of the Kingdom startup avoided 320 duplicate preparations; this is not a steady-frame-rate claim. → [Concurrent warm tasks prepare each shader once](../reference/shaders.md#concurrent-warm-tasks-prepare-each-shader-once)
- the Mac's pipeline prebuild (`DM_PSO_PREBUILD=tool`, the NSP script's `pso_prebuild.log`) runs on far fewer workers than the Mac has: `1 workers` on an M6, where Metroid Prime Remastered's 20,233 pairs took 1,725 s and Link's Awakening's 17,742 took 667 s, and 4 on an M5 Pro, where Donkey Kong Bananza's 21,225 took 6.5 to 7.5 minutes. → [A prebuild pool sized from the Super cores](../reference/shaders.md#a-prebuild-pool-sized-from-the-super-cores)
- `fragmentFunction main0 cannot be used to build a pipeline state` (a Metal validation assertion). → [Function constants specialized at load](../reference/shaders.md#function-constants-specialized-at-load)
+10 -1
View File
@@ -2021,12 +2021,21 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
- **Symptom:** the Mac or iOS shader step of a game with many pixel shaders spends most of its Metal compiles on libraries that few draws load: Pokémon Pokopia's whole map took 366,805 compiles, about 57% of them for `_ba` and `_bl`, and its runs opened none of the 5,775 of each.
- **Cause:** the alpha test and the logic operations were each a whole copy of a pixel shader in a library of its own, compiled apart. Every pixel shader needs them, since which ones draw with either shows only in play: Xenoblade Chronicles 2, Skyward Sword HD, Dark Souls Remastered. Nothing in a game's files tells: every NVN game's binary names both functions, since the loader lists them all. A list per game would turn a miss into a wrong picture ([The alpha test through a library of its own](rendering.md#the-alpha-test-through-a-library-of-its-own), [Logic operations through a library of its own](rendering.md#logic-operations-through-a-library-of-its-own)), and compiling at run time has no `-O1`: GPU code grew by a median of 12% and up to 59%, Default and Size alike, and `-O2` took Odyssey's `alRenderMaterialUber` 25 minutes.
- **Fix:** `dm/gfx/tools/dmsh_side.py` makes one compile unit from a pixel shader's source: each entry point's body once, as a static function, and thin entry points around it, the shader's own and `<entry>_a` (`dmsh_alpha.py`) and `<entry>_l` (`dmsh_logic.py`). `metallib` gives every entry point a complete module whether or not the body is shared, and `metal-tt` compiles every unspecialized entry point of a library, which made the pipeline archive twice as large (1.85 to 3.84 MB for 25 bases). So `cut` splits the library in two, `<key>_b` with the shader's own entry points (+0.6% of archive) and `<key>_bx` with the others, loaded on first need (`at_fn`, `lo_fn`). A cut of one function is byte-identical to `metallib --function-name`, which takes only one name. The Metal cache keeps both pieces under the unit's digest (`compile_split`), so outputs stay clones. `<key>_b.metal` stays the plain source, and `dmsh_mtlcache.py` fill leaves out a library with a `_bx`, which was not compiled from it. A shader whose unit does not build gets its base from the plain source, no side library and a red line, and the host draws it without them.
- **Fix:** `dm/gfx/tools/dmsh_side.py` makes one compile unit from a pixel shader's source: each entry point's body once, as a static function, and thin entry points around it, the shader's own and `<entry>_a` (`dmsh_alpha.py`) and `<entry>_l` (`dmsh_logic.py`). `metallib` gives every entry point a complete module whether or not the body is shared, and `metal-tt` compiles every unspecialized entry point of a library, which made the pipeline archive twice as large (1.85 to 3.84 MB for 25 bases). So `cut` splits the library in two, `<key>_b` with the shader's own entry points (+0.6% of archive) and `<key>_bx` with the others, loaded on first need (`at_fn`, `lo_fn`). A cut of one function is byte-identical to `metallib --function-name`, which takes only one name. The Metal cache keeps both pieces under the unit's digest (`compile_split`), so outputs stay clones. `<key>_b.metal` stays the plain source, and `dmsh_mtlcache.py` fill leaves out a library with a `_bx`, which was not compiled from it. A shader whose unit does not build gets its base from the plain source, no side library and a red line, and the host draws it without them. The readable-tile entry is a third piece of that same compile ([Cold Mac shader builds compile each pixel shader more than once](#cold-mac-shader-builds-compile-each-pixel-shader-more-than-once)).
- **Cost:** a shared body changes the inliner's decisions (a helper now has two callers), so `main0` is no longer byte-identical: GPU code +2.1% at the median and +3.7% at most, on 125 shaders of six games on an M4 Pro, pipeline builds 62.5 against 60.6 ms. Keeping `<key>_b` as it was with a second compile for `<key>_bx` would cost 66-68% of the three compiles' CPU instead of 34-36%.
- **Measurement:** Metal CPU per pixel shader on 125 shaders of six games, three compiles to one: Pokopia 1.503 to 0.512 s with the Mac's flags and 0.830 to 0.285 s with the iPhone's; the others 0.324 to 0.114 s and 0.245 to 0.087 s. Cold builds of 1,021 Pokopia shaders (`J=10`, other jobs on the Mac): Metal compiles 2,444 to 1,095 on the Mac and 2,445 to 1,094 for iOS; the whole build's CPU 1,399 to 670 s and 959 to 451 s; wall 273 to 195 s and 232 to 127 s; libraries 359 to 358 MB. All 1,021 `_b.metal` came out unchanged, and their reflections but for the chain version and the entry point names. Not measured on a device.
- **Found on:** [Pokémon Pokopia](../../dm/games/0400A3A01EE4C000/README.md#found-on-this-game).
- **Check:** `test_dmsh_side.py`, `test_dmsh_alpha.py`, `test_dmsh_logic.py`, `make check_t_alpha`, `make check_t_logic`.
### Cold Mac shader builds compile each pixel shader more than once
- **Symptom:** the first Mac shader build of a title, with an empty output directory and CAS and no keys, takes tens of minutes while `J` Metal workers stay busy. On an Apple M2 MacBook Pro at `J=8`, Mario Kart 8 Deluxe took 22:46 (1366 s) and Super Mario Odyssey 30:02 (1802 s).
- **Cause:** a pixel shader's code went through the Metal compiler several times. The readable-tile version `<key>_bf` was a source and a compile of its own (`fetch_finish`): 13,666 of Mario Kart 8 Deluxe's 29,651 shaders and 10,512 of Odyssey's 27,984. The integer entry points `main0_u` / `main0_m` (`fs_uint`) and the dual-source `main0_d` (`fs_dual`) were each a copy of `main0`'s body, which the compiler built again for each: 4,990 of Pokémon Legends: Arceus's 6,160 pixel shaders have `main0_u`. And each compile launched `metal` and `metallib` through `xcrun`, which looks the tool up again every time (about 4 ms a launch).
- **Fix:** for every game. `dmsh_side.shared_body` makes `main0`'s body one `always_inline` function, `dm_body_main0`, which `main0`, `main0_u`, `main0_m` and `main0_d` call. `dmsh_fetch.fold` rewrites the rewritable samples in that body alone, as `(fx_i == k ? fb_k : sample)` with `fx_i` and `fb0`–`fb7` parameters of the body, and adds `main0_f`, which passes its function constants and the tile's colours; every other caller passes -1 and zeros, which the inlined body folds back to the plain sample, so `main0` and the side entry points declare no function constants. `ps_libraries` cuts `<key>_b`, `<key>_bx` and `<key>_bf` from the one compile (`dmsh_side.cut` with groups, `dmsh_mtlcache.compile_split` with a list); the host's `bf_fn` loads `main0_f`. What does not build is left out alone: a unit whose readable-tile version does not build is compiled again without it, one that does not build at all gives the base from the plain source, each with a red line. A shader with no rewritable sample gets `main0_f` only when its key is in `bf_want.tsv`, as before. `dmsh_build.py` finds `metal` and `metallib` once (`xcrun -f`) and passes `-isysroot` with the SDK, which gives the same `.air` and `.metallib` bytes as `xcrun -sdk macosx`; `MAC_RECORD` still names the `xcrun` command. Two consequences: a library cut with a `_bf` is not taken by `dmsh_mtlcache.py` fill (its base was not compiled from its `.metal`), and `dmsh_side.py` is part of the shader cache key (`CODE_FP`), since `fs_uint` and `fs_dual` call it when a shader misses the cache.
- **Measurement:** cold builds, `own_compilers`, `DMSH_TARGETS=mac`, no keys, `J=8`, Apple M2 MacBook Pro, of PR #1520's first form (the same fold, with copies still in `main0_d`): Mario Kart 8 Deluxe 22:46 (1366 s) to 14:47 (887 s), 1.54×; Super Mario Odyssey 30:02 (1802 s) to 22:23 (1343 s), 1.34×; every shader built in both. Metal CPU on 60 of Odyssey's pixel shaders (Apple M6): 25.8 to 13.6 s for 40 with a readable-tile version (0.53×), 30.5 to 19.6 s for 20 with integer entry points only (0.64×; `007d7e411ef14ebd` 24.5 to 13.6 s); the fold applied to the same 60 shaders as before; `main0`'s bitcode 5.7% smaller at the median and 0.7% larger at most. The `xcrun` lookup was about 4 of a launch's 10 ms with 2 GB resident; launching with `posix_spawn` instead of `subprocess` saved another 0.4–1.2 ms, which is not worth code of its own. Partial cold builds of the same pixel shaders on the previous chain and this one (Apple M6, translation included): Pokémon Legends: Arceus 239 in 24 to 18 s, Metroid Prime Remastered 182 in 26 to 19 s, each shader with the same libraries, entry points, side and readable-tile records and reflection, none failing (MPR's `ab809a7456f59614` has both `main0_d` and `main0_f`). GPU code and pipeline build time not measured.
- **Found on:** [Mario Kart 8 Deluxe](../../dm/games/0100152000022000/README.md#found-on-this-game), [Super Mario Odyssey](../../dm/games/0100000000010000/README.md#found-on-this-game).
- **Check:** `test_dmsh_fetch.py` (`OtherEntryPoints`: a `main0_d`, a copy of the body and a compile unit beside `main0_f`; `OutputMappingOnly`), `test_dmsh_side.py`, `test_shader_toolchain_cache.py`, `make -C dm/gfx/tests GAME=<id> check_t_feedback check_t_alpha check_t_logic`.
### Concurrent warm tasks prepare each shader once
- **Symptom:** startup tasks can prepare the same shader more than once, even though only one object enters the warm dictionary. A measured Tears of the Kingdom startup avoided 320 duplicate preparations; this is not a steady-frame-rate claim.