Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1451,8 +1451,8 @@ chapter-7/structures/packed/signed.sv 2state pass
chapter-7/structures/packed/signed.sv 4state pass
chapter-7/structures/packed/unsigned.sv 2state pass
chapter-7/structures/packed/unsigned.sv 4state pass
chapter-7/structures/unpacked/basic.sv 2state fail
chapter-7/structures/unpacked/basic.sv 4state fail
chapter-7/structures/unpacked/basic.sv 2state pass
chapter-7/structures/unpacked/basic.sv 4state pass
chapter-7/structures/unpacked/default-value.sv 2state fail
chapter-7/structures/unpacked/default-value.sv 4state fail
chapter-7/unions/packed/basic.sv 2state pass
Expand Down
39 changes: 30 additions & 9 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3138,11 +3138,24 @@ impl<'p, 'a> Ff<'p, 'a> {
&mut self,
lhs: &sv::ir::LValue,
rhs: &sv::ir::Expr,
) -> Result<(), sv::AnalyzerError> {
self.assign_value(lhs, rhs, true)
}

/// Assign `rhs` to `lhs`; `convert` turns an integral value assigned to
/// a string variable into its bytes. The parts of a concatenation target
/// take the bits of the value instead: a part that is a string is a
/// member of an unpacked structure, and its bits are a handle.
fn assign_value(
&mut self,
lhs: &sv::ir::LValue,
rhs: &sv::ir::Expr,
convert: bool,
) -> Result<(), sv::AnalyzerError> {
let lhs = self.propagate_lvalue(lhs);
let lhs = self.hoist_lvalue(&lhs)?;
let converted = match self.m.id(lhs.name()) {
Some(id) if matches!(lhs, sv::ir::LValue::Ident(_)) => {
Some(id) if convert && matches!(lhs, sv::ir::LValue::Ident(_)) => {
self.string_conversion(id, rhs.clone())
}
_ => rhs.clone(),
Expand Down Expand Up @@ -3609,9 +3622,11 @@ impl<'p, 'a> Ff<'p, 'a> {
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(rhs, Some((total, signed)), &mut arena)?;
let node = coerce_node_width(&mut arena, node, Some(total), signed).map_err(slt_error)?;
// Capture the value before any part is written.
let (temp, temp_name) = self.m.temp("concat", total, false, true);
// Capture the value before any part is written, in a temporary of
// the value's state kind.
let value = self.lower_slt(&arena, node)?;
let four_state = matches!(self.b.register(&value), RegisterType::Logic { .. });
let (temp, temp_name) = self.m.temp("concat", total, false, four_state);
self.store(temp, SIROffset::Static(0), total, value);
let mut lsb = total;
for (part, width) in parts.iter().zip(widths) {
Expand All @@ -3622,7 +3637,7 @@ impl<'p, 'a> Ff<'p, 'a> {
lsb: sv::ir::ConstExpr::Literal(lsb.to_string()),
signed: false,
};
self.assign(part, &slice)?;
self.assign_value(part, &slice, false)?;
}
Ok(())
}
Expand Down Expand Up @@ -4744,7 +4759,10 @@ impl<'p, 'a> Ff<'p, 'a> {
})?;
let guards = tagged_actual_guards(reference);
self.check_tagged_guards(&guards)?;
outputs.push((param.name.clone(), id, lvalues, guards));
// The members of an unpacked structure take the formal's
// bits, even a single string or handle member.
let concat = matches!(reference, sv::ir::Expr::Concat(_));
outputs.push((param.name.clone(), id, lvalues, guards, concat));
}
}
if param.direction.is_read() {
Expand Down Expand Up @@ -4855,10 +4873,12 @@ impl<'p, 'a> Ff<'p, 'a> {
self.jump(return_block);
}
self.b.switch_to_block(return_block);
for (formal, id, lvalues, guards) in outputs {
for (formal, id, lvalues, guards, concat) in outputs {
self.check_tagged_guards(&guards)?;
let signed = self.m.var(id).signed;
if let [lvalue] = lvalues.as_slice() {
if let [lvalue] = lvalues.as_slice()
&& !concat
{
self.assign(lvalue, &sv::ir::Expr::Ident(formal))?;
} else {
let _ = signed;
Expand Down Expand Up @@ -7820,14 +7840,15 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option<String> {
// Container contents are immutable: reading an element is a
// value of the container handle and index, unlike a class
// property that can change without its handle changing.
// A record of a structure element is immutable as well.
sv::ir::Callee::Object(op)
if matches!(
*op,
sv::ir::ObjectOp::Container {
op: sv::ir::ContainerOp::Get,
..
}
) =>
} | sv::ir::ObjectOp::Unbox(_)
) || matches!(*op, sv::ir::ObjectOp::Load(field) if field.nullable) =>
{
continue;
}
Expand Down
148 changes: 129 additions & 19 deletions crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ impl Ff<'_, '_> {
.collect::<Result<Vec<_>, _>>()?;
if args.iter().any(|arg| self.m.calls(arg)) {
for (index, arg) in args.iter_mut().enumerate() {
// A record is built from a flat structure value, not a handle.
if let ObjectOp::Box(record) = op {
*arg = self.heap_operand(arg, Some((record.width(), false)), None)?;
continue;
}
let (width, signed) = if index == 0 {
(32, false)
} else {
Expand Down Expand Up @@ -118,36 +123,87 @@ impl Ff<'_, '_> {
}
ObjectOp::Load(field) if field.four_state && self.m.four_state => {
let object = self.handle(&args[0])?;
let [value, mask] = [0, field.bytes()].map(|plane| {
let offset = self.constant64(u64::from(field.offset + plane));
let count = self.constant64(u64::from(field.bytes()));
let stored = self.heap_call(ops::OBJECT_LOAD, &[object, offset, count]);
self.complement(stored)
});
let result = self.load_field(object, *field);
let width = field.width as usize;
let result = self.container_join(value, mask, width, true);
let (temp, name) = self.m.temp("object", width, field.signed, true);
self.store(temp, SIROffset::Static(0), width, result);
return Ok(sv::ir::Expr::Ident(name));
}
ObjectOp::Load(field) => {
let object = self.handle(&args[0])?;
let offset = self.constant64(u64::from(field.offset));
let count = self.constant64(u64::from(field.bytes()));
self.heap_call(ops::OBJECT_LOAD, &[object, offset, count])
self.load_field(object, *field)
}
ObjectOp::Unbox(record) => {
let object = self.handle(&args[0])?;
let parts = record
.fields
.iter()
.map(|field| self.load_field(object, *field))
.collect::<Vec<_>>();
let width = record.width();
let four_state = self.m.four_state && record.fields.iter().any(|f| f.four_state);
let value = if four_state {
self.b.alloc_logic(width)
} else {
self.b.alloc_bit(width, false)
};
self.b.emit(SIRInstruction::Concat(value, parts));
let (temp, name) = self.m.temp("record", width, false, four_state);
self.store(temp, SIROffset::Static(0), width, value);
return Ok(sv::ir::Expr::Ident(name));
}
ObjectOp::Box(record) => {
// Evaluate the value first: its calls may end the block, so
// the record's handle is only used after them.
let expr = self.hoist(&args[0])?;
let width = record.width();
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(&expr, Some((width, false)), &mut arena)?;
let node =
coerce_node_width(&mut arena, node, Some(width), false).map_err(slt_error)?;
let value = self.lower_slt(&arena, node)?;
// A record is not seeded: it has no random state, and seeding
// would draw from the creating process's RNG.
let size = self.constant64(u64::from(record.size));
let object = self.heap_call(
ops::encode(ops::OBJECT_NEW, u64::from(sv::ir::Record::CLASS)),
&[size],
);
for field in &record.fields {
if let Some(kind) = field.handle {
let offset = self.constant64(u64::from(field.offset));
let kind = self.constant64(match kind {
HandleProperty::String => 0,
HandleProperty::Object => 1,
});
self.heap_call(ops::OBJECT_HANDLE, &[object, offset, kind]);
}
}
let mut lsb = width;
for field in &record.fields {
lsb -= field.width as usize;
let part = if matches!(self.b.register(&value), RegisterType::Logic { .. }) {
self.b.alloc_logic(field.width as usize)
} else {
self.b.alloc_bit(field.width as usize, false)
};
self.b.emit(SIRInstruction::Slice(
part,
value,
lsb,
field.width as usize,
));
self.store_field(object, *field, part);
}
// An equal value keeps the handle it already has, so that
// storing it again leaves a container unchanged.
self.heap_call(ops::OBJECT_FINISH_RECORD, &[object])
}
ObjectOp::Store(field) if field.four_state && self.m.four_state => {
let object = self.handle(&args[0])?;
let expr = self.hoist(&args[1])?;
let value = self.eval(&expr, Some((field.width as usize, field.signed)))?;
let (value, mask) = self.container_split(value);
for (plane, bits) in [(0, value), (field.bytes(), mask)] {
let place = self.constant64(
u64::from(field.offset + plane) | u64::from(field.bytes()) << 32,
);
let stored = self.complement(bits);
self.heap_call(ops::OBJECT_STORE, &[object, place, stored]);
}
self.store_field(object, *field, value);
self.constant64(0)
}
ObjectOp::Store(field) => {
Expand Down Expand Up @@ -223,7 +279,10 @@ impl Ff<'_, '_> {
let (temp, name) = self.m.temp("object", width, signed, false);
let kind = match op {
ObjectOp::Container { .. } => unreachable!("handled by container_call"),
ObjectOp::New { .. } | ObjectOp::Copy => Some(celox_design::ValueKind::ObjRef),
ObjectOp::New { .. } | ObjectOp::Copy | ObjectOp::Box(_) => {
Some(celox_design::ValueKind::ObjRef)
}
ObjectOp::Unbox(_) => unreachable!("lowered to its own temporary"),
ObjectOp::Load(field) => field.handle.map(|handle| match handle {
HandleProperty::String => celox_design::ValueKind::StrRef,
HandleProperty::Object => celox_design::ValueKind::ObjRef,
Expand Down Expand Up @@ -251,6 +310,57 @@ impl Ff<'_, '_> {
Ok(sv::ir::Expr::Ident(name))
}

/// The value of `field` of the object in 64-bit `object`: a register of
/// the field's width, 4-state for a 4-state field in 4-state simulation.
fn load_field(&mut self, object: RegisterId, field: sv::ir::ObjectField) -> RegisterId {
let opcode = if field.nullable {
ops::OBJECT_LOAD_NULLABLE
} else {
ops::OBJECT_LOAD
};
let width = field.width as usize;
if field.four_state && self.m.four_state {
let [value, mask] = [0, field.bytes()].map(|plane| {
let offset = self.constant64(u64::from(field.offset + plane));
let count = self.constant64(u64::from(field.bytes()));
let stored = self.heap_call(opcode, &[object, offset, count]);
self.complement(stored)
});
return self.container_join(value, mask, width, true);
}
let offset = self.constant64(u64::from(field.offset));
let count = self.constant64(u64::from(field.bytes()));
let loaded = self.heap_call(opcode, &[object, offset, count]);
let value = self.b.alloc_bit(width, field.signed);
self.b.emit(SIRInstruction::Slice(value, loaded, 0, width));
value
}

/// Store register `value` of `field`'s width into `field` of the object in
/// 64-bit `object`.
fn store_field(&mut self, object: RegisterId, field: sv::ir::ObjectField, value: RegisterId) {
let planes = if field.four_state && self.m.four_state {
let (value, mask) = self.container_split(value);
vec![
(0, self.complement(value)),
(field.bytes(), self.complement(mask)),
]
} else {
let known = self.b.alloc_bit(field.width as usize, false);
self.b
.emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, value));
let wide = self.b.alloc_bit(64, false);
self.b
.emit(SIRInstruction::Unary(wide, UnaryOp::Ident, known));
vec![(0, wide)]
};
for (plane, bits) in planes {
let place =
self.constant64(u64::from(field.offset + plane) | u64::from(field.bytes()) << 32);
self.heap_call(ops::OBJECT_STORE, &[object, place, bits]);
}
}

/// A 4-state property holds the complement of its value and mask planes,
/// so the zeroed bytes of a new object read as X (IEEE 1800-2023 6.8).
fn complement(&mut self, plane: RegisterId) -> RegisterId {
Expand Down
6 changes: 6 additions & 0 deletions crates/celox-heap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ pub struct Heap {
next_object: Handle,
containers: HashMap<Handle, Arc<containers::Container>>,
container_lookup: HashMap<Arc<containers::Container>, Handle>,
/// Structure records by their contents, see [`ops::OBJECT_FINISH_RECORD`].
#[serde(default)]
record_lookup: HashMap<objects::RecordContents, Handle>,
/// The first heap operation error since the runtime last checked.
fault: Option<Fault>,
/// Entries below this handle are never collected.
Expand Down Expand Up @@ -112,6 +115,7 @@ impl Heap {
next_object: NULL + 1,
containers: HashMap::default(),
container_lookup: HashMap::default(),
record_lookup: HashMap::default(),
fault: None,
pinned: 1,
created: 0,
Expand Down Expand Up @@ -241,6 +245,8 @@ impl Heap {
self.containers.retain(|handle, _| objects.contains(handle));
self.container_lookup
.retain(|_, handle| objects.contains(handle));
self.record_lookup
.retain(|_, handle| objects.contains(handle));
// No buffer outlives the kernel that built it.
self.buffers.clear();
self.free_buffers.clear();
Expand Down
51 changes: 51 additions & 0 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,36 @@ impl std::fmt::Display for Fault {
}
}

/// The contents of a structure record: its bytes and handle fields.
pub(crate) type RecordContents = (Box<[u8]>, Vec<(u32, HandleKind)>);

impl Heap {
/// The handle of the record with the contents of the finished `record`,
/// so that equal values of an unpacked structure have one handle, as
/// equal strings and containers do: `null` for the default value, whose
/// bytes are all zero (a `null` record reads as its members' defaults).
/// A record is never written after it is finished.
pub fn finish_record(&mut self, record: Handle) -> Handle {
let Some(object) = self.objects.get(&record) else {
return record;
};
if object.bytes.iter().all(|&byte| byte == 0) {
self.objects.remove(&record);
return NULL;
}
let contents = (object.bytes.clone(), object.handles.clone());
match self.record_lookup.get(&contents) {
Some(&canonical) if canonical != record && self.objects.contains_key(&canonical) => {
self.objects.remove(&record);
canonical
}
_ => {
self.record_lookup.insert(contents, record);
record
}
}
}

/// A new object of `class` with `size` zeroed bytes.
pub fn new_object(&mut self, class: u32, size: usize) -> Handle {
let handle = self.next_object;
Expand Down Expand Up @@ -335,6 +364,28 @@ mod tests {
assert_eq!(heap.take_fault(), None);
}

#[test]
fn equal_records_share_one_handle_until_collected() {
let mut heap = Heap::new();
let record = |heap: &mut Heap, value: u64| {
let record = heap.new_object(u32::MAX, 8);
heap.declare_handle(record, 0, HandleKind::String);
heap.store(record, 4, 4, value);
heap.finish_record(record)
};
let first = record(&mut heap, 1);
let second = record(&mut heap, 1);
let other = record(&mut heap, 2);
assert_eq!(first, second);
assert_ne!(first, other);
assert_eq!(heap.objects.len(), 2);
assert_eq!(record(&mut heap, 0), NULL);
assert_eq!(heap.objects.len(), 2);
heap.collect([Root::object(other)]);
assert_eq!(heap.record_lookup.len(), 1);
assert_ne!(record(&mut heap, 1), first);
}

#[test]
fn null_dereferences_are_faults_that_read_zero() {
let mut heap = Heap::new();
Expand Down
Loading
Loading