缺少着色器C兼容性是否重要

Does lack of shader C compatibility matter?

本文关键字:兼容性 是否      更新时间:2023-10-16

我正在学习《与Metal一起运行》第2部分,试图学习如何使用可用的最佳语言功能重写所有代码。其中一个功能是C++构造函数,我很高兴能够在我的着色器中使用它,它来自Cg和GLSL,它们缺乏这一点。

此代码在设备上运行良好,但我收到警告:

"vertex_main"指定了C链接,但返回用户定义的类型"ColoredVertex"与C 不兼容

这有关系吗?我不知道为什么要指定C连杆。我也不知道如何禁用警告,这是我想做的,如果没有关系的话,还可以报告错误。

using namespace metal;
struct ColoredVertex {
    const float4 position [[position]];
    const half4 color;
    ColoredVertex(const float4 position, const half4 color)
    : position(position), color(color) {}
};
vertex ColoredVertex vertex_main(
    constant float4 *position [[buffer(0)]],
    constant float4 *color [[buffer(1)]],
    uint vid [[vertex_id]]
) {return ColoredVertex(position[vid], half4(color[vid]));}
fragment half4 fragment_main(ColoredVertex vert [[stage_in]]) {
    return vert.color;
}

让我们在Metal源代码中再添加一个函数:

int myFunction(int x) { return x / 2; }

然后让我们手动运行编译器,并要求它发出一种人类可读的格式:

xcrun -sdk iphoneos metal MyLibrary.metal -S -emit-llvm

输出为MyLibrary.ll。以下是输出中vertex_main的定义:

define %struct.ColoredVertex.packed @vertex_main(<4 x float> addrspace(2)* nocapture readonly, <4 x float> addrspace(2)* nocapture readonly, i32) local_unnamed_addr #1 {
  %4 = zext i32 %2 to i64
  %5 = getelementptr inbounds <4 x float>, <4 x float> addrspace(2)* %0, i64 %4
  %6 = load <4 x float>, <4 x float> addrspace(2)* %5, align 16, !tbaa !22
  %7 = getelementptr inbounds <4 x float>, <4 x float> addrspace(2)* %1, i64 %4
  %8 = load <4 x float>, <4 x float> addrspace(2)* %7, align 16, !tbaa !22
  %9 = tail call fast <4 x half> @air.convert.f.v4f16.f.v4f32(<4 x float> %8)
  %10 = insertvalue %struct.ColoredVertex.packed undef, <4 x float> %6, 0
  %11 = insertvalue %struct.ColoredVertex.packed %10, <4 x half> %9, 1
  ret %struct.ColoredVertex.packed %11
}

这是myFunction:的定义

define i32 @_Z10myFunctioni(i32) local_unnamed_addr #0 {
  %2 = sdiv i32 %0, 2
  ret i32 %2
}

这里需要注意的重要一点是,名称myFunction被破坏了,这意味着它有C++链接,而名称vertex_main没有被破坏,这意味著它有C链接。因此,我们可以推断,声明一个函数为vertex会自动赋予它C链接。(fragment_main也未映射。)

它可能被赋予了C链接,因为在运行时更容易查找未映射的名称。(回想一下,我们在运行时使用-[MTLLibrary newFunctionWithName:]按名称查找着色器函数。)

我想"与C不兼容"的警告在你的情况下并不重要。我认为ColoredVertex"与C不兼容",因为它有一个非平凡的构造函数,但除此之外,它是一个与C兼容的POD(普通的旧数据类型)。