diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs
index 6ce9b023..284d320d 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs
@@ -53,7 +53,7 @@ partial class ComputeShaderDescriptorGenerator
token.ThrowIfCancellationRequested();
// Compile the shader bytecode
- byte[] bytecode = DxcShaderCompiler.Instance.Compile(key.HlslSource.AsSpan(), token);
+ byte[] bytecode = DxcShaderCompiler.Instance.Compile(key.HlslSource.AsSpan(), key.CompileOptions, token);
token.ThrowIfCancellationRequested();
@@ -72,6 +72,24 @@ partial class ComputeShaderDescriptorGenerator
return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token);
}
+ ///
+ /// Extracts the compile options for the current shader.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ /// The requested compile options to use to compile the shader, if present.
+ public static CompileOptions GetCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol)
+ {
+ // If a [CompileOptions] annotation is present, return the explicit options
+ if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.CompileOptionsAttribute", out AttributeData? attributeData) ||
+ structDeclarationSymbol.ContainingAssembly.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.CompileOptionsAttribute", out attributeData))
+ {
+ return (CompileOptions)attributeData.ConstructorArguments[0].Value!;
+ }
+
+ return CompileOptions.Default;
+ }
+
///
/// Gets any diagnostics from a processed instance.
///
diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs
index 92abac1d..c6253f92 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs
@@ -107,8 +107,13 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
token.ThrowIfCancellationRequested();
+ // Get the compile options as well
+ CompileOptions compileOptions = HlslBytecode.GetCompileOptions(diagnostics, typeSymbol);
+
+ token.ThrowIfCancellationRequested();
+
// Prepare the lookup key for the HLSL shader bytecode
- HlslBytecodeInfoKey hlslInfoKey = new(hlslSource, isCompilationEnabled);
+ HlslBytecodeInfoKey hlslInfoKey = new(hlslSource, compileOptions, isCompilationEnabled);
// Try to get the HLSL bytecode
HlslBytecodeInfo hlslInfo = HlslBytecode.GetBytecode(ref hlslInfoKey, token);
diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
index 8782392a..130b2861 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
+++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
@@ -55,6 +55,7 @@
+
diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs
index 274f712b..9e2edff9 100644
--- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs
+++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs
@@ -1,5 +1,4 @@
using System;
-using System.Buffers;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
@@ -71,42 +70,136 @@ internal sealed unsafe class DxcShaderCompiler
/// Compiles a new HLSL shader from the input source code.
///
/// The HLSL source code to compile.
+ /// The compile options to use.
/// The used to cancel the operation, if needed.
/// The bytecode for the compiled shader.
- public byte[] Compile(ReadOnlySpan source, CancellationToken token)
+ public byte[] Compile(ReadOnlySpan source, CompileOptions compileOptions, CancellationToken token)
{
using ComPtr dxcResult = default;
- // 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);
-
- // Try to compile the new compute shader
- fixed (char* pSourceName = "")
- fixed (char* pEntryPoint = "Execute")
- fixed (char* pTargetProfile = "cs_6_0")
- fixed (char* optimization = "-O3")
- fixed (char* rowMajor = "-Zpr")
- fixed (char* warningsAsErrors = "-Werror")
- fixed (PCWSTR* pArguments = arguments)
+ using (ComPtr dxcCompilerArgs = default)
{
- pArguments[0] = optimization;
- pArguments[1] = rowMajor;
- pArguments[2] = warningsAsErrors;
-
- using ComPtr dxcCompilerArgs = default;
-
// Create the arguments to append others to
- this.dxcUtils.Get()->BuildArguments(
- pSourceName: pSourceName,
- pEntryPoint: pEntryPoint,
- pTargetProfile: pTargetProfile,
- pArguments: pArguments,
- argCount: 3,
- pDefines: null,
- defineCount: 0,
- ppArgs: dxcCompilerArgs.GetAddressOf()).Assert();
+ fixed (char* pSourceName = "")
+ fixed (char* pEntryPoint = "Execute")
+ fixed (char* pTargetProfile = "cs_6_0")
+ fixed (char* pRowMajor = "-Zpr")
+ {
+ // The row major argument is the only one always set automatically.
+ // All the others are dynamically added based on the selected options.
+ PCWSTR rowMajorArgument = pRowMajor;
+
+ this.dxcUtils.Get()->BuildArguments(
+ pSourceName: pSourceName,
+ pEntryPoint: pEntryPoint,
+ pTargetProfile: pTargetProfile,
+ pArguments: &rowMajorArgument,
+ argCount: 1,
+ pDefines: null,
+ defineCount: 0,
+ ppArgs: dxcCompilerArgs.GetAddressOf()).Assert();
+ }
+
+ // Add any other optional arguments
+ fixed (char* pAllResourcesBound = "-all-resources-bound")
+ fixed (char* pDisableValidation = "-Vd")
+ fixed (char* pDisableOptimization = "-Od")
+ fixed (char* pAvoidFlowControl = "-Gfa")
+ fixed (char* pPreferFlowControl = "-Gfp")
+ fixed (char* pEnableStrictness = "-Ges")
+ fixed (char* pIeeeStrictness = "-Gis")
+ fixed (char* pEnableBackwardsCompatibility = "-Gec")
+ fixed (char* pOptimizationLevel0 = "-O0")
+ fixed (char* pOptimizationLevel1 = "-O1")
+ fixed (char* pOptimizationLevel2 = "-O2")
+ fixed (char* pOptimizationLevel3 = "-O3")
+ fixed (char* pWarningsAreErrors = "-WX")
+ fixed (char* pResourcesMayAlias = "-res-may-alias")
+ fixed (char* pStripReflectionData = "-Qstrip_reflect")
+ {
+ // Helper to add a new argument
+ static void AddArgument(IDxcCompilerArgs* args, char* pArgument)
+ {
+ PCWSTR argument = pArgument;
+
+ args->AddArguments(&argument, 1).Assert();
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.AllResourcesBound))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pAllResourcesBound);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.DisableValidation))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pDisableValidation);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.DisableOptimization))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pDisableOptimization);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.AvoidFlowControl))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pAvoidFlowControl);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.PreferFlowControl))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pPreferFlowControl);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.EnableStrictness))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pEnableStrictness);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.IeeeStrictness))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pIeeeStrictness);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.EnableBackwardsCompatibility))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pEnableBackwardsCompatibility);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.OptimizationLevel0))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pOptimizationLevel0);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.OptimizationLevel1))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pOptimizationLevel1);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.OptimizationLevel2))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pOptimizationLevel2);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.OptimizationLevel3))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pOptimizationLevel3);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.WarningsAreErrors))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pWarningsAreErrors);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.ResourcesMayAlias))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pResourcesMayAlias);
+ }
+
+ if (compileOptions.HasFlag(CompileOptions.StripReflectionData))
+ {
+ AddArgument(dxcCompilerArgs.Get(), pStripReflectionData);
+ }
+ }
fixed (char* pSource = source)
{
@@ -127,8 +220,6 @@ internal sealed unsafe class DxcShaderCompiler
riid: &dxcResultIid,
ppResult: (void**)dxcResult.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();
diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs b/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs
index 78bc27a6..d84586d5 100644
--- a/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs
+++ b/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs
@@ -6,5 +6,9 @@ namespace ComputeSharp.SourceGenerators.Models;
/// A model with info to be a unique key for instances.
///
/// The input HLSL source code.
+/// The compile options.
/// Whether compilation should be attempted for the current info.
-internal sealed record HlslBytecodeInfoKey(string HlslSource, bool IsCompilationEnabled);
\ No newline at end of file
+internal sealed record HlslBytecodeInfoKey(
+ string HlslSource,
+ CompileOptions CompileOptions,
+ bool IsCompilationEnabled);
\ No newline at end of file
diff --git a/src/ComputeSharp/Core/Attributes/CompileOptionsAttribute.cs b/src/ComputeSharp/Core/Attributes/CompileOptionsAttribute.cs
new file mode 100644
index 00000000..4348a06f
--- /dev/null
+++ b/src/ComputeSharp/Core/Attributes/CompileOptionsAttribute.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace ComputeSharp;
+
+///
+/// An attribute that indicates the compile options that should be used when compiling a given compute shader.
+///
+/// This attribute can be used to annotate shader types as follows:
+///
+/// [CompileOptions(CompileOptions.IeeeStrictness | CompileOptions.OptimizationLevel3)]
+/// struct MyShader : IComputeShader
+/// {
+/// }
+///
+///
+///
+/// This attribute can also be added to a whole assembly, and will be used by default if not overridden by a shader type.
+///
+///
+/// The compiler options to use to compile the shader.
+[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = false)]
+public sealed class CompileOptionsAttribute(CompileOptions options) : Attribute
+{
+ ///
+ /// Gets the compile options to use to compile the shader.
+ ///
+ public CompileOptions Options { get; } = options;
+}
\ No newline at end of file
diff --git a/src/ComputeSharp/Core/Attributes/Enums/CompileOptions.cs b/src/ComputeSharp/Core/Attributes/Enums/CompileOptions.cs
new file mode 100644
index 00000000..77ff9663
--- /dev/null
+++ b/src/ComputeSharp/Core/Attributes/Enums/CompileOptions.cs
@@ -0,0 +1,150 @@
+using System;
+
+namespace ComputeSharp;
+
+///
+/// Flags to control the options that can be used to compile a compute shader.
+///
+[Flags]
+public enum CompileOptions
+{
+ ///
+ /// Enables agressive flattening.
+ ///
+ ///
+ /// This flag maps to -all-resources-bound.
+ ///
+ AllResourcesBound = 1 << 0,
+
+ ///
+ /// Directs the compiler not to validate the generated code against known capabilities and constraints.
+ /// This option should only be used with shaders that have been successfully compiled in the past.
+ /// DirectX always validates shaders before it sets them to a device.
+ ///
+ ///
+ /// This flag maps to -Vd.
+ ///
+ DisableValidation = 1 << 1,
+
+ ///
+ /// Directs the compiler to skip optimization steps during code generation.
+ /// This option should only be used for debug purposes.
+ ///
+ ///
+ /// This flag maps to -Od.
+ ///
+ DisableOptimization = 1 << 2,
+
+ ///
+ /// Directs the compiler to not use flow-control constructs where possible.
+ ///
+ ///
+ /// This flag maps to -Gfa.
+ ///
+ AvoidFlowControl = 1 << 3,
+
+ ///
+ /// Directs the compiler to prefer using flow-control constructs where possible.
+ ///
+ ///
+ /// This flag maps to -Gfp.
+ ///
+ PreferFlowControl = 1 << 4,
+
+ ///
+ /// Forces strict compile, which might not allow for legacy syntax.
+ /// By default, the compiler disables strictness on deprecated syntax.
+ ///
+ ///
+ /// This flag maps to -Ges.
+ ///
+ EnableStrictness = 1 << 5,
+
+ ///
+ /// Forces the IEEE strict compile which avoids optimizations that may break IEEE rules.
+ ///
+ ///
+ /// This flag maps to -Gis.
+ ///
+ IeeeStrictness = 1 << 6,
+
+ ///
+ /// Enables backward compatibility mode.
+ ///
+ ///
+ /// This flag maps to -Gec.
+ ///
+ EnableBackwardsCompatibility = 1 << 7,
+
+ ///
+ /// Directs the compiler to use the lowest optimization level. If this option is set, the compiler
+ /// might produce slower code but produces the code more quickly. This option should be set when
+ /// shaders are developed iteratively, as it can reduce compilation times.
+ ///
+ ///
+ /// This flag maps to -O0.
+ ///
+ OptimizationLevel0 = 1 << 8,
+
+ ///
+ /// Directs the compiler to use the second lowest optimization level.
+ ///
+ ///
+ /// This flag maps to -O1.
+ ///
+ OptimizationLevel1 = OptimizationLevel0 | (1 << 9),
+
+ ///
+ /// Directs the compiler to use the second highest optimization level.
+ ///
+ ///
+ /// This flag maps to -O2.
+ ///
+ OptimizationLevel2 = OptimizationLevel1 | (1 << 10),
+
+ ///
+ /// Directs the compiler to use the highest optimization level. If this option is set, the compiler
+ /// produces the best possible code but might take significantly longer to do so. This option should
+ /// be set for final builds of an application when performance is the most important factor.
+ ///
+ ///
+ /// This flag maps to -O3.
+ ///
+ OptimizationLevel3 = OptimizationLevel2 | (1 << 11),
+
+ ///
+ /// Directs the compiler to treat all warnings as errors when it compiles the shader code. This
+ /// option is recommended for new shader code, so that warnings can be resolved and the
+ /// number of hard-to-find code defects can be minimized.
+ ///
+ ///
+ /// This flag maps to -WX.
+ ///
+ WarningsAreErrors = 1 << 12,
+
+ ///
+ /// Directs the compiler that UAVs (uniform access views) and SRVs (shader resource views) may alias.
+ ///
+ ///
+ /// This flag maps to -res-may-alias.
+ ///
+ ResourcesMayAlias = 1 << 13,
+
+ ///
+ /// Strips the reflection data from the generated shader bytecode. The bytecode size will be significantly lower, but
+ /// trying to perform reflection on the shader will return inaccurate results. Recommend if not reflection is done.
+ ///
+ ///
+ /// This flag maps to -Qstrip_reflect.
+ ///
+ StripReflectionData = 1 << 14,
+
+ ///
+ /// The default options for shaders compiled by ComputeSharp.
+ ///
+ ///
+ /// This option does not include a flag to pack matrices in column-major order on input and output from the shader,
+ /// as that is always enabled by default (it is necessary to ensure the constant buffer matches the managed layout).
+ ///
+ Default = OptimizationLevel3 | WarningsAreErrors
+}
\ No newline at end of file
diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
index 01f99b32..f18ea12d 100644
--- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
+++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
@@ -559,6 +559,54 @@ namespace ComputeSharp.Tests
this.buffer[ThreadIds.X] *= x;
}
}
+
+ [TestMethod]
+ public void ShaderWithStrippedReflectionData()
+ {
+ ShaderInfo info1 = ReflectionServices.GetShaderInfo();
+
+ // With no reflection data available, the instruction count is just 0
+ Assert.AreEqual(0u, info1.InstructionCount);
+
+ ShaderInfo info2 = ReflectionServices.GetShaderInfo();
+
+ // Sanity check, here instead we should have some valid count
+ Assert.AreNotEqual(0u, info2.InstructionCount);
+
+ // Verify that the bytecode with stripped reflection is much smaller
+ Assert.IsTrue(info1.HlslBytecode.Length < 1800);
+ Assert.IsTrue(info2.HlslBytecode.Length > 3300);
+ }
+
+ [AutoConstructor]
+ [EmbeddedBytecode(DispatchAxis.X)]
+ [CompileOptions(CompileOptions.Default | CompileOptions.StripReflectionData)]
+ [GeneratedComputeShaderDescriptor]
+ internal readonly partial struct ShaderWithStrippedReflectionData1 : IComputeShader
+ {
+ public readonly ReadWriteBuffer buffer;
+
+ ///
+ public void Execute()
+ {
+ this.buffer[ThreadIds.X] = ThreadIds.X;
+ }
+ }
+
+ [AutoConstructor]
+ [EmbeddedBytecode(DispatchAxis.X)]
+ [CompileOptions(CompileOptions.Default)]
+ [GeneratedComputeShaderDescriptor]
+ internal readonly partial struct ShaderWithStrippedReflectionData2 : IComputeShader
+ {
+ public readonly ReadWriteBuffer buffer;
+
+ ///
+ public void Execute()
+ {
+ this.buffer[ThreadIds.X] = ThreadIds.X;
+ }
+ }
}
}