From 3e6f9d27c989c12791c94834e22aaaafa1f436ce Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Nov 2020 16:44:32 +0100 Subject: [PATCH] Code refactoring to the TerraFX shader compiler --- .../ComputeSharp.Core.csproj | 5 + .../Extensions/ComPtrExtensions.cs | 83 +++++++++++ .../ComputeSharp.Graphics.csproj | 1 - .../Helpers/ThrowHelper.cs | 22 --- .../Translation/ShaderCompiler2.cs | 132 ++++++++++-------- 5 files changed, 160 insertions(+), 83 deletions(-) create mode 100644 src/ComputeSharp.Core/Extensions/ComPtrExtensions.cs diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index ed9dfdf5..ff33bf1a 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -2,6 +2,11 @@ net5.0-windows10.0.19041.0 + true + + + + diff --git a/src/ComputeSharp.Core/Extensions/ComPtrExtensions.cs b/src/ComputeSharp.Core/Extensions/ComPtrExtensions.cs new file mode 100644 index 00000000..9c781ace --- /dev/null +++ b/src/ComputeSharp.Core/Extensions/ComPtrExtensions.cs @@ -0,0 +1,83 @@ +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using TerraFX.Interop; + +namespace ComputeSharp +{ + /// + /// Helper methods for working with the type. + /// + public static class ComPtrExtensions + { + /// + /// Gets whether the current instance as is not . + /// + /// The type to wrap in the current instance. + /// The input instance to check. + /// Whether or not is not . + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool Exists(this ComPtr ptr) + where T : unmanaged + { + return ptr.Get() != null; + } + + /// + /// Gets the address of the current instance as a raw double pointer. + /// + /// The type to wrap in the current instance. + /// The input instance to get the address for. + /// The raw pointer to the input instance. + /// This method is only valid when the current instance is on the stack or pinned. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void** GetVoidAddressOf(this in ComPtr ptr) + where T : unmanaged + { + return (void**)Unsafe.AsPointer(ref Unsafe.AsRef(in ptr)); + } + + /// + /// Gets the address of the current instance as a raw double pointer. + /// + /// The type to wrap in the current instance. + /// The input instance to get the address for. + /// The raw pointer to the input instance. + /// This method is only valid when the current instance is on the stack or pinned. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ComPtr Move(this in ComPtr ptr) + where T : unmanaged + { + ComPtr copy = default; + + Unsafe.AsRef(in ptr).Swap(ref copy); + + return copy; + } + + /// + /// Upcasts the current instance as a base type. + /// + /// The type of the current instance. + /// The type to cast the input instance to. + /// The input instance to upcast. + /// A instance of type . + /// + /// This method is meant to be used in a chained expression and it does not increment the reference + /// count for the input pointer. Do not expose the return value of this extension to consumers. + /// + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ComPtr Upcast(this in ComPtr ptr) + where T : unmanaged + where U : unmanaged + { + ComPtr copy = default; + + *(T**)Unsafe.AsPointer(ref copy) = ptr.Get(); + + return copy; + } + } +} diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 8a217a7a..d2bcebb7 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -7,7 +7,6 @@ - diff --git a/src/ComputeSharp.Graphics/Helpers/ThrowHelper.cs b/src/ComputeSharp.Graphics/Helpers/ThrowHelper.cs index 18ed2279..43444b20 100644 --- a/src/ComputeSharp.Graphics/Helpers/ThrowHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/ThrowHelper.cs @@ -27,28 +27,6 @@ namespace ComputeSharp.Graphics.Helpers } } - /// - /// Throws a if represents an error. - /// - /// The input to check. - /// An owned resource to dispose if it is not a null reference. - /// Thrown if represents an error. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void ThrowIfFailed(int result, void* resource) - { - if (result < 0) - { - static void Throw(int result, void* resource) - { - if (resource != null) ((IUnknown*)resource)->Release(); - - throw new Win32Exception(result); - } - - Throw(result, resource); - } - } - /// /// Throws a if represents an error. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs index 25ab56f6..c2811246 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs @@ -1,5 +1,7 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Helpers; using TerraFX.Interop; @@ -15,81 +17,79 @@ namespace ComputeSharp.Shaders.Translation /// /// The instance to use to create the bytecode for HLSL sources. /// - private static readonly IDxcCompiler* DxcCompiler; + private static readonly ComPtr DxcCompiler; /// /// The instance to use to work with . /// - private static readonly IDxcLibrary* DxcLibrary; + private static readonly ComPtr DxcLibrary; /// /// The instance used to compile shaders with . /// - private static readonly IDxcIncludeHandler* DxcIncludeHandler; + private static readonly ComPtr DxcIncludeHandler; /// /// Initializes , and /// static ShaderCompiler2() { + using ComPtr dxcCompiler = default; + using ComPtr dxcLibrary = default; + using ComPtr dxcIncludeHandler = default; + Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler; Guid dxcCompilerGuid = FX.IID_IDxcCompiler; - IDxcCompiler* dxcCompiler; + Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary; + Guid dxcLibraryGuid = FX.IID_IDxcLibrary; - int result = FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, (void**)&dxcCompiler); + int result = FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()); + + ThrowHelper.ThrowIfFailed(result); + + result = FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()); + + ThrowHelper.ThrowIfFailed(result); + + result = dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()); ThrowHelper.ThrowIfFailed(result); DxcCompiler = dxcCompiler; - - Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary; - Guid dxcLibraryGuid = FX.IID_IDxcLibrary; - IDxcLibrary* dxcLibrary; - - result = FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, (void**)&dxcLibrary); - - ThrowHelper.ThrowIfFailed(result); - DxcLibrary = dxcLibrary; - - IDxcIncludeHandler* dxcIncludeHandler; - - result = dxcLibrary->CreateIncludeHandler(&dxcIncludeHandler); - - ThrowHelper.ThrowIfFailed(result); - DxcIncludeHandler = dxcIncludeHandler; } /// - /// Compiles a new HLSL shader from the input source code + /// Compiles a new HLSL shader from the input source code. /// - /// The HLSL source code to compile - /// The bytecode for the compiled shader + /// The HLSL source code to compile. + /// The bytecode for the compiled shader. [Pure] - public static IDxcBlob* CompileShader(string source) + public static ComPtr CompileShader(ReadOnlySpan source) { + using ComPtr dxcBlobEncoding = default; + using ComPtr dxcOperationResult = default; + int result; - IDxcBlobEncoding* dxcBlobEncoding; - IDxcOperationResult* dxcOperationResult; // Get the encoded blob from the source code fixed (char* p = source) { - result = DxcLibrary->CreateBlobWithEncodingOnHeapCopy(p, (uint)source.Length * 2, 1200, &dxcBlobEncoding); + result = DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(p, (uint)source.Length * 2, 1200, dxcBlobEncoding.GetAddressOf()); ThrowHelper.ThrowIfFailed(result); } + // Try to compile the new compute shader fixed (char* entryPoint = "CSMain") fixed (char* shaderProfile = "cs_6_1") fixed (char* optimization = "-O3") { char nullTerminator = '\0'; - // Try to compile the new compute shader - result = DxcCompiler->Compile( - (IDxcBlob*)dxcBlobEncoding, + result = DxcCompiler.Get()->Compile( + dxcBlobEncoding.Upcast().Get(), (ushort*)&nullTerminator, (ushort*)entryPoint, (ushort*)shaderProfile, @@ -97,50 +97,62 @@ namespace ComputeSharp.Shaders.Translation 1, null, 0, - DxcIncludeHandler, - &dxcOperationResult); + DxcIncludeHandler.Get(), + dxcOperationResult.GetAddressOf()); - dxcBlobEncoding->Release(); - - // Handle failures during the operation that are not external to the compiler itself. - // That is, if this call is successful, the compiler might still have found an error - // in the source code, but the operation itself would have been run correctly. Here - // we handle the scenario where that is not the case, so we dispose if needed and throw. - ThrowHelper.ThrowIfFailed(result, dxcOperationResult); + ThrowHelper.ThrowIfFailed(result); } int status; - // Check whether the actual compilation was executed successfully (exit code 0) - result = dxcOperationResult->GetStatus(&status); - - ThrowHelper.ThrowIfFailed(result, dxcOperationResult); - - if (status != 0) - { - ThrowHslsCompilationException(dxcOperationResult); - } - - IDxcBlob* dxcBlob; - - result = dxcOperationResult->GetResult(&dxcBlob); + result = dxcOperationResult.Get()->GetStatus(&status); ThrowHelper.ThrowIfFailed(result); - return dxcBlob; + // The compilation was successful, so we can extract the shader bytecode + if (status == 0) + { + using ComPtr dxcBlob = default; + + result = dxcOperationResult.Get()->GetResult(dxcBlob.GetAddressOf()); + + ThrowHelper.ThrowIfFailed(result); + + return dxcBlob.Move(); + } + + return ThrowHslsCompilationException(dxcOperationResult); } - private static void ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult) + /// + /// Throws an exception when a shader compilation fails. + /// + /// The input (faulting) operation. + /// This method always throws and never actually returs. + [DoesNotReturn] + [MethodImpl(MethodImplOptions.NoInlining)] + private static ComPtr ThrowHslsCompilationException(ComPtr dxcOperationResult) { - IDxcBlobEncoding* dxcBlobEncodingError; + using ComPtr dxcBlobEncodingError = default; - int result = dxcOperationResult->GetErrorBuffer(&dxcBlobEncodingError); + int result = dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()); - dxcOperationResult->Release(); + ThrowHelper.ThrowIfFailed(result); - ThrowHelper.ThrowIfFailed(result, dxcBlobEncodingError); + using ComPtr dxcBlobUtf16Error = default; - throw new HlslCompilationException("Shader compilation error"); + result = DxcLibrary.Get()->GetBlobAsUtf16( + dxcBlobEncodingError.Upcast().Get(), + dxcBlobUtf16Error.Upcast().GetAddressOf()); + + ThrowHelper.ThrowIfFailed(result); + + string message = new string( + (char*)dxcBlobUtf16Error.Get()->GetStringPointer(), + 0, + checked((int)dxcBlobUtf16Error.Get()->GetStringLength())); + + throw new HlslCompilationException(message); } } }