Erfan Ahmadi.

Advanced HLSL · Part 2

Wait, we have templates in GPU shaders?

Why our HLSL library looks heavily templated.

A lot of people are surprised when they see our HLSL shader library, which is heavily templated. And yeah, at first it can look a bit intimidating, just like the internals of the C++ standard library. But it’s all for a reason.

Also, even though we compile HLSL to SPIR-V for Vulkan, most of this post applies to anyone using DXC HLSL 202x for DirectX/DXIL as well.

By the way, you can switch from light mode to dark mode with the button in the top right corner, if you’re more comfortable reading code in blog posts that way.

So why do we have the ugly templates?

Most of the reasons are the same as why you’d want templates in C++ on the CPU side, but here are some of our most common patterns:

1. Specializing on each GPU feature or extension

A lot of Vulkan features and extensions tell you what you can do in a shader. For example, the subgroupArithmetic feature enables doing a scan or a reduction over a subgroup. For DirectX people a subgroup is a wave, and it’s the same as having WaveActiveSum and WavePrefixSum.

If the feature is not there, we implement one ourselves easily, using subgroupShuffleUp in a loop of log⁡2(N)\log_2(N) steps.

GPU supports subgroup arithmetic?shaderSubgroupArithmetic
yes

Use it

subgroupAdd: 1 instruction

value11111111
sum88888888
no

Do it ourselves

subgroupShuffleUp: log2(8) = 3 steps

value11111111
up 112222222
up 212344444
up 412345678
sum88888888
A subgroup of 8 invocations, each holding a 1. Both ways end with the sum in every invocation.

So what we do is have a struct of device capabilities generated at runtime, and we write specializations for these:

What the user writesHLSL
struct device_capabilities
{
const static bool shaderSubgroupArithmetic = true; // or false, or runtime generated
};
uint32_t sum = subgroupSum<uint32_t, device_capabilities>(value);
The implementation, inside the libraryHLSL
template<typename T>
struct sum<T, true>
{
// the GPU can do it: one subgroupAdd
};
template<typename T>
struct sum<T, false>
{
// it can't: subgroupShuffleUp in a log2(N) loop
};
// Just like in C++, you can't partially specialize a function.
// So we specialize structs, and this function picks one of the two.
template<typename T, class Caps>
T subgroupSum(T value)
{
return sum<T, Caps::shaderSubgroupArithmetic>::call(value);
}

Try it out yourself

You can override this struct with your minimum requirements, and it doesn’t have to be just-in-time generated.

The full code of both versions is in subgroup/arithmetic_portability_impl.hlsl.

2. Accessors instead of global resources

We want the users of our algorithms to input their data however they want. The data you want to scan might come from a Uniform Buffer, a StructuredBuffer, a Buffer Device Address, or hell, even an Image or Workgroup memory.

Where does the input data come from?
  • Uniform bufferConstantBuffer<T>Uniform
  • Structured bufferRWStructuredBuffer<T>StorageBuffer
  • Buffer device addressvk::BufferPointer<T>PhysicalStorageBuffer
  • ImageRWTexture2D<T>UniformConstant
  • Workgroup memorygroupshared T data[N]Workgroup
Each one is written differently in HLSL, and is a different storage class in SPIR-V.

It all affects how the algorithm has to place execution and memory barriers, or even do atomics! And we don’t want to rewrite the logic based on where that data comes from. Welp, we don’t have generic pointers, and everything comes from a storage class.

So the trick we did is an accessor pattern. It’s basically an opaque thing to the algorithm, which implements some functions like get and set.

What the user providesHLSL
struct MyAccessor
{
uint32_t get(uint32_t i) { return myBuffer[i]; }
void set(uint32_t i, uint32_t v) { myBuffer[i] = v; }
};
What the algorithm seesHLSL
template<class Accessor>
void algorithm(inout Accessor accessor)
{
uint32_t v = accessor.get(i);
// do something
accessor.set(i, v);
}

Try it out yourself

And we enforce that layout using our own implementation of Concepts! (I’m getting ahead of myself now, that’s for a later blog.)

3. Other nice things

numeric_limits, like in C++:

HLSL
numeric_limits<uint32_t>::max // 4294967295
numeric_limits<float32_t>::max // 3.40282347e+38
numeric_limits<T>::max // in a template: the largest value T can hold, whatever T is

