Skip to content

RI::allocateMemory, RI::freeMemory

What it does

RI::allocateMemory(device, kind, size) reserves a block of memory of at least size bytes with one of four kinds. You then place resources—such as buffers (RI::createBuffer), textures, or acceleration structures—inside that block at offsets you choose. RI::freeMemory(device, memory) releases the block back to the device.

Step by step, allocateMemory:

  1. picks the native memory type (Vulkan, chosen when the device was created) or heap type (D3D12) for kind. If you pass a non-null fourth argument (forResource, as in allocateMemory(device, kind, size, &requirements)), Vulkan instead picks a native memory type of kind that suits that resource, because some drivers allow certain resources only in a subset of a kind's memory types (for example, RADV allows indirect scratch only in its 32-bit-addressable GPU memory types). On D3D12, forResource has no effect because resource heap tier 2 heaps hold any resource;
  2. allocates the block: size bytes on Vulkan (with VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT so buffers placed inside can have GPU addresses), or on D3D12 a heap whose size is std::max<uint64>(size, 1) rounded up to 4 MiB for eGPU (for MSAA texture placement) or 64 KiB for the other kinds;
  3. for every kind except eGPU, maps the block once for CPU access: memory.mapped holds its CPU pointer for the block's entire lifetime. For eGPU, memory.mapped is nullptr;
  4. returns an RI::Memory containing kind, the requested size, and mapped.

Driver memory allocations are slow and limited in number. Allocate a few large blocks and place many resources in each, rather than allocating one block per resource.

Signature

// <RI/RI.hpp>, namespace RI
Memory allocateMemory(Device &device, MemoryKind kind, uint64 size, const MemoryRequirements *forResource = nullptr, std::string_view name = {});

From the header: With forResource, the memory suits that resource: Vulkan picks a native type of kind the resource allows (some drivers allow only some types, e.g. RADV for indirect scratch). Without it, the kind's default type.

// <RI/RI.hpp>, namespace RI
void freeMemory(Device &device, Memory &memory);
// <RI/RI.hpp>, namespace RI
struct Memory {
    MemoryKind kind = MemoryKind::eGPU;
    uint64 size = 0;
    void *mapped = nullptr; // CPU address for every kind except eGPU (P33)
    // internal: backend-private state (not part of the API)
};
Field Type Default Description
kind MemoryKind MemoryKind::eGPU
size uint64 0
mapped void * nullptr CPU address for every kind except eGPU (P33)
// <RI/RI.hpp>, namespace RI
enum class MemoryKind : uint8 {
    eGPU,       // GPU-only; never mapped (P33)
    eUpload,    // CPU writes, GPU reads; mapped for its lifetime, write-only in practice
    eReadback,  // GPU writes, CPU reads; mapped for its lifetime
    eGPUUpload, // GPU memory the CPU can write (ReBAR); availability varies (P32)
};

From the header: The memory kinds (P32). Each backend maps them to its native memory types.

Value Meaning
eGPU GPU-only; never mapped (P33)
eUpload CPU writes, GPU reads; mapped for its lifetime, write-only in practice
eReadback GPU writes, CPU reads; mapped for its lifetime
eGPUUpload GPU memory the CPU can write (ReBAR); availability varies (P32)

Example

RI::Memory gpuMemory = RI::allocateMemory(device, RI::MemoryKind::eGPU, outputOffset + dataReq.size);
RI::Memory uploadMemory = RI::allocateMemory(device, RI::MemoryKind::eUpload, paramsOffset + 256);
RI::Memory readbackMemory = RI::allocateMemory(device, RI::MemoryKind::eReadback, kBytes);

The same in native code

