Translator: specialize refuses an instruction it would leave half specialized

pipeline::specialize copied every instruction outside its list as it was. An
OpExecutionModeId (a LocalSizeId mode among them) beside a WorkgroupSize
composite would leave the entry point with two sizes, and an OpDecorationGroup
could carry a SpecId the pass never reads, so that constant would keep its
default. The translator writes neither, so the pass now refuses both with an
Error::Internal that names the instruction. An OpSpecConstantOp of an opcode
outside SpecOp was already refused; its refusal now names the opcode.

Op::ExecutionModeId and Op::DecorationGroup move into every build, and
ExecutionMode::LocalSizeId into test builds. Both come through
scripts/regen-spirv-grammar's items.txt and a regeneration from Khronos's
grammar (vulkan-sdk-1.4.341.0); table.rs comes out unchanged.

Test: a_module_of_an_instruction_the_pass_does_not_specialize_is_refused takes
the deep kernel with an OpExecutionModeId LocalSizeId of its LocalSize
constants, with an OpDecorationGroup, and with an OpSpecConstantOp turned to
ISub. Each must be refused, and the refusal must name the instruction. The
next check job runs it.
This commit is contained in:
Anees Iqbal committed 2026-11-23 20:59:01 -08:00
1 parent fdeac08272
commit 0630c1d9a7
4 files changed
+92 -15

No files matched your search

