Author SHA1 Message Date
千川白浪 8fd7fb5d9c Merge pull request #3 from liuyaxuan123457-ctrl/fix/host-batch-queue-recording
Allow host-owned copy batches to record before FIFO submission
2026-12-05 13:43:28 +08:00
Xiaochi You b8f9629ba8 Merge pull request #5 from yxc0915/steelbrain/batch-fixed-offset-draws
Batch fixed-offset draws with direct Vulkan commands
2026-12-04 18:13:58 +08:00
YXC0915 1dd4e970c0 🐎 Batch fixed-offset draws with direct Vulkan commands
Reuse the ordinary draw state across a fixed binding without submitting indirect commands. RX 6500M timing showed the indirect command path still took 0.909 ms against 0.351 ms for the same direct workload, even with the ordinary shader.
2026-12-04 18:02:14 +08:00
YXC0915 acb2f3756b 🐎 Keep fixed-offset multi-draw on the ordinary pipeline
Combine repeated vertex bindings without uploading a draw table or switching the shader. Preserve the table path for changing offsets, and exclude modules that can observe DrawIndex. Add a pixel parity and pipeline reuse regression test.
2026-12-04 17:48:08 +08:00
Xiaochi You 8edd5cd27a Merge pull request #4 from yxc0915/steelbrain/sync-metal2vulkan-865592b
Merge the upstream Vulkan runtime into development
2026-12-04 16:10:31 +08:00
YXC0915 7b3aedb5fa Sync upstream metal2vulkan for the Reims runtime
Preserve GPU suspend and replay, Places allocation isolation, and multi-draw indirect. Use the upstream render-offset deltas, static attachment feedback, and 64-bit device-address arithmetic.
2026-12-04 16:07:39 +08:00
liuyaxuan123457-ctrl 0776937c90 Document host batch ownership and keep queue tests after implementation 2026-12-03 17:23:26 +08:00
Codex 728b4701d0 Separate host batch recording from Metal queue admission 2026-12-03 16:50:43 +08:00
YXC0915 19090d5f2e 🐛 Isolate Places allocations from buffer address replay
Keep image placement slabs separate when buffer capture and replay is enabled. Leave buffer replay enabled for captured buffer allocations.
2026-12-03 02:52:31 +08:00
YXC0915 3337b4d868 🐛 Use static flags for eligible attachment feedback draws
Keep the dynamic feedback capability check for path selection. Declare color feedback on the pipeline instead of toggling it for each draw.
2026-12-03 02:52:02 +08:00
YXC0915 94ff838bb8 🆕 Support GPU state capture and replay for VM suspend
Expose buffer address capture, replay and device idle operations for suspend and resume. Preserve the existing dynamic attachment-feedback device capability.
2026-12-03 02:51:52 +08:00
Xiaochi You a97670348c Merge pull request #2 from reiasu2/reims-go/multi-draw-indirect
runtime, spirv: add opt-in multi-draw indirect batching for vertex-offset draws
2026-12-03 01:43:49 +08:00
Xiaochi You 2245ae27b0 Merge PR #1: Optimize render buffer offsets and push constants
runtime: update render buffer offsets locally and submit minimal push-constant deltas
2026-12-03 00:01:41 +08:00
棠渚听潮 6c22641a9c Batch vertex-offset draws with draw-table SPIR-V variants and multi-draw indirect 2026-12-02 19:33:16 +08:00
棠渚听潮 d92aa60353 Submit aligned render push constant deltas
Track the last push length and record only the changed words for a draw. Keep Managed index and slot reaches on the full draw path, and leave device-wide alias and unslotted reads to the existing post-update checks.

Verified with cargo fmt and runtime Clippy, 207 runtime unit tests with the existing CRLF-sensitive stage test skipped, and the draw-offset regression on Intel Arc B390 including a Managed copy back.
2026-12-02 19:33:15 +08:00
棠渚听潮 3c6be6a1ed Update render buffer offsets without rebuilding push data
Reuse retained buffers for offset-only binds and track changed slots by stage. Patch indexed push fields and fixed-function bindings for eligible direct draws, and use full validation and filling when the draw cannot reuse them.

Verified with runtime clippy, the 207 lib tests in a temporary copy with LF in stage.rs, and the offset regression on Intel Arc B390.
2026-12-02 19:33:15 +08:00
YXC0915 ea695f9456 Require dynamic state for native attachment feedback
Enable color feedback around draws using the feedback layout instead of marking every graphics pipeline. Use the attachment shadow when the device lacks the dynamic feature, so drivers with only the static layout can still run workloads that sample their render targets.
2026-12-02 17:50:47 +08:00
YXC0915 729d91d23b Restore device addresses with an explicit carry
The biased slot word let a driver lower a zero-extended 32-bit
displacement as a signed physical storage buffer offset. On AMD Windows
the first draw then read exactly 4 GiB below the intended device address.

Reconstruct the slot address with two words and a carry before adding
the signed byte displacement. Keep the binding layout and invalidate
cached shaders. The existing identity-buffer test checks the carry and
the interpreted values at addresses above 4 GiB.
2026-12-02 16:59:13 +08:00
27 changed files with 2751 additions and 68 deletions

No files matched your search