RI::Memory gpuMemory = RI::allocateMemory(device, RI::MemoryKind::eGPU, outputOffset + dataReq.size);
RI::Memory uploadMemory = RI::allocateMemory(device, RI::MemoryKind::eUpload, paramsOffset + 256);
RI::Memory readbackMemory = RI::allocateMemory(device, RI::MemoryKind::eReadback, kBytes);
// A memory type the resource accepts (`allowedTypes`, from its requirements)
// with every property in `required`.
uint32_t findMemoryType(VkPhysicalDevice gpu, uint32_t allowedTypes, VkMemoryPropertyFlags required) {
    VkPhysicalDeviceMemoryProperties memory{};
    vkGetPhysicalDeviceMemoryProperties(gpu, &memory);
    for (uint32_t i = 0; i < memory.memoryTypeCount; ++i) {
        if ((allowedTypes & (1u << i)) != 0 && (memory.memoryTypes[i].propertyFlags & required) == required) {
            return i;
        }
    }
    std::fprintf(stderr, "no suitable memory type\n");
    std::exit(1);
}
// One block of memory. The flags let buffers placed in it have a GPU address.
VkDeviceMemory allocate(VkDevice device, uint32_t type, VkDeviceSize size) {
    const VkMemoryAllocateFlagsInfo flags{
        .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO,
        .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT,
    };
    const VkMemoryAllocateInfo info{
        .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
        .pNext = &flags,
        .allocationSize = size,
        .memoryTypeIndex = type,
    };
    VkDeviceMemory memory = VK_NULL_HANDLE;
    check(vkAllocateMemory(device, &info, nullptr, &memory), "vkAllocateMemory");
    return memory;
}
// GPU memory: device-local. Upload and readback: CPU-visible and coherent
// (no flush/invalidate calls), mapped once for their whole lifetime.
const VkMemoryPropertyFlags hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
VkDeviceMemory gpuMemory = allocate(
    device, findMemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), outputOffset + req.size);
VkDeviceMemory uploadMemory =
    allocate(device, findMemoryType(gpu, req.memoryTypeBits, hostCoherent), paramsOffset + 256);
VkDeviceMemory readbackMemory = allocate(
    device, findMemoryType(gpu, req.memoryTypeBits, hostCoherent | VK_MEMORY_PROPERTY_HOST_CACHED_BIT), kBytes);
void *uploadMapped = nullptr;
void *readbackMapped = nullptr;
check(vkMapMemory(device, uploadMemory, 0, VK_WHOLE_SIZE, 0, &uploadMapped), "vkMapMemory");
check(vkMapMemory(device, readbackMemory, 0, VK_WHOLE_SIZE, 0, &readbackMapped), "vkMapMemory");

What to watch for: VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT is needed for any buffer in the block to have a GPU address. Drivers limit the number of allocations (maxMemoryAllocationCount, often 4096).

// One block of memory: a heap of a given type. Buffers are placed in it later.
ComPtr<ID3D12Heap> allocate(ID3D12Device10 *device, D3D12_HEAP_TYPE type, UINT64 size) {
    const D3D12_HEAP_DESC desc{
        .SizeInBytes = (size + 65535) / 65536 * 65536, // whole 64 KiB blocks
        .Properties = {.Type = type},
        .Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
        .Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS,
    };
    ComPtr<ID3D12Heap> heap;
    check(device->CreateHeap(&desc, IID_PPV_ARGS(&heap)), "CreateHeap");
    return heap;
}
// DEFAULT: GPU memory. UPLOAD: CPU writes, GPU reads. READBACK: GPU writes, CPU reads.
ComPtr<ID3D12Heap> gpuMemory = allocate(device.Get(), D3D12_HEAP_TYPE_DEFAULT, outputOffset + info.SizeInBytes);
ComPtr<ID3D12Heap> uploadMemory = allocate(device.Get(), D3D12_HEAP_TYPE_UPLOAD, paramsOffset + 256);
ComPtr<ID3D12Heap> readbackMemory = allocate(device.Get(), D3D12_HEAP_TYPE_READBACK, kBytes);

What to watch for: in the canonical code above, the heap size is rounded up to 64 KiB and the heap allows only buffers (D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS). RI's heaps accept both buffers and textures (D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, resource heap tier 2), and RI aligns eGPU heaps to 4 MiB so MSAA textures can be placed in them.

Rules and errors

  • eGPUUpload needs ReBAR: check device.limits.gpuUploadMemory. Calling allocateMemory with eGPUUpload when it is false reports an unsupported error.
  • Running out of host or device memory reports an out of memory error.
  • On Vulkan, passing a forResource whose MemoryRequirements do not allow kind reports a programmer error.
  • Free a block only after destroying every resource placed in it, and only after the GPU has finished using them (after their timeline point).
  • freeMemory resets memory to an empty struct. In validation builds, passing freed memory, default-constructed memory, or memory from another device is a programmer error.
  • On Vulkan, placing a resource in memory whose native type it does not allow is a programmer error for a buffer (validation builds) and an unsupported error for a texture (every build). requirements.kinds lists the kinds that can hold the resource; pass &requirements as the fourth argument to allocateMemory when the kind's default type does not fit.
  • On D3D12, the underlying heap size is std::max<uint64>(size, 1) rounded up to 4 MiB for eGPU and 64 KiB for the other kinds, while memory.size stores the size you asked for.