From 52182f9c961925b3fdae95b8035f683de50fd3c6 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 1 Nov 2026 22:43:52 -0800 Subject: [PATCH] :new: Add the stencil and runtime source-compile oracle probes oracle_passes' stencil case clears a Depth32Float_Stencil8 attachment's stencil and stores it or not, as the depth case does for depth, to read what a DontCare store leaves there. oracle_source compiles one source at run time three ways on a device: the public newLibraryWithSource:options:error:, its Metal base class's implementation, and that class's compiler-task form with no task, which the base form calls on the device and which reaches Metal's compiler service through the base class alone. On the reims-graphics device the first two are the bundle's; the third is Metal's frontend over the device, which the runtime source compile is to build on. --- guest/bundle/tools/oracle/README.md | 3 +- guest/bundle/tools/oracle/build.sh | 2 +- guest/bundle/tools/oracle/oracle_passes.m | 55 +++++++- guest/bundle/tools/oracle/oracle_source.m | 157 ++++++++++++++++++++++ 4 files changed, 214 insertions(+), 3 deletions(-) create mode 100644 guest/bundle/tools/oracle/oracle_source.m diff --git a/guest/bundle/tools/oracle/README.md b/guest/bundle/tools/oracle/README.md index 3adadea6d..521306a01 100644 --- a/guest/bundle/tools/oracle/README.md +++ b/guest/bundle/tools/oracle/README.md @@ -11,10 +11,11 @@ Mac where it shows the gap. What they found is in |---|---| | `oracle_iosurface` | when a texture over an IOSurface sees CPU writes, and when the surface's pages see GPU writes, with and without `IOSurfaceLock`, in one process and across two; the cost of each sync | | `oracle_storage` | Managed buffers and textures with and without `didModifyRange:` / `synchronizeResource:`; Shared textures; linear textures over Shared and Managed buffers; Shared buffers written while the GPU runs | -| `oracle_passes` | what load and store actions (`DontCare`, `Clear`) leave in color, depth and MSAA attachments; memoryless textures, framebuffer fetch, raster order groups and tile pipelines | +| `oracle_passes` | what load and store actions (`DontCare`, `Clear`) leave in color, depth, stencil and MSAA attachments; memoryless textures, framebuffer fetch, raster order groups and tile pipelines | | `oracle_cmdbuf` | the order the device keeps for tracked and untracked resources, fences, barriers and command buffers; scheduled and completed timing, handler threads and order, GPU times, asynchronous pipeline creators | | `oracle_caps` | limits, feature answers (public and the SPI getters core reads) and per-pixel-format answers | | `oracle_errors` | the errors and refusals for purged resources, oversized creates, oversubscribed memory and a GPU timeout | +| `oracle_source` | what a runtime source compile makes (`newLibraryWithSource:options:error:`): the library, its bytes (a `.metallib` of AIR) and its errors, through the device's public selector, its Metal base class's, and that class's compiler-task form, which reaches Metal's compiler service without the device's `compiler` | Each probe picks its device by a substring of its name from `MTLCopyAllDevices` (`AMD`, `Intel`, `Apple`). It never calls `MTLCreateSystemDefaultDevice`, which switches a dual-GPU diff --git a/guest/bundle/tools/oracle/build.sh b/guest/bundle/tools/oracle/build.sh index 19b09d825..29ae7a9e2 100755 --- a/guest/bundle/tools/oracle/build.sh +++ b/guest/bundle/tools/oracle/build.sh @@ -8,7 +8,7 @@ here=$(cd "$(dirname "$0")" && pwd) out=${1:-/tmp/rgk-oracle/x86} arch=${2:-x86_64} mkdir -p "$out" -for p in oracle_iosurface oracle_storage oracle_passes oracle_cmdbuf oracle_caps oracle_errors; do +for p in oracle_iosurface oracle_storage oracle_passes oracle_cmdbuf oracle_caps oracle_errors oracle_source; do xcrun clang -arch "$arch" -mmacosx-version-min=26.0 -fobjc-arc -Wall \ -framework Metal -framework IOSurface -framework Foundation \ "$here/$p.m" -o "$out/$p" diff --git a/guest/bundle/tools/oracle/oracle_passes.m b/guest/bundle/tools/oracle/oracle_passes.m index 58d81da2e..d7fd82217 100644 --- a/guest/bundle/tools/oracle/oracle_passes.m +++ b/guest/bundle/tools/oracle/oracle_passes.m @@ -7,6 +7,7 @@ // row clears it to A and stores, then runs one pass of the row's actions, with or // without a draw of B over its left half; prints what each half holds after // depth a Depth32Float attachment cleared to 0.25 and stored or not (DontCare) +// stencil a Depth32Float_Stencil8 attachment's stencil cleared to 0x25 and stored or not // msaa a 4x RGBA8 attachment cleared to A and resolved, then loaded again by a pass // that only resolves: whether the samples survived a DontCare store // features a framebuffer-fetch pipeline, a raster-order-group pipeline, a tile pipeline @@ -248,6 +249,55 @@ static void case_depth(void) } } +static void case_stencil(void) +{ + printf("case stencil: Depth32Float_Stencil8 256x256, stencil cleared to 0x25 and stored\n"); + MTLTextureDescriptor *td = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatDepth32Float_Stencil8 + width:W + height:H + mipmapped:NO]; + td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + td.storageMode = MTLStorageModePrivate; + id t = [D newTextureWithDescriptor:td]; + id rb = [D newBufferWithLength:W * H options:MTLResourceStorageModeShared]; + uint32_t clears[3] = {0x25, 0x5a, 0x77}; + MTLStoreAction stores[3] = {MTLStoreActionStore, MTLStoreActionDontCare, MTLStoreActionDontCare}; + MTLLoadAction loads[3] = {MTLLoadActionClear, MTLLoadActionClear, MTLLoadActionDontCare}; + for (int k = 0; k < 3; k++) { + MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor]; + rp.depthAttachment.texture = t; + rp.depthAttachment.loadAction = MTLLoadActionClear; + rp.depthAttachment.storeAction = MTLStoreActionStore; + rp.depthAttachment.clearDepth = 0.5; + rp.stencilAttachment.texture = t; + rp.stencilAttachment.loadAction = loads[k]; + rp.stencilAttachment.storeAction = stores[k]; + rp.stencilAttachment.clearStencil = clears[k]; + id cb = [Q commandBuffer]; + [[cb renderCommandEncoderWithDescriptor:rp] endEncoding]; + id e = [cb blitCommandEncoder]; + [e copyFromTexture:t + sourceSlice:0 + sourceLevel:0 + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(W, H, 1) + toBuffer:rb + destinationOffset:0 + destinationBytesPerRow:W + destinationBytesPerImage:W * H + options:MTLBlitOptionStencilFromDepthStencil]; + [e endEncoding]; + oracle_commit_wait(cb, NULL, NULL); + const uint8_t *s = rb.contents; + size_t same = 0; + for (size_t i = 0; i < W * H; i++) + same += s[i] == s[0]; + printf(" load %-8s clear 0x%02x store %-8s -> stencil 0x%02x (%zu of %d texels equal it)\n", + load_name(loads[k]), clears[k], store_name(stores[k]), s[0], same, W * H); + } +} + static void case_msaa(void) { printf("case msaa: 4x RGBA8 256x256 cleared to A\n"); @@ -356,6 +406,8 @@ static int run_case(int argc, char **argv) case_actions(argc > 1 ? argv[1] : "private"); else if (!strcmp(argv[0], "depth")) case_depth(); + else if (!strcmp(argv[0], "stencil")) + case_stencil(); else if (!strcmp(argv[0], "msaa")) case_msaa(); else if (!strcmp(argv[0], "features")) @@ -382,7 +434,8 @@ int main(int argc, char **argv) D = nil; static const char *const all[][2] = { {"actions", "private"}, {"actions", "managed"}, {"actions", "iosurface"}, - {"depth", NULL}, {"msaa", NULL}, {"features", NULL}, + {"depth", NULL}, {"stencil", NULL}, {"msaa", NULL}, + {"features", NULL}, }; for (size_t i = 0; i < sizeof all / sizeof all[0]; i++) { if (argc > 2 && strcmp(argv[2], all[i][0])) diff --git a/guest/bundle/tools/oracle/oracle_source.m b/guest/bundle/tools/oracle/oracle_source.m new file mode 100644 index 000000000..6f46f55e3 --- /dev/null +++ b/guest/bundle/tools/oracle/oracle_source.m @@ -0,0 +1,157 @@ +// oracle_source: what a device's runtime source compile makes, and whether Metal's own frontend +// makes it on the device too: the library newLibraryWithSource:options:error: answers, its class, +// the bytes it holds (libraryDataContents, Metal's own library's: a .metallib) and their kind; the +// same through the implementation of the nearest superclass that is Metal's own (`_MTLDevice` or +// `IOGPUMetalDevice`), called on the device itself; and through that class's compiler-task form, +// newLibraryWithSource:options:compilerTask:error: with no task, which the base form calls on the +// device (measured: macOS 26.7.1 and 27, AMD, Intel and the M3, each reaching the compiler service +// through _MTLDevice's getCompilerConnectionManager:, never the device's -compiler). On a real Mac +// the three are one route; on the reims-graphics device the public selectors are the bundle's, and +// the compiler-task form called on the base class is Metal's frontend over the device with none of +// the bundle's library methods in its way. Also the device's `compiler` (SPI). +// oracle_source DEVICE [OUT] DEVICE a substring of the device's name ("" for the first); +// OUT, where given, a directory each library's bytes are written +// to (`public.metallib`, `base.metallib`, `task.metallib`), to +// compare across devices +// Lines are `key=value`. A selector the object does not respond to prints n/r and is not sent. +// Build: see README.md. +#import "oracle_common.h" +#include +#include + +// A small kernel and a vertex and fragment pair, as ANGLE's and WebKit's translators emit +// such functions at run time. +static NSString *const kSource = + @"#include \n" + @"using namespace metal;\n" + @"struct V { float4 p [[position]]; float2 uv; };\n" + @"vertex V vmain(uint i [[vertex_id]], constant float2 *xy [[buffer(0)]]) {\n" + @" V v; v.p = float4(xy[i], 0, 1); v.uv = xy[i] * 0.5 + 0.5; return v; }\n" + @"fragment float4 fmain(V v [[stage_in]], texture2d t [[texture(0)]],\n" + @" sampler s [[sampler(0)]]) { return t.sample(s, v.uv); }\n" + @"kernel void kmain(device float *o [[buffer(0)]], uint i [[thread_position_in_grid]]) {\n" + @" o[i] = float(i) * 2.0f; }\n"; + +// The bytes `lib` holds, Metal's own library's (nil where it answers none). +static NSData *library_bytes(id lib) +{ + SEL sel = sel_registerName("libraryDataContents"); + if (lib == nil || ![lib respondsToSelector:sel]) + return nil; + return ((id(*)(id, SEL))objc_msgSend)(lib, sel); +} + +// What `bytes` are: a .metallib's magic and size, and whether LLVM bitcode (AIR) is in it. +static void describe(const char *tag, id lib, NSError *error, NSData *bytes, const char *out, + const char *file) +{ + printf("%s.library=%s\n", tag, lib ? class_getName(object_getClass(lib)) : "nil"); + if (error) + printf("%s.error=%s %ld %s\n", tag, error.domain.UTF8String, (long)error.code, + [error.localizedDescription stringByReplacingOccurrencesOfString:@"\n" + withString:@" | "] + .UTF8String); + if (lib) { + NSArray *names = [[(id)lib functionNames] + sortedArrayUsingSelector:@selector(compare:)]; + printf("%s.functions=%s\n", tag, [names componentsJoinedByString:@","].UTF8String); + } + if (lib && ![lib respondsToSelector:sel_registerName("libraryDataContents")]) { + printf("%s.bytes=n/r\n", tag); + return; + } + if (bytes == nil) { + if (lib) + printf("%s.bytes=nil\n", tag); + return; + } + const uint8_t *b = bytes.bytes; + char magic[5] = {0}; + if (bytes.length >= 4) + memcpy(magic, b, 4); + // LLVM bitcode, raw (BC C0 DE) or in its wrapper (DE C0 17 0B). + BOOL bitcode = NO; + for (NSUInteger i = 0; i + 4 <= bytes.length && !bitcode; i++) + bitcode = (b[i] == 0x42 && b[i + 1] == 0x43 && b[i + 2] == 0xc0 && b[i + 3] == 0xde) || + (b[i] == 0xde && b[i + 1] == 0xc0 && b[i + 2] == 0x17 && b[i + 3] == 0x0b); + printf("%s.bytes=%lu magic=%s bitcode=%d\n", tag, (unsigned long)bytes.length, magic, bitcode); + if (out != NULL) { + NSString *path = [NSString stringWithFormat:@"%s/%s", out, file]; + printf("%s.written=%d %s\n", tag, [bytes writeToFile:path atomically:YES], path.UTF8String); + } +} + +// The nearest superclass of `cls` whose name starts with an underscore or `IOGPU`: Metal's own +// device class the device is made of. +static Class metal_base(Class cls) +{ + for (Class c = cls; c != Nil; c = class_getSuperclass(c)) { + const char *n = class_getName(c); + if (!strcmp(n, "_MTLDevice") || !strncmp(n, "IOGPU", 5)) + return c; + } + return Nil; +} + +int main(int argc, char **argv) +{ + setvbuf(stdout, NULL, _IOLBF, 0); + if (argc < 2) { + fprintf(stderr, "usage: %s DEVICE [OUT]\n", argv[0]); + return 2; + } + const char *out = argc > 2 ? argv[2] : NULL; + @autoreleasepool { + id d = oracle_device(argv[1]); + oracle_header("oracle_source", d); + for (Class c = object_getClass(d); c != Nil; c = class_getSuperclass(c)) + printf("class=%s\n", class_getName(c)); + SEL compilerSel = sel_registerName("compiler"); + if ([(id)d respondsToSelector:compilerSel]) { + id compiler = ((id(*)(id, SEL))objc_msgSend)(d, compilerSel); + printf("compiler=%s\n", compiler ? class_getName(object_getClass(compiler)) : "nil"); + } else { + printf("compiler=n/r\n"); + } + + MTLCompileOptions *options = [MTLCompileOptions new]; + SEL sel = @selector(newLibraryWithSource:options:error:); + NSError *error = nil; + double t0 = oracle_now_ms(); + id lib = [d newLibraryWithSource:kSource options:options error:&error]; + printf("public.ms=%.1f\n", oracle_now_ms() - t0); + describe("public", lib, error, library_bytes(lib), out, "public.metallib"); + + Class base = metal_base(object_getClass(d)); + printf("base=%s\n", base ? class_getName(base) : "none"); + if (base != Nil && class_getInstanceMethod(base, sel) != NULL) { + IMP imp = class_getMethodImplementation(base, sel); + BOOL own = imp == class_getMethodImplementation(object_getClass(d), sel); + printf("base.same_as_public=%d\n", own); + error = nil; + t0 = oracle_now_ms(); + id blib = ((id(*)(id, SEL, NSString *, MTLCompileOptions *, NSError **))imp)( + d, sel, kSource, options, &error); + printf("base.ms=%.1f\n", oracle_now_ms() - t0); + describe("base", blib, error, library_bytes(blib), out, "base.metallib"); + } else { + printf("base.selector=n/r\n"); + } + + SEL tsel = sel_registerName("newLibraryWithSource:options:compilerTask:error:"); + if (base != Nil && class_getInstanceMethod(base, tsel) != NULL) { + IMP imp = class_getMethodImplementation(base, tsel); + printf("task.device_overrides=%d\n", + imp != class_getMethodImplementation(object_getClass(d), tsel)); + error = nil; + t0 = oracle_now_ms(); + id tlib = ((id(*)(id, SEL, NSString *, MTLCompileOptions *, id, NSError **))imp)( + d, tsel, kSource, options, nil, &error); + printf("task.ms=%.1f\n", oracle_now_ms() - t0); + describe("task", tlib, error, library_bytes(tlib), out, "task.metallib"); + } else { + printf("task.selector=n/r\n"); + } + } + return 0; +}