From ac79e64e384554cbae9d1d70ccc9ffda83881b64 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 17 Oct 2023 14:31:47 +0200 Subject: [PATCH] Add workaround for Span pointer constructor bug --- .../Dxc/DxcShaderCompiler.cs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs index 281a8794..37636a9e 100644 --- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; @@ -105,17 +106,30 @@ internal sealed unsafe class DxcShaderCompiler fixed (char* rowMajor = "-Zpr") fixed (char* warningsAsErrors = "-Werror") { - Span arguments = stackalloc PCWSTR[] { optimization, rowMajor, warningsAsErrors }; + // We can't use stackalloc here, because the portable Span type has a bug that causes + // the constructor taking a pointer to throw if T is a type that contains a pointer field. + // So we can just rent a buffer from the pool and use that instead, at least for now. + PCWSTR[] arguments = ArrayPool.Shared.Rent(3); - this.dxcCompiler.Get()->Compile( + arguments[0] = optimization; + arguments[1] = rowMajor; + arguments[2] = warningsAsErrors; + + HRESULT hresult = this.dxcCompiler.Get()->Compile( pSource: (IDxcBlob*)dxcBlobEncoding.Get(), pSourceName: "", pEntryPoint: "Execute", pTargetProfile: "cs_6_0", - pArguments: arguments, + pArguments: arguments.AsSpan(0, 3), pDefines: ReadOnlySpan.Empty, pIncludeHandler: this.dxcIncludeHandler.Get(), - ppResult: dxcOperationResult.GetAddressOf()).Assert(); + ppResult: dxcOperationResult.GetAddressOf()); + + ArrayPool.Shared.Return(arguments); + + // Only assert the HRESULT after returning the array from the pool. Since the method itself + // can return a failure but doesn't actually throw, there's no need to throw the buffer away. + hresult.Assert(); } token.ThrowIfCancellationRequested();