|
| 1 | +#include "HLSLCompiler/MetalShaderConverter.h" |
| 2 | + |
| 3 | +#include "Utilities/Logging.h" |
| 4 | +#include "Utilities/NotReached.h" |
| 5 | + |
| 6 | +#include <metal_irconverter.h> |
| 7 | + |
| 8 | +namespace { |
| 9 | + |
| 10 | +IRShaderStage GetShaderStage(ShaderType type) |
| 11 | +{ |
| 12 | + switch (type) { |
| 13 | + case ShaderType::kVertex: |
| 14 | + return IRShaderStageVertex; |
| 15 | + case ShaderType::kPixel: |
| 16 | + return IRShaderStageFragment; |
| 17 | + case ShaderType::kGeometry: |
| 18 | + return IRShaderStageGeometry; |
| 19 | + case ShaderType::kCompute: |
| 20 | + return IRShaderStageCompute; |
| 21 | + case ShaderType::kAmplification: |
| 22 | + return IRShaderStageAmplification; |
| 23 | + case ShaderType::kMesh: |
| 24 | + return IRShaderStageMesh; |
| 25 | + default: |
| 26 | + NOTREACHED(); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +} // namespace |
| 31 | + |
| 32 | +std::vector<uint8_t> ConvertToMetalLibBytecode(ShaderType shader_type, const std::vector<uint8_t>& blob) |
| 33 | +{ |
| 34 | + IRCompiler* compiler = IRCompilerCreate(); |
| 35 | + IRObject* dxil_obj = IRObjectCreateFromDXIL(blob.data(), blob.size(), IRBytecodeOwnershipNone); |
| 36 | + |
| 37 | + if (shader_type == ShaderType::kVertex) { |
| 38 | + IRCompilerSetStageInGenerationMode(compiler, IRStageInCodeGenerationModeUseMetalVertexFetch); |
| 39 | + } |
| 40 | + |
| 41 | + IRError* error = nullptr; |
| 42 | + IRObject* metal_ir = IRCompilerAllocCompileAndLink(compiler, nullptr, dxil_obj, &error); |
| 43 | + if (!metal_ir) { |
| 44 | + Logging::Println("IRCompilerAllocCompileAndLink failed: {}", IRErrorGetCode(error)); |
| 45 | + IRErrorDestroy(error); |
| 46 | + IRObjectDestroy(dxil_obj); |
| 47 | + IRCompilerDestroy(compiler); |
| 48 | + return {}; |
| 49 | + } |
| 50 | + |
| 51 | + auto* metal_lib = IRMetalLibBinaryCreate(); |
| 52 | + IRObjectGetMetalLibBinary(metal_ir, GetShaderStage(shader_type), metal_lib); |
| 53 | + |
| 54 | + size_t metal_lib_size = IRMetalLibGetBytecodeSize(metal_lib); |
| 55 | + std::vector<uint8_t> metal_lib_bytecode(metal_lib_size); |
| 56 | + IRMetalLibGetBytecode(metal_lib, metal_lib_bytecode.data()); |
| 57 | + |
| 58 | + IRMetalLibBinaryDestroy(metal_lib); |
| 59 | + IRObjectDestroy(metal_ir); |
| 60 | + IRObjectDestroy(dxil_obj); |
| 61 | + IRCompilerDestroy(compiler); |
| 62 | + |
| 63 | + return metal_lib_bytecode; |
| 64 | +} |
0 commit comments