Skip to content

SPIR-V target? #2683

Closed
Closed

Description

@jbsolomon

Hello,

What would be involved in adding SPIR-V as a target for Zig? There's a translator from (some subset of?) LLVM to SPIR-V; as I understand it, Zig compiles first to LLVM, so this seems reasonable. There's been some discussion of adding SPIR-V as a Clang target which I'm not sure has materialized further, but I think this would be interesting.

This document goes into detail about the representation of SPIR-V in LLVM:
https://github.com/KhronosGroup/SPIRV-LLVM/blob/khronos/spirv-3.6.1/docs/SPIRVRepresentationInLLVM.rst

Activity

  1. emekoi commented on Jun 15, 2019

    @emekoi
    Contributor

    adding a custom spir-v target might lay the groundwork for adding other backends to zig.

  2. added this to the 0.6.0 milestone on Jun 16, 2019
  3. added
    proposal
    on Jun 16, 2019
  4. andrewrk commented on Jun 16, 2019

    @andrewrk
    Member

    The most straightforward way for this to work would be if LLVM supported it directly. However it's still open for discussion to do this even if that scenario does not happen.

  5. jbsolomon commented on Jun 17, 2019

    @jbsolomon
    ContributorAuthor

    One potential fruitful direction could be to look at how clang does this:
    https://clang.llvm.org/docs/UsersManual.html#opencl-features

    It has nvptx64 and amdgcn targets, and can emit LLVM bitcode for them, and the LLVM to SPIR-V translator is also based on libllvm I think, so probably somebody who knows more than me could figure it out. Seems complicated though.

  6. andrewrk commented on Aug 28, 2019

    @andrewrk
    Member

    Some advice from @paniq about implementing such a backend:

    <lritter> ...there's https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.html, but also have a look at SpvBuilder in glslang - i made a copy of that one and expanded it a little
    <lritter> also, you will need SPIRV Tools for the validator and other stuff. SPIRV Cross can then convert your SPIR-V to GLSL, which is also great for seeing if your stuff produces the code you have in mind
    
  7. added
    accepted
    on Jan 8, 2020
  8. modified the milestones: 0.6.0, 0.7.0 on Jan 8, 2020
  9. jbsolomon commented on Mar 5, 2020

    @jbsolomon
    ContributorAuthor

    Hi @andrewrk -- I think LLVM is well on its way to supporting this, but ISTM that it might be necessary or useful to use MLIR. I'm currently exploring this on my own and it definitely seems like a cool project! Far from groking it just yet, but it should be possible to target other GPU backends besides SPIR-V/Vulkan this way, too. IREE is taking this approach to compile from TensorFlow through LLVM.

  10. BarabasGitHub commented on Mar 5, 2020

    @BarabasGitHub
    Contributor

    How would this work with defining images, buffers, input/output variables and all the binding slots and stuff? Or would this just be for the OpenCL use case? (Or maybe all of this can be solved 'easily'?)

    I see they want to compile C++ to SPIR-V 🤦‍♂ RUN AWAY! 😱

  11. jbsolomon commented on Mar 6, 2020

    @jbsolomon
    ContributorAuthor

    I think the focus here should be on generating MLIR / SPIR-V. Tooling and other stuff (like whether / how to use OpenCL types, how to launch and schedule kernels, native GPU types for components, and all that) isn't out of the question, but can hopefully be done as library layers on top of the core functionality. (Counterargument: if the heterogeneous system is all modeled in one IR, LLVM can optimize across the CPU/GPU boundary, as IREE does.)

    Otherwise it runs the risk of being too much work to implement or to become useful in a reasonable amount of time.

    If adding a SPIR-V backend requires too many {GPU,SPIR-V}-specific features into the core language / compiler, then my proposal is to instead add a feature something like a "Zig @dialect" that can be imported by the build tooling as a library (implemented as MLIR dialects?)

  12. andrewrk commented on Mar 19, 2020

    @andrewrk
    Member

    How would this work with defining images, buffers, input/output variables and all the binding slots and stuff?

    With inline assembly, or with target-specific builtin functions.

  13. removed this from the 0.7.0 milestone on Oct 9, 2020
  14. 2 remaining items

  15. fu5ha commented on Dec 13, 2020

    @fu5ha
    Contributor

    https://github.com/EmbarkStudios/rust-gpu does this (its 0.1 release just came out).

    Actually, rust-gpu does not use LLVM's spirv target at all, it manually codegens direct to spirv (the primary motivation for doing it that way is because LLVM's spirv target only supports an opencl/cuda-like execution model, not shader execution models)

  16. modified the milestones: 0.8.0, 0.9.0 on May 19, 2021
  17. modified the milestones: 0.9.0, 0.10.0 on Nov 20, 2021
  18. modified the milestones: 0.10.0, 0.11.0 on Apr 16, 2022
  19. ProkopRandacek commented on Oct 24, 2022

    @ProkopRandacek
    Contributor

    I'm not sure if a SPIR-V target is the best option, since you never actually
    run the binary. The binary is (from my experience) usually embedded into an
    program at compile time and sent to GPU at runtime, or rarely given to a
    program at runtime and sent to GPU at runtime.

    My workflow with SPIR-V is always something like this:

    GLSL -> SPIR-V -> .o -> binary -> SPIR-V sent to GPU at runtime
                            ^
    other sources -> .o ----+
    

    which makes some sense in this case, since you need extra compiler for the
    GLSL -> SPIR-V step.

    If Zig adds a SPIR-V backend, the workflow would be the same. But I think we
    can do better.

    I propose that there would be a builtin function that takes a Zig function and
    creates a const array of SPIR-V bytecode at compile time.

    This would mean that the same functions can be used by CPU and GPU code, in
    contrast to the regular approach where the codebase is split into GPU and CPU
    side (since they are two different languages and are compiled with two
    different compilers...)

    It also frees the programmer of the cumbersome task of embedding files into
    executables. Although I have to admit that I have not yet explored the Zig
    build system and don't know if this problem is already solved.

    I imagine it could look something like this:

    fn add(a: u32, b: u32) u32 {
        return a + b;
    }
    
    fn compute(gl_GlobalInvocationID: [3]u32, buf: []u32) {
        const idx = gl_GlobalInvocationID[0];
        buf[idx] = add(idx, idx);
    }
    
    const spirv: [_]u32 = @spirv(compute);
    
    fn main() {
        // I can call compute()/add() here on the cpu and at the same time can send
        // them to GPU as a compute shader
    }

    In this case the OpEntryPoint is constructed from the compute function
    signature but I am not sure this is the best way. Further thinking required :D


    Alternatively Zig could just expand the Type.Fn struct to also include the
    function AST (or one of the IRs). This could entirely offload the SPIR-V
    compilation to an external library that would construct SPIR-V bytecode from
    Type.Fn struct. The external library could then have a more flexible way of
    specifying entry point interfaces, spirv target version, optimalisation, ...

    It could then look like this:

    const spirvc = @import("...");
    
    fn add(a: u32, b: u32) u32 {
        return a + b;
    }
    
    fn compute(gl_GlobalInvocationID: [3]u32, buf: []u32) {
        const idx = gl_GlobalInvocationID[0];
        buf[idx] = add(idx, idx);
    }
    
    const spirv: [_]u32 = spirvc.compile(@typeInfo(@TypeOf(compute)), ... more arguments specified by the library ...);
    
    fn main() {
        // I can call compute()/add() here on the cpu and at the same time can send
        // them to GPU as a compute shader
    }

    Should I create a new issue for this proposal?
    I think it's neat :D

  20. Snektron commented on Oct 24, 2022

    @Snektron
    Collaborator

    This would mean that the same functions can be used by CPU and GPU code

    This is already possible because of Zig's lazy compilation. Just dont reference any of the host functions on the device and vice versa and youre good. The only thing that is required really is conditionally exporting entry points, both for the device and host side:

    pub fn frag(...) void {
    
    }
    
    pub fn vert(...) void {
    
    }
    
    pub fn realMain(...) void {
    
    }
    
    usingnamespace if (is_shader) struct {} else { pub const main = realMain; };
    
    comptime {
      if (is_shader) {
        @export("vert", vert, .{});
        @export("frag", frag, .{});
      }
    }

    (instead of conditionally exporting entry points you could also have multiple files that all @import shared code)

  21. ProkopRandacek commented on Oct 24, 2022

    @ProkopRandacek
    Contributor

    Wouldn't this already be possible? In our case the language and the compiler would be the same, but the code would probably be in an external file.

    Yeah you are right. Didn't think of that.

    It also frees the programmer of the cumbersome task of embedding files into
    executables.

    You might be interested in @embedFile.

    @embedFile looks amazing :D

    Looks like a pretty nice workflow to me. One less dependency in terms of compiling the shaders as well.

    +1


    Just dont reference any of the host functions

    What do you mean by host functions? I didn't find anything in the documentation.

  22. Avokadoen commented on Oct 24, 2022

    @Avokadoen

    @ProkopRandacek Host is usually referring to the CPU, while device refers to GPU.

    Robin is saying that if you write code that should only run on the CPU, then the final spirv output will not contain this code as long as you don't call it from any of your GPU code

  23. andrewrk commented on Apr 9, 2023

    @andrewrk
    Member

    This is implemented. Separate issues can be filed for follow-up enhancements.

  24. added
    arch-spirv
    on Apr 9, 2023
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

    acceptedarch-spirvproposal

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions