GPU data

Buffer device addresses

A shader usually finds its buffers through numbered binding slots. With buffer device addresses it gets a 64-bit pointer instead, and reads memory through it like C code does. This page explains how that works, what it costs, and what can go wrong. The last part shows how RASM does it.

In short

  • Every buffer lives at some GPU virtual address. The API can tell you that address as a plain 64-bit number.
  • A shader can treat the number as a pointer: p[i], p->field, p + n. No descriptor, no binding slot.
  • Pointers can be stored inside buffers, so data can link to other data: a tree of tables reached from one root pointer in a push constant.
  • The price: no bounds checks, no type checks, and the address dies with the buffer. A bad pointer reads garbage or loses the device.
  • Textures and samplers still need descriptors. Buffer addresses replace only the buffer bindings.

1How shaders usually find buffers

In the classic model, a shader declares buffers at fixed binding slots: "set 0, binding 2 is the material buffer". Before a draw, the CPU fills a descriptor for each slot (which buffer, which range) and binds the descriptor set.

the shader's slots written by the CPU buffers
shader binding 0: camera binding 1: instances binding 2: materials fixed at compile time descriptor set slot 0 → buffer A slot 1 → buffer B slot 2 → buffer C buffer A buffer B buffer C
The binding model: the CPU decides, before each draw, which buffers the shader can see.
  1. Writeone descriptor per slot: which buffer, which range
  2. Bindthe descriptor set, before the draw
  3. Drawwith a pipeline whose layout matches the shader's slots
  4. Readthe shader reaches only the buffers that were bound

To use a different buffer, the CPU writes or binds another set. Each pipeline needs a layout that matches the shader's slots. The number of slots is limited, and a shader can only reach buffers that were bound before the draw.

Where it stops working well

Fine for a few buffers per draw. Awkward when a GPU-driven frame wants one draw to reach every table of the scene.

2The idea: a GPU pointer

The GPU has a virtual address space, just like a CPU process. Every buffer is placed somewhere in it. A device address is the 64-bit number where the buffer starts. A shader that knows the number can read the buffer directly, with no descriptor in between.

GPU virtual address space buffer A buffer B buffer C free free 0x1_0000_0000 0x1_0010_0000 a pointer in a shader p = 0x1_0020_0000
A pointer is one of these numbers, stored as a 64-bit integer. (Addresses here are made up.)
shader slot 2 descriptor set 2 → buffer C … C

A descriptor says

"The buffer in slot 2." The CPU must fill the slot before the draw.

shader 0x1_0020_0000 reads directly C

An address says

"The bytes at 0x1_0020_0000." It needs no setup per draw.

The shader can keep the number in a variable, in a push constant, or inside another buffer. Adding to it moves inside the buffer, exactly like pointer math in C.

3Getting an address in Vulkan

The feature is buffer device address. It started as the extension VK_KHR_buffer_device_address and is core since Vulkan 1.2. Four steps:

  1. Enable the feature. Turn on bufferDeviceAddress when the device is created. Shaders that use 64-bit pointers usually also need shaderInt64.
  2. Mark the buffer. Create it with the usage bit SHADER_DEVICE_ADDRESS.
  3. Mark the memory. Allocate its memory with the flag DEVICE_ADDRESS (a memory allocator library can do this for you).
  4. Ask. vkGetBufferDeviceAddress returns the 64-bit address. It does not change while the buffer lives, so ask once and keep it.
APINameShader side
Vulkanbuffer device address (core 1.2)GLSL: buffer_reference blocks. Slang, HLSL for Vulkan: pointer types T*. SPIR-V: the PhysicalStorageBuffer storage class.
Direct3D 12GPU virtual address of a resourceUsed for root descriptors and indirect arguments. HLSL itself has no general pointers.
MetalgpuAddress of a buffer (Metal 3)MSL has real device pointers; addresses can be written into argument buffers.
CUDAevery allocation is a pointerC++ pointers, the model this feature copies.
WebGPUnoneOnly bindings.

4Pointers in a shader

Here is a compute shader in Slang that moves particles. The push constant holds a pointer to the particle array and a count. There are no buffer bindings at all.

struct Particle
{
    float3 position;
    float3 velocity;
};

struct Params
{
    Particle *particles;
    uint count;
    float deltaTime;
};

[[vk::push_constant]]
ConstantBuffer<Params> params;