Try it out yourself

Type traits, to ask questions about a type while compiling:

HLSL
vector_traits<float32_t3>::scalar_type // float32_t
vector_traits<float32_t3>::Dimension // 3
is_integral_v<uint32_t> // true
is_same_v<T, float32_t> // true only when T is float32_t

Try it out yourself

And enable_if_t, to make a function exist only for the types it makes sense for:

HLSL
// this function only exists for integers
template<typename T>
enable_if_t<is_integral_v<T>, bool> isPowerOfTwo(T x);
isPowerOfTwo(8u); // fine
isPowerOfTwo(8.0f); // error

Try it out yourself

✕
error: no matching function for call to 'isPowerOfTwo'
note: candidate template ignored: disabled by 'enable_if' [with T = float]

4. SPIR-V

Now we get to the juicy part, which follows Advanced HLSL, Part 1: Inline SPIR-V. Remember when we called SPIR-V intrinsics directly, like this?

HLSL
⋮…
3[[vk::ext_instruction(/*OpAtomicIAdd*/ 234)]]
4uint32_t atomicIAdd([[vk::ext_reference]] uint32_t ptr,
5 uint32_t scope, uint32_t semantics, uint32_t value);
⋮…
10 atomicIAdd(counters[0], /*Device*/ 1, /*Relaxed*/ 0, 1u);
⋮…
SPIR-Vexcerpt
%17 = OpAtomicIAdd %uint %16 %uint_1 %uint_0 %uint_1
The call: a pointer to counters[0], scope Device (1), semantics Relaxed (0), and the value 1.

Try it out yourself

This is literally the same as calling the SPIR-V atomic instruction directly. But notice the I: it means it only works on integral types like uint32_t, so if you want floats you need atomicFAdd (OpAtomicFAddEXT). That’s usually not a problem with higher-level languages, they will just deduce your type and call the correct instruction. We can do that here too, with templated overloads and enable_if_t!

HLSL
template<typename T>
[[vk::ext_instruction(spv::OpAtomicIAdd)]]
enable_if_t<is_integral_v<T>, T> atomicAdd(/* ... */);
template<typename T>
[[vk::ext_instruction(spv::OpAtomicFAddEXT)]]
enable_if_t<is_same_v<T, float32_t>, T> atomicAdd(/* ... */);
atomicAdd(counters[0], scope, semantics, 1u);
atomicAdd(weights[0], scope, semantics, 0.5f);
SPIR-Vexcerpt
%23 = OpAtomicIAdd %uint %22 %uint_1 %uint_0 %uint_1
T is uint32_t, an integer.
%25 = OpAtomicFAddEXT %float %24 %uint_1 %uint_0 %float_0_5
T is float32_t.

Try it out yourself

Both declarations have the same name. enable_if_t removes the one that doesn’t fit the type, so each call ends up on the correct instruction.

There is more to it: sometimes using some types on some functions requires you to declare the usage of a capability or an extension. Want to call atomicExchange on a 64-bit integer? You need to declare the Int64Atomics capability. Need to do an atomic min on a 32-bit float? You need to declare the AtomicFloat32MinMaxEXT capability and the SPV_EXT_shader_atomic_float_min_max extension.

HLSL
template<typename T>
[[vk::ext_capability(spv::CapabilityInt64Atomics)]]
[[vk::ext_instruction(spv::OpAtomicExchange)]]
enable_if_t<is_same_v<T, uint64_t> || is_same_v<T, int64_t>, T>
atomicExchange(/* ptr, scope, semantics, value */);
// 32-bit goes to another overload, with nothing to declare
atomicExchange(small[0], scope, semantics, 1u);
atomicExchange(big[0], scope, semantics, 1ull);
SPIR-Vexcerpt
OpCapability Int64Atomics
Only here because the 64-bit overload is called.
%25 = OpAtomicExchange %ulong %24 %uint_1 %uint_0 %ulong_1
big[0]

Try it out yourself

The capability sits on the 64-bit overload only, so a shader that never calls it never declares it.

These are of course the core internals of our HLSL library; they’re there so that users can use it properly.

Closing remarks

Templates have been in HLSL since HLSL 2021, but I had rarely seen people use them, or take advantage of them like we did. That’s why this series exists.

See you in the next one!

References