`assert` in metal?

Is there an equivalent of assert in metal? I'm looking for a way to abnormally halt a shader and indicate it ought to be debugged.

assert itself is defined ((void) 0), so that won't work. __builtin_trap() will halt execution, but there's no indication the shader was trapped other than lack of side effects of it completing.

I'm wondering if there is some "other" way to trap, like emitting an invalid instruction into the shader, or doing something the metal API validator will flag as illegal.

Answered by drewcrawford in 614215022
One limitation of buffer out-of-bounds, is that a buffer is not always in-scope (such as inside a math function). Adding a buffer argument for the sole purpose of trapping is not ideal.

Based on your suggestion, I am now using this pattern

Code Block
    device float *f = 0;
    *f = 12;

which seems to trap OK without an explicit buffer. I had previously filed FB7731230 for assert.
Currently, there is no support for assert in the Metal Shading Language. We do not recommend using the Clang’s __builtin_trap() for this.
Please submit an enhancement request via Feedback Assistant.

Having said that, please consider turning on the validation layer and performing an out-of-bounds access on a buffer as a solution to what you are trying to do.
For more information on the validation layer please watch Debug GPU-side errors in Metal.

One limitation of buffer out-of-bounds, is that a buffer is not always in-scope (such as inside a math function). Adding a buffer argument for the sole purpose of trapping is not ideal.

Based on your suggestion, I am now using this pattern

Code Block
    device float *f = 0;
    *f = 12;

which seems to trap OK without an explicit buffer. I had previously filed FB7731230 for assert.

I also need an assert. The MBP 16" is generating valid uv, with 0 length derivatives and that causes problems. Being able to assert on this condition would help. Drew's recommendation just seems to result in a compilation failure on macOS Big Sur.

`assert` in metal?
 
 
Q