Skip to content
Merged
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
1 change: 1 addition & 0 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6488,6 +6488,7 @@ fn lower_bit_vector_function_slt<A: std::hash::Hash + Eq + Clone>(
| SystemFunction::UrandomRange
| SystemFunction::Fopen
| SystemFunction::ScopeRandomize
| SystemFunction::ScopeRandomizeEnum
| SystemFunction::Fread
| SystemFunction::Ftell
| SystemFunction::Fseek
Expand Down
67 changes: 67 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ impl<'p, 'a> Ff<'p, 'a> {
use sv::ir::SystemFunction;
match function {
SystemFunction::ScopeRandomize
| SystemFunction::ScopeRandomizeEnum
| SystemFunction::Urandom
| SystemFunction::UrandomRange => {
self.urandom_state();
Expand Down Expand Up @@ -903,6 +904,11 @@ impl<'p, 'a> Ff<'p, 'a> {
args,
..
} => self.fopen(args)?,
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomizeEnum),
args,
..
} => self.randomize_enum(args)?,
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize),
args,
Expand Down Expand Up @@ -1412,6 +1418,67 @@ impl<'p, 'a> Ff<'p, 'a> {
Ok(result)
}

/// Randomize one scalar enum from the process stream. Arguments after the
/// writable destination are its declared values, supplied by the analyzer.
fn randomize_enum(
&mut self,
args: &[Option<sv::ir::Expr>],
) -> Result<sv::ir::Expr, sv::AnalyzerError> {
use sv::ir::{BinaryOp, Expr};
let Some(Some(Expr::Ident(name))) = args.first() else {
return Err(unsupported("scope enum randomize variable"));
};
let values = args[1..]
.iter()
.map(Option::as_ref)
.collect::<Option<Vec<_>>>()
.filter(|values| !values.is_empty())
.ok_or_else(|| unsupported("scope enum randomize domain"))?;
let count = u32::try_from(values.len())
.map_err(|_| unsupported("scope enum randomize domain size"))?;
let threshold = count.wrapping_neg() % count;
let draw_block = self.b.new_block();
let accepted = self.b.new_block();
self.jump(draw_block);
self.b.switch_to_block(draw_block);
let draw = self.randomize_word()?;
let rejected = Expr::Binary {
left: Box::new(draw.clone()),
op: BinaryOp::Lt,
right: Box::new(Expr::Literal(format!("32'd{threshold}"))),
};
let cond = self.eval_truth(&rejected)?.0;
self.b.seal_block(SIRTerminator::Branch {
cond,
true_block: (draw_block, Vec::new()),
false_block: (accepted, Vec::new()),
});
self.b.switch_to_block(accepted);
let index = self.hidden(
"enum_index",
&Expr::Binary {
left: Box::new(draw),
op: BinaryOp::Mod,
right: Box::new(Expr::Literal(format!("32'd{count}"))),
},
false,
)?;
let mut value = (*values.last().unwrap()).clone();
for (position, member) in values.iter().enumerate().rev().skip(1) {
value = Expr::Mux {
condition: Box::new(Expr::Binary {
left: Box::new(index.clone()),
op: BinaryOp::Eq,
right: Box::new(Expr::Literal(format!("32'd{position}"))),
}),
then_expr: Box::new((*member).clone()),
else_expr: Box::new(value),
};
}
self.assign(&sv::ir::LValue::Ident(name.clone()), &value)?;
Ok(Expr::Literal("32'sd1".into()))
}

/// A bijective 32-bit output permutation of the process RNG. Mixing
/// high bits into low bits prevents the LCG's short low-bit periods from
/// freezing bits when a wide variable consumes an even number of words.
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2731,6 +2731,7 @@ struct UnpackedDimension {
#[derive(Debug, Clone, PartialEq, Eq)]
struct VariableDimensions {
randomizable: bool,
enum_values: Option<Vec<i128>>,
real: bool,
/// A `string`: each element is a heap handle, not packed bits.
string: bool,
Expand Down
11 changes: 9 additions & 2 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals(
dimensions.insert(
port.name().to_string(),
VariableDimensions {
randomizable: !port.r#type().is_enum && port.randomizable,
randomizable: (!port.r#type().is_enum || port.r#type().enum_values.is_some())
&& port.randomizable,
enum_values: port.r#type().enum_values.clone(),
real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal),
string: matches!(port.r#type().kind(), TypeKind::String),
class: port.r#type().class().map(str::to_owned),
Expand All @@ -156,7 +158,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals(
dimensions.insert(
signal.name().to_string(),
VariableDimensions {
randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const,
randomizable: (!signal.r#type().is_enum || signal.r#type().enum_values.is_some())
&& !signal.is_net()
&& !signal.is_const,
enum_values: signal.r#type().enum_values.clone(),
real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal),
string: matches!(signal.r#type().kind(), TypeKind::String),
class: signal.r#type().class().map(str::to_owned),
Expand Down Expand Up @@ -365,6 +370,7 @@ fn extend_variable_dimensions_from_const_env(
let mut shape = procedural::dimensions_from_type(&ty);
if let Some(existing) = context.get(name) {
shape.randomizable = existing.randomizable;
shape.enum_values = existing.enum_values.clone();
shape.members = existing.members.clone();
shape.is_2state = existing.is_2state;
shape.signed_element_depth = existing.signed_element_depth;
Expand Down Expand Up @@ -533,6 +539,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP
parameter.name.clone(),
VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
59 changes: 51 additions & 8 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ pub(in crate::ast) fn cast_target_native(
}

enum Finish {
ScopeRandomize(Vec<Option<Vec<i128>>>),
Unary(String),
Binary(String),
Mux,
Expand Down Expand Up @@ -499,6 +500,7 @@ pub(in crate::ast) fn bind_value(
}
let actuals =
args.iter().filter_map(|arg| arg.value).collect::<Vec<_>>();
let mut domains = Vec::with_capacity(actuals.len());
for &actual in &actuals {
let ExprKind::Name(name) = &native.expression(actual).kind else {
return Err(unsupported(
Expand All @@ -509,11 +511,17 @@ pub(in crate::ast) fn bind_value(
let shape = dimensions
.get(&name)
.ok_or_else(|| unsupported("scope randomize variable"))?;
if !shape.unpacked.is_empty() || !shape.randomizable {
if !shape.unpacked.is_empty()
|| !shape.randomizable
|| shape.real
|| shape.string
|| shape.class.is_some()
{
return Err(unsupported(
"scope randomize requires a packed non-enum variable",
"scope randomize requires a packed variable with a supported enum domain",
));
}
domains.push(shape.enum_values.clone());
if !expressions::query_actual_is_writable(
&Expr::Ident(name),
dimensions,
Expand All @@ -524,12 +532,7 @@ pub(in crate::ast) fn bind_value(
}
}
jobs.push(Job::Finish(
Finish::Call {
name: "std::randomize".into(),
args: actuals.iter().copied().map(Some).collect(),
order: Vec::new(),
system: Some(SystemFunction::ScopeRandomize),
},
Finish::ScopeRandomize(domains),
actuals.len(),
scope.clone(),
));
Expand Down Expand Up @@ -930,6 +933,46 @@ pub(in crate::ast) fn bind_value(
Finish::StringCall(op) => {
strings::call(op, strings::operands(op, operands, dimensions))
}
Finish::ScopeRandomize(domains) => {
// Preserve the original call when no enum is present.
// Every scalar operation succeeds and returns signed int 1;
// bitwise AND preserves that type and evaluates all operands.
if domains.iter().all(Option::is_none) {
Expr::Call {
callee: Callee::System(SystemFunction::ScopeRandomize),
args: operands.into_iter().map(Some).collect(),
arg_order: Vec::new(),
}
} else {
let mut calls =
operands.into_iter().zip(domains).map(|(operand, domain)| {
let mut args = vec![Some(operand)];
let function = if let Some(values) = domain {
args.extend(values.into_iter().map(|value| {
Some(Expr::Literal(format_typed_parameter_literal(
value,
64,
value < 0,
)))
}));
SystemFunction::ScopeRandomizeEnum
} else {
SystemFunction::ScopeRandomize
};
Expr::Call {
callee: Callee::System(function),
args,
arg_order: Vec::new(),
}
});
let first = calls.next().ok_or_else(disagreement)?;
calls.fold(first, |left, right| Expr::Binary {
left: Box::new(left),
op: BinaryOp::BitAnd,
right: Box::new(right),
})
}
}
Finish::ObjectLoad(property) => {
let handle = operands.pop().ok_or_else(disagreement)?;
objects::load(&property, handle)
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) -
name.to_string(),
VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/parameters/skipped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ fn pattern_items(
count as i128 - 1,
VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-sv-analyzer/src/ast/patterns/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ fn select<'a>(
let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?;
let sub = Shape::Owned(Rc::new(VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down Expand Up @@ -244,6 +245,7 @@ fn select<'a>(
.ok_or_else(|| unsupported("assignment pattern target width"))?;
let bit = Shape::Owned(Rc::new(VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
3 changes: 2 additions & 1 deletion crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ pub(super) struct BodyBuilder<'s, 't, 'a> {
/// The packed and unpacked shape of a declared type, as selects see it.
pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions {
VariableDimensions {
randomizable: !r#type.is_enum,
randomizable: !r#type.is_enum || r#type.enum_values.is_some(),
enum_values: r#type.enum_values.clone(),
real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal),
string: matches!(r#type.kind(), TypeKind::String),
class: r#type.class().map(str::to_owned),
Expand Down
8 changes: 7 additions & 1 deletion crates/celox-sv-analyzer/src/system_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ pub enum SystemFunction {
Urandom,
/// Scope randomization of packed variables, without constraints (18.12).
ScopeRandomize,
/// Internal scalar enum randomization: destination followed by legal values.
ScopeRandomizeEnum,
/// `$urandom_range` (18.13.2).
UrandomRange,
/// `$fopen` (21.3.1).
Expand Down Expand Up @@ -280,6 +282,7 @@ impl SystemFunction {
Self::ValuePlusargs => "$value$plusargs",
Self::Urandom => "$urandom",
Self::ScopeRandomize => "std::randomize",
Self::ScopeRandomizeEnum => "$__celox_randomize_enum",
Self::UrandomRange => "$urandom_range",
Self::Fopen => "$fopen",
Self::Fread => "$fread",
Expand Down Expand Up @@ -343,6 +346,7 @@ impl SystemFunction {
| Self::Fscanf
| Self::UrandomRange
| Self::ScopeRandomize
| Self::ScopeRandomizeEnum
)
}

Expand All @@ -357,6 +361,7 @@ impl SystemFunction {
/// updates its seed variable.
pub fn writes_argument(self, position: usize) -> bool {
self == Self::ScopeRandomize
|| (self == Self::ScopeRandomizeEnum && position == 0)
|| (matches!(
self,
Self::Random
Expand Down Expand Up @@ -406,7 +411,8 @@ impl SystemFunction {
| Self::Clog2
| Self::Countbits
| Self::Countones
| Self::ScopeRandomize => Some((32, true)),
| Self::ScopeRandomize
| Self::ScopeRandomizeEnum => Some((32, true)),
Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)),
Self::Random
| Self::DistUniform
Expand Down
9 changes: 4 additions & 5 deletions crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6303,11 +6303,10 @@ fn scope_randomize_validates_variable_arguments() {
("bit value[2];", "randomize(value)"),
("wire value;", "randomize(value)"),
("const bit value = 1;", "randomize(value)"),
("enum bit [1:0] {A=0, B=3} value;", "randomize(value)"),
(
"typedef enum bit [1:0] {A=0, B=3} E; E value;",
"std::randomize(value)",
),
("real value;", "randomize(value)"),
("string value;", "randomize(value)"),
("class C; endclass C value;", "randomize(value)"),
("enum bit [1:0] {A=3, B} value;", "randomize(value)"),
("bit value;", "std::randomize(value) with {value == 1;}"),
] {
let source = format!("module Top; {declaration} bit ok; initial ok = {call}; endmodule");
Expand Down
11 changes: 11 additions & 0 deletions crates/celox-test-suite/LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,17 @@ IEEE 1800-2023 18.3. Only `class::randomization_enum_alias` is excluded;
[the mismatch evidence](verification/repros/sv_enum_randomization_verilator.json)
retains its unchanged domain assertion.

Scope enum randomization has two narrow tool exclusions for
`system_functions::scope_randomize_enum_values` and
`system_functions::scope_randomize_enum_order`. Icarus 13.0 rejects scope
randomization calls (`sv_icarus_scope_enum_randomize`;
[compile diagnostics](verification/repros/sv_scope_enum_randomize_icarus.json)).
Verilator 5.052 generates `basicStdRandomization` calls using only integer widths,
without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_randomize`;
[mismatch evidence](verification/repros/sv_scope_enum_randomize_verilator.json)).
IEEE 1800-2023 18.3 and 18.12 require the declared enum domain. The shared
assertions remain unchanged, including the direct-enum case without an alias.

## SystemVerilog packed unions

The `unions` shared group covers hard and soft packed untagged unions. With
Expand Down
Loading
Loading