@@ -217,3 +217,72 @@ fn a_module_without_a_workgroup_composite_keeps_its_mode() {
.count();
assert_eq!(modes, 1);
}
/// `words` with `inst` after the first instruction of `after`, its id bound grown by `ids`.
fn inserted(words: &[u32], after: Op, inst: &[u32], ids: u32) -> Vec<u32> {
let mut at = 5;
while words[at] & 0xFFFF != after as u32 {
at += (words[at] >> 16) as usize;
}
at += (words[at] >> 16) as usize;
let mut out = words.to_vec();
out.splice(at..at, inst.iter().copied());
out[3] += ids;
out
}
/// A module holding an instruction the translator does not write, whose constants the pass would
/// leave half specialized, is refused, the refusal naming it: an `OpExecutionModeId` of
/// `LocalSizeId`, an `OpDecorationGroup`, an `OpSpecConstantOp` of `ISub`.
#[test]
fn a_module_of_an_instruction_the_pass_does_not_specialize_is_refused() {
let (words, ids, _) = linked(deep_kernel());
let entry = (insts(&words).into_iter())
.find(|(op, _)| *op == Op::EntryPoint as u32)
.map(|(_, operands)| operands[1])
.expect("entry point");
let local = |axis| {
(ids.iter())
.find(|&&(key, _)| key == SpecKey::LocalSize(axis))
.map(|&(_, id)| id)
.expect("a LocalSize constant")
};
// The LocalSize constants' result ids, by the SpecId decorations that name them.
let decorated = |spec: u32| {
(insts(&words).into_iter())
.find(|(op, operands)| {
*op == Op::Decorate as u32 && operands[1..] == [Decoration::SpecId as u32, spec]
})
.map(|(_, operands)| operands[0])
.expect("a SpecId decoration")
};
let [x, y, z] = [Axis::X, Axis::Y, Axis::Z].map(|axis| decorated(local(axis)));
let mode_id = [
(6 << 16) | Op::ExecutionModeId as u32,
entry,
ExecutionMode::LocalSizeId as u32,
x,
y,
z,
];
let bound = words[3];
let group = [(2 << 16) | Op::DecorationGroup as u32, bound];
let mut subtract = words.clone();
let mut at = 5;
while subtract[at] & 0xFFFF != Op::SpecConstantOperation as u32 {
at += (subtract[at] >> 16) as usize;
}
subtract[at + 3] = Op::ISub as u32;
for (module, named) in [
(inserted(&words, Op::EntryPoint, &mode_id, 0), "OpExecutionModeId"),
(inserted(&words, Op::Decorate, &group, 1), "OpDecorationGroup"),
(subtract, "OpSpecConstantOp of opcode 130"),
] {
match specialize(&module, &[]) {
Err(crate::error::Error::Internal(error)) => {
assert!(error.detail.contains(named), "{named}: {error}");
}
other => panic!("{named}: {:?}", other.map(|w| w.len())),
}
}
}
+19 -7
View File
@@ -26,10 +26,12 @@ enum Scalar {
}
/// The instructions the pass reads or rewrites; it copies every other as it is.
const READ: [Op; 15] = [
const READ: [Op; 17] = [
Op::Decorate,
Op::DecorationGroup,
Op::EntryPoint,
Op::ExecutionMode,
Op::ExecutionModeId,
Op::TypeBool,
Op::TypeInt,
Op::TypeFloat,
@@ -54,9 +56,11 @@ const READ: [Op; 15] = [
/// literal workgroup size states it. The result is valid where `words` is, under the same
/// requirements, and runs as `words` specialized by `values` does.
///
/// Err: [`Error::Internal`] where the words are not such a module: a malformed instruction, a
/// specialization operation of an opcode the translator does not write, or a `WorkgroupSize`
/// beside a `LocalSize` mode or beside other than one entry point.
/// Err: [`Error::Internal`], naming what it met, where the words are not such a module: a
/// malformed instruction; an instruction the translator does not write, whose constants the pass
/// would leave half specialized (an `OpExecutionModeId`, a `LocalSizeId` mode among them; an
/// `OpDecorationGroup`; an `OpSpecConstantOp` of another opcode); or a `WorkgroupSize` beside a
/// `LocalSize` mode or beside other than one entry point.
pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result<Vec<u32>, Error> {
let header = words
.get(..5)
@@ -99,6 +103,13 @@ pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result<Vec<u32>, Erro
workgroup = Some(operand(1)?);
continue;
}
// A mode of id operands (`LocalSizeId` among them) could name a size the pass would
// set a second time, and a group's decorations a `SpecId` it would miss.
Some(unknown @ (Op::ExecutionModeId | Op::DecorationGroup)) => {
return Err(malformed(format!(
"an Op{unknown:?}, which the translator does not write"
)));
}
Some(Op::EntryPoint) => {
out.extend_from_slice(inst);
entries.push((operand(2)?, out.len()));
@@ -148,8 +159,9 @@ pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result<Vec<u32>, Erro
}
Some(Op::SpecConstantOperation) => {
let (ty, id) = (operand(1)?, operand(2)?);
let op = SpecOp::of_opcode(operand(3)?)
.ok_or_else(|| malformed("a specialization operation of another opcode"))?;
let code = operand(3)?;
let unknown = || malformed(format!("an OpSpecConstantOp of opcode {code}"));
let op = SpecOp::of_opcode(code).ok_or_else(unknown)?;
let operands: Vec<(u64, Scalar)> = (tail(4).iter())
.map(|o| known.get(o).copied())
.collect::<Option<_>>()
@@ -211,7 +223,7 @@ pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result<Vec<u32>, Erro
Ok(out)
}
fn malformed(detail: &str) -> Error {
fn malformed(detail: impl std::fmt::Display) -> Error {
Error::Internal(InternalError::new(
InternalKind::Invariant,
format!("specialize: {detail}"),
+2 -6
View File
@@ -141,7 +141,6 @@ pub enum Op {
InBoundsPtrAccessChain = 70,
Decorate = 71,
MemberDecorate = 72,
#[cfg(test)]
DecorationGroup = 73,
#[cfg(test)]
GroupDecorate = 74,
@@ -474,7 +473,6 @@ pub enum Op {
MemoryNamedBarrier = 329,
#[cfg(test)]
ModuleProcessed = 330,
#[cfg(test)]
ExecutionModeId = 331,
#[cfg(test)]
DecorateId = 332,
@@ -1631,7 +1629,6 @@ impl std::fmt::Debug for Op {
Self::InBoundsPtrAccessChain => "InBoundsPtrAccessChain",
Self::Decorate => "Decorate",
Self::MemberDecorate => "MemberDecorate",
#[cfg(test)]
Self::DecorationGroup => "DecorationGroup",
#[cfg(test)]
Self::GroupDecorate => "GroupDecorate",
@@ -1966,7 +1963,6 @@ impl std::fmt::Debug for Op {
Self::MemoryNamedBarrier => "MemoryNamedBarrier",
#[cfg(test)]
Self::ModuleProcessed => "ModuleProcessed",
#[cfg(test)]
Self::ExecutionModeId => "ExecutionModeId",
#[cfg(test)]
Self::DecorateId => "DecorateId",
@@ -3327,7 +3323,6 @@ impl Op {
70 => Self::InBoundsPtrAccessChain,
71 => Self::Decorate,
72 => Self::MemberDecorate,
#[cfg(test)]
73 => Self::DecorationGroup,
#[cfg(test)]
74 => Self::GroupDecorate,
@@ -3660,7 +3655,6 @@ impl Op {
329 => Self::MemoryNamedBarrier,
#[cfg(test)]
330 => Self::ModuleProcessed,
#[cfg(test)]
331 => Self::ExecutionModeId,
#[cfg(test)]
332 => Self::DecorateId,
@@ -5725,6 +5719,8 @@ pub enum ExecutionMode {
OutputPoints = 27,
#[cfg(test)]
ContractionOff = 31,
#[cfg(test)]
LocalSizeId = 38,
SubgroupUniformControlFlowKHR = 4421,
DenormPreserve = 4459,
SignedZeroInfNanPreserve = 4461,
+2 -2
View File
@@ -64,7 +64,7 @@ values RayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR
values RayQueryGetIntersectionGeometryIndexKHR RayQueryGetIntersectionPrimitiveIndexKHR
values RayQueryGetIntersectionBarycentricsKHR RayQueryGetIntersectionFrontFaceKHR
values RayQueryGetIntersectionObjectToWorldKHR RayQueryGetIntersectionWorldToObjectKHR
values AtomicFAddEXT
values AtomicFAddEXT ExecutionModeId DecorationGroup
test-values *
enum Capability
@@ -89,7 +89,7 @@ values Quads OutputVertices OutputPoints SubgroupUniformControlFlowKHR SignedZer
values StencilRefReplacingEXT RequireFullQuadsKHR OutputLinesEXT OutputPrimitivesEXT
values DerivativeGroupLinearKHR OutputTrianglesEXT PixelInterlockOrderedEXT
values MaximallyReconvergesKHR DenormPreserve RoundingModeRTE
test-values ContractionOff FPFastMathDefault
test-values ContractionOff FPFastMathDefault LocalSizeId
enum StorageClass
values UniformConstant Input Uniform Output Workgroup Private Function PushConstant Image