diff --git a/src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs
new file mode 100644
index 00000000..3277c05b
--- /dev/null
+++ b/src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs
@@ -0,0 +1,29 @@
+using System;
+using System.ComponentModel;
+
+namespace ComputeSharp.__Internals
+{
+ ///
+ /// An attribute that contains info on the number of 32 bit constants for a given shader.
+ ///
+ /// This attribute is not meant to be directly used by applications using ComputeSharp.
+ [AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This attribute is not intended to be used directly by user code")]
+ public sealed class ComputeRoot32BitConstantsAttribute : Attribute
+ {
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The number of 32 bit constants for the annotated method.
+ public ComputeRoot32BitConstantsAttribute(int count)
+ {
+ Count = count;
+ }
+
+ ///
+ /// Gets the number of 32 bit constants for the annotated method.
+ ///
+ internal int Count { get; }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs
index 7cd9407c..ce076d16 100644
--- a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs
+++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs
@@ -25,7 +25,7 @@ namespace ComputeSharp.__Internals
/// The source code for the method.
/// The collection of processed methods.
/// The collection of discovered constants.
- /// The collection of group shared buffers
+ /// The collection of group shared buffers.
public IComputeShaderSourceAttribute(
string shaderTypeName,
string[] types,
diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs
index 58bd809a..3514e5d4 100644
--- a/src/ComputeSharp.Graphics/Commands/CommandList.cs
+++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs
@@ -154,6 +154,18 @@ namespace ComputeSharp.Graphics.Commands
this.d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrier);
}
+ ///
+ /// Binds an input constant buffer to the first root parameter.
+ ///
+ /// The input buffer with the constant data to bind.
+ public readonly unsafe void SetComputeRoot32BitConstants(ReadOnlySpan data)
+ {
+ fixed (uint* p = data)
+ {
+ this.d3D12GraphicsCommandList.Get()->SetComputeRoot32BitConstants(0, (uint)data.Length, p, 0);
+ }
+ }
+
///
/// Binds an input value to a specified root parameter.
///
diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs
index 7cacdccd..e75240ac 100644
--- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs
+++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs
@@ -35,7 +35,6 @@ namespace ComputeSharp.Resources
///
/// The instance for the current resource.
///
- /// This field is dynamically accessed when loading shader dispatch data.
internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle;
///
diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs
index 3b36a343..c4a349c3 100644
--- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs
+++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs
@@ -39,7 +39,6 @@ namespace ComputeSharp.Resources
///
/// The instance for the current resource.
///
- /// This field is dynamically accessed when loading shader dispatch data.
internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle;
///
diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs
index 35ae7c08..2d0a59ac 100644
--- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs
+++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs
@@ -39,7 +39,6 @@ namespace ComputeSharp.Resources
///
/// The instance for the current resource.
///
- /// This field is dynamically accessed when loading shader dispatch data.
internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle;
///
diff --git a/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs
index 88f88aac..fe254f94 100644
--- a/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs
+++ b/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs
@@ -15,11 +15,13 @@ namespace ComputeSharp.Shaders.Extensions
/// Creates a new for a given device.
///
/// The target to use to create the root signature.
+ /// The number of 32 bit root constants to load.
/// The input descriptor ranges for the signature to create.
/// A pointer to the newly allocated instance.
/// Thrown when the creation of the root signature fails.
public static ComPtr CreateRootSignature(
this ref ID3D12Device d3D12Device,
+ int d3D12Root32BitConstantsCount,
ReadOnlySpan d3D12DescriptorRanges1)
{
using ComPtr d3D3Blob = default;
@@ -28,18 +30,22 @@ namespace ComputeSharp.Shaders.Extensions
fixed (D3D12_DESCRIPTOR_RANGE1* d3D12DescriptorRange1 = d3D12DescriptorRanges1)
{
- D3D12_ROOT_PARAMETER1* d3D12RootParameters1 = stackalloc D3D12_ROOT_PARAMETER1[d3D12DescriptorRanges1.Length];
+ D3D12_ROOT_PARAMETER1* d3D12RootParameters1 = stackalloc D3D12_ROOT_PARAMETER1[d3D12DescriptorRanges1.Length + 1];
+
+ // The initial constant buffer is initialized with 32 bit root constants.
+ // This avoids having to manage an extra buffer for each shader dispatch.
+ D3D12_ROOT_PARAMETER1.InitAsConstants(out *d3D12RootParameters1, (uint)d3D12Root32BitConstantsCount, 0);
// Pack each descriptor range into a root parameter with that single range as content
for (int i = 0; i < d3D12DescriptorRanges1.Length; i++)
{
- D3D12_ROOT_PARAMETER1.InitAsDescriptorTable(out d3D12RootParameters1[i], 1, d3D12DescriptorRange1 + i);
+ D3D12_ROOT_PARAMETER1.InitAsDescriptorTable(out d3D12RootParameters1[i + 1], 1, d3D12DescriptorRange1 + i);
}
// Root signature description wrapping the packed collection of root parameters
D3D12_VERSIONED_ROOT_SIGNATURE_DESC.Init_1_1(
out D3D12_VERSIONED_ROOT_SIGNATURE_DESC d3D12VersionedRootSignatureDescription,
- (uint)d3D12DescriptorRanges1.Length,
+ (uint)d3D12DescriptorRanges1.Length + 1,
d3D12RootParameters1);
// Serialize the root signature from the data just computed. When this is done
diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs
index 57accca0..5a1198c7 100644
--- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs
+++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Extensions;
@@ -15,32 +13,6 @@ using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Shaders
{
- ///
- /// A with helper methods to support .
- /// This type is primarily needed to avoid having fields being repeated per generic instantiation.
- ///
- internal static class ShaderRunner
- {
- ///
- /// A thread-safe map of reusable GPU buffers for captured locals.
- ///
- [ThreadStatic]
- private static ConditionalWeakTable>? variablesBuffers;
-
- ///
- /// Gets the reusable instance for a shader invocation.
- ///
- /// The to use to run the shader.
- /// The reusable instance to populate.
- [Pure]
- public static ConstantBuffer GetVariablesBuffer(GraphicsDevice device)
- {
- ConditionalWeakTable> map = variablesBuffers ??= new();
-
- return map.GetValue(device, static gpu => new(gpu, 256, AllocationMode.Default));
- }
- }
-
///
/// A responsible for performing all the necessary operations to compile and run a compute shader.
///
@@ -126,22 +98,17 @@ namespace ComputeSharp.Shaders
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, z);
- // Load the captured buffers
+ // Initialize the loop targets and the captured values
+ commandList.SetComputeRoot32BitConstants(dispatchData.Variables);
+
ReadOnlySpan resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
+ // Load the captured buffers
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
}
- // Initialize the loop targets and the captured values
- ConstantBuffer variablesBuffer = ShaderRunner.GetVariablesBuffer(device);
- ReadOnlySpan variables = dispatchData.Variables;
-
- variablesBuffer.SetData(ref MemoryMarshal.GetReference(variables), variables.Length, 0);
-
- commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle);
-
// Calculate the dispatch values
int
groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1),
@@ -186,7 +153,7 @@ namespace ComputeSharp.Shaders
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData)
{
- using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1);
+ using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1);
using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move());
diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs
index fac76157..c47050ba 100644
--- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs
+++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs
@@ -70,21 +70,21 @@ namespace ComputeSharp.Shaders.Translation.Models
///
/// Gets a with the padded data representing all the captured variables.
///
- public unsafe ReadOnlySpan Variables
+ public unsafe ReadOnlySpan Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if NET5_0
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
- ref Int4 r1 = ref Unsafe.As(ref r0);
- int length = (int)((uint)this.variablesByteSize / (uint)sizeof(Int4));
+ ref uint r1 = ref Unsafe.As(ref r0);
+ int length = (int)((uint)this.variablesByteSize / sizeof(uint));
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
#else
Span span = this.variablesArray.AsSpan(0, this.variablesByteSize);
- return MemoryMarshal.Cast(span);
+ return MemoryMarshal.Cast(span);
#endif
}
}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs
index db6b8bef..faddec59 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs
@@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
+using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
#if NET5_0
@@ -12,6 +13,8 @@ using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal;
using MemoryMarshal = Polyfills.MemoryMarshal;
#endif
+#pragma warning disable CS0618
+
namespace ComputeSharp.Shaders.Translation
{
///
@@ -58,7 +61,7 @@ namespace ComputeSharp.Shaders.Translation
{
// Resources and variables buffers
ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount);
- byte[] variables = ArrayPool.Shared.Rent(4096);
+ byte[] variables = ArrayPool.Shared.Rent(256);
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
@@ -84,6 +87,10 @@ namespace ComputeSharp.Shaders.Translation
Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!;
MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!;
+ // Extract the computed count of 32 bit root constants to load
+ D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count;
+
+ // Create a delegate from the generated shader data loader
this.dispatchDataLoader = method.CreateDelegate();
}
}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs
index 1d6f6257..b2cdd86d 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs
@@ -78,6 +78,11 @@ namespace ComputeSharp.Shaders.Translation
{
}
+ ///
+ /// Gets the number of 32 bit constants in the root signature for the shader.
+ ///
+ public int D3D12Root32BitConstantsCount { get; private set; }
+
///
/// Gets a with the loaded items for the shader.
///
@@ -164,11 +169,6 @@ namespace ComputeSharp.Shaders.Translation
List d3D12DescriptorRanges1 = new();
- // Descriptor for the buffer for captured scalar/vector variables
- D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount++);
-
- d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
-
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
index c49ab22a..724c0a19 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
+++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
@@ -16,6 +16,7 @@
+
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
index 834fb2d9..028d7ed4 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs
@@ -4,6 +4,7 @@ using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
+using ComputeSharp.__Internals;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
@@ -13,6 +14,8 @@ using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+#pragma warning disable CS0618
+
namespace ComputeSharp.SourceGenerators
{
[Generator]
@@ -54,7 +57,7 @@ namespace ComputeSharp.SourceGenerators
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
- BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol));
+ BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol, out int root32BitConstantsCount));
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
@@ -68,6 +71,7 @@ namespace ComputeSharp.SourceGenerators
// {
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
// [System.Obsolete("This method is not intended to be called directly by user code")]
+ // [return: ComputeRoot32BitConstants(42)]
// public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1)
// {
// ...
@@ -94,7 +98,13 @@ namespace ComputeSharp.SourceGenerators
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
- Literal("This method is not intended to be called directly by user code"))))))).AddModifiers(
+ Literal("This method is not intended to be called directly by user code")))))),
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", "")))
+ .AddArgumentListArguments(AttributeArgument(LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(root32BitConstantsCount))))))
+ .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))).AddModifiers(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")),
@@ -118,10 +128,13 @@ namespace ComputeSharp.SourceGenerators
/// Gets a sequence of statements to load the dispatch data for a given shader
///
/// The input instance to process.
+ /// The total number of 32 bit root constants to load.
/// The sequence of instances to load shader dispatch data.
[Pure]
- private static IEnumerable GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol)
+ private static IEnumerable GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol, out int count)
{
+ List statements = new();
+
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * 3;
@@ -135,11 +148,11 @@ namespace ComputeSharp.SourceGenerators
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
- yield return ExpressionStatement(
+ statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"),
- ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")));
+ ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))));
}
else if (HlslKnownTypes.IsScalarOrVectorType(typeName))
{
@@ -156,20 +169,24 @@ namespace ComputeSharp.SourceGenerators
fieldSize,
16);
- yield return ExpressionStatement(
- ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"));
+ statements.Add(ExpressionStatement(
+ ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})")));
rawDataOffset += fieldSize;
}
}
// After all the captured fields have been processed, ansure the reported byte size for
- // the local variables is padded to the standard alignment for constant buffers. This is
- // necessary to enable loading all the dispatch data after reinterpreting it to a sequence
- // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds.
- rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+ // the local variables is padded to a multiple of a 32 bit value. This is necessary to
+ // enable loading all the dispatch data after reinterpreting it to a sequence of values
+ // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
+ rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
- yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)));
+ statements.Add(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset))));
+
+ count = rawDataOffset / sizeof(int);
+
+ return statements;
}
}
}