Extend the decline discipline past the memcpy family, and to the sidecar

Five more handlers outside `memcpy_memset.rs` emit before they know they will decline. They are
less severe than the memcpy cluster — none of them emits a store — but each leaves the caller
holding instructions after reporting that nothing happened:

- `emit_selected_access_tree_phi` builds the access tree for the first incoming edge and bails on a
  later one whose pointer kind does not match, leaving abandoned access chains **and abandoned
  `OpPhi`s** while the caller falls through to `emit_bda_address_phi`;
- `emit_provenance_pointer_icmp` flattens both operands' gep provenance, emitting the index
  arithmetic, then declines when a later index pair will not compare;
- `emit_selected_load_pointer_gep` emits the true arm's access chain and then finds the false arm
  has neither a pointer nor a raw offset — the guard exists precisely because an arm can be absent;
- `emit_pointer_from_local_dynamic_field_load` and
  `emit_first_scalar_aggregate_reinterpret_store` materialize an operand through `value_id_in` and
  then fail a later type check.

All five now run through `staged_emit`.

The last one also had a leak `staged_emit` cannot reach. It pushed a
`LocalPointerDynamicFieldLoad` naming `result` into the emit sidecar *before* three of its four
`Ok(false)` paths — and the handler the caller falls through to is given the same `result`, so a
declined attempt left the sidecar describing an id that a different lowering produced. The record is
still built where its inputs are in scope, but is pushed only on the two paths that define `result`.

Verified: 2880 corpus sources byte-identical against a327e4e, so none of these five declined on a
translating source here — unlike the memcpy leak, which changed three. Fixed for the same reason
that one was: the contract is not checkable by reading, and the next edit does not preserve it.

`cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`,
`cargo test -p metal2vulkan` debug and release, `cargo test -p metal2vulkan-validation`.
This commit is contained in:
Anees Iqbal committed 2026-08-31 21:13:04 +03:00
1 parent a327e4e5ae
commit 6f01edbc44
4 files changed
+361 -328

No files matched your search

