OpenCL代码编译成Vulkan代码(SPIR-V)的工具

最近接到个任务,就是把OpenCL.cl代码编译成Vulkan程序。

请使用 OpenCL代码编译成Vulkan代码的工具clspv 实现这部分功能,官方提供的转换库,目前看来暂时没办法使用。

根据官方文档,Vulkan 1.0支持OpenCL 1.0/2.1的代码直接编译成Vulkan程序。

官方提供了一个名为 KhronosGroup/SPIR 的开源项目,支持OpenCL编译成SPIR-V代码的功能(Vulkan使用SPIR-V)。

这个工具在 macOS Mojave(10.14.2) 系统上使用 Xcode Version 10.1 (10B61) 编译流程如下:

$ cd ~

$ git clone -b khronos/spirv-3.6.1 https://github.com/KhronosGroup/SPIRV-LLVM.git llvm

$ cd llvm/tools

# 默认分支要求检出 spir_12 分支,但是貌似执行完成 clone 之后,就已经在这个分支上了
# git checkout --track -b spir_12 remotes/origin/spir_12
# 默认是 SPIR 的编译,Vulkan 需要 SPIR-V 两者是不同的
# Vulkan 需要编译 SPIR-V 我们需要手工切换到 spirv-1.0 分支上
$ git clone -b spirv-1.0 https://github.com/KhronosGroup/SPIR clang

$ cd ..

$ mkdir build

$ cd build

$ cmake ..

# 多线程同时编译,提高编译速度
$ make -j8

 

编译完成后的使用方式如下:

$ ~/llvm/build/bin/clang -cc1 -emit-spirv -triple <triple> -cl-std=<CLversion> -include opencl.h -x cl -o <output> <input>

# 反汇编查看编译结果
$ spirv-dis <output>
  • <triple>: for 32 bit SPIR-V use spir-unknown-unknown, for 64 bit SPIR-V use spir64-unknown-unknown.
  • -D: to enable support for extension. e.g. -Dcl_khr_fp16 compile option will enable half support.
  • -O: -O0 (default) is the only tested option value at the moment. It's assumed by design that all optimizations are executed by SPIR-V consumer.

比如:

# 编译kernel.cl 到 kernel.spir
$ ~/llvm/build/bin/clang -cc1 -emit-spirv -triple=spir-unknown-unknown -cl-std=CL2.0 -include opencl.h kernel.cl -o kernel.spir

# 反汇编查看编译结果
$ spirv-dis kernel.spir

继续阅读OpenCL代码编译成Vulkan代码(SPIR-V)的工具