Pointers Overview
In high-performance GPU shading, variables and buffers are stored across distinct types of physical memory on the chip. To write modular, reusable code without copying large chunks of data between functions, WGSL uses Pointers.
A pointer is a value that refers to a specific storage location in memory rather than holding a direct data value.
What is a WGSL Pointer?
If you come from a systems programming background (in languages like C, C++, or Rust), you might be familiar with pointers as raw 32-bit or 64-bit integer addresses representing locations in virtual system memory. In those languages, you can perform pointer arithmetic, cast pointers to arbitrary types, or accidentally create "null pointers" that crash your application.
WGSL pointers are fundamentally different:
- Static Compile-Time Abstractions: Pointers in WGSL do not exist as raw, numeric runtime memory addresses. Instead, they are high-level abstractions analyzed and resolved statically by the GPU compiler.
- No Pointer Arithmetic: You cannot add or subtract offsets from a pointer (e.g.,
p + 1is a compiler error). - No Null Pointers: A pointer must always be initialized to point to a valid, existing variable or member. There is no concept of a
nullor uninitialized pointer. - Strict Address Space Binding: Every pointer is bound to a specific Address Space that dictates exactly where the pointed-to memory lives on the physical GPU hardware.
The Role of Address Spaces & Physical Hardware Tiers
When you declare a pointer in WGSL, its type must explicitly declare its Address Space. This is because GPUs are massive parallel engines with several distinct tiers of memory, each optimized for different bandwidth, latency, and sharing requirements.
How these address spaces map to physical GPU architectures is essential for writing high-performance shaders:
GPU Hardware Memory Tiers
Ultra-fast registers dedicated to an individual thread. This is where your local thread execution variables reside.
function, private
Scope: Single Thread
High-speed local data share memory located directly on the GPU compute units. Used for fast synchronization and sharing between threads in a workgroup.
workgroup
Scope: Single Workgroup
Large off-chip global device memory (GDDR/HBM) shared across all threads on the entire GPU, optimized for high bulk throughput.
storage, uniform
Scope: Global GPU
The subsequent sections detail how to write, instantiate, and pass pointers.