Search code examples
swiftconstantsshaderdevicemetal

How can I make a buffer in device(or constant) address space?


Metal has two major address spaces, device and constant.
And these are used like this in a shader function.

void foo(device int *data [[buffer(0)]]) { ... }
void bar(constant int *data [[buffer(0)]]) { ... }

I can understand what they are. But I cannot understand how to make them.
How to make a buffer in device(or constant) address space?

At first, I assume that MTLDevice.makeBuffer(length:options:) will do it.
But it doesn't. There are no options for device or constant address space.

I am confused. What did I miss?

Thank you.
Sincerely.


Solution

  • Short answer is: you can't create a constant MTLBuffer and you don't need to. You can bind any MTLBuffer as a constant or device memory.

    Long answer: constant is kind of like a hint to compiler. It tells the compiler that the data in that buffer is going to be read-only, but not exactly as in const sense.

    There's a WWDC video from 2016 where this is discussed, here's a link with a timestamp: https://developer.apple.com/wwdc16/606?time=272

    I think, this is the key point from the video:

    [...] this is the address space that's optimized for cases with a lot of data reuse. So you want to take advantage of this address space whenever it makes sense.

    But I do suggest watching that part of the presentation to learn more.