void update(uint index)
{
    if (index >= params.count)
        return;
    Particle *p = params.particles + index;
    p->position += p->velocity * params.deltaTime;
}

The pointer math is the same as in C. particles + index means "index elements further", so the byte address is the base plus index × the size of one Particle. The size comes from the struct layout the shader is compiled with; see Struct layout rules.

A worked example

A table of rows that are 108 bytes each, in a buffer at address 0x1_0020_0000. The shader wants field m of row 5. The field starts 64 bytes into the row.

5 rows × 108 bytes = 540 bytes row 0 row 1 row 2 row 3 row 4 row 5 row 6 base = 0x1_0020_0000 row 5, zoomed: 108 bytes m base + 540 base + 604 0 64 108 64 bytes into the row
All the shader does is multiply and add. It does not know where the table ends, and it does not check that row 5 exists.
row 5:   base + 5 × 108      = base + 540 = 0x1_0020_021C
field m: base + 540 + 64     = base + 604 = 0x1_0020_025C

Do the same math for other rows. The shader multiplies by the row size it was compiled with, so also try a row size that is not the real one.

a row of the table field m the load is on m of the wanted row the load is somewhere else
Keep the row size at 108 and raise the index past row 6. Then set the index to 5 and pick 96 or 112: the load moves off m, into the middle of another row.

5The root pointer pattern

Pointers can be stored in buffers too. So one small struct can hold the addresses of every table in the scene, and the shader needs only the address of that struct. Push constants are the cheapest way to pass a few bytes per draw, so the usual design is:

push constant frame (8 bytes) frame struct one per frame or per view camera matrices vertices * instances * materials * draws * vertex buffer instance table material table draw list
One pointer in, everything reachable. A different camera or a different scene is just a different frame struct.

The CPU changes what a whole pass sees by writing a few addresses, not by building and binding descriptor sets.

push constant frame struct table row 1 2 the same for every thread: cached

The cost: dependent loads

Each arrow is a memory read that must finish before the next address is known. A deep chain adds latency. In practice the first two levels are the same for every thread of a draw, so they stay in the cache and cost little.

array A array B array C base base + A base + A + B

Sub-arrays in one buffer

Because a pointer can point anywhere inside a buffer, one allocation can hold several arrays one after another. Each gets its own pointer: the base plus the size of the arrays before it.

6Alignment

A load through a pointer must be aligned: the address of a value must be a multiple of that value's alignment. A float needs a multiple of 4, a 64-bit integer or pointer a multiple of 8. A misaligned access is undefined behaviour: on some GPUs it works, on others it reads the wrong bytes.

The classic mistake is a hand-packed row: a 64-bit pointer, then a 4-byte count.

pointer at a multiple of 8 pointer at a wrong offset the 4-byte count
Packed: 12-byte rows ptr @ 0 n ptr @ 12 n ptr @ 24 n ptr @ 36 n byte offset 0 8 16 24 32 40 48 Padded: 16-byte rows ptr @ 0 n pad ptr @ 16 n pad ptr @ 32 n pad
Packed 12-byte rows: row 1, and so its pointer, starts at 12, which is not a multiple of 8. Pad the row to 16 bytes. C++ does this by itself; a hand-packed layout may not.

Change the row size and the order of the two fields, and watch where the pointers start:

pointer at a multiple of 8 pointer at a wrong offset the 4-byte count; dashed: padding
Try 12, 16, 20 and 24 bytes. Then put the count first: now a row size that is a multiple of 8 is the worst one.

Four more cases:

buffer a mark every 16 bytes

Buffer start: aligned

Buffers are placed at the memory alignment the driver asks for, at least 16 bytes in practice.

row 0 row 1 row 2 0 108 216 324 all multiples of 4

Row i of 108-byte rows of floats: aligned

108 is a multiple of 4, and floats need 4.

N records × 20 bytes uint array starts at 20 × N

A sub-array of uint after N 20-byte records: aligned

20 × N is a multiple of 4.

x y z w one 16-byte load?

A float4 loaded as one 16-byte load: depends

Some compilers emit one wide load only when they can prove 16-byte alignment. GLSL lets you state it with buffer_reference_align.

7Lifetime and safety

An address is just a number. Nothing ties it to the buffer it came from, so all the classic pointer bugs are possible:

6 rows another buffer p[9]

Out of bounds

An index past the end reads another buffer's bytes, or faults. The robust-access features do not cover pointer access.

Avoid: pass counts next to pointers and check them; size tables from known limits.

destroyed p garbage, or a lost device

Use after free

The buffer was destroyed. The address may now belong to another buffer, or to nothing.

Avoid: destroy only after the frames that could use it are done (Frames in flight).

old new, bigger old copy written this frame a new buffer has a new address

Stale address

The buffer was recreated, for example to grow it. Old copies of the old address point at freed memory.

Avoid: write the addresses again every frame, from the current buffers.

buffer p = 0 address 0: nothing there

Null

An unused pointer left at 0. Reading address 0 faults, usually a lost device.

Avoid: a flag or count next to the pointer says whether it may be read. A pointer a loop reads stays valid even when the count is 0: lavapipe runs the loop's body once with no lane on, and still loads a uniform address.

written as 3 floats uint read as uint 3 floats

Wrong type

The shader reads the bytes as a different struct. No error.

Avoid: keep CPU and GPU struct definitions in sync, and check them (Struct layout rules).

Tools help a little. The Vulkan validation layers have a GPU-assisted mode that can check some pointer accesses at run time. Capture tools such as RenderDoc need the bufferDeviceAddressCaptureReplay feature to replay a frame with the same addresses.

8Addresses or descriptors?

Descriptors (bindings)Device addresses
Setup per drawwrite or bind a setnone: write a number
How many buffers one shader can reachthe bound slotsany buffer whose address it can find
Links between dataindices into other bound arraysreal pointers, stored in buffers
Bounds checksthe descriptor knows the range; robust access can clampnone
Pipeline layoutsmust match each shader's slotsone small push constant for all
Textures and samplersyesno: images still need descriptors
Debuggingtools show which buffer is boundtools see only numbers

Modern GPU-driven renderers usually mix the two: device addresses for all buffers, and one big array of texture descriptors for all images (see Bindless resources).

9In RASM

RASM binds no buffer through a descriptor. Every buffer gets a device address at creation, and shaders reach all scene data from one root pointer in a 16-byte push constant: the pattern of section 5. Textures go through the bindless descriptor set.

buffers a pointer computed on the CPU, into the middle of a buffer
PushConstants scene firstDraw · argument SceneData 2008 bytes, one per scene view projection, view, camera, light counts, frustum planes, ... vertsPtr drawInfoPtr instancesPtr materialsPtr geometryPtr allDrawsPtr drawCountsPtr cullSlotsPtr groupCountsPtr cullStatsPtr visibilityPtr hizPtr + 9 more: colors, blend sort, lights, clusters, animation Geometry Vertex Pool Instance Table, this slot Material Table, this slot Geometry Table Draw Info Buffer, this slot Visible Draw Buffer, this slot draws: capacity × 20 B cull slots: capacity × 4 B group counts draw counts: one per run Cull Stats Buffer, this slot Visibility Buffer, this view Hi-Z Buffer, this slot
The twelve pointers that culling and drawing follow; the other nine are colorsPtr, sortKeysPtr, sortDrawsPtr, lightsPtr, sceneLightsPtr, clustersPtr, animatedTransformsPtr, skinnedVertsPtr and previousSkinnedVertsPtr. The three orange ones are computed on the CPU by pointer math into one buffer (section 5, "sub-arrays"), and are set only for a culled view (the normal case); visibilityPtr and hizPtr only with occlusion culling. Otherwise they stay 0. drawInfoPtr points at the visible draws of a culled view, and at the whole draw list otherwise. The visible draws, the visibility flags and the Hi-Z belong to the scene view (SceneView).

The vertex shader in shaders/passes/rasm.slang follows the chain like this (spacing changed):

DrawInfo *draw = pc.scene->drawInfoPtr + getDrawIndex();
InstanceData *instance = pc.scene->instancesPtr + draw->firstInstance;
VertexFull vert = getVertex(pc.scene, instance, draw->vertexOffset, input.vertexID);

getVertex in shaders/lib/core.slang takes a skinned sub-mesh's vertex from the Skin pass's output, and any other from the geometry pool:

int skinned = getSkinnedVertex(scene, instance);
if (skinned >= 0)
    return scene->skinnedVertsPtr[uint(skinned) + vertexID];
