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 @@ -649,8 +649,8 @@ chapter-18/18.7--in-line-constraints--randomize_5.sv 2state fail
chapter-18/18.7--in-line-constraints--randomize_5.sv 4state fail
chapter-18/18.7--in-line-constraints--randomize_6.sv 2state fail
chapter-18/18.7--in-line-constraints--randomize_6.sv 4state fail
chapter-18/18.7.1--local-scope-resolution_0.sv 2state fail
chapter-18/18.7.1--local-scope-resolution_0.sv 4state fail
chapter-18/18.7.1--local-scope-resolution_0.sv 2state pass
chapter-18/18.7.1--local-scope-resolution_0.sv 4state pass
chapter-18/18.7.1--local-scope-resolution_1.sv 2state fail
chapter-18/18.7.1--local-scope-resolution_1.sv 4state fail
chapter-18/18.8--disabling-random-variables-with-rand_mode_0.sv 2state fail
Expand Down
14 changes: 13 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,19 @@ impl Ff<'_, '_> {
buffer = self.heap_call(ops::APPEND_BYTES, &[buffer, value, count]);
}
let program = self.heap_call(ops::FREEZE, &[buffer]);
self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check])
if args.len() == 2 {
self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check])
} else {
let mut inputs = self.heap_call(ops::NEW, &[]);
let one = self.constant64(1);
inputs = self.heap_call(ops::APPEND_BYTES, &[inputs, check, one]);
for value in &args[2..] {
let value = self.integer_of_width(value, 64, false)?;
let eight = self.constant64(8);
inputs = self.heap_call(ops::APPEND_BYTES, &[inputs, value, eight]);
}
self.heap_call(ops::OBJECT_RANDOMIZE_INPUTS, &[object, program, inputs])
}
}
ObjectOp::Container { .. } => unreachable!("handled by container_call"),
ObjectOp::New {
Expand Down
48 changes: 40 additions & 8 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ pub const OBJECT_RANDOM_CYCLIC: u64 = 62;
pub const OBJECT_COPY: u64 = 63;
/// Solve the scalar constraint program in string b for object a; c selects check-only.
pub const OBJECT_RANDOMIZE: u64 = 64;
/// Program b for object a; c is an input buffer (check-only byte followed by
/// big-endian u64 values). The buffer is consumed, including on failure.
pub const OBJECT_RANDOMIZE_INPUTS: u64 = 65;

/// The opcode word of `op` with parameter `parameter`.
pub const fn encode(op: u64, parameter: u64) -> u64 {
Expand Down Expand Up @@ -195,16 +198,45 @@ impl Heap {
0
}
OBJECT_CLASS => self.class_of(a as Handle).into(),
OBJECT_RANDOMIZE => {
match serde_json::from_slice::<crate::randomization::Program>(
self.string(b as Handle),
) {
Ok(program) => u64::from(self.randomize_object(a as Handle, &program, c != 0)),
op @ (OBJECT_RANDOMIZE | OBJECT_RANDOMIZE_INPUTS) => {
let input_bytes = (op == OBJECT_RANDOMIZE_INPUTS).then(|| self.take_buffer(c));
let result = (|| -> Result<_, String> {
let program = serde_json::from_slice::<crate::randomization::Program>(
self.string(b as Handle),
)
.map_err(|error| error.to_string())?;
let (check_only, inputs) = if op == OBJECT_RANDOMIZE_INPUTS {
let bytes = input_bytes.as_ref().unwrap();
let (&check, values) = bytes
.split_first()
.ok_or("missing constraint input buffer")?;
if check > 1 || values.len() % 8 != 0 {
return Err("invalid constraint input buffer".into());
}
(
check != 0,
values
.as_chunks::<8>()
.0
.iter()
.map(|chunk| u64::from_be_bytes(*chunk))
.collect::<Vec<_>>(),
)
} else {
(c != 0, Vec::new())
};
Ok(self.randomize_object_with_inputs(
a as Handle,
&program,
check_only,
&inputs,
))
})();
match result {
Ok(success) => u64::from(success),
Err(error) => {
self.fault
.get_or_insert(crate::Fault::ConstraintRandomization(
error.to_string(),
));
.get_or_insert(crate::Fault::ConstraintRandomization(error));
0
}
}
Expand Down
99 changes: 91 additions & 8 deletions crates/celox-heap/src/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ pub struct Field {
pub enum Expr {
Literal(u32, u64),
Field(usize),
/// Read-only scalar supplied by this call, never a solver variable.
Input {
index: usize,
width: u32,
},
Resize {
value: Box<Expr>,
width: u32,
Expand Down Expand Up @@ -50,9 +55,18 @@ fn boolean(value: Term) -> Term {
}

impl Expr {
fn term(&self, fields: &[Term]) -> Result<Term, String> {
fn term(&self, fields: &[Term], inputs: &[u64]) -> Result<Term, String> {
Ok(match self {
Self::Literal(width, value) => bv(*width, *value),
Self::Input { index, width } => {
if !(1..=64).contains(width) {
return Err("invalid constraint input width".into());
}
bv(
*width,
*inputs.get(*index).ok_or("missing constraint input")?,
)
}
Self::Field(index) => fields
.get(*index)
.ok_or("invalid constraint field")?
Expand All @@ -62,7 +76,7 @@ impl Expr {
width,
signed,
} => {
let value = value.term(fields)?;
let value = value.term(fields, inputs)?;
let Sort::Bv(old) = value.0.sort else {
unreachable!()
};
Expand All @@ -82,7 +96,7 @@ impl Expr {
}
}
Self::Unary { op, value } => {
let value = value.term(fields)?;
let value = value.term(fields, inputs)?;
match op.as_str() {
"!" => boolean(not(truth(value))),
"~" => node(value.0.sort.clone(), "bvnot", vec![value]),
Expand All @@ -101,8 +115,8 @@ impl Expr {
right,
signed,
} => {
let a = left.term(fields)?;
let b = right.term(fields)?;
let a = left.term(fields, inputs)?;
let b = right.term(fields, inputs)?;
let relation = match op.as_str() {
"==" => Some(eq(a.clone(), b.clone())),
"!=" => Some(not(eq(a.clone(), b.clone()))),
Expand Down Expand Up @@ -155,14 +169,27 @@ impl Heap {
program: &Program,
check_only: bool,
) -> bool {
self.randomize_object_with_limits(handle, program, check_only, Limits::default())
self.randomize_object_with_inputs(handle, program, check_only, &[])
}

/// Solve using call-local, read-only scalar values. Inputs are not retained
/// in the object or its RNG state and are never included in the projection.
pub fn randomize_object_with_inputs(
&mut self,
handle: Handle,
program: &Program,
check_only: bool,
inputs: &[u64],
) -> bool {
self.randomize_object_with_limits(handle, program, check_only, inputs, Limits::default())
}

fn randomize_object_with_limits(
&mut self,
handle: Handle,
program: &Program,
check_only: bool,
inputs: &[u64],
limits: Limits,
) -> bool {
if !self.check_object(handle, 0) {
Expand Down Expand Up @@ -194,7 +221,7 @@ impl Heap {
terms.push(term);
}
for constraint in &program.constraints {
formula = and(formula, truth(constraint.term(&terms)?));
formula = and(formula, truth(constraint.term(&terms, inputs)?));
}
let seed = if projection.is_empty() {
0
Expand Down Expand Up @@ -261,6 +288,62 @@ mod tests {
}
}

#[test]
fn per_call_inputs_are_read_only_checked_and_not_retained() {
let mut heap = Heap::new();
let object = heap.new_object(1, 1);
let mut program = program();
program.constraints = vec![Expr::Binary {
op: "==".into(),
left: Box::new(Expr::Field(0)),
right: Box::new(Expr::Input { index: 0, width: 4 }),
signed: false,
}];
for value in [3, 12] {
assert!(heap.randomize_object_with_inputs(object, &program, false, &[value]));
assert_eq!(heap.load(object, 0, 1), value);
}
let mut before = heap.clone();
assert!(!heap.randomize_object_with_inputs(object, &program, true, &[3]));
assert_eq!(heap.load(object, 0, 1), 12);
assert_eq!(heap.random_object(object), before.random_object(object));
assert!(!heap.randomize_object(object, &program, false));
assert!(matches!(
heap.take_fault(),
Some(Fault::ConstraintRandomization(_))
));
let json = heap.intern(&serde_json::to_vec(&program).unwrap());
let mut bytes = vec![0];
bytes.extend(5u64.to_be_bytes());
let inputs = heap.new_buffer(bytes);
assert_eq!(
heap.call(
crate::ops::OBJECT_RANDOMIZE_INPUTS,
object.into(),
json.into(),
inputs
),
1,
"{:?}",
heap.take_fault()
);
assert_eq!(heap.load(object, 0, 1), 5);
let bad = heap.new_buffer(vec![0, 1]);
assert_eq!(
heap.call(
crate::ops::OBJECT_RANDOMIZE_INPUTS,
object.into(),
json.into(),
bad
),
0
);
assert!(matches!(
heap.take_fault(),
Some(Fault::ConstraintRandomization(_))
));
}

#[test]
fn modes_unsat_faults_and_snapshot_replay() {
let mut heap = Heap::new();
Expand All @@ -279,7 +362,7 @@ mod tests {
max_work: 0,
..Limits::default()
};
assert!(!heap.randomize_object_with_limits(object, &program, false, limits));
assert!(!heap.randomize_object_with_limits(object, &program, false, &[], limits));
assert_eq!(heap.load(object, 0, 1), 9);
assert!(matches!(
heap.take_fault(),
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub(super) struct AnalysisState {
interfaces: interface_ast::State,
dimensions: dimensions::State,
root_subroutines: std::cell::Cell<bool>,
inline_randomizations: RefCell<Vec<classes::constraints::Inline>>,
next_call_site: std::rc::Rc<std::cell::Cell<usize>>,
timescales: timescales::State,
diagnostics: RefCell<Vec<warnings::AnalyzerWarning>>,
Expand Down Expand Up @@ -1308,6 +1309,13 @@ impl Module {
)?);
(subroutines, comb_processes, ff_processes, initial_processes)
};
let (inline_subroutines, inline_randomizations) =
procedural::randomization::inline_subroutines(
syntax_tree,
&mut body_state,
&packed_dimensions,
)?;
subroutines.extend(inline_subroutines);
// Static locals of the processes that keep their value are variables
// of the module, initialized once with the declaration initializers.
let statics: HashMap<String, Type> = body_state.statics.drain(..).collect();
Expand Down Expand Up @@ -1410,6 +1418,7 @@ impl Module {
// A package keeps its symbols for the scopes that use it.
let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols {
classes: classes::scope_classes(syntax_tree, &const_env),
inline_randomizations,
declarations_only: imported.declarations_only,
type_parameter_bindings: HashMap::default(),
pattern_parameter_bindings: HashMap::default(),
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::rc::Rc;
use super::*;
use crate::system_functions::{HandleProperty, ObjectField, ObjectOp};

mod constraints;
pub(super) mod constraints;
pub(super) mod specializations;

/// Bit width of a handle, see `celox_design::HANDLE_WIDTH`.
Expand Down
Loading
Loading