+6
View File
@@ -59,6 +59,12 @@ impl Block {
Block { claim }
}
/// Returns capture/replay address metadata for this block (if supported).
pub fn capture_info(&self) -> Option<memory::BlockCaptureInfo> {
let (core, block) = self.held().ok()?;
core.pool.capture_info(&block.memory)
}
/// Whether the block is of `core`'s device.
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core)
@@ -1629,6 +1629,10 @@ impl Building {
self.tally.count(metric);
}
pub(crate) fn count_by(&mut self, metric: Metric, count: u64) {
self.tally.count_by(metric, count);
}
/// Copies `bytes` into the parameter ring, returning their address.
pub(crate) fn write_ring(&mut self, bytes: &[u8]) -> Result<u64, Error> {
Ok(self.write_ring_placed(bytes)?.address)
+21 -1
View File
@@ -289,6 +289,10 @@ pub(crate) enum Metric {
PipelineCacheWritesSkipped,
/// [`Metrics::ring_writes`].
RingWrites,
/// [`Metrics::multi_draw_calls`].
MultiDrawCalls,
/// [`Metrics::multi_draw_items`].
MultiDrawItems,
/// [`Metrics::pushes`].
Pushes,
/// [`Metrics::pushes_held`].
@@ -411,6 +415,8 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::KernelMakesDropped,
Metric::PipelineCacheWritesSkipped,
Metric::RingWrites,
Metric::MultiDrawCalls,
Metric::MultiDrawItems,
Metric::Pushes,
Metric::PushesHeld,
Metric::BoundDispatches,
@@ -484,7 +490,11 @@ impl Default for Tally {
impl Tally {
/// Counts one more of `metric`.
pub(crate) fn count(&mut self, metric: Metric) {
self.counts[metric as usize] += 1;
self.count_by(metric, 1);
}
pub(crate) fn count_by(&mut self, metric: Metric, count: u64) {
self.counts[metric as usize] += count;
self.counted |= 1 << metric as usize;
}
}
@@ -887,6 +897,8 @@ struct Atomics {
kernel_makes_dropped: AtomicU64,
pipeline_cache_writes_skipped: AtomicU64,
ring_writes: AtomicU64,
multi_draw_calls: AtomicU64,
multi_draw_items: AtomicU64,
pushes: AtomicU64,
pushes_held: AtomicU64,
bound_dispatches: AtomicU64,
@@ -1155,6 +1167,8 @@ impl Counters {
Metric::KernelMakesDropped => &a.kernel_makes_dropped,
Metric::PipelineCacheWritesSkipped => &a.pipeline_cache_writes_skipped,
Metric::RingWrites => &a.ring_writes,
Metric::MultiDrawCalls => &a.multi_draw_calls,
Metric::MultiDrawItems => &a.multi_draw_items,
Metric::Pushes => &a.pushes,
Metric::PushesHeld => &a.pushes_held,
Metric::BoundDispatches => &a.bound_dispatches,
@@ -2279,6 +2293,8 @@ impl Counters {
pipeline_cache_writes_skipped: a.pipeline_cache_writes_skipped.load(Relaxed),
cache_bytes_written: a.cache_bytes_written.load(Relaxed),
ring_writes: a.ring_writes.load(Relaxed),
multi_draw_calls: a.multi_draw_calls.load(Relaxed),
multi_draw_items: a.multi_draw_items.load(Relaxed),
pushes: a.pushes.load(Relaxed),
pushes_held: a.pushes_held.load(Relaxed),
bound_dispatches: a.bound_dispatches.load(Relaxed),
@@ -3220,6 +3236,10 @@ pub struct Metrics {
/// its dispatch region at 256 bytes, more than 8 at 128), and each `set_bytes` copy, a render
/// encoder's too.
pub ring_writes: u64,
/// Recorded multi-draw indirect calls.
pub multi_draw_calls: u64,
/// Metal draws submitted by those indirect calls, excluding the direct heads.
pub multi_draw_items: u64,
/// `vkCmdPushConstants` recorded: a draw's or a dispatch's push bytes, where the command
/// buffer did not already hold them.
pub pushes: u64,
+56
View File
@@ -275,6 +275,7 @@ pub(crate) struct Core {
/// pipeline of a state whose functions can read a texture, which takes the loop's colour flag
/// at the state's make (`crate::render::Draws::reads_textures`).
pub(crate) feedback_loop: bool,
pub(crate) capture_replay: bool,
/// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists
/// it): a lost device's fault report, read once, at its first loss (`crate::fault`).
pub(crate) fault: Option<ash::ext::device_fault::Device>,
@@ -282,6 +283,8 @@ pub(crate) struct Core {
/// caches, where device creation enabled it (`floor::Capabilities::indirect_commands`); an
/// indirect command buffer is refused without them.
pub(crate) indirect: Option<crate::indirect::Indirect>,
draw_indirect_limit: u32,
pub(crate) draw_indirect_first_instance: bool,
/// A draw may read an attachment of its own pass through a texture
/// (`floor::Capabilities::attachment_reads`): through the feedback loop where `feedback_loop`
/// holds, else through a copy of the image into its shadow (`crate::shadow`).
@@ -465,6 +468,9 @@ pub(crate) struct Queues {
#[non_exhaustive]
#[derive(Clone, Default)]
pub struct DeviceOptions {
/// No Metal counterpart. Opt in to combining draws into a Vulkan indirect draw command
/// where the logical device enables `multiDrawIndirect`.
pub multi_draw_indirect: bool,
/// The consumer's hooks around each allocation of the pool: its map before any of its blocks
/// goes out, and its unmap before the allocation is freed. `None` where the consumer keeps no
/// mapping of its own.
@@ -926,8 +932,12 @@ impl Device {
ticks,
calibrated,
feedback_loop: capabilities.feedback_loop,
capture_replay: capabilities.buffer_device_address_capture_replay,
fault,
indirect,
draw_indirect_limit: capabilities.draw_indirect_limit(options.multi_draw_indirect),
draw_indirect_first_instance: capabilities.features.core.draw_indirect_first_instance
== vk::TRUE,
attachment_reads: capabilities.attachment_reads,
linear_attachments: (capabilities.features.linear_attachment).linear_color_attachment
== vk::TRUE,
@@ -1231,6 +1241,42 @@ impl Device {
complete::lose(&self.shared.core, loss);
}
/// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device.
pub fn buffer_device_address_capture_replay(&self) -> bool {
self.shared.core.capture_replay
}
/// Waits non-destructively until all in-flight GPU work has completed and retired.
pub fn wait_idle(&self) -> Result<(), Error> {
let core = &self.shared.core;
if core.closed() {
return Err(Error::Quiesced);
}
// Wait for submitted command buffers to retire on the completion thread.
let deadline = Instant::now() + Duration::from_secs(10);
while core.pool.in_flight() > 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(1));
}
// SAFETY: `device` is live and wait_idle synchronizes all host queues.
let _q = lock(&core.queues.runtime);
unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?;
Ok(())
}
/// Replays a previously captured block at its exact Vulkan device address.
pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result<Block, Error> {
let core = &self.shared.core;
if core.closed() {
return Err(Error::Quiesced);
}
let memory =
core.pool
.take_replayed(core, capture, crate::counters::Site::take(capture.class))?;
let info = memory.info();
let block = memory::Block::new(memory, Arc::clone(core));
Ok(Block::claim(core, info, block))
}
/// No Metal counterpart: takes a block of `class` memory of `len` bytes rounded up to 64 KiB
/// (to the device's `bufferImageGranularity` where that is larger), for the consumer to place
/// buffers in: a handle ([`Block`]) whose last drop gives it back. A block is a range of one
@@ -1352,6 +1398,12 @@ impl Device {
&self.shared.core
}
/// No Metal counterpart. The maximum number of draws in one Vulkan indirect draw command
/// with batching enabled, or zero when batching is unavailable or disabled.
pub fn draw_indirect_limit(&self) -> u32 {
self.core().draw_indirect_limit()
}
/// Gives up this handle where it is not the last, which ends nothing; the last comes back,
/// for the caller to drop once it holds no lock, which ends the device on its thread. A call
/// that holds a handle while another thread may drop the consumer's last one gives its own up
@@ -1737,6 +1789,10 @@ pub(crate) struct EncoderLimits {
}
impl Core {
pub(crate) fn draw_indirect_limit(&self) -> u32 {
self.draw_indirect_limit
}
/// A digest of what the device enabled: its extensions, the consumer's features and the
/// translator's profile of the device (its features, properties and limits). Two devices of
/// one physical device opened with the same [`DeviceOptions`] have one; the stage keys and a
+32 -13
View File
@@ -165,15 +165,10 @@ impl Event {
}
}
impl SharedEvent {
/// `signaledValue`: the higher of the value of the signal the semaphore's count reached and the
/// host's floor, that count being one a host wait confirmed: a counter read finds it, and a
/// wait with a timeout of 0 confirms it where it is above the count last confirmed. Where the
/// value rose since the host last saw it, the Shared memory command buffers in flight may
/// write is flushed and invalidated first (`crate::coherence`), so the host reads what the GPU
/// wrote before its signal.
impl Event {
/// Reads the Metal timeline value for checkpointing.
pub fn signaled_value(&self) -> u64 {
let inner = &self.event.inner;
let inner = &self.inner;
let (signalled, floor) = {
let state = lock(&inner.state);
// A lost device answers with what was seen before the loss.
@@ -188,11 +183,16 @@ impl SharedEvent {
signalled.max(floor)
}
/// `setSignaledValue:`: raises the host's floor to `value`; a value not above it changes
/// nothing. The semaphore is never signalled from the host. Segments the submit thread holds
/// and host waits that the new value meets go on, and listeners it reaches run.
pub fn set_signaled_value(&self, value: u64) {
let inner = &self.event.inner;
/// Restores the Metal timeline value on a freshly created event.
pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> {
// The Vulkan semaphore counts submissions, independently of the Metal value.
// Raising the host floor also satisfies waits on the restored value.
self.set_floor(value);
Ok(())
}
fn set_floor(&self, value: u64) {
let inner = &self.inner;
let reached = {
let mut state = lock(&inner.state);
if value <= state.floor {
@@ -208,6 +208,25 @@ impl SharedEvent {
core.done.fire(core, Arc::clone(inner));
}
}
}
impl SharedEvent {
/// `signaledValue`: the higher of the value of the signal the semaphore's count reached and the
/// host's floor, that count being one a host wait confirmed: a counter read finds it, and a
/// wait with a timeout of 0 confirms it where it is above the count last confirmed. Where the
/// value rose since the host last saw it, the Shared memory command buffers in flight may
/// write is flushed and invalidated first (`crate::coherence`), so the host reads what the GPU
/// wrote before its signal.
pub fn signaled_value(&self) -> u64 {
self.event.signaled_value()
}
/// `setSignaledValue:`: raises the host's floor to `value`; a value not above it changes
/// nothing. The semaphore is never signalled from the host. Segments the submit thread holds
/// and host waits that the new value meets go on, and listeners it reaches run.
pub fn set_signaled_value(&self, value: u64) {
self.event.set_floor(value);
}
/// `waitUntilSignaledValue:timeoutMS:`: true once [`signaled_value`](Self::signaled_value)
/// reaches `value`, false when `timeout` passes first.
+23
View File
@@ -757,6 +757,7 @@ pub(crate) const OPTIONAL: &[Feature] = &[
// the device offers it, else a branch over the offset's values, each with its value as
// `ConstOffset` (Vulkan 1.0's).
feature!(maintenance8.maintenance8 => Maintenance8),
feature!(core.multi_draw_indirect),
];
/// The feature of the attachment feedback loop ([`ATTACHMENT_READ_EXTENSIONS`]): enabled where the
@@ -1141,6 +1142,8 @@ pub struct Capabilities {
/// loop, the feedback layout its image moves to and the colour flag the pipelines of a state
/// whose functions can read a texture take.
pub feedback_loop: bool,
/// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore.
pub buffer_device_address_capture_replay: bool,
/// The features device creation enables: every one the floor requires, each of the optional,
/// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment
/// and fault-report ones the device reports, the attachment-read ones where
@@ -1162,6 +1165,19 @@ pub struct Capabilities {
/// What an indirect command buffer's execution may take, where device creation enables
/// [`INDIRECT_COMMANDS`]; `None` on a device without them.
pub indirect_commands: Option<IndirectCommandLimits>,
/// The physical limit for draws in one Vulkan indirect draw command.
pub max_draw_indirect_count: u32,
}
impl Capabilities {
/// The effective multi-draw limit when the runtime opts in and device creation enables it.
pub(crate) fn draw_indirect_limit(&self, enabled: bool) -> u32 {
if enabled && self.features.core.multi_draw_indirect == vk::TRUE {
self.max_draw_indirect_count
} else {
0
}
}
}
impl std::fmt::Debug for Capabilities {
@@ -1186,6 +1202,7 @@ impl std::fmt::Debug for Capabilities {
.field("extensions", &self.extensions)
.field("queue_family", &self.queue_family)
.field("indirect_commands", &self.indirect_commands)
.field("max_draw_indirect_count", &self.max_draw_indirect_count)
.finish_non_exhaustive()
}
}
@@ -1493,6 +1510,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else {
return Err(BelowFloor { missing });
};
let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE;
if capture_replay {
features.vulkan12.buffer_device_address_capture_replay = vk::TRUE;
}
for feature in (OPTIONAL.iter().chain(PORTABILITY_STATED))
.chain(STEP_RATES)
.chain(MIN_LOD_CLAMPS)
@@ -1565,6 +1586,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE,
attachment_reads,
feedback_loop,
buffer_device_address_capture_replay: capture_replay,
features,
extensions: DEVICE_EXTENSIONS
.iter()
@@ -1586,6 +1608,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
queue_family,
memory: device.memory,
indirect_commands,
max_draw_indirect_count: device.limits.max_draw_indirect_count,
})
}
+5 -3
View File
@@ -103,7 +103,9 @@ pub use host_bytes::HostBytes;
pub use import::ImportHandle;
pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType};
pub use instance::{Instance, PhysicalDevice};
pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
pub use memory::{
AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass,
};
/// `MTLLibrary`: the translator's, read from AIR or a metallib.
/// `MTLSamplerDescriptor`: the translator's.
pub use metal2vulkan::bind::SamplerDescriptor;
@@ -159,8 +161,8 @@ pub use positions::SamplePosition;
pub use queue::CommandQueue;
pub use render::RenderPipelineState;
pub use render_encoder::{
IndexBuffer, PatchIndexBuffers, RenderCommandEncoder, ScissorRect, Viewport,
VisibilityResultMode,
BatchStop, IndexBuffer, PatchIndexBuffers, RenderCommandEncoder, ScissorRect, VertexOffsetDraw,
Viewport, VisibilityResultMode,
};
pub use sampler::SamplerState;
pub use stage::{serve_stage, StageBreach, StageFill, StageRequest, StageSpans};
+249 -11
View File
@@ -259,8 +259,28 @@ impl AllocationId {
/// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer
/// usage and a device address, spans it; an imported or exported block is the whole of an
/// allocation of its own. Only an exported block is exportable.
/// Capture/replay address metadata for restoring a block at its exact Vulkan device address.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockCaptureInfo {
/// Storage mode (`Shared` or `Private`).
pub class: MemoryClass,
/// Full parent Vulkan allocation length in bytes.
pub alloc_len: u64,
/// Offset of this block inside its parent allocation.
pub offset: u64,
/// Block length in bytes.
pub len: u64,
/// Guest-visible `VkDeviceAddress` of this block's first byte.
pub gpu_address: u64,
/// Opaque capture address of the parent `VkBuffer`.
pub opaque_buffer_address: u64,
/// Opaque capture address of the parent `VkDeviceMemory`.
pub opaque_memory_address: u64,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
/// Metadata describing an allocated GPU memory block.
pub struct BlockInfo {
/// The block's number.
pub id: BlockId,
@@ -666,6 +686,10 @@ struct Allocation {
buffer: vk::Buffer,
/// The device address of its first byte.
address: u64,
/// Opaque capture address of `buffer` (0 if capture-replay unsupported).
opaque_buffer_address: u64,
/// Opaque capture address of `memory` (0 if capture-replay unsupported).
opaque_memory_address: u64,
len: u64,
mapping: Option<Mapping>,
device_local: bool,
@@ -679,6 +703,9 @@ struct Allocation {
/// Its block out is a texture block ([`crate::places`]), which fills its allocation: a whole
/// unit, or a long allocation of its own length. False once it is idle.
texture: bool,
/// Reserved for image placement when buffer address replay is enabled. This allocation
/// stays in the texture pool after its last block comes back.
texture_only: bool,
/// When it became idle, in nanoseconds of [`host_time`](crate::host_time): when it was made,
/// or when its last live block came back. The oldest idle allocation is freed first.
idle_since: u64,
@@ -884,6 +911,8 @@ struct State {
/// The internal the block-maker thread took up and is making ([`run`]).
making: Option<Internal>,
stop: bool,
replaying: bool,
making_ahead: bool,
next_id: u32,
next_allocation: u32,
/// The allocations [`BlockMappings::map`] accepted whose unmap has not run.
@@ -1013,6 +1042,8 @@ impl Pool {
asked: [true; INTERNALS],
making: None,
stop: false,
replaying: false,
making_ahead: false,
next_id: 1,
next_allocation: 1,
mapped: HashSet::new(),
@@ -1255,7 +1286,9 @@ impl Pool {
return Err(Error::Quiesced);
}
let texture = matches!(site, Site::TextureBlock);
if let Some((carve, idle_since, long, ahead)) = state.fit(class, len, align, texture) {
if let Some((carve, idle_since, long, ahead)) =
state.fit(class, len, align, texture, core.capture_replay)
{
if ahead {
self.counters.site_take_ahead(site, len);
}
@@ -1471,6 +1504,160 @@ impl Pool {
}
}
/// Returns capture/replay info for a pool block, if capture-replay is enabled.
pub(crate) fn capture_info(&self, memory: &Memory) -> Option<BlockCaptureInfo> {
if memory.own.is_some() {
return None;
}
let state = self.lock();
let alloc = state.allocations[memory.class.index()]
.iter()
.find(|a| a.memory == memory.memory && !a.texture_only)?;
Some(BlockCaptureInfo {
class: memory.class,
alloc_len: alloc.len,
offset: memory.base,
len: memory.len,
gpu_address: memory.address,
opaque_buffer_address: alloc.opaque_buffer_address,
opaque_memory_address: alloc.opaque_memory_address,
})
}
/// Replays a previously captured pool block at its exact Vulkan device address.
pub(crate) fn take_replayed(
&self,
core: &Core,
cap: BlockCaptureInfo,
site: Site,
) -> Result<Memory, Error> {
let index = cap.class.index();
// 1. Check if the parent allocation is already present (e.g. another sub-block restored it,
// or a pre-stocked idle reserve landed at the exact same address!).
{
let mut state = self.lock();
if state.stop {
return Err(Error::Quiesced);
}
let id = number(&mut state)?;
let want_base = cap.gpu_address.saturating_sub(cap.offset);
if let Some(alloc) = state.allocations[index].iter_mut().find(|a| {
!a.texture_only
&& a.address == want_base
&& a.opaque_buffer_address == cap.opaque_buffer_address
&& a.opaque_memory_address == cap.opaque_memory_address
&& a.len == cap.alloc_len
}) {
if alloc.free.take_at(cap.offset, cap.len) {
let carve = alloc.carve(cap.offset);
alloc.live += 1;
alloc.placed += cap.len;
alloc.ahead = false;
self.counters.rise_by(cap.class.placed_gauge(), cap.len);
self.settle(&mut state, cap.class);
self.changed.notify_all();
return Ok(carve.block(id, cap.class, cap.len));
}
}
}
// 2. Pause block-maker ahead allocations, wait for any in-flight ahead make,
// and purge idle reserve slabs so none collide with the target opaque VA!
let idle_allocs: Vec<Allocation> = {
let mut state = self.lock();
state.replaying = true;
while state.making_ahead {
state = self.wait(state);
}
// Re-check if an ahead allocation that just finished landed at the exact target VA!
let want_base = cap.gpu_address.saturating_sub(cap.offset);
let hit = state.allocations[index].iter_mut().find_map(|a| {
if !a.texture_only
&& a.address == want_base
&& a.opaque_buffer_address == cap.opaque_buffer_address
&& a.opaque_memory_address == cap.opaque_memory_address
&& a.len == cap.alloc_len
&& a.free.take_at(cap.offset, cap.len)
{
let carve = a.carve(cap.offset);
a.live += 1;
a.placed += cap.len;
a.ahead = false;
Some(carve)
} else {
None
}
});
if let Some(carve) = hit {
let id = number(&mut state)?;
state.replaying = false;
self.counters.rise_by(cap.class.placed_gauge(), cap.len);
self.settle(&mut state, cap.class);
self.changed.notify_all();
return Ok(carve.block(id, cap.class, cap.len));
}
let mut drained = Vec::new();
for c in MemoryClass::ALL {
let ci = c.index();
let mut kept = Vec::new();
for a in state.allocations[ci].drain(..) {
if a.live == 0 {
drained.push(a);
} else {
kept.push(a);
}
}
state.allocations[ci] = kept;
self.settle(&mut state, c);
}
drained
};
for a in idle_allocs {
free_idle(core, a);
}
// 3. Allocate at the exact captured opaque buffer + memory addresses.
let alloc_res = make_allocation_ex(
core,
cap.class,
cap.alloc_len,
Some(site),
Some((cap.opaque_buffer_address, cap.opaque_memory_address)),
);
let mut allocation = match alloc_res {
Ok(a) => a,
Err(e) => {
let mut state = self.lock();
state.replaying = false;
self.changed.notify_all();
return Err(e);
}
};
let mapped = self.map(&allocation, cap.class, true);
if !mapped {
free_allocation(core, allocation);
let mut state = self.lock();
state.replaying = false;
self.changed.notify_all();
return Err(Error::Limit(Limit::AllocationNotMapped {
class: cap.class,
len: cap.alloc_len,
}));
}
let ok = allocation.free.take_at(cap.offset, cap.len);
debug_assert!(ok, "fresh allocation must contain captured block range");
let mut state = self.lock();
let id = number(&mut state)?;
let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len);
allocation.live = 1;
allocation.placed = cap.len;
state.allocations[index].push(allocation);
state.replaying = false;
self.counters.rise_by(cap.class.placed_gauge(), cap.len);
self.settle(&mut state, cap.class);
self.changed.notify_all();
Ok(memory)
}
/// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its
/// allocation at once.
pub(crate) fn give_back(&self, memory: Memory) {
@@ -1632,8 +1819,12 @@ impl State {
/// free bytes would wait until they ran low; in return a take of up to a unit, the 16 MiB
/// ones among them, lands in memory made ahead once the block-maker thread has made it.
fn whole(&self, class: MemoryClass) -> bool {
(self.allocations[class.index()].iter())
.any(|allocation| allocation.unit() && !allocation.retiring && allocation.live == 0)
(self.allocations[class.index()].iter()).any(|allocation| {
allocation.unit()
&& !allocation.texture_only
&& !allocation.retiring
&& allocation.live == 0
})
}
/// The allocation of `class` whose memory is `memory`.
@@ -1653,9 +1844,11 @@ impl State {
len: u64,
align: u64,
texture: bool,
split_textures: bool,
) -> Option<(Carve, Option<u64>, bool, bool)> {
let texture_only = split_textures && texture;
let (allocation, base) = (self.allocations[class.index()].iter_mut())
.filter(|allocation| allocation.serves(len))
.filter(|allocation| allocation.texture_only == texture_only && allocation.serves(len))
.find_map(|allocation| {
let base = allocation.free.take(len, align)?;
Some((allocation, base))
@@ -1684,7 +1877,9 @@ impl State {
fn aging(&self, class: MemoryClass) -> (Vec<(u64, vk::DeviceMemory)>, u64) {
let idle = (self.allocations[class.index()].iter())
.filter(|allocation| allocation.live == 0 && !allocation.retiring);
let reserve = idle.clone().rfind(|allocation| allocation.unit());
let reserve = idle
.clone()
.rfind(|allocation| allocation.unit() && !allocation.texture_only);
let mut weighed: Vec<(u64, vk::DeviceMemory)> = idle
.filter(|allocation| reserve.is_none_or(|reserve| reserve.memory != allocation.memory))
.map(|allocation| (allocation.idle_since, allocation.memory))
@@ -1895,12 +2090,18 @@ pub(crate) fn run(core: Arc<Core>) {
state = pool.lock();
continue;
}
let wanted = (MemoryClass::ALL.into_iter())
.find(|&class| !state.failed[class.index()] && !state.whole(class));
let wanted = (!state.replaying)
.then(|| {
(MemoryClass::ALL.into_iter())
.find(|&class| !state.failed[class.index()] && !state.whole(class))
})
.flatten();
if let Some(class) = wanted {
state.making_ahead = true;
drop(state);
let made = ahead(&core, class);
state = pool.lock();
state.making_ahead = false;
match made {
// Idle from now: the reserve, which the idle rule does not weigh.
Some(mut allocation) => {
@@ -2181,8 +2382,20 @@ fn make_allocation(
class: MemoryClass,
len: u64,
site: Option<Site>,
) -> Result<Allocation, Error> {
make_allocation_ex(core, class, len, site, None)
}
fn make_allocation_ex(
core: &Core,
class: MemoryClass,
len: u64,
site: Option<Site>,
replay: Option<(u64, u64)>,
) -> Result<Allocation, Error> {
let device = &core.device;
let texture_only = core.capture_replay && matches!(site, Some(Site::TextureBlock));
let capture_replay = core.capture_replay && !texture_only;
let (id, freed_at) = {
let mut state = core.pool.lock();
(
@@ -2190,22 +2403,38 @@ fn make_allocation(
state.freed_at[class.index()],
)
};
let info = vk::BufferCreateInfo::default()
let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default()
.opaque_capture_address(replay.map_or(0, |(b, _)| b));
let mut info = vk::BufferCreateInfo::default()
.size(len)
.usage(floor::BUFFER_USAGE)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
if capture_replay {
info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY);
if replay.is_some_and(|(b, _)| b != 0) {
info = info.push_next(&mut buf_opaque);
}
}
// SAFETY: the device is live, and the create info valid: `len` is at most its
// `maxBufferSize`.
let buffer =
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
// SAFETY: the buffer is the device's.
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
let mut flags =
vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS);
let allocate_info = vk::MemoryAllocateInfo::default()
let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS;
if capture_replay {
mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY;
}
let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags);
let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default()
.opaque_capture_address(replay.map_or(0, |(_, m)| m));
let mut allocate_info = vk::MemoryAllocateInfo::default()
.allocation_size(requirements.size.max(len))
.memory_type_index(core.memory_type(class))
.push_next(&mut flags);
if capture_replay && replay.is_some_and(|(_, m)| m != 0) {
allocate_info = allocate_info.push_next(&mut mem_opaque);
}
let bits = requirements.memory_type_bits;
// SAFETY: the floor chose the memory type for buffers of this usage on this device, and
// `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow.
@@ -2224,6 +2453,8 @@ fn make_allocation(
memory,
buffer,
address: 0,
opaque_buffer_address: 0,
opaque_memory_address: 0,
len,
mapping: None,
device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0,
@@ -2232,6 +2463,7 @@ fn make_allocation(
live: 0,
placed: 0,
texture: false,
texture_only,
idle_since: crate::host_time(),
made: (0, 0),
wait: Wait::Progress(0),
@@ -2260,6 +2492,12 @@ fn make_allocation(
let of = vk::BufferDeviceAddressInfo::default().buffer(buffer);
// SAFETY: the buffer has device-address usage and is bound.
allocation.address = unsafe { device.get_buffer_device_address(&of) };
if capture_replay {
allocation.opaque_buffer_address = unsafe { device.get_buffer_opaque_capture_address(&of) };
let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory);
allocation.opaque_memory_address =
unsafe { device.get_device_memory_opaque_capture_address(&mof) };
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
allocation.address += core.placed_past;
+29
View File
@@ -1,6 +1,8 @@
//! Places: the Private blocks the runtime places textures' images in, taken as the consumer takes
//! blocks. A texture block holds images alone, so no buffer lies beside an optimal image in one
//! block.
//! When the device enables buffer address replay, the pool keeps texture allocations separate
//! and leaves their replay flags clear. Restoring a buffer can still request its captured address.
//!
//! A place is a resource's bytes at a multiple of its alignment. One no longer than the class's
//! block length ([`MemoryClass::block_len`]) is the first that fits in the blocks of that length,
@@ -248,6 +250,33 @@ impl Ranges {
Some(at)
}
/// Takes the exact range `at..at + len` if it is completely free.
pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool {
let Some(stop) = at.checked_add(len) else {
return false;
};
let Some(index) = self
.free
.iter()
.position(|&(start, end)| start <= at && stop <= end)
else {
return false;
};
let (start, end) = self.free[index];
match (start < at, stop < end) {
(false, false) => {
self.free.remove(index);
}
(true, false) => self.free[index] = (start, at),
(false, true) => self.free[index] = (stop, end),
(true, true) => {
self.free[index] = (start, at);
self.free.insert(index + 1, (stop, end));
}
}
true
}
/// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it.
pub(crate) fn give(&mut self, offset: u64, len: u64) {
let end = offset + len;
+62 -9
View File
@@ -20,7 +20,7 @@ pub struct CommandQueue {
/// The queue itself: what its command buffers and the submit thread hold.
pub(crate) struct QueueInner {
max: u32,
recording: Recording,
/// The command buffers made and not yet retired, and the lists retired ones left.
live: Mutex<Live>,
/// Signalled when one retires.
@@ -46,13 +46,34 @@ pub(crate) struct QueueInner {
/// A queue's live command buffers: those made and not yet retired, and the kept-object lists
/// of retired ones, empty, with their capacity, each in the allocation it came in
/// (`crate::kept::Objects`): together at most the queue's maximum, since each list is a live
/// command buffer's or one retired since.
/// (`crate::kept::Objects`). Host batches keep only a submission group's worth of idle lists.
struct Live {
count: u32,
count: usize,
objects: Vec<Objects>,
}
#[derive(Clone, Copy)]
enum Recording {
Metal(u32),
HostBatch,
}
impl Recording {
fn has_room(self, live: usize) -> bool {
match self {
Self::Metal(max) => live < max as usize,
Self::HostBatch => true,
}
}
fn recycle(self, idle: usize) -> bool {
match self {
Self::Metal(_) => true,
Self::HostBatch => idle < crate::submit::GROUP,
}
}
}
impl Device {
/// `newCommandQueueWithMaxCommandBufferCount:`; `newCommandQueue` is this call with 64.
///
@@ -65,10 +86,22 @@ impl Device {
if max_command_buffer_count == 0 {
return Err(Error::Refused(Refusal::NoCommandBuffers));
}
Ok(self.queue_with_recording(Recording::Metal(max_command_buffer_count)))
}
/// A private FIFO for host copies prepared together and published after their dependencies
/// have been recorded. Recording must never wait for another member of that transaction to
/// retire. Committed work follows the ordinary submit thread's ordering and GPU pacing.
/// The host owns the lifetime of the batch and the memory held by its recorded copies.
pub fn new_host_batch_queue(&self) -> CommandQueue {
self.queue_with_recording(Recording::HostBatch)
}
fn queue_with_recording(&self, recording: Recording) -> CommandQueue {
let core = self.core();
Ok(CommandQueue {
CommandQueue {
inner: Arc::new(QueueInner {
max: max_command_buffer_count,
recording,
live: Mutex::new(Live {
count: 0,
objects: Vec::new(),
@@ -82,7 +115,7 @@ impl Device {
core: Arc::downgrade(core),
}),
device: self.clone(),
})
}
}
}
@@ -100,7 +133,7 @@ impl CommandQueue {
if core.closed() {
return Err(Error::Quiesced);
}
if live.count < self.inner.max {
if self.inner.recording.has_room(live.count) {
break;
}
if crate::device::on_handler_thread(core) {
@@ -205,7 +238,9 @@ impl QueueInner {
self.counters.fall(Gauge::CommandBuffers);
let mut live = lock(&self.live);
live.count -= 1;
live.objects.push(kept);
if self.recording.recycle(live.objects.len()) {
live.objects.push(kept);
}
drop(live);
self.room.notify_one();
}
@@ -221,3 +256,21 @@ pub(crate) fn next_run(expected: Option<u64>, nanos: u64) -> u64 {
_ => nanos.min(u64::MAX - 1),
}
}
#[cfg(test)]
mod recording_tests {
use super::Recording;
#[test]
fn host_batches_stage_independently_of_the_metal_recording_window() {
let metal = Recording::Metal(2);
assert!(metal.has_room(1));
for live in [2, 3, 64, 65, 128] {
assert!(!metal.has_room(live));
assert!(Recording::HostBatch.has_room(live));
}
let group = crate::submit::GROUP;
assert!(Recording::HostBatch.recycle(group - 1));
assert!(!Recording::HostBatch.recycle(group));
}
}
+208 -25
View File
@@ -99,9 +99,10 @@ use metal2vulkan::metal::{
BindingAccess, PrimitiveTopologyClass, TessellationControlPointIndexType, TextureUsage,
};
use metal2vulkan::pipeline::{
specialize, BufferKind, CombinedSampler, NumberedSampler, PrecisionNote, PushField, PushLoc,
RenderPipeline, RenderPipelineDescriptor, RenderPipelineKeys, RuntimeFact, SamplerRef,
SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource, VertexStride,
draw_table_variant, specialize, BufferKind, CombinedSampler, NumberedSampler, PrecisionNote,
PushField, PushLoc, RenderPipeline, RenderPipelineDescriptor, RenderPipelineKeys, RuntimeFact,
SamplerRef, SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource,
VertexStride,
};
use metal2vulkan::Budget;
use std::ffi::CString;
@@ -348,6 +349,55 @@ pub(crate) struct Draws {
pub(crate) stencil_bit: Option<u32>,
}
#[derive(Clone, Copy)]
pub(crate) struct TableSlot {
pub(crate) address: usize,
pub(crate) mask: u64,
pub(crate) bounds: Option<usize>,
}
impl Draws {
fn table_slot(&self, slot: u32) -> Option<TableSlot> {
let uses = self.offsets.as_ref()?.uses(VERTEX, slot);
if !self.buffers.contains(&(VERTEX, slot, Access::Read)) {
return None;
}
let (&OffsetUse::Address { at, mask }, bounds) = (match uses {
[address] => (address, None),
[address, OffsetUse::Bounds(bounds)] | [OffsetUse::Bounds(bounds), address] => {
(address, Some(*bounds))
}
_ => return None,
}) else {
return None;
};
(at.is_multiple_of(8) && bounds.is_none_or(|b| b.is_multiple_of(8) && b != at)).then_some(
TableSlot {
address: at,
mask,
bounds,
},
)
}
}
struct DrawTable {
words: Box<[u32]>,
cache: Mutex<TableCache>,
}
#[derive(Default)]
struct TableCache {
rejected: u32,
variant: Option<TableVariant>,
}
struct TableVariant {
slot: u32,
vertex: vk::ShaderModule,
pipelines: Vec<(vk::PrimitiveTopology, Raster, vk::Pipeline)>,
}
impl Draws {
/// Whether a function of the content can read a texture, so that a draw may hand it an
/// attachment of its pass to read other than as one: a texture slot a function reads, at any
@@ -407,6 +457,7 @@ pub(crate) struct RenderCompiled {
named: Option<vk::PrimitiveTopology>,
/// The words twin, where a stage declares `SpecKey::TexelBufferWords`.
words: Option<Box<RenderWords>>,
table: Option<DrawTable>,
/// Whether a draw of points rasterizes them: the vertex function writes `[[point_size]]`, or
/// the descriptor names the point class, under which Metal draws a point of a function that
/// writes no size 1 pixel wide (the module writes `PointSize` 1.0). Under any other class
@@ -1520,6 +1571,17 @@ impl RenderCompiled {
draws(&pipeline, (nonzero_first_instance, window), arrays)?;
let samples = lowered.raster_sample_count;
let mut stages = Vec::new();
let mut table = None;
let can_table = core.draw_indirect_limit() > 0
&& !lowered.support_indirect_command_buffers
&& !draws.patches
&& draws.stencil_bit.is_none()
&& !draws.writes_memory
&& !draws.reads_unbound
&& !draws.writes_unbound
&& !draws.unbound_storage
&& draws.fetched.is_empty()
&& (0..BUFFER_SLOTS).any(|slot| draws.table_slot(slot).is_some());
let mut notes: Vec<_> = constexpr_notes(translator.profile(), &constexprs).collect();
// Where a stage declares `SpecKey::TexelBufferWords`, whether one reaches a texture buffer
// through a handle: the content's words twin is made beside it.
@@ -1531,7 +1593,15 @@ impl RenderCompiled {
}
}
match stage_module(core, stage, samples, false) {
Ok(module) => stages.push(module),
Ok((module, words)) => {
if can_table && module.stage == vk::ShaderStageFlags::VERTEX {
table = Some(DrawTable {
words: words.into_boxed_slice(),
cache: Mutex::default(),
});
}
stages.push(module);
}
Err(error) => {
release(core, &stages);
return Err(error);
@@ -1546,7 +1616,7 @@ impl RenderCompiled {
let mut twin = Vec::new();
for stage in &pipeline.stages {
match stage_module(core, stage, samples, true) {
Ok(module) => twin.push(module),
Ok((module, _)) => twin.push(module),
Err(error) => {
release(core, &stages);
release(core, &twin);
@@ -1589,6 +1659,7 @@ impl RenderCompiled {
},
cells: Cells::default(),
named,
table: if words.is_none() { table } else { None },
words,
rasterizes_points: pipeline.graphics.writes_point_size
|| lowered.input_primitive_topology == PrimitiveTopologyClass::Point,
@@ -1673,6 +1744,95 @@ impl RenderCompiled {
self.fixed.discard
}
pub(crate) fn table_slot(&self, slot: u32) -> Option<TableSlot> {
self.table.as_ref()?;
self.draws.table_slot(slot)
}
pub(crate) fn table_pipeline(
&self,
slot: u32,
fields: TableSlot,
topology: vk::PrimitiveTopology,
raster: Raster,
) -> Result<Option<vk::Pipeline>, Error> {
let Some(table) = &self.table else {
return Ok(None);
};
if raster.positions && self.interpolates_at_sample {
return Ok(None);
}
let (class, raster) = self.pipeline_key(topology, raster);
let mut cache = lock(&table.cache);
if let Some(variant) = &mut cache.variant {
if variant.slot != slot {
return Ok(None);
}
if let Some(&(.., pipeline)) = variant
.pipelines
.iter()
.find(|&&(c, r, _)| (c, r) == (class, raster))
{
return Ok(Some(pipeline));
}
let pipeline = self.make(&self.stages, class, raster, Some(variant.vertex))?;
variant.pipelines.push((class, raster, pipeline));
return Ok(Some(pipeline));
}
let bit = 1 << slot;
if cache.rejected & bit != 0 {
return Ok(None);
}
let Some(words) = draw_table_variant(
&table.words,
self.stages[VERTEX]
.entry
.to_str()
.expect("translator entry is UTF-8"),
fields.address as u32,
fields.bounds.map(|at| at as u32),
) else {
cache.rejected |= bit;
return Ok(None);
};
let info = vk::ShaderModuleCreateInfo::default().code(&words);
// SAFETY: the variant preserves the module's interface and uses enabled features.
let vertex =
unsafe { self.core.device.create_shader_module(&info, None) }.map_err(|result| {
Error::Vulkan {
call: "vkCreateShaderModule",
result,
}
})?;
let pipeline = match self.make(&self.stages, class, raster, Some(vertex)) {
Ok(pipeline) => pipeline,
Err(error) => {
// SAFETY: the module has not been published or used by another thread.
unsafe { self.core.device.destroy_shader_module(vertex, None) };
return Err(error);
}
};
cache.variant = Some(TableVariant {
slot,
vertex,
pipelines: vec![(class, raster, pipeline)],
});
Ok(Some(pipeline))
}
fn pipeline_key(
&self,
topology: vk::PrimitiveTopology,
mut raster: Raster,
) -> (vk::PrimitiveTopology, Raster) {
let class = self.class(topology);
raster.lines &= matches!(
class,
vk::PrimitiveTopology::TRIANGLE_LIST | vk::PrimitiveTopology::PATCH_LIST
);
(class, raster)
}
/// The `VkPipeline` of the content for draws of `topology`'s class, a point, line or triangle
/// one, or for a post-tessellation vertex function's content the patch one, which the encoder
/// draws alone with it, under `raster`, whose fill mode a line or point class does not take:
@@ -1690,19 +1850,12 @@ impl RenderCompiled {
raster: Raster,
words: bool,
) -> Result<vk::Pipeline, Error> {
use vk::PrimitiveTopology as T;
if raster.positions && self.interpolates_at_sample {
return Err(Error::Unsupported(Gap::Draw {
kind: crate::DrawKind::SamplePositions,
}));
}
let class = self.class(topology);
let polygons = matches!(class, T::TRIANGLE_LIST | T::PATCH_LIST);
let raster = Raster {
clamp: raster.clamp,
lines: raster.lines && polygons,
positions: raster.positions,
};
let (class, raster) = self.pipeline_key(topology, raster);
let plain = self.found(&self.cells, (class, raster), || {
self.make_twinned(class, raster)
})?;
@@ -1784,7 +1937,7 @@ impl RenderCompiled {
class: vk::PrimitiveTopology,
raster: Raster,
) -> Result<vk::Pipeline, Error> {
let plain = self.make(&self.stages, class, raster)?;
let plain = self.make(&self.stages, class, raster, None)?;
let Some(twin) = &self.words else {
return Ok(plain);
};
@@ -1883,7 +2036,7 @@ impl RenderCompiled {
raster: Raster,
) -> Result<vk::Pipeline, Error> {
let began = host_time();
let made = self.make(&twin.stages, class, raster)?;
let made = self.make(&twin.stages, class, raster, None)?;
self.core
.counters
.word_pipeline(host_time().saturating_sub(began));
@@ -1900,13 +2053,17 @@ impl RenderCompiled {
stages: &[Module],
topology: vk::PrimitiveTopology,
raster: Raster,
vertex: Option<vk::ShaderModule>,
) -> Result<vk::Pipeline, Error> {
let core = &self.core;
let fixed = &self.fixed;
// A stage at the subgroup size the translator pins, as a kernel's is: one it pins none for
// runs at the device's own size.
let mut subgroups = subgroup_sizes(stages);
let stages = stage_infos(stages, &mut subgroups);
let mut stages = stage_infos(stages, &mut subgroups);
if let Some(vertex) = vertex {
stages[VERTEX].module = vertex;
}
let mut divided = vk::PipelineVertexInputDivisorStateCreateInfoKHR::default()
.vertex_binding_divisors(&fixed.divisors);
let mut vertex_input = vk::PipelineVertexInputStateCreateInfo::default()
@@ -2026,7 +2183,15 @@ impl RenderCompiled {
// SAFETY: the modules, the layout and the cache are the device's; each module holds
// its constants fixed; the formats are the attachments' the translator maps for the
// device, for the features device creation enabled.
unsafe { core.device.create_graphics_pipelines(cache, &[info], None) }
unsafe {
core.device
.create_graphics_pipelines(cache, &[info], None)
.inspect_err(|(pipelines, _)| {
for &pipeline in pipelines.iter().filter(|&&p| p != vk::Pipeline::null()) {
core.device.destroy_pipeline(pipeline, None);
}
})
}
})
}
}
@@ -2043,7 +2208,7 @@ fn stage_module(
stage: &metal2vulkan::pipeline::StageModule,
samples: u32,
words: bool,
) -> Result<Module, Error> {
) -> Result<(Module, Vec<u32>), Error> {
let mut values = Vec::new();
for constant in &stage.specialization.constants {
let value: u32 = match (constant.key, constant.size) {
@@ -2072,13 +2237,16 @@ fn stage_module(
// translator's are, for the features device creation enabled.
let module = unsafe { core.device.create_shader_module(&info, None) }
.map_err(Error::vulkan("vkCreateShaderModule"))?;
Ok(Module {
module,
entry,
stage: kind,
flags,
subgroup_size: stage.required_subgroup_size,
})
Ok((
Module {
module,
entry,
stage: kind,
flags,
subgroup_size: stage.required_subgroup_size,
},
words,
))
}
/// Gives `stages`' modules to the reaper: a creation that failed after making them.
@@ -2372,6 +2540,21 @@ impl Drop for RenderCompiled {
for pipeline in self.cells.made() {
(self.core.reaper).give(Job::Free(Free::Pipeline(pipeline)));
}
if let Some(variant) = self.table.as_mut().and_then(|table| {
table
.cache
.get_mut()
.unwrap_or_else(|e| e.into_inner())
.variant
.take()
}) {
for (.., pipeline) in variant.pipelines {
self.core.reaper.give(Job::Free(Free::Pipeline(pipeline)));
}
self.core
.reaper
.give(Job::Free(Free::ShaderModule(variant.vertex)));
}
release(&self.core, &self.stages);
if let Some(twin) = &mut self.words {
for pipeline in twin.cells.made() {
@@ -95,7 +95,7 @@ use crate::counters::Metric;
use crate::depth_stencil::{BitDraws, DepthStencilState, Face, Tests, EVERY_FRAGMENT};
use crate::device::Core;
use crate::encoder::{
check_alignment, check_usage, merge, Declared, Resource, ResourceUsage, BUFFER_SLOTS,
bounds, check_alignment, check_usage, merge, Declared, Resource, ResourceUsage, BUFFER_SLOTS,
SAMPLER_SLOTS, TEXTURE_SLOTS,
};
use crate::error::{DrawKind, Error, Gap, IndirectCommandsKind, Limit, Refusal, RenderPassKind};
@@ -146,6 +146,67 @@ pub struct Viewport {
pub zfar: f64,
}
/// One vertex buffer offset followed by one non-indexed draw in a batch.
#[derive(Clone, Copy, Debug)]
pub struct VertexOffsetDraw {
/// Offset of the buffer binding, in bytes.
pub offset: u64,
/// The first vertex.
pub vertex_start: u32,
/// The number of vertices.
pub vertex_count: u32,
/// The number of instances.
pub instance_count: u32,
/// The first instance.
pub base_instance: u32,
}
/// How recording a batch stopped after consuming a prefix of its items.
#[derive(Debug)]
pub enum BatchStop {
/// The bind at `index` failed.
Bind {
/// The item whose bind was attempted.
index: usize,
/// The original binding error.
error: Error,
},
/// The draw at `index` failed after its bind succeeded.
Draw {
/// The item whose draw was attempted.
index: usize,
/// The original draw error.
error: Error,
},
/// Device loss after recording the completed prefix.
Device {
/// Items whose bind and draw completed.
completed: usize,
/// The Vulkan device-loss error.
error: Error,
},
}
#[expect(
clippy::result_large_err,
reason = "the batch preserves the original Error by value"
)]
fn batch_tail<T>(result: Result<T, Error>) -> Result<Option<T>, BatchStop> {
match result {
Ok(value) => Ok(Some(value)),
Err(
error @ Error::Vulkan {
result: vk::Result::ERROR_DEVICE_LOST,
..
},
) => Err(BatchStop::Device {
completed: 1,
error,
}),
Err(_) => Ok(None),
}
}
/// `MTLScissorRect`: a rectangle of pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ScissorRect {
@@ -884,6 +945,8 @@ pub struct RenderCommandEncoder {
declared: Declarations,
/// The push bytes of the last draw.
push: Vec<u8>,
/// Scratch for an indirect batch's ring payload, then its table push.
batch_bytes: Vec<u8>,
/// The parameter blocks of the last draw's functions, where their fields spill.
blocks: [Vec<u8>; 2],
/// The push bytes are those of the bound pipeline state and resources, and of the images the
@@ -975,6 +1038,7 @@ impl CommandBuffer {
facts: Facts::default(),
declared: Declarations::default(),
push: Vec::new(),
batch_bytes: Vec::new(),
blocks: [Vec::new(), Vec::new()],
push_filled: false,
dirty_offsets: [0; 2],
@@ -2534,6 +2598,264 @@ impl RenderCommandEncoder {
self.draw(primitives(primitive_type), call, instances)
}
/// Records a prefix of buffer binds and non-indexed draws of the same primitive type.
/// A fixed-offset prefix reuses the ordinary draw state; changing offsets use the draw
/// table. The caller can process the remaining items with ordinary bind and draw calls.
/// A successful return of zero leaves the encoder unchanged.
#[expect(
clippy::result_large_err,
reason = "the batch preserves the original Error by value"
)]
pub fn draw_primitives_batch(
&mut self,
primitive: PrimitiveType,
slot: u32,
buffer: &Buffer,
draws: &[VertexOffsetDraw],
) -> Result<usize, BatchStop> {
const MIN_TAIL: usize = 8;
const ROW: usize = 16;
let cap = (self.core.draw_indirect_limit() as usize).min(CHUNK as usize / (2 * ROW));
if cap < MIN_TAIL || draws.len() < MIN_TAIL || slot >= BUFFER_SLOTS {
return Ok(0);
}
let Some(state) = &self.pipeline else {
return Ok(0);
};
let Some(fields) = state.inner.compiled.table_slot(slot) else {
return Ok(0);
};
if !self.table_draw_environment() || buffer.held().1.is_some() {
return Ok(0);
}
let fixed_count = draws[1..]
.iter()
.take(cap)
.take_while(|draw| draw.offset == draws[0].offset)
.count();
let fixed_offset = fixed_count >= MIN_TAIL;
let (topology, restart) = primitives(primitive);
let lines = matches!(
topology,
vk::PrimitiveTopology::LINE_LIST | vk::PrimitiveTopology::LINE_STRIP
);
// A fixed binding starts with an ordinary draw so the pipeline, descriptors and push
// constants are current even after a preceding draw-table batch.
let skip_head = !fixed_offset
&& self.pass_drew
&& self.table_draw_facts_ready()
&& matches!(
&self.tables[VERTEX].buffers[slot as usize],
Bound::Buffer { buffer: held, .. } if held.address() == buffer.address()
)
&& (!self.tests.stencil || self.pass.stencil.is_some())
&& (!lines || self.line_width == 1.0);
let head_done = usize::from(!skip_head);
if !skip_head {
if draws.len() == MIN_TAIL {
return Ok(0);
}
let head = draws[0];
self.set_vertex_buffer(Some(buffer), head.offset, slot)
.map_err(|error| BatchStop::Bind { index: 0, error })?;
self.draw_primitives(
primitive,
head.vertex_start,
head.vertex_count,
head.instance_count,
head.base_instance,
)
.map_err(|error| BatchStop::Draw { index: 0, error })?;
if head.vertex_count == 0
|| head.instance_count == 0
|| !self.table_draw_facts_ready()
|| !self.table_draw_environment()
{
return Ok(head_done);
}
}
let state = self
.pipeline
.as_ref()
.expect("the batch draws with this pipeline");
let compiled = &state.inner.compiled;
let first_instance = !compiled.draws.first_instance_zero
&& (fixed_offset || self.core.draw_indirect_first_instance);
let length = buffer.length();
let tail = &draws[head_done..];
let count = tail
.iter()
.take(if fixed_offset { fixed_count } else { cap })
.take_while(|draw| {
(fixed_offset
|| check_alignment(
slot,
fields.mask,
BufferObject::object(buffer),
draw.offset,
)
.is_ok())
&& draw.vertex_count != 0
&& draw.instance_count != 0
&& (draw.base_instance == 0 || first_instance)
&& draw.offset < length
})
.count();
if count < MIN_TAIL {
return Ok(head_done);
}
if fixed_offset {
// SAFETY: the ordinary head established rendering, the pipeline, and the
// unchanged buffer binding. These draw arguments were validated above, and the
// table and environment guards exclude draws that need per-draw synchronization.
let device = &self.core.device;
for draw in &tail[..count] {
unsafe {
device.cmd_draw(
self.command,
draw.vertex_count,
draw.instance_count,
draw.vertex_start,
draw.base_instance,
);
}
}
if self.facts.levels {
self.building()
.count_by(Metric::LevelFieldCommands, count as u64);
}
return Ok(head_done + count);
}
let tail_error = |mut stop| {
if let BatchStop::Device { completed, .. } = &mut stop {
*completed = head_done;
}
stop
};
let Some(Some(pipeline)) =
batch_tail(compiled.table_pipeline(slot, fields, topology, self.raster))
.map_err(tail_error)?
else {
return Ok(head_done);
};
let discards = compiled.discards();
let hidden = topology == vk::PrimitiveTopology::POINT_LIST && !compiled.rasterizes_points();
let table_len = ROW * count;
let bytes = &mut self.batch_bytes;
let upload_len = 2 * table_len;
bytes.resize(bytes.len().max(upload_len).max(self.push.len()), 0);
let (table, commands) = bytes[..upload_len].split_at_mut(table_len);
let address = buffer.gpu_address();
for ((row, command), draw) in table
.as_chunks_mut::<ROW>()
.0
.iter_mut()
.zip(commands.as_chunks_mut::<ROW>().0)
.zip(&tail[..count])
{
let word = address_word(address.wrapping_add(draw.offset));
row[..8].copy_from_slice(&word.to_le_bytes());
row[8..].copy_from_slice(&bounds(length, draw.offset));
command[..4].copy_from_slice(&draw.vertex_count.to_le_bytes());
command[4..8].copy_from_slice(&draw.instance_count.to_le_bytes());
command[8..12].copy_from_slice(&draw.vertex_start.to_le_bytes());
command[12..].copy_from_slice(&draw.base_instance.to_le_bytes());
}
let building = self.building.as_mut().expect("the encoder is open");
let Some(placed) =
batch_tail(building.write_ring_placed(&bytes[..upload_len])).map_err(tail_error)?
else {
return Ok(head_done);
};
bytes[..self.push.len()].copy_from_slice(&self.push);
bytes[fields.address..fields.address + 8].copy_from_slice(&placed.address.to_le_bytes());
let (bind, _) = building.bind_graphics(pipeline);
let command = self.command;
// SAFETY: a draw established rendering, descriptors and vertex bindings. The same
// state owns the variant, and the command buffer holds the ring data until retirement.
unsafe {
if bind {
self.core.device.cmd_bind_pipeline(
command,
vk::PipelineBindPoint::GRAPHICS,
pipeline,
);
if discards {
self.core
.device
.cmd_set_rasterizer_discard_enable(command, true);
}
}
self.record_state(topology, restart, hidden);
let building = self.building.as_mut().expect("the encoder is open");
building.push_draw(&self.core, command, &self.batch_bytes[..self.push.len()]);
self.core.device.cmd_draw_indirect(
command,
placed.buffer,
placed.offset + table_len as u64,
count as u32,
ROW as u32,
);
}
let building = self.building.as_mut().expect("the encoder is open");
building.count(Metric::MultiDrawCalls);
building.count_by(Metric::MultiDrawItems, count as u64);
if self.facts.levels {
building.count_by(Metric::LevelFieldCommands, count as u64);
}
// Keep the ordinary CPU push current. Building still holds the table push and variant.
let Bound::Buffer { offset, .. } = &mut self.tables[VERTEX].buffers[slot as usize] else {
unreachable!("the batch's buffer is bound");
};
*offset = tail[count - 1].offset;
let table = &self.tables[VERTEX];
write_buffer_address(&mut self.push, fields.address, table, slot, 0);
if let Some(at) = fields.bounds {
self.push[at..at + 4].copy_from_slice(&table.bounds(slot)[..4]);
}
(self.drew, self.pass_drew) = (true, true);
Ok(head_done + count)
}
fn table_draw_facts_ready(&self) -> bool {
self.facts.held
&& self.push_filled
&& self.dirty_offsets == [0; 2]
&& !self.facts.attachments
&& !self.facts.managed
&& !self.facts.host
}
fn table_draw_environment(&self) -> bool {
let building = self.building.as_ref().expect("the encoder is open");
let ordinary = |texture: &Texture| {
!texture.has_managed_backing()
&& !TextureObject::object(texture)
.placement()
.is_some_and(|placement| placement.linked())
};
self.declared.each.is_empty()
&& self.visibility.is_none()
&& !self.results.counting()
&& self.moved.is_empty()
&& self.shadowed.is_empty()
&& self.shadow_slots.is_empty()
&& !self.owed
&& !building.aliased()
&& !building.copies_over()
&& self.pass.targets().all(|target| ordinary(&target.texture))
&& (!self.pass.resolving
|| self
.pass
.resolves()
.all(|resolve| ordinary(&resolve.texture)))
}
/// `drawPrimitives:indirectBuffer:indirectBufferOffset:`: one `vkCmdDrawIndirect` on the
/// buffer at `indirect_buffer_offset`, whose `MTLDrawPrimitivesIndirectArguments` (vertex
/// count, instance count, vertex start, base instance) the GPU reads as Vulkan's own
@@ -4319,6 +4641,10 @@ impl RenderCommandEncoder {
#[path = "tests/render_offsets.rs"]
mod offset_tests;
#[cfg(all(test, m2v_gpu))]
#[path = "tests/multi_draw.rs"]
mod multi_draw_tests;
impl Drop for RenderCommandEncoder {
fn drop(&mut self) {
self.end();
@@ -112,6 +112,32 @@ fn the_semaphore_counts_signals_not_values() {
});
}
#[test]
fn a_restored_value_does_not_advance_the_semaphore() {
each_device("event_restored_value", |name, _, device| {
let event = device.new_event().expect("an event");
let saved = 1 << 40;
event
.restore_signaled_value(saved)
.expect("restore the event");
assert_eq!(event.signaled_value(), saved);
assert_eq!(on_semaphore(&device, &event), 0);
let queue = queue(&device);
let commands = queue.command_buffer().expect("a command buffer");
commands
.encode_wait_for_event(&event, saved)
.expect("wait for the restored value");
commands
.encode_signal_event(&event, saved + 1)
.expect("signal after restore");
submitted(name, &device, &commands);
finished(name, &commands);
assert_eq!(event.signaled_value(), saved + 1);
assert_eq!(on_semaphore(&device, &event), 1);
});
}
/// A lower signal moves neither the event's value nor its semaphore. Metal keeps the highest value
/// signalled: the conformance case `event-highest-signal`, recorded on an Apple M3 Max under macOS
/// 27.0.1, reads 7 after 7 then 4 and after 4 then 7. After a 7, a 4 on another queue is left out,
@@ -92,7 +92,9 @@ fn creation_features() -> BTreeSet<VkFeature> {
/// which creation enables, the translator names, and the description does not state.
#[test]
fn every_feature_creation_enables_reaches_the_translator() {
let unstated = unstated("feature");
let mut unstated = unstated("feature");
// Multi-draw is enabled for the runtime's indirect command, outside the translator profile.
unstated.insert("multiDrawIndirect".into());
let mut met = BTreeSet::new();
let mut device = at_the_floor();
for feature in ENABLED.iter().copied().flatten() {
+37 -2
View File
@@ -1984,7 +1984,7 @@ fn a_set_layout_the_device_does_not_support_is_named() {
#[test]
fn the_optional_features_decide_the_capabilities() {
type Set = fn(&mut Features);
let cases: [(Set, &str); 8] = [
let cases: [(Set, &str); 9] = [
(|f| f.vulkan12.shader_float16 = vk::TRUE, "float16"),
(
|f| f.core.shader_storage_image_read_without_format = vk::TRUE,
@@ -2014,6 +2014,10 @@ fn the_optional_features_decide_the_capabilities() {
|f| f.maintenance8.maintenance8 = vk::TRUE,
"texel_offset_operand",
),
(
|f| f.core.multi_draw_indirect = vk::TRUE,
"multi_draw_indirect",
),
];
assert_eq!(
cases.len(),
@@ -2039,6 +2043,10 @@ fn the_optional_features_decide_the_capabilities() {
capabilities.subgroup_uniform_control_flow,
),
("texel_offset_operand", capabilities.texel_offset_operand),
(
"multi_draw_indirect",
capabilities.features.core.multi_draw_indirect == vk::TRUE,
),
];
for (name, value) in answers {
assert_eq!(
@@ -2058,6 +2066,26 @@ fn the_optional_features_decide_the_capabilities() {
}
}
#[test]
fn multi_draw_indirect_is_optional_at_small_limits() {
assert!(!crate::DeviceOptions::default().multi_draw_indirect);
for limit in [1, 4, 32] {
for supported in [vk::FALSE, vk::TRUE] {
let mut device = at_the_floor();
device.limits.max_draw_indirect_count = limit;
device.features.core.multi_draw_indirect = supported;
let capabilities = decide(&device).unwrap_or_else(|below| panic!("{below}"));
assert_eq!(capabilities.max_draw_indirect_count, limit);
assert_eq!(capabilities.features.core.multi_draw_indirect, supported);
assert_eq!(capabilities.draw_indirect_limit(false), 0);
assert_eq!(
capabilities.draw_indirect_limit(true),
if supported == vk::TRUE { limit } else { 0 }
);
}
}
}
/// A table row's cells, each trimmed and stripped of code quotes.
fn cells(line: &str) -> Vec<String> {
line.trim()
@@ -2203,11 +2231,18 @@ fn the_readme_states_the_floor() {
.into_iter()
.map(|row| (row[1].clone(), row[0].clone()))
.collect();
let code: BTreeSet<(String, String)> = features
let mut code: BTreeSet<(String, String)> = features
.iter()
.map(|feature| (feature.structure.to_string(), vulkan_name(feature.member)))
.collect();
assert_eq!(code.len(), features.len(), "a feature listed twice");
if header[0] == "Optional feature" {
// Device creation enables this bit before any draw path uses it.
assert!(code.remove(&(
"VkPhysicalDeviceFeatures".into(),
"multiDrawIndirect".into(),
)));
}
assert_eq!(stated, code, "the README's {}s", header[0].to_lowercase());
}
@@ -0,0 +1,81 @@
target datalayout = "e-p:64:64:64-i64:64-i128:128-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
define internal <{ <4 x float>, <4 x float> }> @quad(i32 %vid, i32 %iid, <4 x float> %p) alwaysinline {
%col = and i32 %vid, 1
%row.bit = lshr i32 %vid, 1
%row = and i32 %row.bit, 1
%lane = and i32 %iid, 1
%cx = uitofp i32 %col to float
%cy = uitofp i32 %row to float
%iy = uitofp i32 %lane to float
%dx = fmul float %cx, 0.75
%dy = fmul float %cy, 0.75
%instance = fmul float %iy, 0.25
%ox = extractelement <4 x float> %p, i32 0
%oy = extractelement <4 x float> %p, i32 1
%x = fadd float %ox, %dx
%y0 = fadd float %oy, %dy
%y = fadd float %y0, %instance
%pos.x = insertelement <4 x float> <float 0.0, float 0.0, float 0.0, float 1.0>, float %x, i32 0
%pos = insertelement <4 x float> %pos.x, float %y, i32 1
%color = shufflevector <4 x float> %p, <4 x float> <float 0.0, float 0.25, float 0.0, float 0.0>, <4 x i32> <i32 2, i32 3, i32 4, i32 5>
%out.pos = insertvalue <{ <4 x float>, <4 x float> }> poison, <4 x float> %pos, 0
%out = insertvalue <{ <4 x float>, <4 x float> }> %out.pos, <4 x float> %color, 1
ret <{ <4 x float>, <4 x float> }> %out
}
define <{ <4 x float>, <4 x float> }> @constant_quad(i32 %vid, i32 %iid, ptr addrspace(2) readonly align 16 dereferenceable(16) %data, i32 %base.vertex, i32 %base.instance) {
%params = load <4 x float>, ptr addrspace(2) %data, align 16
%base = add i32 %base.vertex, %base.instance
%lane = and i32 %base, 3
%value = uitofp i32 %lane to float
%tint = fmul float %value, 0.03125
%green = extractelement <4 x float> %params, i32 3
%marked = fadd float %green, %tint
%p = insertelement <4 x float> %params, float %marked, i32 3
%out = call <{ <4 x float>, <4 x float> }> @quad(i32 %vid, i32 %iid, <4 x float> %p)
ret <{ <4 x float>, <4 x float> }> %out
}
define <{ <4 x float>, <4 x float> }> @bounded_quad(i32 %vid, i32 %iid, ptr addrspace(1) readonly %data) {
%lane = and i32 %iid, 3
%index = sub i32 %lane, 1
%signed = sext i32 %index to i64
%at = getelementptr i8, ptr addrspace(1) %data, i64 %signed
%byte = load i8, ptr addrspace(1) %at, align 1
%value = uitofp i8 %byte to float
%red = fmul float %value, 0.00390625
%p = insertelement <4 x float> <float -0.75, float -0.75, float 0.0, float 0.25>, float %red, i32 2
%out = call <{ <4 x float>, <4 x float> }> @quad(i32 %vid, i32 %iid, <4 x float> %p)
ret <{ <4 x float>, <4 x float> }> %out
}
define <4 x float> @quad_color(<4 x float> %color) {
ret <4 x float> %color
}
!air.version = !{!0}
!air.language_version = !{!1}
!air.vertex = !{!2, !3}
!air.fragment = !{!13}
!0 = !{i32 2, i32 8, i32 0}
!1 = !{!"Metal", i32 4, i32 0, i32 0}
!2 = !{ptr @constant_quad, !4, !7}
!3 = !{ptr @bounded_quad, !4, !8}
!4 = !{!5, !6}
!5 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!6 = !{!"air.vertex_output", !"generated(5colorDv4_f)", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"}
!7 = !{!9, !10, !11, !18, !19}
!8 = !{!9, !10, !12}
!9 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"}
!10 = !{i32 1, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"}
!11 = !{i32 2, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"data"}
!12 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 1, !"air.arg_type_align_size", i32 1, !"air.arg_type_name", !"uchar", !"air.arg_name", !"data"}
!13 = !{ptr @quad_color, !14, !16}
!14 = !{!15}
!15 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}
!16 = !{!17}
!17 = !{i32 0, !"air.fragment_input", !"generated(5colorDv4_f)", !"air.flat", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"}
!18 = !{i32 3, !"air.base_vertex", !"air.arg_type_name", !"uint", !"air.arg_name", !"base_vertex"}
!19 = !{i32 4, !"air.base_instance", !"air.arg_type_name", !"uint", !"air.arg_name", !"base_instance"}
@@ -0,0 +1,561 @@
use super::*;
use crate::tests::command::on_device::{each_device_with, finished, within};
use crate::tests::draw::on_device::{floats, pass, read, run, state, target, Buffers};
use crate::{Device, DeviceOptions};
use metal2vulkan::library::Library;
use metal2vulkan::metal::{BlendFactor, PixelFormat, TextureUsage};
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource,
};
use metal2vulkan_devtools::llvm_assemble_text;
const PRIMITIVE: PrimitiveType = PrimitiveType::TriangleStrip;
const FORMAT: PixelFormat = PixelFormat::RGBA8Unorm;
fn pipelines(name: &str, device: &Device) -> [RenderPipelineState; 2] {
let air = llvm_assemble_text(include_str!("multi_draw.ll")).expect("assemble batch shaders");
let library = Library::from_air(&air).unwrap();
let stage =
|entry| StageSource::Function(FunctionDescriptor::new(library.function(entry).unwrap()));
["constant_quad", "bounded_quad"].map(|entry| {
let mut desc = RenderPipelineDescriptor::new(stage(entry));
desc.fragment = Some(stage("quad_color"));
let mut color = ColorAttachmentDescriptor::new(FORMAT);
color.blending_enabled = true;
color.source_rgb_blend_factor = BlendFactor::SourceAlpha;
color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha;
desc.color_attachments[0] = Some(color);
state(name, device, &desc)
})
}
fn quad(offset: u64, base_instance: u32) -> VertexOffsetDraw {
VertexOffsetDraw {
offset,
vertex_start: 0,
vertex_count: 4,
instance_count: 1,
base_instance,
}
}
fn draw(encoder: &mut RenderCommandEncoder, item: VertexOffsetDraw) {
encoder
.draw_primitives(
PRIMITIVE,
item.vertex_start,
item.vertex_count,
item.instance_count,
item.base_instance,
)
.unwrap();
}
fn direct(encoder: &mut RenderCommandEncoder, buffer: &Buffer, items: &[VertexOffsetDraw]) {
for &item in items {
encoder
.set_vertex_buffer(Some(buffer), item.offset, 0)
.unwrap();
draw(encoder, item);
}
}
fn batch(
encoder: &mut RenderCommandEncoder,
buffer: &Buffer,
items: &[VertexOffsetDraw],
consumed: usize,
) {
assert_eq!(
encoder
.draw_primitives_batch(PRIMITIVE, 0, buffer, items)
.unwrap(),
consumed
);
if consumed > 1 {
let slot = encoder
.pipeline
.as_ref()
.unwrap()
.inner
.compiled
.table_slot(0)
.unwrap();
let push = encoder
.building()
.last_draw_push
.as_ref()
.expect("the table push");
assert!(push.start >= slot.address && push.end <= slot.address + 8);
assert_ne!(
encoder.push,
encoder.batch_bytes[..encoder.push.len()],
"the CPU holds the direct push"
);
}
}
fn options() -> DeviceOptions {
DeviceOptions {
multi_draw_indirect: true,
..DeviceOptions::default()
}
}
#[test]
fn multi_draw_order_bounds_and_state_match_each_pixel() {
each_device_with("multi_draw_pixels", options, |name, _, device| {
let [constant, bounded] = pipelines(name, &device);
let limit = device.draw_indirect_limit();
if limit < 8 {
assert_eq!(constant.inner.compiled.table_slot(0).is_some(), limit > 0);
let mut buffers = Buffers::new(&device);
let data = buffers.of(&device, &floats(&[-0.75, -0.75, 0.125, 0.25]));
let color = target(&device, FORMAT, TextureUsage::RENDER_TARGET);
let queue = device.new_command_queue(1).unwrap();
let command = queue.command_buffer().unwrap();
let mut encoder = command.render_command_encoder(&pass(&color, None)).unwrap();
encoder.set_render_pipeline_state(&constant).unwrap();
let items = [quad(0, 1); 10];
let before = device.counters().metrics();
batch(&mut encoder, &data, &items, 0);
encoder.end_encoding();
run(name, &command);
assert_eq!(
device.counters().metrics().multi_draw_calls,
before.multi_draw_calls
);
return;
}
assert!(constant
.inner
.compiled
.table_slot(0)
.unwrap()
.bounds
.is_none());
assert!(bounded
.inner
.compiled
.table_slot(0)
.unwrap()
.bounds
.is_some());
let mut buffers = Buffers::new(&device);
let params = buffers.of(
&device,
&floats(
&(0..24)
.flat_map(|i| {
[
-1.0 + (i % 4) as f32 * 0.375,
-1.0 + (i % 3) as f32 * 0.5,
(i + 1) as f32 / 32.0,
(24 - i) as f32 / 32.0,
]
})
.collect::<Vec<_>>(),
),
);
let bytes = buffers.of(&device, &[64, 0, 32, 96, 128, 0, 0, 192]);
let items: [_; 12] = std::array::from_fn(|i| VertexOffsetDraw {
vertex_start: (i % 2) as u32,
vertex_count: 4 - (i % 2) as u32,
instance_count: 1 + (i % 3) as u32,
..quad((i * 16) as u64, i as u32)
});
let edge = [quad(1, 0), quad(7, 1), quad(7, 2), quad(0, 0)];
let dynamic: [_; 12] = std::array::from_fn(|i| edge[i % edge.len()]);
let queue = device.new_command_queue(4).unwrap();
let render = |mdi| {
let color = target(&device, FORMAT, TextureUsage::RENDER_TARGET);
let command = queue.command_buffer().unwrap();
let mut encoder = command.render_command_encoder(&pass(&color, None)).unwrap();
let series =
|encoder: &mut RenderCommandEncoder, buffer, items: &[VertexOffsetDraw]| {
if mdi {
batch(encoder, buffer, items, items.len());
} else {
direct(encoder, buffer, items);
}
};
encoder.set_render_pipeline_state(&constant).unwrap();
series(&mut encoder, &params, &items);
draw(&mut encoder, quad(0, 1));
encoder.set_vertex_buffer_offset(16 * 12, 0).unwrap();
draw(&mut encoder, quad(0, 0));
encoder.set_render_pipeline_state(&bounded).unwrap();
series(&mut encoder, &bytes, &dynamic);
draw(&mut encoder, quad(0, 1));
encoder.set_render_pipeline_state(&constant).unwrap();
series(&mut encoder, &params, &items[1..]);
encoder.end_encoding();
run(name, &command);
read(&color, 4)
};
let plain = render(false);
let before = device.counters().metrics();
assert_eq!(
render(true),
plain,
"{name}: alpha blending, draw IDs and state restoration"
);
let after = device.counters().metrics();
let calls = after.multi_draw_calls - before.multi_draw_calls;
let draws = after.multi_draw_items - before.multi_draw_items;
assert_eq!(
(calls, draws, after.ring_writes - before.ring_writes),
(3, 32, 3)
);
assert_eq!(
(after.pushes + after.pushes_held) - (before.pushes + before.pushes_held),
9,
"three heads, three table pushes and three ordinary draws"
);
assert!(
plain
.as_chunks::<4>()
.0
.iter()
.filter(|p| p[0] != 0)
.count()
> 12
);
println!("{name}: 64/64 identical pixels, {calls} MDI calls, {draws} merged draws, one table upload and push per MDI");
for (label, item, max_red) in [
("negative in-range index", edge[0], 16),
("last byte", edge[1], 48),
("past the last byte", edge[2], 0),
("negative out-of-range index", edge[3], 0),
] {
let render_edge = |mdi| {
let color = target(&device, FORMAT, TextureUsage::RENDER_TARGET);
let command = queue.command_buffer().unwrap();
let mut encoder = command.render_command_encoder(&pass(&color, None)).unwrap();
encoder.set_render_pipeline_state(&bounded).unwrap();
let mut draws = [quad(6, 1); 9];
draws[8] = item;
if mdi {
batch(&mut encoder, &bytes, &draws, 9);
} else {
direct(&mut encoder, &bytes, &draws);
}
encoder.end_encoding();
run(name, &command);
read(&color, 4)
};
let expected = render_edge(false);
assert_eq!(render_edge(true), expected, "{name}: {label}");
assert_eq!(
expected.as_chunks::<4>().0.iter().map(|p| p[0]).max(),
Some(max_red),
"{label}"
);
println!("{name}: {label}, 64/64 identical pixels, max red {max_red}");
}
let color = target(&device, FORMAT, TextureUsage::RENDER_TARGET);
let command = queue.command_buffer().unwrap();
let mut encoder = command.render_command_encoder(&pass(&color, None)).unwrap();
encoder.set_render_pipeline_state(&constant).unwrap();
let mut invalid = items;
invalid[9].offset += 1;
batch(&mut encoder, &params, &invalid, 9);
let mut invalid_head = items;
invalid_head[0].offset += 1;
batch(&mut encoder, &params, &invalid_head, 0);
invalid_head[0] = items[0];
invalid_head[0].vertex_count = 0;
batch(&mut encoder, &params, &invalid_head, 0);
batch(&mut encoder, &params, &items[..8], 8);
encoder
.set_vertex_buffer(Some(&params), invalid[9].offset, 0)
.unwrap();
assert!(matches!(
encoder.draw_primitives(PRIMITIVE, 0, 4, 1, 0),
Err(Error::Refused(Refusal::BufferOffsetAlignment { .. }))
));
invalid[0].offset += 1;
assert!(matches!(
encoder.draw_primitives_batch(PRIMITIVE, 0, &params, &invalid),
Err(BatchStop::Draw { index: 0, .. })
));
invalid[0] = items[0];
invalid[4].vertex_count = 0;
batch(&mut encoder, &params, &invalid, 1);
batch(&mut encoder, &params, &items[..7], 0);
encoder.set_render_pipeline_state(&bounded).unwrap();
let mut over = dynamic;
over[10].offset = bytes.length() + 1;
batch(&mut encoder, &bytes, &over, 10);
direct(&mut encoder, &bytes, &over[10..]);
encoder.end_encoding();
run(name, &command);
println!(
"{name}: invalid first offsets and zero vertices returned 0 on a clean binding. Other invalid draws stopped at prefixes 9, 1 and 10"
);
});
}
#[test]
fn fixed_offset_draw_batch_uses_the_ordinary_pipeline() {
each_device_with("fixed_offset_multi_draw", options, |name, _, device| {
let [constant, _] = pipelines(name, &device);
let mut buffers = Buffers::new(&device);
let data = buffers.of(
&device,
&floats(&[-0.75, -0.75, 0.125, 0.25, -0.5, -0.5, 0.25, 0.125]),
);
let items: [_; 13] = std::array::from_fn(|i| VertexOffsetDraw {
vertex_start: (i % 2) as u32,
vertex_count: 4 - (i % 2) as u32,
instance_count: 1 + (i % 3) as u32,
..quad(if i < 12 { 16 } else { 0 }, 0)
});
let limit = device.draw_indirect_limit() as usize;
let expected_tail = if limit >= 8 {
limit.min(items.len() - 2)
} else {
0
};
let queue = device.new_command_queue(1).unwrap();
let render = |mdi| {
let color = target(&device, FORMAT, TextureUsage::RENDER_TARGET);
let command = queue.command_buffer().unwrap();
let mut encoder = command.render_command_encoder(&pass(&color, None)).unwrap();
encoder.set_render_pipeline_state(&constant).unwrap();
let consumed = if mdi {
let consumed = encoder
.draw_primitives_batch(PRIMITIVE, 0, &data, &items)
.unwrap();
assert_eq!(consumed, expected_tail + usize::from(expected_tail > 0));
consumed
} else {
0
};
direct(&mut encoder, &data, &items[consumed..]);
draw(&mut encoder, quad(0, 0));
encoder.set_vertex_buffer_offset(16, 0).unwrap();
draw(&mut encoder, quad(16, 0));
encoder.end_encoding();
run(name, &command);
read(&color, 4)
};
let plain = render(false);
let before = device.counters().metrics();
assert_eq!(
render(true),
plain,
"{name}: pixels and the following ordinary draws"
);
let after = device.counters().metrics();
assert_eq!(
after.pipelines_created, before.pipelines_created,
"{name}: the cached ordinary pipeline"
);
assert_eq!(after.multi_draw_calls, before.multi_draw_calls);
assert_eq!(after.multi_draw_items, before.multi_draw_items);
assert_eq!(after.ring_writes, before.ring_writes);
});
}
#[test]
fn multi_draw_builds_the_variant_from_warm_render_records() {
let cache = std::env::temp_dir().join(format!("m2v-rt-multi-draw-{}", std::process::id()));
std::fs::create_dir(&cache).unwrap();
let mut cold = std::collections::VecDeque::new();
for mdi in [false, true] {
each_device_with(
"multi_draw_cache",
|| DeviceOptions {
multi_draw_indirect: mdi,
pipeline_cache_dir: Some(cache.clone()),
..DeviceOptions::default()
},
|name, _, device| {
let [constant, _] = pipelines(name, &device);
let before = device.counters().metrics();
let limit = device.draw_indirect_limit();
let active = mdi && limit >= 8;
assert_eq!(
constant.inner.compiled.table_slot(0).is_some(),
mdi && limit > 0
);
assert_eq!(before.render_records_read, 2 * u64::from(mdi));
let mut buffers = Buffers::new(&device);
let vertices = [-0.75, -0.75, 0.125, 0.25];
let data = buffers.of(&device, &floats(&[vertices, vertices].concat()));
let color = target(&device, FORMAT, TextureUsage::RENDER_TARGET);
let queue = device.new_command_queue(1).unwrap();
let command = queue.command_buffer().unwrap();
let mut encoder = command.render_command_encoder(&pass(&color, None)).unwrap();
encoder.set_render_pipeline_state(&constant).unwrap();
let items: Vec<_> = (0..2050).map(|i| quad((i % 2) * 16, 1)).collect();
for clip in [DepthClipMode::Clip, DepthClipMode::Clamp] {
encoder.set_depth_clip_mode(clip).unwrap();
let consumed = if active {
let cap = (limit as usize).min(2048);
let consumed = cap + usize::from(clip == DepthClipMode::Clip);
batch(&mut encoder, &data, &items, consumed);
consumed
} else {
batch(&mut encoder, &data, &items, 0);
0
};
direct(&mut encoder, &data, &items[consumed..]);
}
encoder.end_encoding();
run(name, &command);
let pixels = read(&color, 4);
if mdi {
assert_eq!((name.to_owned(), pixels), cold.pop_front().unwrap());
let metrics = device.counters().metrics();
if active {
assert_eq!(metrics.multi_draw_calls, 2);
assert_eq!(
metrics.pipelines_created - before.pipelines_created,
3,
"one plain Clamp pipeline and two variants"
);
println!(
"{name}: warm render record, 64/64 identical pixels, 2 MDI calls, {} merged draws across two raster states",
metrics.multi_draw_items
);
} else {
assert_eq!(metrics.multi_draw_calls, 0);
}
} else {
cold.push_back((name.to_owned(), pixels));
}
},
);
}
std::fs::remove_dir_all(&cache).unwrap();
}
#[test]
fn multi_draw_ring_is_retained_by_two_pending_command_buffers() {
each_device_with("multi_draw_pending", options, |name, _, device| {
let [constant, _] = pipelines(name, &device);
let mut buffers = Buffers::new(&device);
let data = [
[-0.75, -0.75, 0.125, 0.25, 0.0, 0.0, 0.25, 0.125],
[-0.5, -0.5, 0.25, 0.125, 0.25, 0.25, 0.125, 0.25],
]
.map(|params| buffers.of(&device, &floats(&params)));
let colors = std::array::from_fn::<_, 3, _>(|_| {
target(&device, FORMAT, TextureUsage::RENDER_TARGET)
});
let queue = device.new_command_queue(4).unwrap();
let gate = device.new_shared_event().unwrap();
let occupied_chunks = || {
device
.core()
.ring
.chunks()
.map(|(blocks, free)| blocks * crate::ring::SPARE - free)
};
let cap = (device.draw_indirect_limit() as usize).min(2048);
if cap < 32 {
if cap < 8 {
let command = queue.command_buffer().unwrap();
let mut encoder = command
.render_command_encoder(&pass(&colors[0], None))
.unwrap();
encoder.set_render_pipeline_state(&constant).unwrap();
let items = [quad(0, 1); 10];
let before = device.counters().metrics();
batch(&mut encoder, &data[0], &items, 0);
encoder.end_encoding();
run(name, &command);
assert_eq!(
device.counters().metrics().multi_draw_calls,
before.multi_draw_calls
);
}
return;
}
let record = |color: &Texture, mdi: bool| {
let command = queue.command_buffer().unwrap();
if mdi {
command.encode_wait_for_event(gate.as_event(), 1).unwrap();
}
let mut encoder = command.render_command_encoder(&pass(color, None)).unwrap();
encoder.set_render_pipeline_state(&constant).unwrap();
if mdi {
encoder
.set_vertex_bytes(&vec![0; CHUNK as usize], 30)
.unwrap();
}
let items: [_; 32] = std::array::from_fn(|i| quad((i % 2 * 16) as u64, (i % 4) as u32));
for start in (0..10_000).step_by(items.len()) {
let slice = &items[..(10_000 - start).min(items.len())];
let buffer = &data[start / 256 % data.len()];
if mdi {
batch(&mut encoder, buffer, slice, slice.len());
} else {
direct(&mut encoder, buffer, slice);
}
}
encoder.end_encoding();
command
};
let before = device.counters().metrics();
let occupied = occupied_chunks().unwrap();
let pending = std::thread::scope(|scope| {
let first = scope.spawn(|| record(&colors[0], true));
let second = record(&colors[1], true);
[first.join().unwrap(), second]
});
for command in &pending {
command.commit().unwrap();
}
let mut held = 0;
within("both command buffers' allocations", || {
let Some(chunks) = occupied_chunks() else {
return false;
};
held = chunks - occupied;
true
});
gate.set_signaled_value(1);
for command in &pending {
finished(name, command);
assert_eq!(command.error(), None);
}
assert!(
held >= 12,
"{name}: uploads crossed chunks in both pending command buffers"
);
within("retired ring chunks", || {
occupied_chunks() == Some(occupied)
});
let after = device.counters().metrics();
let calls = after.multi_draw_calls - before.multi_draw_calls;
let draws = after.multi_draw_items - before.multi_draw_items;
assert_eq!(
(calls, draws, after.ring_writes - before.ring_writes),
(626, 19_920, 628)
);
let heads =
(after.pushes + after.pushes_held) - (before.pushes + before.pushes_held) - calls;
assert_eq!(
heads, 80,
"one direct head per 256 draws in each command buffer"
);
assert_eq!(
after.pipelines_created - before.pipelines_created,
1,
"one shared variant pipeline"
);
run(name, &record(&colors[2], false));
let expected = read(&colors[2], 4);
for color in &colors[..2] {
assert_eq!(read(color, 4), expected);
}
println!(
"{name}: 128/128 identical pixels across two pending CBs, {held} ring chunks returned, {calls} MDI calls, {draws} merged draws, {heads} direct heads"
);
});
}
@@ -1,6 +1,34 @@
use super::{update_offset, DrawPlace, FieldValue, OffsetLayout, OffsetUse, FRAGMENT, VERTEX};
use crate::hazard::Access;
#[test]
fn batch_tail_only_stops_on_device_loss() {
use super::{batch_tail, BatchStop, Error};
use ash::vk;
assert!(matches!(batch_tail(Ok(7)), Ok(Some(7))));
assert!(matches!(
batch_tail::<()>(Err(Error::Vulkan {
call: "vkCreateGraphicsPipelines",
result: vk::Result::ERROR_OUT_OF_DEVICE_MEMORY,
})),
Ok(None)
));
assert!(matches!(
batch_tail::<()>(Err(Error::Vulkan {
call: "vkAllocateMemory",
result: vk::Result::ERROR_DEVICE_LOST,
})),
Err(BatchStop::Device {
completed: 1,
error: Error::Vulkan {
call: "vkAllocateMemory",
result: vk::Result::ERROR_DEVICE_LOST,
},
})
));
}
#[test]
fn indexes_offset_uses_by_stage_and_slot() {
let layout = OffsetLayout::new(
@@ -5057,6 +5057,14 @@ impl TextureInner {
}
impl Texture {
/// Whether the attachment names Managed bytes or lies over a Managed buffer's device copy.
pub(crate) fn has_managed_backing(&self) -> bool {
self.inner
.named
.as_ref()
.is_some_and(|named| named.form == Form::Managed || named.buffer.held().1.is_some())
}
/// A Managed texture's named bytes ([`Device::new_managed_texture`]), as a handle of the
/// buffer, and their places, one for each level and, within it, each slice. `None` for any
/// other texture.
+1 -1
View File
@@ -157,7 +157,7 @@ pub use crate::lower::dispatch::{
};
// A module's specialization constants made the fixed constants of their values, which a consumer
// hands the driver in place of a `VkSpecializationInfo`.
pub use crate::spirv::specialize::specialize;
pub use crate::spirv::{draw_table::draw_table_variant, specialize::specialize};
// The threadgroup memory of an emulated-simdgroup module's arena (`RuntimeFact::SimdgroupEmulation`),
// which a consumer of the identity domains counts with each dispatch's scratch.
pub use crate::lower::simd::workgroup::arena_bytes;
+474
View File
@@ -0,0 +1,474 @@
//! A separate vertex module for drawing with per-draw buffer parameters.
use std::collections::BTreeMap;
use crate::spirv::serialize::string;
use crate::spv::{
AddressingModel, BuiltIn, Capability, Decoration, ExecutionModel, Op, StorageClass,
};
#[cfg(test)]
mod tests;
const PUSH: u32 = StorageClass::PushConstant as u32;
const INPUT: u32 = StorageClass::Input as u32;
const PHYSICAL: u32 = StorageClass::PhysicalStorageBuffer as u32;
const BUILTIN_DRAW_INDEX: [u32; 2] = [Decoration::BuiltIn as u32, BuiltIn::DrawIndex as u32];
#[derive(Clone, Copy)]
struct Instruction<'a> {
opcode: u32,
operands: &'a [u32],
}
impl Instruction<'_> {
fn is(self, op: Op) -> bool {
self.opcode == op as u32
}
}
fn decode(mut words: &[u32]) -> Option<Vec<Instruction<'_>>> {
let mut instructions = Vec::new();
while let Some(&first) = words.first() {
let (instruction, rest) = words.split_at_checked((first >> 16) as usize)?;
instructions.push(Instruction {
opcode: first & 0xffff,
operands: instruction.get(1..)?,
});
words = rest;
}
Some(instructions)
}
/// Builds a separate variant of a valid, specialized vertex module produced by this translator.
/// At the reflected push byte offset `address_at`, the variant takes a raw buffer device address
/// of a table. Each 16-byte row contains the original address word and, at byte 8, the optional
/// bounds word. The vertex invocation selects its row with `DrawIndex`.
///
/// Returns `None` when the module, layout or uses of the selected fields fall outside the
/// supported direct push-member loads. The input module is left intact.
pub fn draw_table_variant(
words: &[u32],
entry: &str,
address_at: u32,
bounds_at: Option<u32>,
) -> Option<Vec<u32>> {
let &[crate::spv::MAGIC_NUMBER, version, _, bound, _] = words.get(..5)? else {
return None;
};
let instructions = decode(words.get(5..)?)?;
let first_function = instructions.iter().position(|i| i.is(Op::Function))?;
let (globals, functions) = instructions.split_at_checked(first_function)?;
let mut entries = globals.iter().filter(|i| i.is(Op::EntryPoint));
let [model, entry_id, entry_tail @ ..] = entries.next()?.operands else {
return None;
};
let interfaces = entry_tail.strip_prefix(string(entry).as_slice())?;
if *model != ExecutionModel::Vertex as u32
|| entry.contains('\0')
|| entries.next().is_some()
|| !globals.iter().any(|i| {
i.is(Op::MemoryModel)
&& matches!(i.operands, [model, _] if *model == AddressingModel::PhysicalStorageBuffer64 as u32)
})
|| globals.iter().any(|i| {
(i.is(Op::MemberDecorate) && i.operands.ends_with(&BUILTIN_DRAW_INDEX))
|| [Op::SpecConstantTrue, Op::SpecConstantFalse, Op::SpecConstant,
Op::SpecConstantComposite, Op::SpecConstantOperation].iter().any(|&op| i.is(op))
})
{
return None;
}
let mut push_vars = globals.iter().filter_map(|i| match i.operands {
[ty, id, PUSH] if i.is(Op::Variable) => Some((*ty, *id)),
_ => None,
});
let (push_type, push) = push_vars.next()?;
if push_vars.next().is_some() {
return None;
}
let structure = globals.iter().find_map(|i| match i.operands {
[ptr, PUSH, ty] if i.is(Op::TypePointer) && *ptr == push_type => Some(*ty),
_ => None,
})?;
let members = globals.iter().find_map(|i| match i.operands {
[ty, members @ ..] if i.is(Op::TypeStruct) && *ty == structure => Some(members),
_ => None,
})?;
let u32_type = globals.iter().find_map(|i| match i.operands {
[ty, 32, 0] if i.is(Op::TypeInt) => Some(*ty),
_ => None,
})?;
let pair_type = globals.iter().find_map(|i| match i.operands {
[ty, elem, 2] if i.is(Op::TypeVector) && *elem == u32_type => Some(*ty),
_ => None,
})?;
let mut draw_builtins = globals.iter().filter_map(|i| {
let [id, rest @ ..] = i.operands else {
return None;
};
(i.is(Op::Decorate) && rest == BUILTIN_DRAW_INDEX).then_some(*id)
});
let existing_draw = draw_builtins.next();
if draw_builtins.next().is_some()
|| existing_draw.is_some_and(|id| functions.iter().any(|i| uses(*i).contains(&id)))
{
return None;
}
let field = |at: u32| {
let end = at.checked_add(8)?;
if !at.is_multiple_of(8) {
return None;
}
let mut found = None;
for (member, &ty) in members.iter().enumerate() {
let member = member as u32;
let offset = globals.iter().find_map(|i| match i.operands {
[id, index, decoration, offset]
if i.is(Op::MemberDecorate)
&& *id == structure
&& *index == member
&& *decoration == Decoration::Offset as u32 =>
{
Some(*offset)
}
_ => None,
})?;
if offset < end && at < offset.checked_add(type_size(globals, ty)?)? {
if offset != at || ty != pair_type || found.is_some() {
return None;
}
found = Some(member);
}
}
found
};
let address = field(address_at)?;
let bounds = match bounds_at {
Some(at) if at != address_at => Some(field(at)?),
Some(_) => return None,
None => None,
};
let mut pointers = BTreeMap::new();
let mut root = None;
for i in functions {
if !uses(*i).contains(&push) {
continue;
}
let [ptr_type, id, base, index, rest @ ..] = i.operands else {
return None;
};
if !i.is(Op::AccessChain) || *base != push {
return None;
}
let member = constant32(globals, *index)?;
if member == address || Some(member) == bounds {
if !rest.is_empty()
|| !globals
.iter()
.any(|i| i.is(Op::TypePointer) && i.operands == [*ptr_type, PUSH, pair_type])
{
return None;
}
let is_bounds = member != address;
pointers.insert(*id, is_bounds);
if !is_bounds {
root = Some((*ptr_type, *index));
}
}
}
let mut in_entry = false;
let mut replacements = BTreeMap::new();
for (at, i) in functions.iter().enumerate() {
if i.is(Op::Function) {
in_entry = i.operands.get(1) == Some(entry_id);
}
if let [ty, _, ptr] = i.operands {
if let Some(&is_bounds) = pointers.get(ptr).filter(|_| i.is(Op::Load)) {
if !in_entry || *ty != pair_type {
return None;
}
replacements.insert(at, is_bounds);
continue;
}
}
if uses(*i).iter().any(|id| pointers.contains_key(id))
&& !(i.is(Op::AccessChain) && i.operands.get(2) == Some(&push))
{
return None;
}
}
if !replacements.values().any(|&is_bounds| !is_bounds) {
return None;
}
let (push_ptr, address_index) = root?;
let entry_start = functions
.iter()
.position(|i| i.is(Op::Function) && i.operands.get(1) == Some(entry_id))?;
let entry_body = functions.get(entry_start + 1..)?;
let first_label = entry_body
.iter()
.take_while(|i| !i.is(Op::FunctionEnd))
.position(|i| i.is(Op::Label))?;
let after_label = entry_body.get(first_label + 1..)?;
let insert_at = entry_start
+ first_label
+ 2
+ after_label
.iter()
.take_while(|i| i.is(Op::Variable))
.count();
if *replacements.first_key_value()?.0 < insert_at {
return None;
}
let mut next = bound;
let mut id = || {
let result = next;
next += 1;
result
};
// The rewrite reserves at most 24 IDs.
bound.checked_add(24)?;
let mut decls = Vec::new();
let wide = globals
.iter()
.find_map(|i| match i.operands {
[ty, 64, 0] if i.is(Op::TypeInt) => Some(*ty),
_ => None,
})
.unwrap_or_else(|| {
let ty = id();
emit(&mut decls, Op::TypeInt, &[ty, 64, 0]);
ty
});
let mut ptr = |storage, ty| {
globals
.iter()
.find_map(|i| match i.operands {
[ptr, class, pointee]
if i.is(Op::TypePointer) && *class == storage && *pointee == ty =>
{
Some(*ptr)
}
_ => None,
})
.unwrap_or_else(|| {
let ptr = id();
emit(&mut decls, Op::TypePointer, &[ptr, storage, ty]);
ptr
})
};
let row_ptr = ptr(PHYSICAL, pair_type);
let (draw, index_type) = match existing_draw {
Some(draw) => {
let input_ptr = globals.iter().find_map(|i| match i.operands {
[ty, id, INPUT] if i.is(Op::Variable) && *id == draw => Some(*ty),
_ => None,
})?;
let ty = globals.iter().find_map(|i| match i.operands {
[ptr, INPUT, ty] if i.is(Op::TypePointer) && *ptr == input_ptr => Some(*ty),
_ => None,
})?;
if !globals
.iter()
.any(|i| i.is(Op::TypeInt) && matches!(i.operands, [id, 32, _] if *id == ty))
{
return None;
}
(draw, ty)
}
None => {
let index_ptr = ptr(INPUT, u32_type);
let draw = id();
emit(&mut decls, Op::Variable, &[index_ptr, draw, INPUT]);
(draw, u32_type)
}
};
let mut constant = |value| {
globals
.iter()
.find_map(|i| match i.operands {
[ty, constant, lo, 0] if i.is(Op::Constant) && *ty == wide && *lo == value => {
Some(*constant)
}
_ => None,
})
.unwrap_or_else(|| {
let constant = id();
emit(&mut decls, Op::Constant, &[wide, constant, value, 0]);
constant
})
};
let shift = constant(32);
let stride = constant(16);
let bounds_offset = replacements
.values()
.any(|&is_bounds| is_bounds)
.then(|| constant(8));
let mut entry_code = Vec::new();
let mut value = |op, ty, operands: &[u32]| {
let result = id();
let mut args = vec![ty, result];
args.extend_from_slice(operands);
emit(&mut entry_code, op, &args);
result
};
let root_ptr = value(Op::AccessChain, push_ptr, &[push, address_index]);
let root = value(Op::Load, pair_type, &[root_ptr]);
let low = value(Op::CompositeExtract, u32_type, &[root, 0]);
let high = value(Op::CompositeExtract, u32_type, &[root, 1]);
let low = value(Op::UConvert, wide, &[low]);
let high = value(Op::UConvert, wide, &[high]);
let high = value(Op::ShiftLeftLogical, wide, &[high, shift]);
let table = value(Op::BitwiseOr, wide, &[low, high]);
let index = value(Op::Load, index_type, &[draw]);
let index = value(Op::UConvert, wide, &[index]);
let offset = value(Op::IMul, wide, &[index, stride]);
let row = value(Op::IAdd, wide, &[table, offset]);
let address_ptr = value(Op::ConvertUToPtr, row_ptr, &[row]);
let address_word = value(Op::Load, pair_type, &[address_ptr, 0x2, 8]); // Aligned 8
let bounds_word = bounds_offset.map(|offset| {
let address = value(Op::IAdd, wide, &[row, offset]);
let ptr = value(Op::ConvertUToPtr, row_ptr, &[address]);
value(Op::Load, pair_type, &[ptr, 0x2, 8])
});
// Vulkan 1.2 SPIR-V validation caps the header ID bound at 0x3fffff (4,194,303).
if next > 0x003f_ffff {
return None;
}
let mut out = words.get(..5)?.to_vec();
*out.get_mut(3)? = next;
for capability in [Capability::DrawParameters, Capability::Int64] {
if !globals
.iter()
.any(|i| i.is(Op::Capability) && i.operands == [capability as u32])
{
emit(&mut out, Op::Capability, &[capability as u32]);
}
}
let extension = string("SPV_KHR_shader_draw_parameters");
let add_extension = version < 0x0001_0300
&& !globals
.iter()
.any(|i| i.is(Op::Extension) && i.operands == extension);
let annotation_at = globals
.iter()
.position(|i| i.is(Op::Decorate) || i.is(Op::MemberDecorate))?;
let after_caps = globals.iter().take_while(|i| i.is(Op::Capability)).count();
for (at, i) in globals.iter().enumerate() {
if at == after_caps && add_extension {
emit(&mut out, Op::Extension, &extension);
}
if at == annotation_at && existing_draw.is_none() {
emit(
&mut out,
Op::Decorate,
&[draw, Decoration::BuiltIn as u32, BuiltIn::DrawIndex as u32],
);
}
if i.is(Op::EntryPoint) && !interfaces.contains(&draw) {
let mut operands = i.operands.to_vec();
operands.push(draw);
u16::try_from(operands.len() + 1).ok()?;
emit(&mut out, Op::EntryPoint, &operands);
} else {
copy(&mut out, *i);
}
}
out.extend(decls);
for (at, i) in functions.iter().enumerate() {
if at == insert_at {
out.extend_from_slice(&entry_code);
}
if let Some(&is_bounds) = replacements.get(&at) {
let [ty, result, _] = i.operands else {
return None;
};
let from = if is_bounds {
bounds_word?
} else {
address_word
};
emit(&mut out, Op::CopyObject, &[*ty, *result, from]);
} else {
copy(&mut out, *i);
}
}
Some(out)
}
/// For the translator's push layout, scalar/vector byte sizes and the span of fixed arrays.
fn type_size(globals: &[Instruction<'_>], ty: u32) -> Option<u32> {
globals.iter().find_map(|i| match i.operands {
[id, width, _] if i.is(Op::TypeInt) && *id == ty => Some(*width / 8),
[id, elem, count] if i.is(Op::TypeVector) && *id == ty => {
let width = globals.iter().find_map(|i| match i.operands {
[id, width, _] if i.is(Op::TypeInt) && id == elem => Some(*width),
_ => None,
})?;
(width / 8).checked_mul(*count)
}
[id, _, count] if i.is(Op::TypeArray) && *id == ty => {
let stride = globals.iter().find_map(|i| match i.operands {
[id, decoration, stride]
if i.is(Op::Decorate)
&& *id == ty
&& *decoration == Decoration::ArrayStride as u32 =>
{
Some(*stride)
}
_ => None,
})?;
stride.checked_mul(constant32(globals, *count)?)
}
_ => None,
})
}
fn constant32(globals: &[Instruction<'_>], id: u32) -> Option<u32> {
let (ty, value) = globals.iter().find_map(|i| match i.operands {
[ty, result, value] if i.is(Op::Constant) && *result == id => Some((*ty, *value)),
_ => None,
})?;
globals
.iter()
.any(|i| i.is(Op::TypeInt) && matches!(i.operands, [result, 32, _] if *result == ty))
.then_some(value)
}
/// Ignore literal tails of common instructions. For any other instruction, an operand word
/// equal to a tracked pointer is conservatively considered a use.
fn uses<'a>(i: Instruction<'a>) -> &'a [u32] {
match i.operands {
[ids @ .., _] if i.is(Op::SelectionMerge) => ids,
ids if i.is(Op::CompositeExtract) || i.is(Op::BranchConditional) => {
ids.get(..3).unwrap_or(ids)
}
ids if i.is(Op::CompositeInsert) || i.is(Op::VectorShuffle) => ids.get(..4).unwrap_or(ids),
ids if i.is(Op::LoopMerge) => ids.get(..2).unwrap_or(ids),
[_, _, _, ids @ ..] if i.is(Op::Function) => ids,
operands => operands,
}
}
fn emit(words: &mut Vec<u32>, op: Op, operands: &[u32]) {
copy(
words,
Instruction {
opcode: op as u32,
operands,
},
);
}
fn copy(words: &mut Vec<u32>, i: Instruction<'_>) {
words.push(((i.operands.len() as u32 + 1) << 16) | i.opcode);
words.extend_from_slice(i.operands);
}
@@ -0,0 +1,64 @@
; AIR from the Reims render_small benchmark shader (llvm-dis of render_small.metallib).
source_filename = "render_small"
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_v29-apple-macosx27.2.0"
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
define <{ <4 x float> }> @render_small(i32 noundef %0, ptr addrspace(2) noundef readonly align 16 captures(none) dereferenceable(16) "air-buffer-no-alias" %1) local_unnamed_addr #0 {
%3 = shl i32 %0, 1
%4 = and i32 %3, 2
%5 = tail call fast float @air.convert.f.f32.u.i32(i32 %4) #2
%6 = insertelement <2 x float> undef, float %5, i64 0
%7 = and i32 %0, 2
%8 = tail call fast float @air.convert.f.f32.u.i32(i32 %7) #2
%9 = insertelement <2 x float> %6, float %8, i64 1
%10 = fmul fast <2 x float> %9, splat (float 5.000000e-01)
%11 = load <4 x float>, ptr addrspace(2) %1, align 16, !alias.scope !21
%12 = shufflevector <4 x float> %11, <4 x float> poison, <2 x i32> <i32 0, i32 1>
%13 = shufflevector <4 x float> %11, <4 x float> poison, <2 x i32> <i32 2, i32 3>
%14 = fmul fast <2 x float> %10, %13
%15 = fadd fast <2 x float> %14, %12
%16 = shufflevector <2 x float> %15, <2 x float> poison, <4 x i32> <i32 0, i32 1, i32 poison, i32 poison>
%17 = shufflevector <4 x float> %16, <4 x float> <float poison, float poison, float 0.000000e+00, float 1.000000e+00>, <4 x i32> <i32 0, i32 1, i32 6, i32 7>
%18 = insertvalue <{ <4 x float> }> undef, <4 x float> %17, 0
ret <{ <4 x float> }> %18
}
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1
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 nosync nounwind willreturn memory(none) }
attributes #2 = { nounwind willreturn memory(none) }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8}
!llvm.ident = !{!9}
!air.version = !{!10}
!air.language_version = !{!11}
!air.compile_options = !{!12, !13, !14}
!air.vertex = !{!15}
!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 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"}
!10 = !{i32 2, i32 9, i32 0}
!11 = !{!"Metal", i32 4, i32 1, i32 0}
!12 = !{!"air.compile.denorms_disable"}
!13 = !{!"air.compile.fast_math_enable"}
!14 = !{!"air.compile.framebuffer_fetch_enable"}
!15 = !{ptr @render_small, !16, !18}
!16 = !{!17}
!17 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"pos"}
!18 = !{!19, !20}
!19 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"}
!20 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"d"}
!21 = !{!22}
!22 = distinct !{!22, !23, !"air-alias-scope-arg(1)"}
!23 = distinct !{!23, !"air-alias-scopes(render_small)"}
@@ -0,0 +1,426 @@
use super::*;
use crate::device::DevicePolicy;
use crate::pipeline::lower_inputs::LoweringInputs;
use crate::pipeline::testing::{
compile, compile_with, engine_dir, link_standalone, llvm_assemble, llvm_assemble_text, profile,
};
use crate::pipeline::{PushField, PushLoc, SlotClass, Stage};
use crate::spirv::specialize::specialize;
use metal2vulkan_devtools::spirv::{spirv_dis, spirv_val};
use metal2vulkan_devtools::AssembleError;
const ENTRY: &str = "main";
fn assembled(result: Result<Vec<u8>, AssembleError>) -> Option<Vec<u8>> {
match result {
Ok(bitcode) => Some(bitcode),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(error) => panic!("{error:?}"),
}
}
fn translated(bitcode: &[u8], name: &str) -> (Vec<u32>, u32, Option<u32>, u32) {
let profile = profile("runtime-floor", DevicePolicy::default()).unwrap();
let artifact = compile(bitcode, name, &profile).unwrap();
let mut address = None;
let mut bounds = None;
for field in &artifact.interface.push.fields {
let PushLoc::Push { offset } = field.loc else {
continue;
};
match field.field {
PushField::SlotGuestBase(slot)
if slot.index == 0 && slot.class == SlotClass::Buffer =>
{
assert_eq!(slot.stage, Stage::Vertex);
address = Some(offset);
}
PushField::SlotBounds(slot) if slot.index == 0 && slot.class == SlotClass::Buffer => {
assert_eq!(slot.stage, Stage::Vertex);
bounds = Some(offset);
}
_ => {}
}
}
let (_, words) = link_standalone(&artifact, &profile).unwrap();
if bounds.is_some() {
assert!(
crate::lower::push::tail(&artifact.interface.push).is_some(),
"{name}"
);
}
let next_stage = crate::lower::push::fragment_base(&artifact.interface.push, false);
(
specialize(&words, &[]).unwrap(),
address.unwrap(),
bounds,
next_stage,
)
}
fn render_small() -> Option<(Vec<u32>, u32, Option<u32>)> {
let bitcode = assembled(llvm_assemble_text(include_str!("render_small.ll")))?;
let (words, address, bounds, _) = translated(&bitcode, "render_small");
Some((words, address, bounds))
}
fn validate(label: &str, words: &[u32]) {
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
crate::spirv_binary::parse_bytes(&bytes).unwrap();
spirv_val(words, "vulkan1.2", &[])
.unwrap_or_else(|error| panic!("{label}: {error}\n{}", spirv_dis(words)));
println!("{label}: spirv-val --target-env vulkan1.2 passed");
}
fn check_variant(words: &[u32], variant: &[u32], bounds: bool) {
let instructions = decode(&variant[5..]).unwrap();
let draw = instructions
.iter()
.find_map(|i| match i.operands {
[id, builtin, draw_index]
if i.is(Op::Decorate)
&& *builtin == Decoration::BuiltIn as u32
&& *draw_index == BuiltIn::DrawIndex as u32 =>
{
Some(*id)
}
_ => None,
})
.unwrap();
let entry = instructions.iter().find(|i| i.is(Op::EntryPoint)).unwrap();
let original = decode(&words[5..]).unwrap();
let original_entry = original.iter().find(|i| i.is(Op::EntryPoint)).unwrap();
assert_eq!(
entry.operands.strip_suffix(&[draw]),
Some(original_entry.operands)
);
assert!(instructions
.iter()
.any(|i| i.is(Op::Variable) && matches!(i.operands, [_, id, INPUT] if *id == draw)));
assert!(variant[3] > words[3]);
assert_eq!(
instructions
.iter()
.filter(|i| i.is(Op::Capability) && i.operands == [Capability::DrawParameters as u32])
.count(),
1
);
assert!(!instructions
.iter()
.any(|i| i.is(Op::Extension) && i.operands == string("SPV_KHR_shader_draw_parameters")));
let new_loads: Vec<_> = instructions
.iter()
.filter(|i| i.is(Op::Load) && i.operands[1] >= words[3])
.collect();
let aligned: Vec<_> = new_loads
.iter()
.filter(|i| matches!(i.operands, [_, _, _, 2, 8]))
.collect();
assert_eq!(new_loads.len(), 3 + usize::from(bounds));
assert_eq!(aligned.len(), 1 + usize::from(bounds));
let replaced: Vec<_> = instructions
.iter()
.filter(|i| i.is(Op::CopyObject) && i.operands[1] < words[3] && i.operands[2] >= words[3])
.collect();
assert_eq!(replaced.len(), aligned.len());
for (copy, load) in replaced.iter().zip(&aligned) {
assert_eq!(copy.operands[2], load.operands[1]);
assert!(original
.iter()
.any(|i| i.is(Op::Load) && i.operands[..2] == copy.operands[..2]));
}
let arithmetic = |i: &&Instruction<'_>| i.is(Op::Select) || i.is(Op::CompositeExtract);
assert_eq!(
original
.iter()
.filter(arithmetic)
.map(|i| i.operands)
.collect::<Vec<_>>(),
instructions
.iter()
.filter(arithmetic)
.filter(|i| i.operands[1] < words[3])
.map(|i| i.operands)
.collect::<Vec<_>>()
);
}
#[test]
fn render_small_uses_the_address_row_without_reading_bounds() {
let Some((words, address, bounds)) = render_small() else {
return;
};
assert_eq!(bounds, None);
let original = words.clone();
let variant = draw_table_variant(&words, ENTRY, address, bounds).unwrap();
assert_eq!(words, original);
check_variant(&words, &variant, false);
validate("render_small original", &words);
validate("render_small draw table (one Aligned 8 load)", &variant);
}
#[test]
fn dynamic_vertex_reads_both_table_fields_and_preserves_its_tail_fold() {
let Some(bitcode) = assembled(llvm_assemble(&engine_dir().join("cof_offsets.ll"))) else {
return;
};
let (words, address, bounds, fragment_base) = translated(&bitcode, "cof_device");
let bounds = Some(bounds.expect("dynamic buffer access needs bounds"));
let profile = profile("runtime-floor", DevicePolicy::default()).unwrap();
let mut inputs = LoweringInputs::new();
inputs.push_base = fragment_base;
let fragment = compile_with(&bitcode, "cof_flat", &profile, &inputs).unwrap();
let same_slot = fragment
.interface
.push
.fields
.iter()
.find_map(|field| match (field.field, field.loc) {
(PushField::SlotGuestBase(slot), PushLoc::Push { offset }) if slot.index == 0 => {
assert_eq!(slot.stage, Stage::Fragment);
Some(offset)
}
_ => None,
})
.unwrap();
let (_, fragment) = link_standalone(&fragment, &profile).unwrap();
let fragment = specialize(&fragment, &[]).unwrap();
assert!(draw_table_variant(&fragment, ENTRY, same_slot, None).is_none());
assert!(draw_table_variant(&words, ENTRY, same_slot, bounds).is_none());
let original = words.clone();
let variant = draw_table_variant(&words, ENTRY, address, bounds).unwrap();
assert_eq!(words, original);
check_variant(&words, &variant, true);
validate("cof_device original", &words);
validate("cof_device draw table (two Aligned 8 loads)", &variant);
validate("cof_flat fragment, same buffer slot", &fragment);
assert!(draw_table_variant(&words, ENTRY, address, Some(address)).is_none());
}
#[test]
fn unsupported_entry_and_push_uses_are_rejected() {
let Some((words, address, _)) = render_small() else {
return;
};
let variant = |words: &[u32]| draw_table_variant(words, ENTRY, address, None);
assert!(draw_table_variant(&words, "other", address, None).is_none());
assert!(draw_table_variant(&words, ENTRY, address + 1, None).is_none());
assert!(draw_table_variant(&words, ENTRY, 4096, None).is_none());
let with_draw = variant(&words).unwrap();
assert!(variant(&with_draw).is_none(), "existing DrawIndex read");
let code = decode(&words[5..]).unwrap();
let at = |op| code.iter().position(|i| i.is(op)).unwrap();
let mut unused_draw = with_draw[..5].to_vec();
for i in decode(&with_draw[5..])
.unwrap()
.into_iter()
.take_while(|i| !i.is(Op::Function))
{
copy(&mut unused_draw, i);
}
for &i in &code[at(Op::Function)..] {
copy(&mut unused_draw, i);
}
let reused = variant(&unused_draw).expect("reuse an unread DrawIndex");
assert_eq!(
decode(&reused[5..])
.unwrap()
.iter()
.filter(|i| i.is(Op::Decorate) && i.operands.ends_with(&BUILTIN_DRAW_INDEX))
.count(),
1
);
validate("render_small with an existing, unused DrawIndex", &reused);
let [push_ptr, push, PUSH] = code
.iter()
.find(|i| i.is(Op::Variable) && matches!(i.operands, [_, _, PUSH]))
.unwrap()
.operands
else {
unreachable!()
};
let [_, PUSH, block] = code
.iter()
.find(|i| i.is(Op::TypePointer) && i.operands[0] == *push_ptr)
.unwrap()
.operands
else {
unreachable!()
};
let chain_at = code
.iter()
.position(|i| {
i.is(Op::AccessChain)
&& i.operands[2] == *push
&& code.iter().any(|d| {
d.is(Op::MemberDecorate)
&& d.operands
== [
*block,
constant32(&code, i.operands[3]).unwrap(),
Decoration::Offset as u32,
address,
]
})
})
.unwrap();
let [member_ptr, ptr, _, index] = code[chain_at].operands else {
unreachable!()
};
let field_load = code
.iter()
.find(|i| i.is(Op::Load) && i.operands[2] == *ptr)
.unwrap();
let pair = field_load.operands[0];
let bound = words[3];
let edited = |new_ids, edit: &mut dyn FnMut(usize, Instruction<'_>, &mut Vec<u32>)| {
let mut edited = words[..5].to_vec();
edited[3] += new_ids;
for (index, &i) in code.iter().enumerate() {
edit(index, i, &mut edited);
}
edited
};
let multiple = edited(0, &mut |index, i, out| {
copy(out, i);
if index == at(Op::EntryPoint) {
let mut other = i.operands[..2].to_vec();
other.extend(string("second"));
other.extend_from_slice(&i.operands[2 + string(ENTRY).len()..]);
emit(out, Op::EntryPoint, &other);
}
});
assert!(variant(&multiple).is_none(), "multiple entries");
let after_chain = |op, operands: &[u32]| {
edited(1, &mut |index, i, out| {
copy(out, i);
if index == chain_at {
emit(out, op, operands);
}
})
};
assert!(
variant(&after_chain(Op::Load, &[*block, bound, *push])).is_none(),
"whole-block load"
);
assert!(
variant(&after_chain(Op::CopyObject, &[*member_ptr, bound, *ptr])).is_none(),
"pointer escape"
);
let multiple_loads = after_chain(Op::Load, &[pair, bound, *ptr]);
let transformed = variant(&multiple_loads).expect("multiple loads of the address");
let added = decode(&transformed[5..]).unwrap();
let copy_of_address = added
.iter()
.find(|i| i.is(Op::CopyObject) && i.operands[1] == bound)
.unwrap();
assert!(added.iter().any(|i| i.is(Op::CopyObject)
&& i.operands[1] == field_load.operands[1]
&& i.operands[2] == copy_of_address.operands[2]));
validate("render_small with repeated address loads", &transformed);
let helper = edited(5, &mut |index_in_module, i, out| {
let [void, _, _, fn_type] = code[at(Op::Function)].operands else {
unreachable!()
};
if index_in_module == at(Op::Return) {
emit(out, Op::FunctionCall, &[*void, bound + 4, bound]);
}
copy(out, i);
if index_in_module == code.len() - 1 {
emit(out, Op::Function, &[*void, bound, 0, *fn_type]);
emit(out, Op::Label, &[bound + 1]);
emit(
out,
Op::AccessChain,
&[*member_ptr, bound + 2, *push, *index],
);
emit(out, Op::Load, &[pair, bound + 3, bound + 2]);
emit(out, Op::Return, &[]);
emit(out, Op::FunctionEnd, &[]);
}
});
validate("render_small with a called push-reading helper", &helper);
assert!(variant(&helper).is_none(), "helper read");
}
#[test]
fn spirv_1_2_adds_the_extension_and_inserts_after_locals() {
use crate::spv::MemoryModel;
let mut words = vec![crate::spv::MAGIC_NUMBER, 0x0001_0200, 0, 16, 0];
let code: &[(Op, &[u32])] = &[
(Op::Capability, &[Capability::Shader as u32]),
(
Op::Capability,
&[Capability::PhysicalStorageBufferAddresses as u32],
),
(Op::Extension, &string("SPV_KHR_physical_storage_buffer")),
(
Op::MemoryModel,
&[
AddressingModel::PhysicalStorageBuffer64 as u32,
MemoryModel::GLSL450 as u32,
],
),
(
Op::EntryPoint,
&[
ExecutionModel::Vertex as u32,
1,
u32::from_le_bytes(*b"main"),
0,
],
),
(Op::Decorate, &[5, Decoration::Block as u32]),
(Op::MemberDecorate, &[5, 0, Decoration::Offset as u32, 0]),
(Op::MemberDecorate, &[5, 1, Decoration::Offset as u32, 8]),
(Op::TypeVoid, &[2]),
(Op::TypeInt, &[3, 32, 0]),
(Op::TypeVector, &[4, 3, 2]),
(Op::TypeStruct, &[5, 4, 3]),
(Op::TypePointer, &[6, PUSH, 5]),
(Op::TypePointer, &[7, PUSH, 4]),
(Op::TypePointer, &[8, StorageClass::Function as u32, 3]),
(Op::TypeFunction, &[9, 2]),
(Op::Constant, &[3, 10, 0]),
(Op::Variable, &[6, 11, PUSH]),
(Op::Function, &[2, 1, 0, 9]),
(Op::Label, &[12]),
(Op::Variable, &[8, 13, StorageClass::Function as u32]),
(Op::AccessChain, &[7, 14, 11, 10]),
(Op::Load, &[4, 15, 14]),
(Op::Return, &[]),
(Op::FunctionEnd, &[]),
];
for &(op, operands) in code {
emit(&mut words, op, operands);
}
let variant = draw_table_variant(&words, ENTRY, 0, None).unwrap();
let instructions = decode(&variant[5..]).unwrap();
assert_eq!(variant[1], words[1]);
assert!(instructions
.iter()
.any(|i| i.is(Op::Extension) && i.operands == string("SPV_KHR_shader_draw_parameters")));
let label = instructions.iter().position(|i| i.is(Op::Label)).unwrap();
assert!(instructions[label + 1].is(Op::Variable));
assert!(instructions[label + 2].is(Op::AccessChain));
assert!(instructions[label + 2].operands[1] >= words[3]);
assert!(
draw_table_variant(&words, ENTRY, 8, None).is_none(),
"wrong member type"
);
validate("SPIR-V 1.2 original", &words);
validate(
"SPIR-V 1.2 draw table with DrawParameters extension",
&variant,
);
}
+1
View File
@@ -7,6 +7,7 @@
pub mod builder;
pub mod carry;
pub mod dead;
pub mod draw_table;
pub mod error;
pub mod half_hold;
pub mod hoist;
@@ -838,7 +838,7 @@ impl Writer {
}
/// A literal string: UTF-8, NUL-terminated, padded to a word.
fn string(s: &str) -> Vec<u32> {
pub(super) fn string(s: &str) -> Vec<u32> {
let mut bytes = s.as_bytes().to_vec();
bytes.push(0);
while !bytes.len().is_multiple_of(4) {
@@ -611,6 +611,7 @@ enum metal2vulkan-air::tensor_ops::Mode #[derive(Clone, Copy, Debug, PartialEq,
enum metal2vulkan-air::tensor_ops::OperandForm #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum OperandForm
enum metal2vulkan-air::tensor_ops::OperandIndex #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum OperandIndex
enum metal2vulkan-air::tensor_ops::TensorSpace #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum TensorSpace
enum metal2vulkan-runtime::BatchStop #[derive(Debug)] pub enum BatchStop
enum metal2vulkan-runtime::BlitOption #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum BlitOption
enum metal2vulkan-runtime::CommandBufferError #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum CommandBufferError
enum metal2vulkan-runtime::CommandBufferStatus #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CommandBufferStatus
@@ -1324,6 +1325,7 @@ field metal2vulkan-runtime::DeviceLoss.result pub result: vk::Result
field metal2vulkan-runtime::DeviceOptions.block_mappings pub block_mappings: Option<Arc<dyn BlockMappings>>
field metal2vulkan-runtime::DeviceOptions.extensions pub extensions: Vec<DeviceExtension>
field metal2vulkan-runtime::DeviceOptions.features pub features: Vec<ConsumerFeature>
field metal2vulkan-runtime::DeviceOptions.multi_draw_indirect pub multi_draw_indirect: bool
field metal2vulkan-runtime::DeviceOptions.pipeline_cache_cap pub pipeline_cache_cap: Option<u64>
field metal2vulkan-runtime::DeviceOptions.pipeline_cache_dir pub pipeline_cache_dir: Option<PathBuf>
field metal2vulkan-runtime::DeviceOptions.stage_memory_ceiling pub stage_memory_ceiling: u64
@@ -1550,6 +1552,8 @@ field metal2vulkan-runtime::Metrics.maker_waits pub maker_waits: u64
field metal2vulkan-runtime::Metrics.maker_yield_nanos pub maker_yield_nanos: u64
field metal2vulkan-runtime::Metrics.maker_yields pub maker_yields: u64
field metal2vulkan-runtime::Metrics.managed_bytes_captured pub managed_bytes_captured: u64
field metal2vulkan-runtime::Metrics.multi_draw_calls pub multi_draw_calls: u64
field metal2vulkan-runtime::Metrics.multi_draw_items pub multi_draw_items: u64
field metal2vulkan-runtime::Metrics.other_barriers pub other_barriers: u64
field metal2vulkan-runtime::Metrics.over_copies pub over_copies: u64
field metal2vulkan-runtime::Metrics.over_copies_alignment pub over_copies_alignment: u64
@@ -1914,6 +1918,11 @@ field metal2vulkan-runtime::VariantMake.variant pub variant: DispatchVariant
field metal2vulkan-runtime::VariantMake.waits pub waits: u32
field metal2vulkan-runtime::VertexDescriptor.attributes pub attributes: BTreeMap<u32, VertexAttributeDescriptor>
field metal2vulkan-runtime::VertexDescriptor.layouts pub layouts: BTreeMap<u32, VertexBufferLayoutDescriptor>
field metal2vulkan-runtime::VertexOffsetDraw.base_instance pub base_instance: u32
field metal2vulkan-runtime::VertexOffsetDraw.instance_count pub instance_count: u32
field metal2vulkan-runtime::VertexOffsetDraw.offset pub offset: u64
field metal2vulkan-runtime::VertexOffsetDraw.vertex_count pub vertex_count: u32
field metal2vulkan-runtime::VertexOffsetDraw.vertex_start pub vertex_start: u32
field metal2vulkan-runtime::Viewport.height pub height: f64
field metal2vulkan-runtime::Viewport.origin_x pub origin_x: f64
field metal2vulkan-runtime::Viewport.origin_y pub origin_y: f64
@@ -1930,6 +1939,7 @@ field metal2vulkan-runtime::floor::Capabilities.feedback_loop pub feedback_loop:
field metal2vulkan-runtime::floor::Capabilities.float16 pub float16: bool
field metal2vulkan-runtime::floor::Capabilities.float64 pub float64: bool
field metal2vulkan-runtime::floor::Capabilities.indirect_commands pub indirect_commands: Option<IndirectCommandLimits>
field metal2vulkan-runtime::floor::Capabilities.max_draw_indirect_count pub max_draw_indirect_count: u32
field metal2vulkan-runtime::floor::Capabilities.maximal_reconvergence pub maximal_reconvergence: bool
field metal2vulkan-runtime::floor::Capabilities.memory pub memory: vk::PhysicalDeviceMemoryProperties
field metal2vulkan-runtime::floor::Capabilities.queue_family pub queue_family: u32
@@ -2950,6 +2960,7 @@ fn metal2vulkan::metal::vertex::attribute_fetch pub fn attribute_fetch(format: V
fn metal2vulkan::metal::vertex::vertex_alignment pub fn vertex_alignment(format: VertexFormat) -> Result<u32, Error>
fn metal2vulkan::metal::vertex::vk_vertex_format pub fn vk_vertex_format(format: VertexFormat) -> Result<vk::Format, Error>
fn metal2vulkan::pipeline::arena_bytes pub fn arena_bytes(arena: Option<u32>, regions: u64) -> u64
fn metal2vulkan::pipeline::draw_table_variant pub fn draw_table_variant(words: &[u32], entry: &str, address_at: u32, bounds_at: Option<u32>) -> Option<Vec<u32>>
fn metal2vulkan::pipeline::grid_tile pub fn grid_tile(threads: [u32; 3]) -> [u32; 3]
fn metal2vulkan::pipeline::heap_sampler_capacity pub fn heap_sampler_capacity(p: &DeviceProfile) -> u32
fn metal2vulkan::pipeline::heap_unused_while_pending pub fn heap_unused_while_pending(p: &DeviceProfile) -> bool
@@ -6068,6 +6079,7 @@ method metal2vulkan-runtime::Device::buffer_alignment pub fn buffer_alignment(&s
method metal2vulkan-runtime::Device::counters pub fn counters(&self) -> Counters
method metal2vulkan-runtime::Device::default_sample_positions pub fn default_sample_positions(&self, count: u32) -> Result<Vec<SamplePosition>, Error>
method metal2vulkan-runtime::Device::dma_buf_granule #[cfg(unix)] pub fn dma_buf_granule(&self) -> Option<u64>
method metal2vulkan-runtime::Device::draw_indirect_limit pub fn draw_indirect_limit(&self) -> u32
method metal2vulkan-runtime::Device::extensions pub fn extensions(&self) -> &[CString]
method metal2vulkan-runtime::Device::features pub fn features(&self) -> &[ConsumerFeature]
method metal2vulkan-runtime::Device::fill_stage pub fn fill_stage(&self, request: &StageRequest, mut to_helper: impl Write, mut from_helper: impl Read) -> Result<StageSpans, StageFill>
@@ -6180,6 +6192,7 @@ method metal2vulkan-runtime::RenderCommandEncoder::draw_indexed_primitives_indir
method metal2vulkan-runtime::RenderCommandEncoder::draw_patches pub fn draw_patches(&mut self, number_of_patch_control_points: u32, patch_start: u32, patch_count: u32, patch_index_buffer: Option<(&Buffer, u64)>, instance_count: u32, base_instance: u32) -> Result<(), Error>
method metal2vulkan-runtime::RenderCommandEncoder::draw_patches_indirect pub fn draw_patches_indirect(&mut self, number_of_patch_control_points: u32, patch_index_buffer: Option<(&Buffer, u64)>, indirect_buffer: &Buffer, indirect_buffer_offset: u64) -> Result<(), Error>
method metal2vulkan-runtime::RenderCommandEncoder::draw_primitives pub fn draw_primitives(&mut self, primitive_type: PrimitiveType, vertex_start: u32, vertex_count: u32, instance_count: u32, base_instance: u32) -> Result<(), Error>
method metal2vulkan-runtime::RenderCommandEncoder::draw_primitives_batch pub fn draw_primitives_batch(&mut self, primitive: PrimitiveType, slot: u32, buffer: &Buffer, draws: &[VertexOffsetDraw]) -> Result<usize, BatchStop>
method metal2vulkan-runtime::RenderCommandEncoder::draw_primitives_indirect pub fn draw_primitives_indirect(&mut self, primitive_type: PrimitiveType, indirect_buffer: &Buffer, indirect_buffer_offset: u64) -> Result<(), Error>
method metal2vulkan-runtime::RenderCommandEncoder::end_encoding pub fn end_encoding(mut self)
method metal2vulkan-runtime::RenderCommandEncoder::execute_commands_in_buffer pub fn execute_commands_in_buffer(&mut self, buffer: &IndirectCommandBuffer, range: std::ops::Range<u32>) -> Result<(), Error>
@@ -6987,6 +7000,7 @@ struct metal2vulkan-runtime::TextureSwizzleChannels #[cfg_attr(feature = "serde"
struct metal2vulkan-runtime::Timed #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct Timed
struct metal2vulkan-runtime::VariantMake #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct VariantMake
struct metal2vulkan-runtime::VertexDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VertexDescriptor
struct metal2vulkan-runtime::VertexOffsetDraw #[derive(Clone, Copy, Debug)] pub struct VertexOffsetDraw
struct metal2vulkan-runtime::Viewport #[derive(Clone, Copy, Debug, PartialEq)] pub struct Viewport
struct metal2vulkan-runtime::VisibleFunctionTable #[derive(Clone)] pub struct VisibleFunctionTable
struct metal2vulkan-runtime::VisibleFunctionTableDescriptor #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct VisibleFunctionTableDescriptor
@@ -8416,6 +8430,9 @@ variant metal2vulkan-air::tensor_ops::OperandIndex::Right Right
variant metal2vulkan-air::tensor_ops::TensorSpace::Device Device
variant metal2vulkan-air::tensor_ops::TensorSpace::Thread Thread
variant metal2vulkan-air::tensor_ops::TensorSpace::Threadgroup Threadgroup
variant metal2vulkan-runtime::BatchStop::Bind Bind { index: usize, error: Error }
variant metal2vulkan-runtime::BatchStop::Device Device { completed: usize, error: Error }
variant metal2vulkan-runtime::BatchStop::Draw Draw { index: usize, error: Error }
variant metal2vulkan-runtime::BlitOption::DepthFromDepthStencil DepthFromDepthStencil
variant metal2vulkan-runtime::BlitOption::None None
variant metal2vulkan-runtime::BlitOption::StencilFromDepthStencil StencilFromDepthStencil
Can't render this file because it is too large.
+1
View File
@@ -314,6 +314,7 @@ surface! {
const DEEP_THREADGROUP;
fn threadgroup_constants;
fn specialize;
fn draw_table_variant;
const COMPILED_STAGE_WEIGHT;
fn own_kernel;
struct ExecutionCounts E;