You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
MSL does not support address-of vector component #1931
WGSL currently allows address-of vector component, e.g.:
{
var v = vec4<f32>();
let vp = &v.w;
...
*vp = 1.0;
}
MSL does not support an equivalent syntax using either component accessors or array indexes:
foo.metal:6:22: error: address of vector element requested
thread float* vp = &v.w;
foo.metal:6:22: error: address of vector element requested
thread float* vp = &v[3];
The only wording around this that I could find in the MSL spec was "A pointer or reference to a vector with swizzles is an error". I'm not sure that &v[3] is classed as a swizzle, but the MSL compiler rejects that code anyway.
But it's unclear whether this is supposed to be valid or not, and therefore we might not be able to rely on this approach.
So, I think we should consider whether WGSL should drop support for address-of vector component. I struggle to think of any use cases for this given all the other restrictions we have around pointers (you cannot pass a pointer-to-vector-component to a user-defined function, for example).
The relevant spec change would be something like "you can have a ref of a member of a vector but not a pointer to a member of a vector"
We have to determine what to do with matrices (which may or may not match what we're doing with vectors)
Two potential implementation strategies:
a. Model a pointer to a member of a vector as a pointer to the vector and a field to tell you which member it references
b. Don't use vectors and instead use arrays (where necessary)
The 3a. strategy would mean we might have to duplicate functions if they have a parameter of ptr<float> if it was called twice, one with a regular float pointer and one with a pointer into a vector.
The alignment guarantees of arrays and vectors are different, so if an array happens to exist in memory for whatever reason (maybe it was spilled) it can't necessarily be loaded in a single instruction.
There is also another mitigation strategy which is:
3c. Sink the pointer calculation to its uses. This is what Tint does (example below).
This relies on the fact that you can do very few things with a pointer. All essential uses are either immediately surrounded in an expression (conversion back to a reference), saved into a let-declaration, or passed as a function formal parameter.
Conversion back to a reference: This is uninteresting, because then you don't have a pointer anymore.
Passed as a function formal parameter: The bad case is banned by a function parameter restriction.
Saving into a let-declaration with identifier, say, P. This is the interesting case. Then any use of the pointer is in scope of that declaration of P. The let-declaration's initializer expression is either:
an identifier, Q (yet another let-declaration, or a function parameter). Now replace uses of P's in scope with Q, while renaming any shadowed Qs. (Q's scope is a superset of the scope of P).
an address-of expression. Recurse. Otherwise, the remaining interesting case is where it's address-of a single-letter swizzle, or an array-like subscript.
if it's a single-letter swizzle, then sink the address-of the single-letter swizzle to uses.
if it's an array-like subscript, then save the index in a hoisted variable, and sink the address-of array-like subscript to the uses.
So that's the transform that requires no changes in underlying data representation, either of the vector or of the pointer type.
This is essentially what Tint does.
Here's the case where it sinks let-declared pointer of address-of a .x swizzle:
[[block]]structB{cond:i32;
a: vec4<f32>;};[[group(0),binding(0)]]
var<storage,read_write> b:B;[[stage(fragment)]]fnmain() -> [[location(0)]] vec4<f32> {let p = &b.a.x;////////////// address of a .x referenceif(b.cond < 0){*p = 12.0;}else{*p = 0x1.0p20;}return vec4<f32>();}
MM: Haven’t heard anyone complain about MSL not supporting this. Would rather forbid in the language than try to emulate somehow.
DN: One approach would be to translate vec4 as float[4], which would work in MTL. There could be a perf cliff, but that’s up to the user to run into and solve if needed.
MM: Seems scary. E.g. builtins would need to handle both? Go in and out?
DN: Yeah, but that’s probably ok? I think we’re investigating it. I’m pretty aggressive about this one, and we’re not at-consensus within Google yet.
MM: So you may have already paid the implementation cost, and you are evaluating the perf cost. How do you feel about my assertion about usefulness?
DN: I feel like removing this adds an orthogonality to the language, which I would like to avoid.
DM: Maybe could have reference to the element of vector, but not a pointer to the element of the vector?
JB: So we’d have a carve-out to forbid converting certain refs into pointers?
JB: Maybe we should ask MSL people, if they were to support this, how would they do it?
MM: Can’t speak for them, but I expect them to say “drivers don’t have that functionality”.
MM: MSL doesn’t support this, but SPIR-V does. Do we forbid it for ourselves, or do we allow it and emulate on MSL?
DN: We may want to make vectors more complicated later, so might not want to sign up to handle those extra complications in the future.
MM: With this restriction, we could convert WGSL pointers directly into MSL pointers.
MM: Feedback:
“There’s a reason that MSL doesn’t support these things, because LLVM doesn’t support (or will later be unsupported).” SPIR-V is based on LLVM, so how does it work there?
This hasn't always been forcefully disallowed, though it's not recommended. It leads to awkward special cases in the optimizers, and fundamental inconsistency in the IR. In the future, it will probably be outright disallowed.
DN: They have commonalities, but they aren’t the same. Each side has their own changes, experts, and goals/targets. I think that the issue you’re raising is sort of the least of their concerns vis a vis gpu compiling.
GR: Are there any spir-v compilers that generate this?
DN: Yes
“If we want to represent the pointer to a part of the vector in a different way than a pointer to a scalar, we would need to have 2^N overloads for e.g. builtins
DN: That’s forbidden today in WGSL due to SPIR-V restrictions for passing pointers to functions.
“If we want to represent vectors as arrays instead, it would probably have performance overhead, which would be unfortunate”
RM: If we forbid this for now, we could add it later. I also wonder how useful this is, since MSL devs don’t seem to use it.
DN: Sort of selection/survivorship bias, where people aren’t as likely to complain about something that’s just missing/forbidden in MSL.
Instead, you should cast your pointer types and use arrays instead of
vectors for addressing. Arrays have the same in-memory representation
as vectors, so the addressing is interchangeable.
Google has discussed this more internally, and we are now in agreement that WGSL should not support creating pointers to components of vectors.
There are (at least) a couple of different ways that we could approach this in the spec:
Restrict the address-of operator.
e.g. "a vector access expression cannot be used as the operand to the address-of operator".
Remove the ability to form a reference to a vector component.
We would then have to add a special mechanism to continue to allow assigning to vector components. For example, we could say that this: v.x = 1.0;
is just syntactic sugar for this: v = vec4<f32>(1.0, v.yzw);
C++ TBAA (Type based alias analysis) considerations helped change minds at Google.
C++14 3.10 "Lvalues and rvalues" is the basis for TBAA.
Paragraph 10 says “If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:” and then gives cases, e.g. relating cv-qualified types to original types, signed vs. unsigned;
And crucially:
“an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members…”
“A char or unsigned char type”
An “aggregate” type in C++ is an array, struct, or union (essentially).
MSL 2.12 says “Metal supports several aggregate types: arrays, structures, classes, and unions.”
@ben-clayton has implemented source-to-source transforms which can sink pointer calculations into its uses. The intra-procedural form of it is part of Tint's production flow for the HLSL backend. The inter-procedural form is prototyped (with tests) and described here: #3276 (comment)
You might think that applying that transform here would allow us to circumvent this limitation in MSL.
It would, but it would break semantics because it could transform a program that does not race into one that does race.
That is, a program that has two invocations writing to components 0 and 1 respectively, would be transformed into one where both MSL threads write to the whole vector (non-atomically), and therefore race against each other.
Activity
alan-baker commentedon Jul 14, 2021
If we do want to prevent this, it should be as simple removing the reference version of vector access expressions.
kvark commentedon Jul 14, 2021
@alan-baker that would mean we can't do
vector.y = 1.0any more.dneto0 commentedon Oct 5, 2021
Slightly related #2152 which says that when you write to a vector component, the other components may be written too.
litherum commentedon Oct 5, 2021
Please don't do this. It's undefined.
dneto0 commentedon Oct 5, 2021
The MSL manual doesn't clearly define "swizzle". It's hinted at from context. But it's not nearly pinned down enough to adjudicate this.
The text James quoted is given with this example:
That I can see as distinct from what we're asking about.
litherum commentedon Oct 6, 2021
Some notes from today's discussion:
a. Model a pointer to a member of a vector as a pointer to the vector and a field to tell you which member it references
b. Don't use vectors and instead use arrays (where necessary)
litherum commentedon Oct 6, 2021
The 3a. strategy would mean we might have to duplicate functions if they have a parameter of
ptr<float>if it was called twice, one with a regular float pointer and one with a pointer into a vector.litherum commentedon Oct 6, 2021
The alignment guarantees of arrays and vectors are different, so if an array happens to exist in memory for whatever reason (maybe it was spilled) it can't necessarily be loaded in a single instruction.
litherum commentedon Oct 6, 2021
I'm discussing this with the Metal team.
dneto0 commentedon Oct 6, 2021
That case won't be needed because there's a restriction on pointer parameters:
So, for example, this is invalid:
dneto0 commentedon Oct 6, 2021
There is also another mitigation strategy which is:
3c. Sink the pointer calculation to its uses. This is what Tint does (example below).
This relies on the fact that you can do very few things with a pointer. All essential uses are either immediately surrounded in an expression (conversion back to a reference), saved into a let-declaration, or passed as a function formal parameter.
Conversion back to a reference: This is uninteresting, because then you don't have a pointer anymore.
Passed as a function formal parameter: The bad case is banned by a function parameter restriction.
Saving into a let-declaration with identifier, say, P. This is the interesting case. Then any use of the pointer is in scope of that declaration of P. The let-declaration's initializer expression is either:
So that's the transform that requires no changes in underlying data representation, either of the vector or of the pointer type.
This is essentially what Tint does.
Here's the case where it sinks let-declared pointer of address-of a .x swizzle:
tint --format msl c.wgslyields:This shows sinking of a subscripted array:
and the result
kdashg commentedon Oct 6, 2021
WGSL meeting minutes 2021-10-05
litherum commentedon Oct 7, 2021
https://llvm.org/docs/GetElementPtr.html#can-gep-index-into-vector-elements
kdashg commentedon Oct 12, 2021
WGSL meeting minutes 2021-10-12
Can GEP index into vector elements?This hasn't always been forcefully disallowed, though it's not recommended. It leads to awkward special cases in the optimizers, and fundamental inconsistency in the IR. In the future, it will probably be outright disallowed.dneto0 commentedon Oct 19, 2021
(Reminder: the "sink the pointer calculation" is a fine implementation, just as performant as what a user would write.)
Meanwhile, let me revisit this:
I traced this back through history, to this, from February 2010:
llvm/llvm-project@f51af9d#diff-d1467b767ede3f08a4d7183a6f0ca51749960b5efd8bb09ca775ec64c61e5ca5R276
Where it says:
That's mitigation strategy 3b.
jrprice commentedon Oct 26, 2021
Google has discussed this more internally, and we are now in agreement that WGSL should not support creating pointers to components of vectors.
There are (at least) a couple of different ways that we could approach this in the spec:
Restrict the address-of operator.
e.g. "a vector access expression cannot be used as the operand to the address-of operator".
Remove the ability to form a reference to a vector component.
We would then have to add a special mechanism to continue to allow assigning to vector components. For example, we could say that this:
v.x = 1.0;is just syntactic sugar for this:
v = vec4<f32>(1.0, v.yzw);dneto0 commentedon Oct 27, 2021
C++ TBAA (Type based alias analysis) considerations helped change minds at Google.
So this is undefined behaviour in MSL
To get around this, you would need to use either
Both these seem too far to go.
wgsl: Disallow taking the address of a vector component
wgsl: Disallow taking the address of a vector component (#2225)
wgsl: Disallow taking the address of a vector component (gpuweb#2225)
kdashg commentedon Nov 8, 2021
WGSL meeting minutes 2021-11-02
dneto0 commentedon Oct 14, 2022
@ben-clayton has implemented source-to-source transforms which can sink pointer calculations into its uses. The intra-procedural form of it is part of Tint's production flow for the HLSL backend. The inter-procedural form is prototyped (with tests) and described here: #3276 (comment)
You might think that applying that transform here would allow us to circumvent this limitation in MSL.
It would, but it would break semantics because it could transform a program that does not race into one that does race.
That is, a program that has two invocations writing to components 0 and 1 respectively, would be transformed into one where both MSL threads write to the whole vector (non-atomically), and therefore race against each other.
jrprice commentedon Oct 14, 2022
@dneto0
This is already considered to be a race in WGSL. See Component Reference from Vector Reference: