Skip to content

MSL does not support address-of vector component #1931

Closed

Description

@jrprice

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.

You can workaround this with pointer casting:

float4 v;
thread float* vp = ((thread float*)&v) + 3;

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).

Activity

  1. added
    wgsl
    on Jul 13, 2021
  2. alan-baker commented on Jul 14, 2021

    @alan-baker
    Contributor

    If we do want to prevent this, it should be as simple removing the reference version of vector access expressions.

  3. kvark commented on Jul 14, 2021

    @kvark
    Contributor

    @alan-baker that would mean we can't do vector.y = 1.0 any more.

  4. dneto0 commented on Oct 5, 2021

    @dneto0
    Contributor

    Slightly related #2152 which says that when you write to a vector component, the other components may be written too.

  5. litherum commented on Oct 5, 2021

    @litherum
    Contributor

    You can workaround this with pointer casting:

    Please don't do this. It's undefined.

  6. dneto0 commented on Oct 5, 2021

    @dneto0
    Contributor

    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:

    • A pointer or reference to a vector with swizzles is an error:

    float4 pos = float4(1.0f, 2.0f, 3.0f, 4.0f);
    my_func(&pos.xy); // This is an illegal pointer to a swizzle.
    

    That I can see as distinct from what we're asking about.

  7. litherum commented on Oct 6, 2021

    @litherum
    Contributor

    Some notes from today's discussion:

    1. 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"
    2. We have to determine what to do with matrices (which may or may not match what we're doing with vectors)
    3. 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)
  8. litherum commented on Oct 6, 2021

    @litherum
    Contributor

    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.

  9. litherum commented on Oct 6, 2021

    @litherum
    Contributor

    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.

  10. litherum commented on Oct 6, 2021

    @litherum
    Contributor

    I'm discussing this with the Metal team.

  11. dneto0 commented on Oct 6, 2021

    @dneto0
    Contributor

    That case won't be needed because there's a restriction on pointer parameters:

    Each argument of pointer type to a user-defined function must be one of:

    • An address-of expression of a variable identifier expression
    • A function parameter

    So, for example, this is invalid:

    fn foo() {
       var a: vec4<f32>;
       bar(&a.x); // invalid
    }
  12. dneto0 commented on Oct 6, 2021

    @dneto0
    Contributor

    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]] struct B {
      cond: i32;
      a: vec4<f32>;
    };
    
    [[group(0), binding(0)]]
    var<storage,read_write> b: B;
    
    
    [[stage(fragment)]]
    fn main() -> [[location(0)]] vec4<f32> {
       let p = &b.a.x;           ////////////// address of a .x reference
       if (b.cond < 0) {
         *p = 12.0;
       } else {
         *p = 0x1.0p20;
       }
       return vec4<f32>();
    }

    tint --format msl c.wgsl yields:

    #include <metal_stdlib>
    
    using namespace metal;
    struct B {
      /* 0x0000 */ int cond;
      /* 0x0004 */ int8_t tint_pad[12];
      /* 0x0010 */ float4 a;
    };
    struct tint_symbol_1 {
      float4 value [[color(0)]];
    };
    
    float4 tint_symbol_inner(device B& b) {
      if ((b.cond < 0)) {
        b.a.x = 12.0f;
      } else {
        b.a.x = 1048576.0f;
      }
      return float4();
    }
    
    fragment tint_symbol_1 tint_symbol(device B& b [[buffer(0)]]) {
      float4 const inner_result = tint_symbol_inner(b);
      tint_symbol_1 wrapper_result = {};
      wrapper_result.value = inner_result;
      return wrapper_result;
    }

    This shows sinking of a subscripted array:

    [[block]] struct B {
      cond: i32;
      a: vec4<f32>;
    };
    
    [[group(0), binding(0)]]
    var<storage,read_write> b: B;
    
    
    [[stage(fragment)]]
    fn main() -> [[location(0)]] vec4<f32> {
       var i: i32;
       let p = &b.a[i]; //////////  subscripted component selection
       if (b.cond < 0) {
         i = 1;  // intentionally overwrite the index.
         *p = 12.0;
       } else {
         i = 2;
         *p = 0x1.0p20;
       }
       return vec4<f32>();
    }

    and the result

    #include <metal_stdlib>
    
    using namespace metal;
    struct B {
      /* 0x0000 */ int cond;
      /* 0x0004 */ int8_t tint_pad[12];
      /* 0x0010 */ float4 a;
    };
    struct tint_symbol_1 {
      float4 value [[color(0)]];
    };
    
    float4 tint_symbol_inner(device B& b) {
      int i = 0;
      int const p_save = i;
      if ((b.cond < 0)) {
        i = 1;
        b.a[p_save] = 12.0f;
      } else {
        i = 2;
        b.a[p_save] = 1048576.0f;
      }
      return float4();
    }
    
    fragment tint_symbol_1 tint_symbol(device B& b [[buffer(0)]]) {
      float4 const inner_result = tint_symbol_inner(b);
      tint_symbol_1 wrapper_result = {};
      wrapper_result.value = inner_result;
      return wrapper_result;
    }
    
  13. kdashg commented on Oct 6, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-10-05
    • 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”.
    • Check back next meeting, but no promises
  14. kdashg commented on Oct 12, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-10-12
    • 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:
      1. “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?
      • 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
      1. “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.
      1. “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.
    • MM: Seems pretty restrictive
    • Let’s think about it more
  15. dneto0 commented on Oct 19, 2021

    @dneto0
    Contributor

    (Reminder: the "sink the pointer calculation" is a fine implementation, just as performant as what a user would write.)

    Meanwhile, let me revisit this:

    https://llvm.org/docs/GetElementPtr.html#can-gep-index-into-vector-elements

    I traced this back through history, to this, from February 2010:

    llvm/llvm-project@f51af9d#diff-d1467b767ede3f08a4d7183a6f0ca51749960b5efd8bb09ca775ec64c61e5ca5R276

    Where it says:

    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.

    That's mitigation strategy 3b.

  16. jrprice commented on Oct 26, 2021

    @jrprice
    ContributorAuthor

    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:

    1. Restrict the address-of operator.
      e.g. "a vector access expression cannot be used as the operand to the address-of operator".

    2. 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);

  17. dneto0 commented on Oct 27, 2021

    @dneto0
    Contributor

    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.”
      • So that does not include vectors.

    So this is undefined behaviour in MSL

    float4 v;
    auto* p = (float*) &v;
    *p = 1.0;  // undefined behaviour
    

    To get around this, you would need to use either

    • char based access
    • unions

    Both these seem too far to go.

  18. added a commit that references this issue on Oct 29, 2021
    fd8ce43
  19. added a commit that references this issue on Nov 3, 2021
    58f1b04
  20. added a commit that references this issue on Nov 4, 2021
    c2acf6f
  21. kdashg commented on Nov 8, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-11-02
  22. added
    whynot
    on Oct 14, 2022
  23. dneto0 commented on Oct 14, 2022

    @dneto0
    Contributor

    @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.

  24. jrprice commented on Oct 14, 2022

    @jrprice
    ContributorAuthor

    @dneto0

    a program that has two invocations writing to components 0 and 1 respectively

    This is already considered to be a race in WGSL. See Component Reference from Vector Reference:

    A write access to component of a vector may access all of the memory locations associated with that vector.

    Note: This means accesses to different components of a vector by different invocations must be synchronized if at least one access is a write access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    wgslwhynot

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions