diff --git a/guest/bundle/Makefile b/guest/bundle/Makefile index bdc3312ae..e5dd683b1 100644 --- a/guest/bundle/Makefile +++ b/guest/bundle/Makefile @@ -285,6 +285,17 @@ $(ORACLE_REFLECTION_LIB): tools/oracle/oracle_reflection.metal Makefile -o $(BUILD)/oracle_reflection.air xcrun -sdk macosx metallib $(BUILD)/oracle_reflection.air -o $@ +# The overlapping arguments' functions of the oracle probe oracle_overlap +# (tools/oracle/oracle_overlap.metal), built for macOS 26 and Metal 3.0 as build.sh builds it, whose +# specialisations the x86 Macs' and the M3 Max's answers were measured over; never committed. +ORACLE_OVERLAP_LIB = $(BUILD)/oracle_overlap.metallib + +$(ORACLE_OVERLAP_LIB): tools/oracle/oracle_overlap.metal Makefile + @mkdir -p $(@D) + xcrun -sdk macosx metal -c -std=metal3.0 -mmacosx-version-min=26.0 tools/oracle/oracle_overlap.metal \ + -o $(BUILD)/oracle_overlap.air + xcrun -sdk macosx metallib $(BUILD)/oracle_overlap.air -o $@ + # The library of pipeline_reflection_check's c_atomic_texture case, of a language Metal 3.0 has not # (tools/oracle/oracle_reflection_31.metal); never committed. ORACLE_REFLECTION_31_LIB = $(BUILD)/oracle_reflection_31.metallib @@ -375,6 +386,7 @@ $(VIDEO_DRIVER_TESTBIN): $(VIDEO_DRIVER_TESTOBJS) tests/video_driver_tests.cpp $ -framework IOSurface -framework CoreFoundation -o $@ test: $(SER_TESTBIN) $(AIR_TESTBIN) $(AIR_LIB) $(AIR_OLD_LIB) $(AIR_11_LIB) $(AIR_REFLECTED) $(ORACLE_REFLECTION_LIB) \ + $(ORACLE_OVERLAP_LIB) \ $(SHELL_TESTBIN) $(CI_KERNEL) $(STITCHABLE) $(STITCH_CONSTANTS) $(PATCH_LIB) $(INHERIT_TESTBIN) \ $(MEMBERS_TESTBIN) $(VIDEO_TESTBIN) $(VIDEO_H265_TESTBIN) $(VIDEO_DRIVER_TESTBIN) $(BUNDLEBIN) arch -$(ARCH) $(SER_TESTBIN) @@ -384,7 +396,7 @@ test: $(SER_TESTBIN) $(AIR_TESTBIN) $(AIR_LIB) $(AIR_OLD_LIB) $(AIR_11_LIB) $(AI RGFX_CI_KERNEL=$(CI_KERNEL) RGFX_STITCHABLE=$(STITCHABLE) RGFX_STITCH_CONSTANTS=$(STITCH_CONSTANTS) \ RGFX_AIR_ARGUMENTS=$(AIR_LIB) RGFX_AIR_ARGUMENTS_11=$(AIR_11_LIB) RGFX_LIBRARY_FILE=$(LIBRARY_FILE) \ RGFX_AIR_REFLECTED=$(AIR_REFLECTED) RGFX_ORACLE_REFLECTION=$(ORACLE_REFLECTION_LIB) \ - RGFX_PATCH=$(PATCH_LIB) $(SHELL_TESTBIN) + RGFX_PATCH=$(PATCH_LIB) RGFX_ORACLE_OVERLAP=$(ORACLE_OVERLAP_LIB) $(SHELL_TESTBIN) arch -$(ARCH) $(INHERIT_TESTBIN) $(BUNDLEBIN) arch -$(ARCH) $(MEMBERS_TESTBIN) $(BUNDLEBIN) tests/protocol_members.txt \ tests/protocol_members_releases.txt src diff --git a/guest/bundle/src/RgfxAirArguments.cpp b/guest/bundle/src/RgfxAirArguments.cpp index 59f4cf175..a23634a3e 100644 --- a/guest/bundle/src/RgfxAirArguments.cpp +++ b/guest/bundle/src/RgfxAirArguments.cpp @@ -1445,6 +1445,14 @@ bool entryPoint(const Module &m, uint64_t id, RgfxAirStage stage, RgfxAirFunctio out.name.clear(); out.stage = stage; out.arguments.clear(); + out.locationsMayOverlap = false; + // Each binding argument's table (0 buffers, 1 threadgroup memory, 2 textures, 3 samplers) and + // declared location, for locationsMayOverlap. + struct Location { + int table; + uint64_t from, to; + }; + std::vector locations; const Module::Md *entry = mdAt(m, id); if (entry == nullptr || entry->kind != Module::Md::kNode || entry->ops.size() < 3) return false; @@ -1493,7 +1501,19 @@ bool entryPoint(const Module &m, uint64_t id, RgfxAirStage stage, RgfxAirFunctio continue; // a built-in or a stage input, of no binding if (!binding(m, *arg, kindAt + 1, a)) return false; - if (a.kind == RgfxAirKind::Buffer && threadgroupMemory(m, *arg)) + const bool threadgroup = a.kind == RgfxAirKind::Buffer && threadgroupMemory(m, *arg); + const int table = threadgroup ? 1 + : a.kind == RgfxAirKind::Texture ? 2 + : a.kind == RgfxAirKind::Sampler ? 3 + : 0; + if (a.anyIndex || a.anyCount) + out.locationsMayOverlap = true; + const uint64_t from = a.index, to = static_cast(a.index) + a.count; + for (const Location &l : locations) + if (l.table == table && l.from < to && from < l.to) + out.locationsMayOverlap = true; + locations.push_back({table, from, to}); + if (threadgroup) continue; // threadgroup memory: no buffer at its index // A texture of no access the reader knows is one it may write. if (a.kind == RgfxAirKind::Texture && a.access == RgfxAirAccess::Unknown) diff --git a/guest/bundle/src/RgfxAirArguments.hpp b/guest/bundle/src/RgfxAirArguments.hpp index de13209f9..3d452ba22 100644 --- a/guest/bundle/src/RgfxAirArguments.hpp +++ b/guest/bundle/src/RgfxAirArguments.hpp @@ -114,6 +114,12 @@ struct RgfxAirFunction { std::vector arguments; std::vector constants; bool constantsRead = false; + // Whether function constants may put two of its binding arguments at overlapping locations of + // one argument table (its buffers, argument buffers among them; its threadgroup memory; its + // textures; its samplers), which Metal refuses where it makes the specialised function + // (RgfxOverlappingArgumentError): where two of them declare locations that overlap, or one's + // index or count is computed from function constants. False where none can. + bool locationsMayOverlap = false; // A kernel's `[[max_total_threads_per_threadgroup(n)]]`: n, which its entry point's node states // in a node of its own after its arguments' (`air.max_work_group_size` and n), read whether or // not its arguments read; 0 where it states none, or one not of that form. diff --git a/guest/bundle/src/RgfxLibrary.mm b/guest/bundle/src/RgfxLibrary.mm index 0ab4dd1f1..4473e9444 100644 --- a/guest/bundle/src/RgfxLibrary.mm +++ b/guest/bundle/src/RgfxLibrary.mm @@ -18,6 +18,7 @@ #import "RgfxInterop.h" #import "RgfxMetalError.h" #import "RgfxMetalPrivate.h" +#import "RgfxPipelineReflection.h" #include #include @@ -1028,6 +1029,31 @@ rgfxDeclaredConstants(const std::vector &decls) constants.push_back(k); } } + // Values that put two of its present arguments at overlapping locations of one argument table: + // Metal refuses the function here (RgfxOverlappingArgumentError), and so does the bundle, where + // its module's nodes and code tell; where they do not, the host's compile refuses its pipeline. + // Looked at only where its arguments may overlap at all (RgfxAirFunction's + // locationsMayOverlap, or arguments that did not read). + if (entry != nullptr && !constants.empty() && + (entry->type == MTLFunctionTypeKernel || entry->type == MTLFunctionTypeVertex || + entry->type == MTLFunctionTypeFragment)) { + std::shared_ptr air = [self rgfxAirFunctionNamed:entry->name]; + std::shared_ptr module = + air == nullptr || air->locationsMayOverlap ? [self rgfxAirEntryNamed:entry->name] : nullptr; + NSError *overlap = module != nullptr && !module->entries.empty() + ? RgfxOverlappingArgumentError(*module, module->entries.front(), constants.data(), + static_cast(constants.size())) + : nil; + if (overlap != nil) { + static char site; + if (rgfxLogFirst(&site)) + NSLog(@"RGFX: function %@ refused, as Metal refuses it: %@ (logged once a process)", name, + overlap.localizedDescription); + if (error) + *error = overlap; + return nil; + } + } id fn = [self rgfxFunctionNamed:name constants:constants]; // Its shadow is made with the same values, should a stitch or a link need it. if ([(id)fn isKindOfClass:[RgfxFunction class]]) diff --git a/guest/bundle/src/RgfxPipelineReflection.h b/guest/bundle/src/RgfxPipelineReflection.h index bdad0a311..25c156505 100644 --- a/guest/bundle/src/RgfxPipelineReflection.h +++ b/guest/bundle/src/RgfxPipelineReflection.h @@ -122,6 +122,26 @@ bool RgfxStageReflectionOfEntry(const RgfxAirEntries &module, const RgfxAirEntry const std::vector &buffers, RgfxStageReflection &out, NSString *__strong _Nullable *_Nonnull why); +// Metal's refusal of the entry point `entry` of the module `module` (rgfxReadAirEntries) specialised +// by the `count` function constant values at `values`, where they put two of its present arguments +// at overlapping locations of one argument table; nil where they put none there, and nil where +// that is not known. Metal refuses such values where it makes the function, by values or by a +// descriptor, at once or with a completion handler, the function's specialized name or not +// (MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "error: buffer argument b has invalid +// location (<0,1>) in k_overlap\n"): a line for each argument, in their order, whose location +// overlaps an earlier present one's in its table, with its own index and count, as `buffer` (a +// buffer, a constant buffer, an argument buffer, threadgroup memory), `texture` (a texture or an +// array of them) or `sampler`. A buffer's table is not threadgroup memory's. An argument is +// present where its predicate is true, used or not, its code dead or not; its index or count may +// be a function constant's. A kernel's, a vertex function's and a fragment function's alike +// (measured: tools/oracle/oracle_overlap, the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 +// on macOS 26.7.1 and the M3 Max on macOS 27.0.1, the same answers). Not known, so not +// refused: a predicate, index or count the module's code does not compute from the values, a +// buffer whose address space is not stated, and an argument of another table's kind (a function +// table, an acceleration structure), which the host's compile then refuses. +NSError *_Nullable RgfxOverlappingArgumentError(const RgfxAirEntries &module, const RgfxAirEntry &entry, + const RgfxFunctionConstant *_Nullable values, uint32_t count); + // As RgfxStageReflectionOfEntry, of `function`, one of our libraries' (RgfxFunction); where // `openCLMode` and the function is a kernel's of OpenCL mode (RgfxFunction's rgfxClBindings), as // its pipeline of OpenCL mode binds it (RgfxClMode.hpp). This and the creators' three below are diff --git a/guest/bundle/src/RgfxPipelineReflection.mm b/guest/bundle/src/RgfxPipelineReflection.mm index 4a826c1e0..f03b12361 100644 --- a/guest/bundle/src/RgfxPipelineReflection.mm +++ b/guest/bundle/src/RgfxPipelineReflection.mm @@ -1238,6 +1238,88 @@ std::vector RgfxStageInputBuffers(MTLStageInputOutputDescr return out; } +NSError *RgfxOverlappingArgumentError(const RgfxAirEntries &module, const RgfxAirEntry &entry, + const RgfxFunctionConstant *values, uint32_t count) +{ + // Each binding node's table: 0 buffers, 1 threadgroup memory, 2 textures, 3 samplers; -1 for a + // node of none (a built-in, a stage input), -2 for one of a table the answer is not known for. + auto tableOf = [](const RgfxAirNode &n) { + if (!n.hasLocation || isStageInput(n.kind)) + return -1; + if (n.kind == "air.buffer") + return !n.hasAddressSpace ? -2 : n.addressSpace == 3 ? 1 : 0; + if (n.kind == "air.indirect_buffer" || n.kind == "air.constant") + return 0; + if (n.kind == "air.texture") + return 2; + if (n.kind == "air.sampler") + return 3; + return -2; + }; + static const char *const kWords[] = {"buffer", "buffer", "texture", "sampler"}; + RgfxAirSpecialisation spec; + if (!rgfxAirSpecialise(module, entry, values, count, spec)) + return nil; + auto global = [&](uint64_t g, int64_t &v) { + auto it = spec.globals.find(g); + if (it == spec.globals.end()) + return false; + v = it->second; + return true; + }; + struct Taken { + int table; + uint64_t from, to; + }; + std::vector taken; + NSMutableString *what = nil; + for (const RgfxAirNode &n : entry.arguments) { + const int table = tableOf(n); + if (table == -1) + continue; + if (table == -2) + return nil; + int64_t v = 0; + if (n.predicated) { + if (!global(n.predicateGlobal, v)) + return nil; + if (v == 0) + continue; + } + uint64_t index = n.index, length = n.count; + if (n.indexIsGlobal) { + if (!global(n.indexGlobal, v) || v < 0 || v > UINT32_MAX) + return nil; + index = static_cast(v); + } + if (n.countIsGlobal) { + if (!global(n.countGlobal, v) || v < 0 || v > UINT32_MAX) + return nil; + length = static_cast(v); + } + if (length == 0) + continue; + bool overlaps = false; + for (const Taken &t : taken) + overlaps = overlaps || (t.table == table && t.from < index + length && index < t.to); + if (overlaps) { + if (n.name.empty()) + return nil; + if (what == nil) + what = [NSMutableString string]; + [what appendFormat:@"error: %s argument %s has invalid location (<%llu,%llu>) in %s\n", kWords[table], + n.name.c_str(), static_cast(index), + static_cast(length), entry.name.c_str()]; + } + taken.push_back({table, index, index + length}); + } + if (what == nil) + return nil; + return [NSError errorWithDomain:MTLLibraryErrorDomain + code:MTLLibraryErrorCompileFailure + userInfo:@{NSLocalizedDescriptionKey : [what copy]}]; +} + bool RgfxStageReflectionOfEntry(const RgfxAirEntries &module, const RgfxAirEntry &entry, const RgfxFunctionConstant *values, uint32_t count, NSString *prefix, const std::vector &buffers, RgfxStageReflection &out, diff --git a/guest/bundle/tests/shell_tests.mm b/guest/bundle/tests/shell_tests.mm index f6956802a..c26f0829f 100644 --- a/guest/bundle/tests/shell_tests.mm +++ b/guest/bundle/tests/shell_tests.mm @@ -7725,6 +7725,155 @@ static std::vector exportedFunctionMetallib() return metallibOf({ { "rgfx_exported", 3, {} } }); } +// What making a function of tools/oracle/oracle_overlap.metal's answers, for each value of its +// constants that put two present arguments of one argument table at overlapping locations or not, +// by every way of making a specialised function: values set by index, by name, by range and a copy +// of them, a descriptor and a copy of it, one naming a specialized name, and each completion +// handler form. Each answer, the function or nil and the error's domain, code and words, is Metal's +// own for the same bytes on this Mac, and the x86 Macs' (measured: oracle_overlap on the AMD Radeon +// Pro 5300M and the Intel UHD Graphics 630, macOS 26.7.1, and the M3 Max, macOS 27.0.1, the same +// answers): the bundle refuses such a function where Metal does, with no call to the host. +void test_overlapping_arguments_refused_as_metal() +{ + Fixture fx(0x20000); // the library's bytes fit + const char *path = getenv("RGFX_ORACLE_OVERLAP"); + CHECK(path != nullptr); + if (path == nullptr) + return; + NSData *bytes = [NSData dataWithContentsOfFile:@(path)]; + CHECK(bytes.length > 0); + uint32_t status = 0; + RgfxLibrary *ours = [RgfxLibrary libraryWithData:bytes.bytes + length:bytes.length + key:nullptr + device:nil + serializer:&fx.ser + status:&status]; + CHECK(ours != nil); + dispatch_data_t data = dispatch_data_create(bytes.bytes, bytes.length, nil, ^{ + (void)bytes; + }); + id theirs = [MTLCreateSystemDefaultDevice() newLibraryWithData:data error:nil]; + CHECK(theirs != nil); + if (ours == nil || theirs == nil) + return; + auto values = [](bool a, bool b, uint32_t idx, int how) { + MTLFunctionConstantValues *v = [MTLFunctionConstantValues new]; + short w = 3; + if (how == 1) { + [v setConstantValue:&a type:MTLDataTypeBool withName:@"useA"]; + [v setConstantValue:&b type:MTLDataTypeBool withName:@"useB"]; + [v setConstantValue:&w type:MTLDataTypeShort withName:@"kW"]; + [v setConstantValue:&idx type:MTLDataTypeUInt withName:@"kIdx"]; + return v; + } + if (how == 2) { + const bool both[2] = {a, b}; + [v setConstantValues:both type:MTLDataTypeBool withRange:NSMakeRange(0, 2)]; + } else { + [v setConstantValue:&a type:MTLDataTypeBool atIndex:0]; + [v setConstantValue:&b type:MTLDataTypeBool atIndex:1]; + } + [v setConstantValue:&w type:MTLDataTypeShort atIndex:2]; + [v setConstantValue:&idx type:MTLDataTypeUInt atIndex:3]; + return v; + }; + // The function `name` of `lib`, by way `way`, and the error with it. + auto make = [&](id lib, NSString *name, bool a, bool b, uint32_t idx, int way, + NSError *__strong *error) -> id { + *error = nil; + MTLFunctionDescriptor *fd = [MTLFunctionDescriptor functionDescriptor]; + fd.name = name; + fd.constantValues = values(a, b, idx, 0); + __block id got = nil; + __block NSError *gotError = nil; + dispatch_semaphore_t done = dispatch_semaphore_create(0); + NSError *e = nil; + id made = nil; + if (way <= 2) + made = [lib newFunctionWithName:name constantValues:values(a, b, idx, way) error:&e]; + else if (way == 3) + made = [lib newFunctionWithName:name constantValues:[values(a, b, idx, 0) copy] error:&e]; + else if (way == 4) + made = [lib newFunctionWithDescriptor:fd error:&e]; + else if (way == 5) + made = [lib newFunctionWithDescriptor:[fd copy] error:&e]; + else if (way == 6) { + fd.specializedName = [name stringByAppendingString:@"_spec"]; + made = [lib newFunctionWithDescriptor:fd error:&e]; + } + if (way <= 6) { + *error = e; + return made; + } + if (way == 7) + [lib newFunctionWithName:name + constantValues:values(a, b, idx, 0) + completionHandler:^(id f, NSError *err) { + got = f; + gotError = err; + dispatch_semaphore_signal(done); + }]; + else + [lib newFunctionWithDescriptor:fd + completionHandler:^(id f, NSError *err) { + got = f; + gotError = err; + dispatch_semaphore_signal(done); + }]; + dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER); + *error = gotError; + return got; + }; + static const char *const kWays[] = {"values", "names", "range", "copy", "descriptor", + "desc-copy", "specialized", "async", "async-desc"}; + NSArray *functions = @[ + @"k_overlap", @"k_tex", @"k_texarr", @"k_smp", @"k_tg", @"k_derived", @"k_idx", @"k_bufconst", + @"k_unused", @"k_dead", @"k_argbuf", @"k_three", @"v_overlap", @"f_overlap" + ]; + const bool cases[4][2] = {{false, false}, {true, false}, {false, true}, {true, true}}; + int refused = 0; + for (NSString *name in functions) { + for (int c = 0; c < 4; c++) { + for (uint32_t idx = 0; idx < ([name isEqual:@"k_idx"] ? 2u : 1u); idx++) { + for (int way = 0; way < 9; way++) { + const bool a = cases[c][0], b = cases[c][1]; + NSError *ourError = nil, *theirError = nil; + id f = make(ours, name, a, b, idx, way, &ourError); + id g = make(theirs, name, a, b, idx, way, &theirError); + const bool same = (f == nil) == (g == nil) && (ourError == nil) == (theirError == nil) && + (ourError == nil || ([ourError.domain isEqual:theirError.domain] && + ourError.code == theirError.code && + [ourError.localizedDescription + isEqual:theirError.localizedDescription])); + if (!same) + NSLog(@"FAIL detail: %@ a=%d b=%d idx=%u %s: ours %@ %@, Metal's %@ %@", name, a, b, idx, + kWays[way], f ? @"fn" : @"nil", ourError, g ? @"fn" : @"nil", theirError); + CHECK(same); + refused += f == nil; + } + } + } + } + // The x86 Macs' words, which this Mac's Metal gives too. + NSError *e = nil; + CHECK(make(ours, @"k_overlap", true, true, 0, 0, &e) == nil && [e.domain isEqual:MTLLibraryErrorDomain] && + e.code == MTLLibraryErrorCompileFailure && + [e.localizedDescription isEqual:@"error: buffer argument b has invalid location (<0,1>) in k_overlap\n"]); + CHECK(make(ours, @"k_texarr", true, true, 0, 0, &e) == nil && + [e.localizedDescription isEqual:@"error: texture argument t has invalid location (<1,1>) in k_texarr\n"]); + CHECK(make(ours, @"k_smp", true, true, 0, 4, &e) == nil && + [e.localizedDescription isEqual:@"error: sampler argument t has invalid location (<0,1>) in k_smp\n"]); + CHECK(make(ours, @"k_tg", true, true, 0, 1, &e) == nil && + [e.localizedDescription isEqual:@"error: buffer argument b has invalid location (<0,1>) in k_tg\n"]); + CHECK(make(ours, @"k_three", true, true, 0, 6, &e) == nil && + [e.localizedDescription isEqual:@"error: buffer argument c has invalid location (<0,1>) in k_three\n" + @"error: buffer argument d has invalid location (<1,1>) in k_three\n"]); + CHECK(make(ours, @"k_derived", true, true, 0, 0, &e) != nil && e == nil); + CHECK(make(ours, @"k_idx", false, false, 1, 0, &e) != nil && e == nil); + CHECK(refused > 0); +} + // A post-tessellation vertex function answers its [[patch]]'s type and control point count, from // the library's function list, and every other function MTLPatchTypeNone and -1, as Metal's own // functions answer for the same bytes (RgfxLibrary.mm, rgfxPatchOf). @@ -18390,6 +18539,7 @@ int main(int argc, char **argv) test_linked_function_specialised_on_the_wire(); test_core_image_extern_functions(); test_function_patch_answers(); + test_overlapping_arguments_refused_as_metal(); test_stitched_library_over_shadows(); test_stitch_over_specialised_functions(); test_stitched_dag_over_shadows();