Measure a replayed execution of commands a page's vertex function wrote, among many resident resources, while two other queues commit

What: the owned fixture icb_vertex_encode_indexed (ive_encode, a vertex function that encodes
one draw_indexed_primitives of 6 16-bit indices per draw, of primitive type iid % 5) and the
measurement lane runtime_lane::replayed_frames: a rasterization-off pass sets ive_encode's state
and draws one point 5000 times, each instance writing command i of an indirect command buffer
that inherits the executing encoder's state and buffers; a second pass executes the 5000 commands,
making REPLAYED_FRAMES_RESIDENT buffers and textures resident besides (as a page's bind groups);
meanwhile a presenter queue blits from a texture the page made resident and a bystander queue
fills a buffer of its own, each one command buffer at a time. It prints per frame the frame's time,
the host step's time, pipelines made and records read, and the other queues' largest and mean
commit-to-completion times.

Why: the consumer's renderBundles page took 15 to 20 s a frame on an RTX 5080, each host-replayed
execution stalling the display. This is that shape.

How verified: release, --cfg m2v_gpu, M3 Max under MoltenVK (the host step's time; the
presenter's and the bystander's largest waits): 0 resident: 13 ms, 18 ms, 18 ms; 1000 of each:
195 ms, 200 ms, 200 ms; 5000 of each: 1.3 s, 1.31 s, 1.31 s, 5000 records read and no pipeline
made a warm frame.

(cherry picked from commit 074bef7d78795bf30444cfff4e368c5215e89c5c)
This commit is contained in:
Anees Iqbal committed 2026-11-04 21:54:25 -08:00
1 parent bf1055e10e
commit 20747c70a1
6 files changed
+576

No files matched your search

@@ -164,6 +164,7 @@ fixture icb_reset_encode: metal: Apple metal version 32023.921 (metalfe-32023.92
fixture icb_routed_writes: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118)
fixture icb_stage_in_encode: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture icb_stage_in_template: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture icb_vertex_encode_indexed: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118)
fixture ido_draw_order: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture kernel_bit_manipulation: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118)
fixture kernel_frexp_ilogb: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
@@ -0,0 +1,110 @@
; Generated by scripts/regen-air-fixtures from icb_vertex_encode_indexed.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"
%struct.Encoder = type { %"struct.metal::command_buffer" }
%"struct.metal::command_buffer" = type { %struct._command_buffer_t addrspace(1)* }
%struct._command_buffer_t = type opaque
; Function Attrs: mustprogress nounwind willreturn
define void @ive_encode(%struct.Encoder addrspace(1)* nocapture noundef readonly align 8 dereferenceable(8) "air-buffer-no-alias" %0, i16 addrspace(1)* noundef "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #0 {
%4 = getelementptr inbounds %struct.Encoder, %struct.Encoder addrspace(1)* %0, i64 0, i32 0, i32 0
%5 = load %struct._command_buffer_t addrspace(1)*, %struct._command_buffer_t addrspace(1)* addrspace(1)* %4, align 8, !tbaa.struct !32, !alias.scope !37, !noalias !40
%6 = urem i32 %2, 5
%7 = and i32 %2, 63
%8 = mul nuw nsw i32 %7, 6
%9 = zext i32 %8 to i64
%10 = getelementptr inbounds i16, i16 addrspace(1)* %1, i64 %9
tail call void @air.draw_indexed_primitives_render_command.p1i16(%struct._command_buffer_t addrspace(1)* nocapture %5, i32 %2, i32 %6, i32 6, i16 addrspace(1)* %10, i32 1, i32 0, i32 0) #5
ret void
}
; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn
define <{ <4 x float>, float }> @ive_vertex(i32 noundef %0) local_unnamed_addr #1 {
%2 = and i32 %0, 7
%3 = tail call fast float @air.convert.f.f32.u.i32(i32 %2) #6
%4 = fmul fast float %3, 2.500000e-01
%5 = fadd fast float %4, -8.750000e-01
%6 = lshr i32 %0, 3
%7 = and i32 %6, 7
%8 = tail call fast float @air.convert.f.f32.u.i32(i32 %7) #6
%9 = fmul fast float %8, 2.500000e-01
%10 = fadd fast float %9, -8.750000e-01
%11 = insertelement <4 x float> <float poison, float poison, float 0.000000e+00, float 1.000000e+00>, float %5, i64 0
%12 = insertelement <4 x float> %11, float %10, i64 1
%13 = insertvalue <{ <4 x float>, float }> undef, <4 x float> %12, 0
%14 = insertvalue <{ <4 x float>, float }> %13, float 1.000000e+00, 1
ret <{ <4 x float>, float }> %14
}
; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn
declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #2
; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn
define <4 x half> @ive_fragment() local_unnamed_addr #3 {
ret <4 x half> <half 0xH0000, half 0xH3C00, half 0xH0000, half 0xH3C00>
}
; Function Attrs: mustprogress nounwind willreturn
declare void @air.draw_indexed_primitives_render_command.p1i16(%struct._command_buffer_t addrspace(1)* nocapture, i32, i32, i32, i16 addrspace(1)*, i32, i32, i32) local_unnamed_addr #4
attributes #0 = { mustprogress nounwind 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 = { 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 #2 = { mustprogress nofree nosync nounwind readnone willreturn }
attributes #3 = { 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 #4 = { mustprogress nounwind willreturn }
attributes #5 = { nounwind willreturn }
attributes #6 = { nounwind readnone willreturn }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8}
!air.vertex = !{!9, !17}
!air.fragment = !{!23}
!air.compile_options = !{!26, !27, !28}
!llvm.ident = !{!29}
!air.version = !{!30}
!air.language_version = !{!31}
!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 = !{void (%struct.Encoder addrspace(1)*, i16 addrspace(1)*, i32)* @ive_encode, !10, !11}
!10 = !{}
!11 = !{!12, !15, !16}
!12 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.struct_type_info", !13, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Encoder", !"air.arg_name", !"encoder"}
!13 = !{i32 0, i32 8, i32 0, !"command_buffer", !"commands", !"air.indirect_argument", !14}
!14 = !{i32 0, !"air.command_buffer", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"command_buffer", !"air.arg_name", !"commands"}
!15 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 2, !"air.arg_type_align_size", i32 2, !"air.arg_type_name", !"ushort", !"air.arg_name", !"indices"}
!16 = !{i32 2, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"}
!17 = !{<{ <4 x float>, float }> (i32)* @ive_vertex, !18, !21}
!18 = !{!19, !20}
!19 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!20 = !{!"air.point_size", !"air.arg_type_name", !"float", !"air.arg_name", !"size"}
!21 = !{!22}
!22 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"}
!23 = !{<4 x half> ()* @ive_fragment, !24, !10}
!24 = !{!25}
!25 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}
!26 = !{!"air.compile.denorms_disable"}
!27 = !{!"air.compile.fast_math_enable"}
!28 = !{!"air.compile.framebuffer_fetch_enable"}
!29 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"}
!30 = !{i32 2, i32 8, i32 0}
!31 = !{!"Metal", i32 4, i32 0, i32 0}
!32 = !{i64 0, i64 8, !33}
!33 = !{!34, !34, i64 0}
!34 = !{!"__metal_command_buffer_t", !35, i64 0}
!35 = !{!"omnipotent char", !36, i64 0}
!36 = !{!"Simple C++ TBAA"}
!37 = !{!38}
!38 = distinct !{!38, !39, !"air-alias-scope-arg(0)"}
!39 = distinct !{!39, !"air-alias-scopes(ive_encode)"}
!40 = !{!41}
!41 = distinct !{!41, !39, !"air-alias-scope-arg(1)"}
@@ -0,0 +1,109 @@
; Generated by scripts/regen-air-fixtures from icb_vertex_encode_indexed.metal (llvm-dis of icb_vertex_encode_indexed.air). Do not edit.
; ModuleID = '<stdin>'
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"
%struct.Encoder = type { %"struct.metal::command_buffer" }
%"struct.metal::command_buffer" = type { ptr addrspace(1) }
; Function Attrs: mustprogress nounwind willreturn
define void @ive_encode(ptr addrspace(1) noundef readonly align 8 captures(none) dereferenceable(8) "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, i32 noundef %2) local_unnamed_addr #0 {
%4 = getelementptr inbounds %struct.Encoder, ptr addrspace(1) %0, i64 0, i32 0, i32 0
%5 = load ptr addrspace(1), ptr addrspace(1) %4, align 8, !tbaa.struct !32, !alias.scope !37, !noalias !40
%6 = urem i32 %2, 5
%7 = and i32 %2, 63
%8 = mul nuw nsw i32 %7, 6
%9 = zext i32 %8 to i64
%10 = getelementptr inbounds i16, ptr addrspace(1) %1, i64 %9
tail call void @air.draw_indexed_primitives_render_command.p1i16(ptr addrspace(1) captures(none) %5, i32 %2, i32 %6, i32 6, ptr addrspace(1) %10, i32 1, i32 0, i32 0) #5
ret void
}
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
define <{ <4 x float>, float }> @ive_vertex(i32 noundef %0) local_unnamed_addr #1 {
%2 = and i32 %0, 7
%3 = tail call fast float @air.convert.f.f32.u.i32(i32 %2) #6
%4 = fmul fast float %3, 2.500000e-01
%5 = fadd fast float %4, -8.750000e-01
%6 = lshr i32 %0, 3
%7 = and i32 %6, 7
%8 = tail call fast float @air.convert.f.f32.u.i32(i32 %7) #6
%9 = fmul fast float %8, 2.500000e-01
%10 = fadd fast float %9, -8.750000e-01
%11 = insertelement <4 x float> <float poison, float poison, float 0.000000e+00, float 1.000000e+00>, float %5, i64 0
%12 = insertelement <4 x float> %11, float %10, i64 1
%13 = insertvalue <{ <4 x float>, float }> undef, <4 x float> %12, 0
%14 = insertvalue <{ <4 x float>, float }> %13, float 1.000000e+00, 1
ret <{ <4 x float>, float }> %14
}
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #2
; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none)
define <4 x half> @ive_fragment() local_unnamed_addr #3 {
ret <4 x half> <half 0xH0000, half 0xH3C00, half 0xH0000, half 0xH3C00>
}
; Function Attrs: mustprogress nounwind willreturn
declare void @air.draw_indexed_primitives_render_command.p1i16(ptr addrspace(1) captures(none), i32, i32, i32, ptr addrspace(1), i32, i32, i32) local_unnamed_addr #4
attributes #0 = { mustprogress nounwind 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 = { 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 #2 = { mustprogress nofree nosync nounwind willreturn memory(none) }
attributes #3 = { 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 #4 = { mustprogress nounwind willreturn }
attributes #5 = { nounwind willreturn }
attributes #6 = { nounwind willreturn memory(none) }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8}
!air.vertex = !{!9, !17}
!air.fragment = !{!23}
!air.compile_options = !{!26, !27, !28}
!llvm.ident = !{!29}
!air.version = !{!30}
!air.language_version = !{!31}
!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 @ive_encode, !10, !11}
!10 = !{}
!11 = !{!12, !15, !16}
!12 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.struct_type_info", !13, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Encoder", !"air.arg_name", !"encoder"}
!13 = !{i32 0, i32 8, i32 0, !"command_buffer", !"commands", !"air.indirect_argument", !14}
!14 = !{i32 0, !"air.command_buffer", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"command_buffer", !"air.arg_name", !"commands"}
!15 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 2, !"air.arg_type_align_size", i32 2, !"air.arg_type_name", !"ushort", !"air.arg_name", !"indices"}
!16 = !{i32 2, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"}
!17 = !{ptr @ive_vertex, !18, !21}
!18 = !{!19, !20}
!19 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!20 = !{!"air.point_size", !"air.arg_type_name", !"float", !"air.arg_name", !"size"}
!21 = !{!22}
!22 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"}
!23 = !{ptr @ive_fragment, !24, !10}
!24 = !{!25}
!25 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}
!26 = !{!"air.compile.denorms_disable"}
!27 = !{!"air.compile.fast_math_enable"}
!28 = !{!"air.compile.framebuffer_fetch_enable"}
!29 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"}
!30 = !{i32 2, i32 8, i32 0}
!31 = !{!"Metal", i32 4, i32 0, i32 0}
!32 = !{i64 0, i64 8, !33}
!33 = !{!34, !34, i64 0}
!34 = !{!"__metal_command_buffer_t", !35, i64 0}
!35 = !{!"omnipotent char", !36, i64 0}
!36 = !{!"Simple C++ TBAA"}
!37 = !{!38}
!38 = distinct !{!38, !39, !"air-alias-scope-arg(0)"}
!39 = distinct !{!39, !"air-alias-scopes(ive_encode)"}
!40 = !{!41}
!41 = distinct !{!41, !39, !"air-alias-scope-arg(1)"}
@@ -0,0 +1,42 @@
// Owned fixture: a vertex function whose only effect is the indexed draw it encodes, as a pass
// with rasterization off encodes one a draw. The draw of instance `iid` (its base instance)
// writes command `iid`: a draw of 6 indices from the 16-bit `indices`, from index
// 6 * (iid % 64), once, of primitive type iid % 5 (point, line, line strip, triangle, triangle
// strip), at base vertex 0. The commands inherit the executing encoder's pipeline state and
// buffers. `ive_vertex` places vertex `vid` on a grid of 8 by 8 points, one pixel wide, and
// `ive_fragment` colours it green. Written for this repository; no third-party source. Loop-free.
#include <metal_stdlib>
using namespace metal;
struct Encoder {
command_buffer commands;
};
vertex void ive_encode(device const Encoder &encoder [[buffer(0)]],
const device ushort *indices [[buffer(1)]],
uint iid [[instance_id]])
{
render_command command(encoder.commands, iid);
command.draw_indexed_primitives(static_cast<primitive_type>(iid % 5), 6,
indices + 6 * (iid % 64), 1, 0, 0);
}
struct GridPoint {
float4 position [[position]];
float size [[point_size]];
};
vertex GridPoint ive_vertex(uint vid [[vertex_id]])
{
GridPoint point;
float x = float(vid % 8) / 4.0 - 0.875;
float y = float(vid / 8 % 8) / 4.0 - 0.875;
point.position = float4(x, y, 0.0, 1.0);
point.size = 1.0;
return point;
}
fragment half4 ive_fragment()
{
return half4(0.0, 1.0, 0.0, 1.0);
}
@@ -743,6 +743,8 @@ mod render_state;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod renders;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod replayed_frames;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod resident_draws;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod resolve_rounding;
@@ -0,0 +1,312 @@
//! A page's frame whose indirect command buffer its own vertex function writes, on the device the
//! cfg selects, without the validation layer, while two other queues commit work: what the host
//! step of the execution costs, and how long the other queues' command buffers wait behind it.
//!
//! The owned fixture `icb_vertex_encode_indexed`: a pass with rasterization off draws one point
//! per instance [`DRAWS`] times, setting `ive_encode`'s state before each, as a page's validation
//! pass does; the draw of instance `i` encodes command `i`, a draw of 6 16-bit indices of
//! primitive type `i % 5` (`ive_encode` may call `draw_indexed_primitives` alone). The pass makes
//! the buffer resident for writing, the indices for reading, and a texture the presenter samples
//! for reading. A second pass executes the buffer's [`DRAWS`] commands, which inherit its state
//! (`ive_vertex`, `ive_fragment`) and buffers: the GPU may write the records, so a host step
//! records the execution from them.
//!
//! Meanwhile a presenter queue commits a blit that reads the texture, and a bystander queue one
//! that fills a buffer of its own, each one at a time, again as each completes, until the frame
//! completes. [`replayed_frames`] prints, per frame (the first cold, the rest warm), as
//! `REPLAYED-FRAMES` lines: the frame's time from commit to completion, the counters' moves that
//! split it (host steps and their time, pipelines made and their time, records read), and the
//! presenter's and the bystander's command buffers' times from commit to completion, largest and
//! count. [`FRAMES_VAR`] sets the frames (4 by default), and [`RESIDENT_VAR`] how many buffers
//! and textures, one of each, the execution's pass makes resident besides, as a page's bind
//! groups do (none by default): the step's time should grow with the records alone, not with
//! them times the resident resources. It is ignored by default: run it by name with
//! `--run-ignored all`.
use super::{buffer_with, validated_device_with, Messages, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::metal::{
IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureUsage,
};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
BlitOption, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device,
IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, Origin,
PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction,
Texture, TextureDescriptor, WorkCounts,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
/// The variable that sets the frames timed.
const FRAMES_VAR: &str = "REPLAYED_FRAMES_FRAMES";
/// The variable that sets how many buffers and textures the execution's pass makes resident
/// besides (none by default).
const RESIDENT_VAR: &str = "REPLAYED_FRAMES_RESIDENT";
/// The commands the pass encodes, one a draw.
const DRAWS: u32 = 5000;
/// The target's width and height.
const SIDE: u64 = 64;
/// The fixture's states and buffers on a device.
struct Page {
encode: RenderPipelineState,
draw: RenderPipelineState,
icb: IndirectCommandBuffer,
table: Buffer,
indices: Buffer,
target: Texture,
surface: Texture,
/// The buffers and textures the execution's pass makes resident besides, as a page's bind
/// groups, one of each a draw, do ([`RESIDENT_VAR`]).
resident: Vec<(Buffer, Texture)>,
}
impl Page {
fn new(device: &Device) -> Page {
let bitcode = llvm_assemble(&engine_dir().join("icb_vertex_encode_indexed.ll")).unwrap();
let library = device.new_library_with_air(&bitcode).unwrap();
let function = |library: &Library, name: &str| {
let function = library.new_function_with_name(name).unwrap();
StageSource::Function(function.function_descriptor())
};
let rgba = PixelFormat::RGBA8Unorm;
let mut descriptor = RenderPipelineDescriptor::new(function(&library, "ive_encode"));
descriptor.rasterization_enabled = false;
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(rgba));
let options = PipelineOptions::default();
let encode = device
.new_render_pipeline_state(&descriptor, &options)
.unwrap();
let mut descriptor = RenderPipelineDescriptor::new(function(&library, "ive_vertex"));
descriptor.fragment = Some(function(&library, "ive_fragment"));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(rgba));
descriptor.support_indirect_command_buffers = true;
let draw = device
.new_render_pipeline_state(&descriptor, &options)
.unwrap();
let mut commands = IndirectCommandBufferDescriptor::new();
commands.command_types = IndirectCommandType::DRAW_INDEXED;
commands.inherit_pipeline_state = true;
commands.inherit_buffers = true;
let icb = device
.new_indirect_command_buffer(&commands, u64::from(DRAWS), ResourceOptions::shared())
.unwrap();
let table = buffer_with(device, &icb.gpu_resource_id().0.to_le_bytes()).unwrap();
let indices: Vec<u8> = (0..64u16 * 6)
.map(|at| (at * 37 + 11) % 64)
.flat_map(u16::to_le_bytes)
.collect();
let indices = buffer_with(device, &indices).unwrap();
let texture = |usage: TextureUsage| {
let mut descriptor = TextureDescriptor::texture_2d(rgba, SIDE, SIDE, false);
descriptor.usage = usage;
descriptor.resource_options = ResourceOptions::shared();
device.new_texture(&descriptor).unwrap()
};
let resident = std::env::var(RESIDENT_VAR).map_or(0, |count| count.parse().unwrap());
let resident = (0..resident)
.map(|_| {
let buffer = device.new_buffer(256, ResourceOptions::shared()).unwrap();
let mut descriptor = TextureDescriptor::texture_2d(rgba, 4, 4, false);
descriptor.usage = TextureUsage::SHADER_READ;
(buffer, device.new_texture(&descriptor).unwrap())
})
.collect();
Page {
encode,
draw,
icb,
table,
indices,
target: texture(TextureUsage::RENDER_TARGET),
surface: texture(TextureUsage::SHADER_READ),
resident,
}
}
fn pass(&self) -> RenderPassDescriptor {
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(self.target.clone());
color.load_action = LoadAction::Clear;
color.store_action = StoreAction::Store;
pass
}
/// One frame on `queue`, committed: the encoding pass, then the execution's.
fn frame(&self, queue: &CommandQueue) -> CommandBuffer {
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&self.pass()).unwrap();
let vertex = RenderStages::VERTEX;
let uses = [
(self.icb.as_resource(), ResourceUsage::WRITE),
(self.indices.as_resource(), ResourceUsage::READ),
(self.table.as_resource(), ResourceUsage::READ),
(self.surface.as_resource(), ResourceUsage::READ),
];
for (resource, usage) in uses {
encoder.use_resource(resource, usage, vertex).unwrap();
}
encoder.set_vertex_buffer(Some(&self.table), 0, 0).unwrap();
encoder
.set_vertex_buffer(Some(&self.indices), 0, 1)
.unwrap();
for draw in 0..DRAWS {
encoder.set_render_pipeline_state(&self.encode).unwrap();
encoder
.draw_primitives(PrimitiveType::Point, 0, 1, 1, draw)
.unwrap();
}
encoder.end_encoding().unwrap();
let mut encoder = command_buffer.render_command_encoder(&self.pass()).unwrap();
encoder.set_render_pipeline_state(&self.draw).unwrap();
let stages = RenderStages::VERTEX | RenderStages::FRAGMENT;
for (buffer, texture) in &self.resident {
for resource in [buffer.as_resource(), texture.as_resource()] {
encoder
.use_resource(resource, ResourceUsage::READ, stages)
.unwrap();
}
}
encoder
.execute_commands_in_buffer(&self.icb, 0..u64::from(DRAWS))
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
}
}
/// What another queue's command buffers took, one at a time from commit to completion, while
/// `done` is unset.
#[derive(Debug, Default)]
struct Waits {
count: usize,
largest: Duration,
total: Duration,
}
/// Commit `encode`'s command buffers on `queue`, each after the last completed, until `done`.
fn commit_until(queue: &CommandQueue, done: &AtomicBool, encode: impl Fn(&CommandBuffer)) -> Waits {
let mut waits = Waits::default();
while !done.load(Ordering::Acquire) {
let command_buffer = queue.command_buffer().unwrap();
encode(&command_buffer);
let start = Instant::now();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
let took = start.elapsed();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
waits.count += 1;
waits.total += took;
waits.largest = waits.largest.max(took);
}
waits
}
/// The frames to time: 4 unless [`FRAMES_VAR`] sets another count.
fn frames() -> usize {
std::env::var(FRAMES_VAR).map_or(4, |count| count.trim().parse().expect(FRAMES_VAR))
}
/// What `after` moved past `before` of the counters that split a frame.
fn split(before: &WorkCounts, after: &WorkCounts) -> String {
let ms = |nanos: u64| nanos as f64 / 1e6;
format!(
"host_steps {} host_step_ms {:.1} render_pipelines_made_ms {:.1} \
compute_pipelines_made_ms {:.1} variant_pipelines_made {} records_read {}",
after.host_steps_recorded - before.host_steps_recorded,
ms(after.host_step_nanos - before.host_step_nanos),
ms(after.render_pipeline_create_nanos - before.render_pipeline_create_nanos),
ms(after.compute_pipeline_create_nanos - before.compute_pipeline_create_nanos),
after.variant_pipelines_made - before.variant_pipelines_made,
after.indirect_records_read - before.indirect_records_read,
)
}
#[test]
#[ignore = "a measurement, not a check: run by name with --run-ignored all"]
fn replayed_frames() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.layers.clear();
// A consumer's device keeps no execution record.
options.record_executions = false;
})
.unwrap();
let name = device.name().to_owned();
let page = Page::new(&device);
let (page_queue, presenter, bystander) = (
device.new_command_queue().unwrap(),
device.new_command_queue().unwrap(),
device.new_command_queue().unwrap(),
);
let read = device
.new_buffer(SIDE * SIDE * 4, ResourceOptions::shared())
.unwrap();
let own = device
.new_buffer(1 << 16, ResourceOptions::shared())
.unwrap();
for frame in 0..frames() {
let done = AtomicBool::new(false);
let before = device.work_counts();
let (took, presented, stood) = thread::scope(|scope| {
let presented = scope.spawn(|| {
commit_until(&presenter, &done, |command_buffer| {
let mut blit = command_buffer.blit_command_encoder().unwrap();
let size = Size::new(SIDE, SIDE, 1);
blit.copy_from_texture_to_buffer(
&page.surface,
0,
0,
Origin::new(0, 0, 0),
size,
&read,
0,
SIDE * 4,
SIDE * SIDE * 4,
BlitOption::None,
)
.unwrap();
blit.end_encoding().unwrap();
})
});
let stood = scope.spawn(|| {
commit_until(&bystander, &done, |command_buffer| {
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(&own, 0..1 << 16, 7).unwrap();
blit.end_encoding().unwrap();
})
});
let start = Instant::now();
let command_buffer = page.frame(&page_queue);
command_buffer.wait_until_completed_for(WAIT).unwrap();
let took = start.elapsed();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
done.store(true, Ordering::Release);
(took, presented.join().unwrap(), stood.join().unwrap())
});
let after = device.work_counts();
println!(
"REPLAYED-FRAMES {name} frame {frame}: {:.1} ms (encoding to completion), {}; \
presenter {} command buffers, largest {:.1} ms, mean {:.1} ms; bystander {}, \
largest {:.1} ms, mean {:.1} ms",
took.as_secs_f64() * 1e3,
split(&before, &after),
presented.count,
presented.largest.as_secs_f64() * 1e3,
presented.total.as_secs_f64() * 1e3 / presented.count.max(1) as f64,
stood.count,
stood.largest.as_secs_f64() * 1e3,
stood.total.as_secs_f64() * 1e3 / stood.count.max(1) as f64,
);
}
}