+131 -110
View File
@@ -510,125 +510,146 @@ impl Emitter {
ptr: &TypedValue,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let LlType::Ptr(_) = result_ty else {
return Ok(false);
};
let Some((root, prefix, index, suffix)) = self.local_pointer_dynamic_field_index(ptr)?
else {
return self.emit_pointer_from_local_multidynamic_field_load(
result_name,
result,
result_ty,
ptr,
instructions,
);
};
let values = self
.local_pointer_fields
.iter()
.filter_map(|(key, value)| {
let suffix_start = prefix.len() + 1;
(key.root == root
&& key.indices.len() == suffix_start + suffix.len()
&& key.indices.starts_with(&prefix)
&& &key.indices[suffix_start..] == suffix.as_slice())
.then(|| (key.indices[prefix.len()], value.clone()))
})
.collect::<Vec<_>>();
let index_id = self.value_id_in(&index.value, &index.ty, instructions)?;
self.emit_sidecar.local_pointer_dynamic_field_loads.push(
crate::emit_sidecar::LocalPointerDynamicFieldLoad {
staged_emit(instructions, |instructions| {
let LlType::Ptr(_) = result_ty else {
return Ok(false);
};
let Some((root, prefix, index, suffix)) =
self.local_pointer_dynamic_field_index(ptr)?
else {
return self.emit_pointer_from_local_multidynamic_field_load(
result_name,
result,
result_ty,
ptr,
instructions,
);
};
let values = self
.local_pointer_fields
.iter()
.filter_map(|(key, value)| {
let suffix_start = prefix.len() + 1;
(key.root == root
&& key.indices.len() == suffix_start + suffix.len()
&& key.indices.starts_with(&prefix)
&& &key.indices[suffix_start..] == suffix.as_slice())
.then(|| (key.indices[prefix.len()], value.clone()))
})
.collect::<Vec<_>>();
let index_id = self.value_id_in(&index.value, &index.ty, instructions)?;
// Built here, where its inputs are in scope, but recorded only on the paths that
// actually define `result`. It names `result` as a dynamic field load, and the handlers
// this one declines to are given the same `result` — so recording it before the
// remaining checks leaves the sidecar describing an id a different lowering produced.
let dynamic_field_load = crate::emit_sidecar::LocalPointerDynamicFieldLoad {
id: result,
root,
prefix: prefix.clone(),
index: index_id,
suffix: suffix.clone(),
},
);
if values.is_empty() {
let LlType::Ptr(addrspace) = result_ty else {
};
if values.is_empty() {
let LlType::Ptr(addrspace) = result_ty else {
return Ok(false);
};
self.emit_unmodeled_byte_pointer_copy(
result_name,
result,
*addrspace,
instructions,
)?;
self.emit_sidecar
.local_pointer_dynamic_field_loads
.push(dynamic_field_load);
return Ok(true);
}
let mut values = values;
values.sort_by_key(|(idx, _)| *idx);
let value_refs = values
.iter()
.map(|(_, value)| &value.value)
.collect::<Vec<_>>();
let Some(pointer_meta) = self.pointer_merge_meta(&value_refs, result_ty)? else {
return Ok(false);
};
self.emit_unmodeled_byte_pointer_copy(result_name, result, *addrspace, instructions)?;
return Ok(true);
}
let mut values = values;
values.sort_by_key(|(idx, _)| *idx);
let value_refs = values
.iter()
.map(|(_, value)| &value.value)
.collect::<Vec<_>>();
let Some(pointer_meta) = self.pointer_merge_meta(&value_refs, result_ty)? else {
return Ok(false);
};
if !matches!(
pointer_meta.storage,
StorageClass::StorageBuffer | StorageClass::UniformConstant | StorageClass::Workgroup
) {
return Ok(false);
}
let index_ty = self.resolve_type(&index.ty)?;
let LlType::Int(index_bits) = index_ty else {
return Ok(false);
};
let result_type = self.pointer_aware_type_id(result_ty, Some(&pointer_meta))?;
let bool_type = self.type_id(&LlType::Bool)?;
let mut current = self.value_id_in(&values[0].1.value, &values[0].1.ty, instructions)?;
if values.len() == 1 {
instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(current)],
));
} else {
for (entry_idx, (stored_index, stored_value)) in values.iter().enumerate().skip(1) {
let stored_id =
self.value_id_in(&stored_value.value, &stored_value.ty, instructions)?;
let index_const = self.const_int(index_bits, *stored_index as u64)?;
let is_entry = self.fresh();
instructions.push(Self::inst(
Op::IEqual,
Some(bool_type),
Some(is_entry),
vec![Operand::IdRef(index_id), Operand::IdRef(index_const)],
));
let selected = if entry_idx + 1 == values.len() {
result
} else {
self.fresh()
};
instructions.push(Self::inst(
Op::Select,
Some(result_type),
Some(selected),
vec![
Operand::IdRef(is_entry),
Operand::IdRef(stored_id),
Operand::IdRef(current),
],
));
current = selected;
if !matches!(
pointer_meta.storage,
StorageClass::StorageBuffer
| StorageClass::UniformConstant
| StorageClass::Workgroup
) {
return Ok(false);
}
}
self.record_pointer_meta(result_name.to_string(), pointer_meta);
self.dynamic_pointer_tables.insert(
result_name.to_string(),
DynamicPointerTable {
selector: index_id,
selector_bits: index_bits,
entries: values,
},
);
if !self.pointer_phi_values.is_empty() && !self.pointer_nullness.contains_key(result_name) {
let is_null = self.const_bool(false)?;
self.record_pointer_nullness(result_name.to_string(), is_null);
}
Ok(true)
let index_ty = self.resolve_type(&index.ty)?;
let LlType::Int(index_bits) = index_ty else {
return Ok(false);
};
let result_type = self.pointer_aware_type_id(result_ty, Some(&pointer_meta))?;
let bool_type = self.type_id(&LlType::Bool)?;
let mut current =
self.value_id_in(&values[0].1.value, &values[0].1.ty, instructions)?;
if values.len() == 1 {
instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(current)],
));
} else {
for (entry_idx, (stored_index, stored_value)) in values.iter().enumerate().skip(1) {
let stored_id =
self.value_id_in(&stored_value.value, &stored_value.ty, instructions)?;
let index_const = self.const_int(index_bits, *stored_index as u64)?;
let is_entry = self.fresh();
instructions.push(Self::inst(
Op::IEqual,
Some(bool_type),
Some(is_entry),
vec![Operand::IdRef(index_id), Operand::IdRef(index_const)],
));
let selected = if entry_idx + 1 == values.len() {
result
} else {
self.fresh()
};
instructions.push(Self::inst(
Op::Select,
Some(result_type),
Some(selected),
vec![
Operand::IdRef(is_entry),
Operand::IdRef(stored_id),
Operand::IdRef(current),
],
));
current = selected;
}
}
self.record_pointer_meta(result_name.to_string(), pointer_meta);
self.dynamic_pointer_tables.insert(
result_name.to_string(),
DynamicPointerTable {
selector: index_id,
selector_bits: index_bits,
entries: values,
},
);
if !self.pointer_phi_values.is_empty()
&& !self.pointer_nullness.contains_key(result_name)
{
let is_null = self.const_bool(false)?;
self.record_pointer_nullness(result_name.to_string(), is_null);
}
self.emit_sidecar
.local_pointer_dynamic_field_loads
.push(dynamic_field_load);
Ok(true)
})
}
/// Load from a local pointer table addressed by two or more dynamic aggregate indices. Each
+66 -64
View File
@@ -820,73 +820,75 @@ impl Emitter {
pointee: &LlType,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if !matches!(pointee, LlType::Array(_, _) | LlType::Struct(_)) {
return Ok(false);
}
if matches!(object_ty, LlType::Vector(_, _)) {
return Ok(false);
}
let storage = match self.resolve_type(&ptr.ty)? {
LlType::Ptr(addrspace) => self.pointer_storage_for(&ptr.value, addrspace)?,
other => {
return Err(format!(
"native emitter: store pointer is not a pointer: {other:?}"
))
}
};
if !matches!(
storage,
StorageClass::Function | StorageClass::Workgroup | StorageClass::Private
) {
return Ok(false);
}
let Some((scalar_ty, access_path)) = first_scalar_access_path(pointee) else {
return Ok(false);
};
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
let store_value = if types_compatible(object_ty, &scalar_ty) {
object_id
} else {
let Some(object_bits) = bitcast_width(object_ty) else {
return Ok(false);
};
let Some(scalar_bits) = bitcast_width(&scalar_ty) else {
return Ok(false);
};
if object_bits != scalar_bits {
staged_emit(instructions, |instructions| {
if !matches!(pointee, LlType::Array(_, _) | LlType::Struct(_)) {
return Ok(false);
}
let scalar_type = self.type_id(&scalar_ty)?;
let cast = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(scalar_type),
Some(cast),
vec![Operand::IdRef(object_id)],
));
cast
};
if matches!(object_ty, LlType::Vector(_, _)) {
return Ok(false);
}
let storage = match self.resolve_type(&ptr.ty)? {
LlType::Ptr(addrspace) => self.pointer_storage_for(&ptr.value, addrspace)?,
other => {
return Err(format!(
"native emitter: store pointer is not a pointer: {other:?}"
))
}
};
if !matches!(
storage,
StorageClass::Function | StorageClass::Workgroup | StorageClass::Private
) {
return Ok(false);
}
let Some((scalar_ty, access_path)) = first_scalar_access_path(pointee) else {
return Ok(false);
};
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
let store_value = if types_compatible(object_ty, &scalar_ty) {
object_id
} else {
let Some(object_bits) = bitcast_width(object_ty) else {
return Ok(false);
};
let Some(scalar_bits) = bitcast_width(&scalar_ty) else {
return Ok(false);
};
if object_bits != scalar_bits {
return Ok(false);
}
let scalar_type = self.type_id(&scalar_ty)?;
let cast = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(scalar_type),
Some(cast),
vec![Operand::IdRef(object_id)],
));
cast
};
let ptr_id = self.value_id_in(&ptr.value, &ptr.ty, instructions)?;
let scalar_ptr_ty = self.ptr_type_id(storage, &scalar_ty)?;
let scalar_ptr = self.fresh();
let mut ops = vec![Operand::IdRef(ptr_id)];
for idx in access_path {
ops.push(Operand::IdRef(self.const_uint(idx)?));
}
instructions.push(Self::inst(
Op::InBoundsAccessChain,
Some(scalar_ptr_ty),
Some(scalar_ptr),
ops,
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(scalar_ptr), Operand::IdRef(store_value)],
));
Ok(true)
let ptr_id = self.value_id_in(&ptr.value, &ptr.ty, instructions)?;
let scalar_ptr_ty = self.ptr_type_id(storage, &scalar_ty)?;
let scalar_ptr = self.fresh();
let mut ops = vec![Operand::IdRef(ptr_id)];
for idx in access_path {
ops.push(Operand::IdRef(self.const_uint(idx)?));
}
instructions.push(Self::inst(
Op::InBoundsAccessChain,
Some(scalar_ptr_ty),
Some(scalar_ptr),
ops,
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(scalar_ptr), Operand::IdRef(store_value)],
));
Ok(true)
})
}
pub(in crate::native::emitter) fn emit_first_pointer_aggregate_reinterpret_load(
+80 -76
View File
@@ -263,47 +263,49 @@ impl Emitter {
result_ty: &LlType,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let LlType::Ptr(_) = result_ty else {
return Ok(false);
};
let pointee = self
.tir_use_pointees
.get(name)
.cloned()
.or_else(|| self.pointer_pointees.get(name).cloned());
let Some(pointee) = pointee else {
return Ok(false);
};
let mut trees = Vec::with_capacity(incoming.len());
for (value, label) in incoming {
let LlValue::Local(local) = value else {
staged_emit(instructions, |instructions| {
let LlType::Ptr(_) = result_ty else {
return Ok(false);
};
let tree = if let Some(tree) = self.selected_access_trees.get(local).cloned() {
if !types_compatible(&self.resolve_type(&tree.pointee)?, &pointee) {
let pointee = self
.tir_use_pointees
.get(name)
.cloned()
.or_else(|| self.pointer_pointees.get(name).cloned());
let Some(pointee) = pointee else {
return Ok(false);
};
let mut trees = Vec::with_capacity(incoming.len());
for (value, label) in incoming {
let LlValue::Local(local) = value else {
return Ok(false);
}
tree
} else if let Some(selected) = self.selected_pointers.get(local).cloned() {
self.build_selected_access_tree(
&selected,
&pointee,
&[],
&mut HashSet::new(),
instructions,
)?
} else {
};
let tree = if let Some(tree) = self.selected_access_trees.get(local).cloned() {
if !types_compatible(&self.resolve_type(&tree.pointee)?, &pointee) {
return Ok(false);
}
tree
} else if let Some(selected) = self.selected_pointers.get(local).cloned() {
self.build_selected_access_tree(
&selected,
&pointee,
&[],
&mut HashSet::new(),
instructions,
)?
} else {
return Ok(false);
};
trees.push((tree, self.label_id(label)?));
}
let Some(tree) = self.merge_selected_access_tree_phi(&trees, instructions)? else {
return Ok(false);
};
trees.push((tree, self.label_id(label)?));
}
let Some(tree) = self.merge_selected_access_tree_phi(&trees, instructions)? else {
return Ok(false);
};
self.pointer_pointees
.insert(name.to_string(), tree.pointee.clone());
self.selected_access_trees.insert(name.to_string(), tree);
Ok(true)
self.pointer_pointees
.insert(name.to_string(), tree.pointee.clone());
self.selected_access_trees.insert(name.to_string(), tree);
Ok(true)
})
}
fn merge_selected_access_tree_phi(
@@ -863,47 +865,49 @@ impl Emitter {
rhs: &LlValue,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let Some(lhs_provenance) =
self.normalized_pointer_icmp_provenance(lhs, name, instructions)?
else {
return Ok(false);
};
let Some(rhs_provenance) =
self.normalized_pointer_icmp_provenance(rhs, name, instructions)?
else {
return Ok(false);
};
if !compatible_pointer_provenance(&lhs_provenance, &rhs_provenance) {
return Ok(false);
}
let Some(equal) = self.emit_pointer_index_equality(
&lhs_provenance.indices,
&rhs_provenance.indices,
instructions,
)?
else {
return Ok(false);
};
staged_emit(instructions, |instructions| {
let Some(lhs_provenance) =
self.normalized_pointer_icmp_provenance(lhs, name, instructions)?
else {
return Ok(false);
};
let Some(rhs_provenance) =
self.normalized_pointer_icmp_provenance(rhs, name, instructions)?
else {
return Ok(false);
};
if !compatible_pointer_provenance(&lhs_provenance, &rhs_provenance) {
return Ok(false);
}
let Some(equal) = self.emit_pointer_index_equality(
&lhs_provenance.indices,
&rhs_provenance.indices,
instructions,
)?
else {
return Ok(false);
};
let result_ty = LlType::Bool;
let result_type = self.type_id(&result_ty)?;
let result = self.result_id(name, &result_ty)?;
match pred {
Op::IEqual => instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(equal)],
)),
Op::INotEqual => instructions.push(Self::inst(
Op::LogicalNot,
Some(result_type),
Some(result),
vec![Operand::IdRef(equal)],
)),
_ => return Ok(false),
}
Ok(true)
let result_ty = LlType::Bool;
let result_type = self.type_id(&result_ty)?;
let result = self.result_id(name, &result_ty)?;
match pred {
Op::IEqual => instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(equal)],
)),
Op::INotEqual => instructions.push(Self::inst(
Op::LogicalNot,
Some(result_type),
Some(result),
vec![Operand::IdRef(equal)],
)),
_ => return Ok(false),
}
Ok(true)
})
}
pub(in crate::native::emitter) fn normalized_pointer_icmp_provenance(
+84 -78
View File
@@ -395,84 +395,90 @@ impl Emitter {
indices: &[TypedValue],
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if !types_compatible(&self.resolve_type(&selected.pointee)?, source_ty) {
return Ok(false);
}
let pointee = gep_pointee(source_ty, indices)?;
let true_raw = selected
.true_raw
.clone()
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
.transpose()?;
let false_raw = selected
.false_raw
.clone()
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
.transpose()?;
let true_ptr_type = selected
.true_ptr
.is_some()
.then(|| self.ptr_type_id(selected.true_storage, &pointee))
.transpose()?;
let false_ptr_type = selected
.false_ptr
.is_some()
.then(|| self.ptr_type_id(selected.false_storage, &pointee))
.transpose()?;
let true_ptr = match (selected.true_ptr, true_ptr_type) {
(Some(ptr), Some(ptr_type)) => Some(self.emit_selected_pointer_access_chain_from_id(
ptr_type,
ptr,
selected.true_storage,
source_ty,
&pointee,
indices,
instructions,
)?),
(None, _) => None,
(Some(_), None) => return Ok(false),
};
let false_ptr = match (selected.false_ptr, false_ptr_type) {
(Some(ptr), Some(ptr_type)) => Some(self.emit_selected_pointer_access_chain_from_id(
ptr_type,
ptr,
selected.false_storage,
source_ty,
&pointee,
indices,
instructions,
)?),
(None, _) => None,
(Some(_), None) => return Ok(false),
};
if (true_ptr.is_none() && true_raw.is_none())
|| (false_ptr.is_none() && false_raw.is_none())
{
return Ok(false);
}
self.selected_load_pointers.insert(
name.to_string(),
SelectedLoadPointer {
cond: selected.cond,
true_ptr,
false_ptr,
true_storage: selected.true_storage,
false_storage: selected.false_storage,
pointee: pointee.clone(),
true_raw,
false_raw,
},
);
if selected.true_storage == selected.false_storage {
self.pointer_storage
.insert(name.to_string(), selected.true_storage);
}
self.pointer_pointees.insert(name.to_string(), pointee);
if !self.pointer_phi_values.is_empty() {
let is_null = self.const_bool(false)?;
self.record_pointer_nullness(name.to_string(), is_null);
}
Ok(true)
staged_emit(instructions, |instructions| {
if !types_compatible(&self.resolve_type(&selected.pointee)?, source_ty) {
return Ok(false);
}
let pointee = gep_pointee(source_ty, indices)?;
let true_raw = selected
.true_raw
.clone()
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
.transpose()?;
let false_raw = selected
.false_raw
.clone()
.map(|raw| self.apply_raw_gep(raw, source_ty, indices))
.transpose()?;
let true_ptr_type = selected
.true_ptr
.is_some()
.then(|| self.ptr_type_id(selected.true_storage, &pointee))
.transpose()?;
let false_ptr_type = selected
.false_ptr
.is_some()
.then(|| self.ptr_type_id(selected.false_storage, &pointee))
.transpose()?;
let true_ptr = match (selected.true_ptr, true_ptr_type) {
(Some(ptr), Some(ptr_type)) => {
Some(self.emit_selected_pointer_access_chain_from_id(
ptr_type,
ptr,
selected.true_storage,
source_ty,
&pointee,
indices,
instructions,
)?)
}
(None, _) => None,
(Some(_), None) => return Ok(false),
};
let false_ptr = match (selected.false_ptr, false_ptr_type) {
(Some(ptr), Some(ptr_type)) => {
Some(self.emit_selected_pointer_access_chain_from_id(
ptr_type,
ptr,
selected.false_storage,
source_ty,
&pointee,
indices,
instructions,
)?)
}
(None, _) => None,
(Some(_), None) => return Ok(false),
};
if (true_ptr.is_none() && true_raw.is_none())
|| (false_ptr.is_none() && false_raw.is_none())
{
return Ok(false);
}
self.selected_load_pointers.insert(
name.to_string(),
SelectedLoadPointer {
cond: selected.cond,
true_ptr,
false_ptr,
true_storage: selected.true_storage,
false_storage: selected.false_storage,
pointee: pointee.clone(),
true_raw,
false_raw,
},
);
if selected.true_storage == selected.false_storage {
self.pointer_storage
.insert(name.to_string(), selected.true_storage);
}
self.pointer_pointees.insert(name.to_string(), pointee);
if !self.pointer_phi_values.is_empty() {
let is_null = self.const_bool(false)?;
self.record_pointer_nullness(name.to_string(), is_null);
}
Ok(true)
})
}
pub(in crate::native::emitter) fn emit_selected_raw_pointer_gep(