From 75228b052bebf7809d6cc0715074d93c8e02ecd3 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 4 Nov 2026 23:36:44 -0800 Subject: [PATCH] Record no device-nan-encoding for a color output that only ever returns NaN-free constants A fragment function's color output to a half-float attachment recorded PrecisionNote::DeviceNanEncoding wherever the device's conversion stores a NaN otherwise than Metal, even when every value the function returns there is a constant with no NaN lane, which stores no NaN. Texture writes already skip the note for such a constant texel (texture::holds_no_nan); color outputs now apply the same structural rule. stage_io::returns_no_nan follows each `ret` of the function to the output's member (through insertvalue chains and aggregate constants), and color_write::plan, called from the output-variable path and from the storage-form path, leaves the note out when every return holds such a constant. Any computed, undef, argument or partly unknown member keeps the note. Per-site audit of the device-nan-encoding notes on MoltenVK on the M3 (the reims strict Mac tests), with the translator CLI over each site's stages: - (a) undefined tests x3 (xr_constant_fragment and the other constant-colour fragments): their outputs are NaN-free constants, so the note was wrong there. Fixed here. - (c) encode_render x2 (sweep_fragment, sweep_half_fragment): computed outputs that sweep through NaN values. The device stores its own NaN encoding, so the note stays. - (c) rgbx x3 (rgbx_write_half, store_half, read_write_half, and the NaN clears and half NaN writes): deliberate NaN texel writes. The note stays. - (c) slice_write_repro x1 (slice_write, slice_write_l0): computed texel writes. The note stays. New public fixture ncw_constant_colors (our own MSL, compiled by scripts/regen-air-fixtures). It covers a half and a float constant colour, a constant NaN colour, a computed colour, and a two-member struct whose member 0 is a constant and member 1 computed. The new test engine_link::constant_colors_without_a_nan_record_no_nan_encoding checks, on the lavapipe and moltenvk-m3 profiles, that the note is recorded exactly for the NaN constant, the computed colour and the pair's computed member, and that each stage links and validates. docs/API.md's device-nan-encoding entry states the rule. SEMANTICS_VERSION goes to 1963 because the recorded notes change. The golden tables need the new fixture's rows, re-blessed on development. Verification: the new test and the touched suites run in the branch's next CPU job. (cherry picked from commit 2d436ebc2963f1aac1854b850ff1808e654c61f3) --- .../fixtures/public/engine/TOOLCHAIN | 1 + .../public/engine/ncw_constant_colors.air.ll | 121 ++++++++++++++++++ .../public/engine/ncw_constant_colors.ll | 121 ++++++++++++++++++ .../public/engine/ncw_constant_colors.metal | 40 ++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- .../metal2vulkan/src/lower/fragment/fetch.rs | 3 +- .../src/lower/stage_io/color_write.rs | 15 ++- crates/metal2vulkan/src/lower/stage_io/mod.rs | 64 +++++++++ .../metal2vulkan/src/lower/stage_io/plan.rs | 3 +- crates/metal2vulkan/src/lower/texture/mod.rs | 2 +- crates/metal2vulkan/src/tests/engine_link.rs | 42 ++++++ docs/API.md | 4 +- 12 files changed, 408 insertions(+), 10 deletions(-) create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.air.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.metal diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index c8842445a..45f18d6e8 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -220,6 +220,7 @@ fixture nan_narrow: metal: Apple metal version 32023.921 (metalfe-32023.921.6); fixture nan_narrow_fast: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture nan_signbits: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture nan_signbits_fast: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) +fixture ncw_constant_colors: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture not_mipmapped_anisotropic: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture ob1_buffer_atomic: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture ob1_device_address: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.air.ll new file mode 100644 index 000000000..2baa64389 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.air.ll @@ -0,0 +1,121 @@ +; Generated by scripts/regen-air-fixtures from ncw_constant_colors.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +define <{ <4 x float> }> @ncw_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = alloca [3 x <2 x float>], align 8 + %3 = bitcast [3 x <2 x float>]* %2 to i8* + call void @llvm.lifetime.start.p0i8(i64 24, i8* nonnull %3) #4 + %4 = getelementptr inbounds [3 x <2 x float>], [3 x <2 x float>]* %2, i64 0, i64 0 + store <2 x float> , <2 x float>* %4, align 8 + %5 = getelementptr inbounds [3 x <2 x float>], [3 x <2 x float>]* %2, i64 0, i64 1 + store <2 x float> , <2 x float>* %5, align 8 + %6 = getelementptr inbounds [3 x <2 x float>], [3 x <2 x float>]* %2, i64 0, i64 2 + store <2 x float> , <2 x float>* %6, align 8 + %7 = zext i32 %0 to i64 + %8 = getelementptr inbounds [3 x <2 x float>], [3 x <2 x float>]* %2, i64 0, i64 %7 + %9 = load <2 x float>, <2 x float>* %8, align 8, !tbaa !35 + %10 = shufflevector <2 x float> %9, <2 x float> poison, <4 x i32> + %11 = shufflevector <4 x float> %10, <4 x float> , <4 x i32> + call void @llvm.lifetime.end.p0i8(i64 24, i8* nonnull %3) #4 + %12 = insertvalue <{ <4 x float> }> undef, <4 x float> %11, 0 + ret <{ <4 x float> }> %12 +} + +; Function Attrs: argmemonly mustprogress nocallback nofree nosync nounwind willreturn +declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture) #1 + +; Function Attrs: argmemonly mustprogress nocallback nofree nosync nounwind willreturn +declare void @llvm.lifetime.end.p0i8(i64 immarg, i8* nocapture) #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x half> @ncw_constant_half() local_unnamed_addr #2 { + ret <4 x half> +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x float> @ncw_constant_float() local_unnamed_addr #3 { + ret <4 x float> +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x half> @ncw_constant_nan() local_unnamed_addr #2 { + ret <4 x half> +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <{ <4 x half>, <4 x half> }> @ncw_constant_pair(<4 x float> %0) local_unnamed_addr #3 { + %2 = extractelement <4 x float> %0, i64 0 + %3 = fptrunc float %2 to half + %4 = fmul fast half %3, 0xH1419 + %5 = insertelement <4 x half> poison, half %4, i64 0 + %6 = shufflevector <4 x half> %5, <4 x half> poison, <4 x i32> zeroinitializer + %7 = insertvalue <{ <4 x half>, <4 x half> }> <{ <4 x half> , <4 x half> undef }>, <4 x half> %6, 1 + ret <{ <4 x half>, <4 x half> }> %7 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x half> @ncw_computed_half(<4 x float> %0) local_unnamed_addr #3 { + %2 = extractelement <4 x float> %0, i64 0 + %3 = fptrunc float %2 to half + %4 = fmul fast half %3, 0xH1419 + %5 = insertelement <4 x half> poison, half %4, i64 0 + %6 = shufflevector <4 x half> %5, <4 x half> poison, <4 x i32> zeroinitializer + ret <4 x half> %6 +} + +attributes #0 = { mustprogress nofree nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { argmemonly mustprogress nocallback nofree nosync nounwind willreturn } +attributes #2 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { nounwind } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9} +!air.fragment = !{!14, !18, !21, !22, !28} +!air.compile_options = !{!29, !30, !31} +!llvm.ident = !{!32} +!air.version = !{!33} +!air.language_version = !{!34} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{<{ <4 x float> }> (i32)* @ncw_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} +!14 = !{<4 x half> ()* @ncw_constant_half, !15, !17} +!15 = !{!16} +!16 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"} +!17 = !{} +!18 = !{<4 x float> ()* @ncw_constant_float, !19, !17} +!19 = !{!20} +!20 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!21 = !{<4 x half> ()* @ncw_constant_nan, !15, !17} +!22 = !{<{ <4 x half>, <4 x half> }> (<4 x float>)* @ncw_constant_pair, !23, !26} +!23 = !{!24, !25} +!24 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4", !"air.arg_name", !"constant_color"} +!25 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"half4", !"air.arg_name", !"computed_color"} +!26 = !{!27} +!27 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!28 = !{<4 x half> (<4 x float>)* @ncw_computed_half, !15, !26} +!29 = !{!"air.compile.denorms_disable"} +!30 = !{!"air.compile.fast_math_enable"} +!31 = !{!"air.compile.framebuffer_fetch_enable"} +!32 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!33 = !{i32 2, i32 8, i32 0} +!34 = !{!"Metal", i32 4, i32 0, i32 0} +!35 = !{!36, !36, i64 0} +!36 = !{!"omnipotent char", !37, i64 0} +!37 = !{!"Simple C++ TBAA"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.ll b/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.ll new file mode 100644 index 000000000..72b50eff0 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.ll @@ -0,0 +1,121 @@ +; Generated by scripts/regen-air-fixtures from ncw_constant_colors.metal (llvm-dis of ncw_constant_colors.air). Do not edit. +; ModuleID = '' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +define <{ <4 x float> }> @ncw_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = alloca [3 x <2 x float>], align 8 + %3 = bitcast ptr %2 to ptr + call void @llvm.lifetime.start.p0(i64 24, ptr nonnull %3) #4 + %4 = getelementptr inbounds [3 x <2 x float>], ptr %2, i64 0, i64 0 + store <2 x float> splat (float -1.000000e+00), ptr %4, align 8 + %5 = getelementptr inbounds [3 x <2 x float>], ptr %2, i64 0, i64 1 + store <2 x float> , ptr %5, align 8 + %6 = getelementptr inbounds [3 x <2 x float>], ptr %2, i64 0, i64 2 + store <2 x float> , ptr %6, align 8 + %7 = zext i32 %0 to i64 + %8 = getelementptr inbounds [3 x <2 x float>], ptr %2, i64 0, i64 %7 + %9 = load <2 x float>, ptr %8, align 8, !tbaa !35 + %10 = shufflevector <2 x float> %9, <2 x float> poison, <4 x i32> + %11 = shufflevector <4 x float> %10, <4 x float> , <4 x i32> + call void @llvm.lifetime.end.p0(i64 24, ptr nonnull %3) #4 + %12 = insertvalue <{ <4 x float> }> undef, <4 x float> %11, 0 + ret <{ <4 x float> }> %12 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x half> @ncw_constant_half() local_unnamed_addr #1 { + ret <4 x half> +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x float> @ncw_constant_float() local_unnamed_addr #2 { + ret <4 x float> +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x half> @ncw_constant_nan() local_unnamed_addr #1 { + ret <4 x half> +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <{ <4 x half>, <4 x half> }> @ncw_constant_pair(<4 x float> %0) local_unnamed_addr #2 { + %2 = extractelement <4 x float> %0, i64 0 + %3 = fptrunc float %2 to half + %4 = fmul fast half %3, 0xH1419 + %5 = insertelement <4 x half> poison, half %4, i64 0 + %6 = shufflevector <4 x half> %5, <4 x half> poison, <4 x i32> zeroinitializer + %7 = insertvalue <{ <4 x half>, <4 x half> }> <{ <4 x half> , <4 x half> undef }>, <4 x half> %6, 1 + ret <{ <4 x half>, <4 x half> }> %7 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x half> @ncw_computed_half(<4 x float> %0) local_unnamed_addr #2 { + %2 = extractelement <4 x float> %0, i64 0 + %3 = fptrunc float %2 to half + %4 = fmul fast half %3, 0xH1419 + %5 = insertelement <4 x half> poison, half %4, i64 0 + %6 = shufflevector <4 x half> %5, <4 x half> poison, <4 x i32> zeroinitializer + ret <4 x half> %6 +} + +; Function Attrs: nocallback nofree nosync nounwind willreturn memory(argmem: readwrite) +declare void @llvm.lifetime.start.p0(i64 immarg, ptr captures(none)) #3 + +; Function Attrs: nocallback nofree nosync nounwind willreturn memory(argmem: readwrite) +declare void @llvm.lifetime.end.p0(i64 immarg, ptr captures(none)) #3 + +attributes #0 = { mustprogress nofree nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { nocallback nofree nosync nounwind willreturn memory(argmem: readwrite) } +attributes #4 = { nounwind } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9} +!air.fragment = !{!14, !18, !21, !22, !28} +!air.compile_options = !{!29, !30, !31} +!llvm.ident = !{!32} +!air.version = !{!33} +!air.language_version = !{!34} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @ncw_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} +!14 = !{ptr @ncw_constant_half, !15, !17} +!15 = !{!16} +!16 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"} +!17 = !{} +!18 = !{ptr @ncw_constant_float, !19, !17} +!19 = !{!20} +!20 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!21 = !{ptr @ncw_constant_nan, !15, !17} +!22 = !{ptr @ncw_constant_pair, !23, !26} +!23 = !{!24, !25} +!24 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4", !"air.arg_name", !"constant_color"} +!25 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"half4", !"air.arg_name", !"computed_color"} +!26 = !{!27} +!27 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!28 = !{ptr @ncw_computed_half, !15, !26} +!29 = !{!"air.compile.denorms_disable"} +!30 = !{!"air.compile.fast_math_enable"} +!31 = !{!"air.compile.framebuffer_fetch_enable"} +!32 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!33 = !{i32 2, i32 8, i32 0} +!34 = !{!"Metal", i32 4, i32 0, i32 0} +!35 = !{!36, !36, i64 0} +!36 = !{!"omnipotent char", !37, i64 0} +!37 = !{!"Simple C++ TBAA"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.metal b/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.metal new file mode 100644 index 000000000..69761dfc3 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/ncw_constant_colors.metal @@ -0,0 +1,40 @@ +// ncw_constant_colors.metal (metal2vulkan): fragment functions whose color outputs are constants, +// written from scratch for the color write's NaN note (`lower::stage_io::returns_no_nan`): a +// constant `half4` and `float4` none of whose lanes is a NaN, a constant `half4` whose red is one +// (bits 0x7e01), a struct of a constant color 0 and a computed color 1, and a computed `half4`. +#include +using namespace metal; + +struct NcwVertex { + float4 position [[position]]; +}; + +vertex NcwVertex ncw_vertex(uint vid [[vertex_id]]) { + const float2 p[3] = {float2(-1, -1), float2(3, -1), float2(-1, 3)}; + return NcwVertex{float4(p[vid], 0, 1)}; +} + +fragment half4 ncw_constant_half() { + return half4(0.5h, 0.25h, 0.75h, 1.0h); +} + +fragment float4 ncw_constant_float() { + return float4(0.5f, 0.25f, 0.75f, 1.0f); +} + +fragment half4 ncw_constant_nan() { + return half4(as_type(ushort(0x7e01)), 0.25h, 0.75h, 1.0h); +} + +struct NcwPair { + half4 constant_color [[color(0)]]; + half4 computed_color [[color(1)]]; +}; + +fragment NcwPair ncw_constant_pair(NcwVertex in [[stage_in]]) { + return NcwPair{half4(0.5h, 0.25h, 0.75h, 1.0h), half4(half(in.position.x) * 0.001h)}; +} + +fragment half4 ncw_computed_half(NcwVertex in [[stage_in]]) { + return half4(half(in.position.x) * 0.001h); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 40464a432..c47ea12d2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1962; +pub const SEMANTICS_VERSION: u32 = 1963; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index c93027b9c..0356d9904 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -2100,7 +2100,8 @@ pub fn select_output( .insert(color, rules); } } else { - stage_io::color_write::plan(cx, color, form); + let nan_free = stage_io::returns_no_nan(cx, field); + stage_io::color_write::plan(cx, color, form, nan_free); // An 8-bit unorm blend's result is the storage image's to convert, the device's // conversion ([`unorm8_blended`]). if sc.view.blend.is_some() && !sc.view.generic_blend && unorm8_format(sc.view.pixel_format) diff --git a/crates/metal2vulkan/src/lower/stage_io/color_write.rs b/crates/metal2vulkan/src/lower/stage_io/color_write.rs index 2d0c4ebb2..9cbc610c9 100644 --- a/crates/metal2vulkan/src/lower/stage_io/color_write.rs +++ b/crates/metal2vulkan/src/lower/stage_io/color_write.rs @@ -30,7 +30,8 @@ //! output's (held widened, its payload in the significand's top bits) where it takes //! `MetalHalfColorNans`; elsewhere the module records the note (`runtime_lane::color_writes`: //! ANV and RADV store `0xfe00`, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK -//! canonicalizes it). +//! canonicalizes it). An output every return of which holds a constant none of whose lanes is a +//! NaN (`stage_io::returns_no_nan`) stores none, and records no note for one. //! //! On a profile that stores Metal's codes itself (`VkProperty::MetalColorWrites`) the map holds //! only half-float channels (`pipeline::color_writes`): only the NaN note is recorded, and the @@ -71,8 +72,9 @@ use std::collections::BTreeSet; /// Plan the write of a fragment function's output of form `f` to color attachment `color` /// (dual-source index 0), through an output variable or in the storage form (see the module -/// docs). -pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { +/// docs). `nan_free`: every value the function returns there is a constant none of whose lanes is +/// a NaN, which stores no NaN. +pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) { if cx.stage != Stage::Fragment { return; } @@ -106,7 +108,10 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { let mut relied = BTreeSet::new(); for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) { let Some(rule) = rule else { continue }; - nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f); + nans |= !shader_blended + && !nan_free + && color_writes::half_float(rule) + && !nan_kept(cx, rule, f); if sixteen_blended && f.float_fmt() == Some(FloatFmt::F32) { match cx .profile @@ -142,7 +147,7 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) { (ChannelWrite::Device, _) => device |= !shader_blended, (rule, Some(fmt)) => match conversion(cx, rule, fmt, storage, &mut relied) { Conversion::Metal => {} - Conversion::MetalButNan => nans |= !shader_blended, + Conversion::MetalButNan => nans |= !shader_blended && !nan_free, Conversion::Device => device |= !shader_blended, }, } diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index 8f5f5f3c8..3351ac541 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -736,6 +736,70 @@ pub fn select_return(cx: &mut SelectCx<'_>, _at: InstId, v: Option) -> Re } } +/// Whether every value the entry returns holds output field `field` (the whole value where it +/// returns no struct) as a constant none of whose lanes is a NaN (`texture::holds_no_nan`): a +/// field built by an insertion of such a constant into the returned struct, or a member of a +/// constant struct. The output then stores no NaN, so no device's encoding of one can show. Any +/// other value may hold one, and so may an entry that returns none. +pub(crate) fn returns_no_nan(cx: &SelectCx<'_>, field: u32) -> bool { + use crate::air::ir::{Const, InstKind, Type}; + let e = cx.entry; + let Some(func) = e.module.func(e.func) else { + return false; + }; + let Some(body) = func.body.as_ref() else { + return false; + }; + let returns_struct = match e.module.types().get(func.ty) { + Some(Type::Function { ret, .. }) => { + matches!(e.module.types().get(*ret), Some(Type::Struct { .. })) + } + _ => false, + }; + let consts = e.module.consts(); + // The value field `field` of the returned value `v` holds, where its insertions or its + // constant state it. + let member = |mut v: Value| -> Option { + if !returns_struct { + return Some(v); + } + for _ in 0..=body.insts.len() { + match v { + Value::Inst(i) => match body.insts.get(i).map(|x| &x.kind) { + Some(InstKind::InsertValue { agg, val, indices }) => match indices[..] { + [f] if f == field => return Some(*val), + [f, ..] if f == field => return None, + _ => v = *agg, + }, + _ => return None, + }, + Value::Const(c) => { + return match consts.get(c).map(|k| &k.value) { + Some(Const::Aggregate(elems)) => { + elems.get(field as usize).map(|&k| Value::Const(k)) + } + _ => None, + }; + } + Value::Arg(_) => return None, + } + } + None + }; + let mut returns = 0; + for inst in body.insts.values() { + let InstKind::Ret(returned) = &inst.kind else { + continue; + }; + let held = (*returned).and_then(&member); + if !held.is_some_and(|v| crate::lower::texture::holds_no_nan(cx, v)) { + return false; + } + returns += 1; + } + returns > 0 +} + /// The varyings vertex function `e`, compiled under `inputs`, writes the same value at every /// vertex of a primitive (`StageIo::uniform_outputs`), sorted: its user varyings, and the raw /// varyings of the slice and viewport indices it writes (`VaryingKey::render_target_array_index`, diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 761fd5f22..e246b936f 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2501,7 +2501,8 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { index: 0, .. } if cx.stage == Stage::Fragment => { - super::color_write::plan(cx, color, link.form); + let nan_free = super::returns_no_nan(cx, o.field); + super::color_write::plan(cx, color, link.form, nan_free); Some(color) } _ => None, diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index e68d7e855..137d26e4d 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -2267,7 +2267,7 @@ pub(super) fn half_write_nans( /// Whether texel `value` is a constant none of whose lanes is a NaN: a `half` or `float` scalar or /// vector constant whose every lane's bits are not a NaN's. Its write stores no NaN, so no device's /// encoding of one can show. An `undef` texel, a composite, and any computed value may hold one. -fn holds_no_nan(cx: &SelectCx<'_>, value: Value) -> bool { +pub(crate) fn holds_no_nan(cx: &SelectCx<'_>, value: Value) -> bool { use crate::lower::arith::legal::LoweredConst as C; use crate::spirv::ids::ScalarTy; let nan = |ty: ScalarTy, bits: u64| match ty { diff --git a/crates/metal2vulkan/src/tests/engine_link.rs b/crates/metal2vulkan/src/tests/engine_link.rs index c1f29f979..c3854a5d8 100644 --- a/crates/metal2vulkan/src/tests/engine_link.rs +++ b/crates/metal2vulkan/src/tests/engine_link.rs @@ -648,6 +648,48 @@ fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() { } } +/// A fragment function's output every return of which holds a constant none of whose lanes is a +/// NaN (`stage_io::returns_no_nan`) stores no NaN, so its write to a half-float channel records no +/// `PrecisionNote::DeviceNanEncoding` where a computed one does: a constant `half4` and `float4`, +/// and a struct's constant color 0, record none; a constant whose red is a NaN, a computed +/// `half4` and the struct's computed color 1 record it, on lavapipe and MoltenVK (whose `half` +/// outputs' NaNs the device canonicalizes). +#[test] +fn constant_colors_without_a_nan_record_no_nan_encoding() { + use crate::pipeline::artifact::PrecisionNote; + let Some(bc) = assemble("ncw_constant_colors.ll") else { + return; + }; + let note = PrecisionNote::DeviceNanEncoding; + for stem in ["lavapipe", "moltenvk-m3"] { + let p = prof(stem); + let v = compile(&bc, "ncw_vertex", &p).expect("vertex"); + for (entry, color, noted) in [ + ("ncw_constant_half", 0, false), + ("ncw_constant_float", 0, false), + ("ncw_constant_nan", 0, true), + ("ncw_computed_half", 0, true), + ("ncw_constant_pair", 0, false), + ("ncw_constant_pair", 1, true), + ] { + let what = format!("{stem} {entry} color {color}"); + let mut r = RenderLinkInputs::new(); + r.color_attachments[color] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float)); + let f = compile_with(&bc, entry, &p, &fragment_inputs(&r, &p)) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!( + f.precision.contains(¬e), + noted, + "{what}: {:?}", + f.precision + ); + let l = link(&[&v, &f], &render(&r), &p).unwrap_or_else(|e| panic!("{what}: {e}")); + validate_all(&l, &[&v, &f], &p); + } + } +} + /// Under `TextureWriteRoundingMode::NearestEven` a `float` output to a half-float attachment rounds /// to nearest even in the function on every profile, MoltenVK's included (listed as rounded, no /// device conversion noted, the device's blend of one and zero dropped), and the pipeline links diff --git a/docs/API.md b/docs/API.md index 371e29c83..ba50c483d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3205,7 +3205,9 @@ bound. a fragment function computes into a 16-bit float attachment through the pixel interlock: a NaN of the blend is the device's arithmetic's, which the storage image's store converts, where Metal stores every NaN of the blend as `0x7e00`. A texture write records it where the stored NaN is the - device's: a constant texel none of whose lanes is a NaN records nothing. **Exempt:** a `half` + device's: a constant texel none of whose lanes is a NaN records nothing. So does a fragment + function's color output where the device's conversion stores its NaN, but one every return of + which holds such a constant records nothing. **Exempt:** a `half` texel's write to a 32-bit float storage image on a profile that takes `DriverDeviation::MetalNanMoves` (the image stores the widened `float`'s bits, Metal's `0x7fc00000`; the module requires `VkProperty::MetalNanMoves`), and a `float` or `half` texel's