35#ifndef __BC_METAL_UTILS_H__
36#define __BC_METAL_UTILS_H__
40#import <Metal/Metal.h>
43extern id<MTLDevice> neko_metal_device(
void);
44extern id<MTLLibrary> neko_metal_library(
void);
51static NSMutableDictionary<NSString *, id<MTLComputePipelineState>> *bc_pipelines = nil;
53static inline id<MTLComputePipelineState> bc_get_pipeline(NSString *name) {
55 bc_pipelines = [NSMutableDictionary
new];
57 id<MTLComputePipelineState> pso = bc_pipelines[name];
60 id<MTLLibrary> lib = neko_metal_library();
61 id<MTLFunction> fn = [lib newFunctionWithName:name];
63 NSLog(
@"Metal BC: kernel '%@' not found in library", name);
66 pso = neko_metal_new_pipeline(fn, NEKO_METAL_MAX_THREADS, &err);
68 NSLog(
@"Metal BC: pipeline error for '%@': %@", name, err);
71 bc_pipelines[name] = pso;
80#define METAL_BC_NTHREADS 1024
82static inline void bc_dispatch_1d(id<MTLCommandQueue> queue,
83 id<MTLComputePipelineState> pso,
84 void (^encode)(id<MTLComputeCommandEncoder>),
88 id<MTLCommandBuffer> cb = [queue commandBuffer];
89 id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
90 [enc setComputePipelineState:pso];
92 MTLSize threads = MTLSizeMake(n, 1, 1);
93 NSUInteger tpg = n < METAL_BC_NTHREADS ? n : METAL_BC_NTHREADS;
94 if (tpg > pso.maxTotalThreadsPerThreadgroup)
95 tpg = pso.maxTotalThreadsPerThreadgroup;
96 MTLSize tg = MTLSizeMake(tpg, 1, 1);
97 [enc dispatchThreads:threads threadsPerThreadgroup:tg];
100 [cb waitUntilCompleted];