return scene->vertsPtr[vertexID + draw->vertexOffset];

And Renderer::prepareSceneView in src/renderer/gpuScene.cpp does the CPU-side pointer math for the sub-arrays (line breaks added):

sceneData.cullSlotsPtr =
    sceneData.drawInfoPtr + static_cast<uint64_t>(visibleCapacity) * sizeof(gfx::DrawInfo);
sceneData.groupCountsPtr =
    sceneData.cullSlotsPtr + static_cast<uint64_t>(visibleCapacity) * sizeof(uint32_t);

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Enabling itfeature + usage bit + memory flagThe device requires bufferDeviceAddress, shaderInt64 and scalarBlockLayout. toVkBufferUsageFlags adds the device-address bit to every buffer. The VMA allocator is created with VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT, which handles the memory flag.
Asking oncekeep the addressVulkanDevice::createBuffer calls vkGetBufferDeviceAddress once and stores it in Buffer::deviceAddress. RenderContext::getBufferDeviceAddress returns it, or logs an error and returns 0.
Root pointera push constant with one pointerPushConstants: scene (8 bytes), plus firstDraw and argument: 16 bytes, PUSH_CONSTANTS_SIZE.
Frame structone per frame or viewOne SceneData per scene view (a scene, a camera and a target). Each frame slot has one "Scene Data Buffer" with room for MAX_SCENE_VIEWS = 16 of them; view v uses the buffer's address + v × 1824 (getSceneDataAddress).
Sub-arraysbase + size of what comes beforecullSlotsPtr, groupCountsPtr and drawCountsPtr point into the visible draw buffer, after the draws.
Stale addresseswrite them again every frameThe same: Renderer::prepareSceneView writes every address of a view every frame, from the current buffers. A buffer that grew is picked up at once: the draw lists, and the visible draws and Hi-Z, which RenderContext::resizeBuffer grows under the same handle but at a new address.
Null pointersa flag says whether to readUnused pointers stay 0 (SceneData starts as {}). countMain reads visibilityPtr and hizPtr only when hizLevelCount is not 0. A null clustersPtr is the flag itself: the pixel then shades every local light. A pointer a loop reads is never null, even for a count of 0: a shaded view's sceneLightsPtr names the light table when the scene has no light, and each scene's list ends with a 0 (B38).
Boundspass counts and check themCounts travel with the data (drawCount, runFirst, localLightCount, sizes from EngineConfig), but shaders trust them: there is no bounds check on any pointer.
ImagesdescriptorsTextures use one bindless descriptor set. The Hi-Z pyramid is not an image: it is a float buffer read through hizPtr, with its levels packed one after another.
Other passes—Some passes have their own 16-byte push constants with one address: the stats overlay's text buffer (textPtr in statsOverlay.slang), the UI pass's first vertex of the draw (gfx::UiPushConstants::vertices), and the Inspect pass's parameters (gfx::InspectPushConstants::params), which hold the view's SceneData address in turn.
Classic bindings—Not all gone: the index buffer is bound with bindIndexBuffer, and indirect draws take their buffers as handles (drawIndexedIndirectCount). Fixed-function stages cannot read through pointers.

Where it lives in code

WhatWhere
Features, usage bit, VMA flagsrc/rhi/vulkan/vulkanDevice.cpp: device selection, toVkBufferUsageFlags, the allocator creation
Getting the addressVulkanDevice::createBuffer; RenderContext::getBufferDeviceAddress in src/rhi/renderContext.cpp
The pointer structsSceneData, PushConstants in shaders/lib/core.slang and src/renderer/uberMaterialTypes.h
Writing the addressesRenderer::prepareSceneView in src/renderer/gpuScene.cpp
Reading through themvertMain, fragMain in shaders/passes/rasm.slang; countMain, writeMain in shaders/passes/cull.slang; hizMain in shaders/passes/hiz.slang
Keep these true
  • Write every address in SceneData from the current buffers every frame; never cache an address across a buffer that can be recreated or resized.
  • Destroy a buffer only when no frame in flight can still read its address.
  • A pointer that is 0 must not be read. Guard it with a count or a flag, like hizLevelCount.
  • Keep 64-bit fields at 8-byte aligned offsets in every shared struct. SceneData and PushConstants are CPU↔GPU structs: follow the struct contract.

Further reading