Skip to content

Instantly share code, notes, and snippets.

@marysaka
Last active December 9, 2021 03:13
Show Gist options
  • Save marysaka/6add1652d959701c81f793e4dade9013 to your computer and use it in GitHub Desktop.
Save marysaka/6add1652d959701c81f793e4dade9013 to your computer and use it in GitHub Desktop.
Simple program to compile a given Metal file into a device specific dynamic Metal library (GPU code)
// clang gpu_compiler.m -fobjc-arc -fmodules -mmacosx-version-min=11.0 -framework Foundation -framework CoreGraphics -o gpu_compiler
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
void compile_to_gpu_code(id<MTLDevice> device, NSString *programString, NSString *destinationPath) {
NSError *error;
MTLCompileOptions *options = [MTLCompileOptions new];
options.libraryType = MTLLibraryTypeDynamic;
options.installName = [NSString stringWithFormat:@"@executable_path/userCreatedDylib.metallib"];
id<MTLLibrary> lib = [device newLibraryWithSource:programString
options:options
error:&error];
if(!lib && error)
{
NSLog(@"Error compiling library from source: %@", error);
return;
}
id<MTLDynamicLibrary> dynamicLib = [device newDynamicLibrary:lib
error:&error];
if(!dynamicLib && error)
{
NSLog(@"Error creating dynamic library from source library: %@", error);
return;
}
NSURL *destinationURL = [NSURL URLWithString:destinationPath];
bool result = [dynamicLib serializeToURL:destinationURL error:&error];
if (!result && error)
{
NSLog(@"Error serializing dynamic library: %@", error);
return;
}
NSLog(@"Compilation done.");
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSError *error;
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
NSString *sourcePath = [NSString stringWithUTF8String:argv[1]];
NSString *destinationPath = [NSString stringWithUTF8String:argv[2]];
NSString *source = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:&error];
compile_to_gpu_code(device, source, destinationPath);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment