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: 4 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1969,6 +1969,8 @@ pub enum PortDirection {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Type {
is_enum: bool,
/// Resolved legal values for a scalar enum; None if its domain is unsupported.
enum_values: Option<Vec<i128>>,
kind: TypeKind,
is_signed: bool,
packed_ranges: Vec<PackedRange>,
Expand All @@ -1986,6 +1988,7 @@ impl Type {
fn implicit() -> Self {
Self {
is_enum: false,
enum_values: None,
kind: TypeKind::Implicit,
is_signed: false,
packed_ranges: Vec::new(),
Expand All @@ -2000,6 +2003,7 @@ impl Type {
Self {
kind,
is_enum: false,
enum_values: None,
is_signed: false,
packed_ranges: Vec::new(),
unpacked_ranges: Vec::new(),
Expand Down
7 changes: 5 additions & 2 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,12 @@ impl Class {
if property.randc {
return Err(unsupported("class randomize with randc properties"));
}
if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) {
if property.rand
&& (property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none()))
{
return Err(unsupported(
"class randomize requires integral non-enum rand properties",
"class randomize requires integral rand properties with a supported enum domain",
));
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ fn extend_variable_dimensions_from_const_env(
let packed_ranges = ranges.split_off(unpacked);
let ty = Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Logic,
is_signed: variable_type_is_signed(const_env, name),
packed_ranges,
Expand Down
9 changes: 5 additions & 4 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ enum Finish {
/// A string operation on the bound children, see [`strings`].
StringCall(StringOp),
/// A read of property `property` of the object handle child.
ObjectLoad(crate::ast::classes::Property),
ObjectLoad(Box<crate::ast::classes::Property>),
/// A call of method subroutine `name` with `formals` formals; the first
/// child is the object handle when `receiver` is one.
MethodCall {
Expand Down Expand Up @@ -756,9 +756,10 @@ pub(in crate::ast) fn bind_value(
let (property, receiver) = objects::property(tree, id, native, dimensions)?
.expect("checked by the guard");
match receiver {
Some(receiver) => {
(Finish::ObjectLoad(property), vec![(receiver, None)])
}
Some(receiver) => (
Finish::ObjectLoad(Box::new(property)),
vec![(receiver, None)],
),
None => {
values.push(objects::load(&property, objects::this()));
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,9 +555,12 @@ pub(super) fn random_selection(
if property.constant {
return Err(unsupported("randomize argument is a const property"));
}
if property.field.handle.is_some() || property.r#type.is_enum || property.randc {
if property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
|| property.randc
{
return Err(unsupported(
"randomize arguments require integral non-enum, non-randc properties",
"randomize arguments require integral, non-randc properties with a supported enum domain",
));
}
bits[index + 1] = '1';
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-sv-analyzer/src/ast/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,11 @@ pub(super) fn coerce_const_parameter_value(value: i128, width: usize, signed: bo
}
}

fn enum_initializer_fits_base_type(value: i128, value_type: ExprType, base_type: ExprType) -> bool {
pub(super) fn enum_initializer_fits_base_type(
value: i128,
value_type: ExprType,
base_type: ExprType,
) -> bool {
// A same-width initializer may change its numeric interpretation when
// the enum base has different signedness, but it does not lose any bits.
if value_type.width <= base_type.width || base_type.width >= 128 {
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap<String, i128>) -
pub(super) fn int_type() -> Type {
Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Bit,
is_signed: true,
packed_ranges: vec![PackedRange::new(
Expand Down
81 changes: 70 additions & 11 deletions crates/celox-sv-analyzer/src/ast/procedural/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ pub(super) fn lower(
for property in &class.properties {
if property.constant
|| property.field.handle.is_some()
|| property.r#type.is_enum
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
{
continue;
}
Expand All @@ -150,16 +150,7 @@ pub(super) fn lower(
vec![Expr::Ident(this.clone())],
)),
},
then_body: vec![Stmt::Eval(classes::object_call(
ObjectOp::Store(property.field),
vec![
Expr::Ident(this.clone()),
classes::object_call(
ObjectOp::Random,
vec![Expr::Ident(this.clone())],
),
],
))],
then_body: random_property(&mut builder, property, &this),
else_body: Vec::new(),
});
}
Expand Down Expand Up @@ -264,3 +255,71 @@ pub(super) fn lower(
}
Ok(result)
}

/// Select a declared enum value with rejection sampling, so non-power-of-two
/// domains are uniform (IEEE 1800-2023 18.3, 18.4.1). Keep the draws inside the
/// mode guard: a disabled property must not consume its object's random stream.
fn random_property(
builder: &mut BodyBuilder<'_, '_, '_>,
property: &classes::Property,
this: &str,
) -> Vec<Stmt> {
let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]);
let mut body = Vec::new();
let value = if let Some(values) = &property.r#type.enum_values {
let count = values.len() as u64;
let threshold = count.wrapping_neg() % count;
let draw = builder.declare("$enum_draw", classes::unsigned_type(64));
body.push(Stmt::Loop {
kind: LoopKind::DoWhile,
init: Vec::new(),
condition: Some(Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Lt,
right: Box::new(Expr::Literal(format!("64'd{threshold}"))),
}),
step: Vec::new(),
body: vec![Stmt::Assign {
lhs: LValue::Ident(draw.clone()),
rhs: random(),
nonblocking: false,
}],
});
body.push(Stmt::Assign {
lhs: LValue::Ident(draw.clone()),
rhs: Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Mod,
right: Box::new(Expr::Literal(format!("64'd{count}"))),
},
nonblocking: false,
});
let literal = |value| {
Expr::Literal(format_typed_parameter_literal(
value,
property.field.width as usize,
property.field.signed,
))
};
let mut value = literal(*values.last().unwrap());
for (index, &member) in values.iter().enumerate().rev().skip(1) {
value = Expr::Mux {
condition: Box::new(Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Eq,
right: Box::new(Expr::Literal(format!("64'd{index}"))),
}),
then_expr: Box::new(literal(member)),
else_expr: Box::new(value),
};
}
value
} else {
random()
};
body.push(Stmt::Eval(classes::object_call(
ObjectOp::Store(property.field),
vec![Expr::Ident(this.into()), value],
)));
body
}
73 changes: 70 additions & 3 deletions crates/celox-sv-analyzer/src/ast/type_binding/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub(in crate::ast) fn bind_in(
) -> Converted<Option<Type>> {
enum Job {
Enter(TypeId),
Enum(Vec<PackedRange>),
Enum(TypeId, Vec<PackedRange>),
Aggregate {
owner: Arc<str>,
union: bool,
Expand Down Expand Up @@ -79,11 +79,12 @@ pub(in crate::ast) fn bind_in(
}
DataTypeKind::Enum { base, .. } => {
if let Some(base) = base {
jobs.push(Job::Enum(ranges));
jobs.push(Job::Enum(id, ranges));
jobs.push(Job::Enter(*base));
} else {
let mut ty = builtin_type("int", None).unwrap();
ty.is_enum = true;
ty.enum_values = enum_values(id, native, tree, context, &ty);
ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect();
values.push(ty);
}
Expand Down Expand Up @@ -159,14 +160,15 @@ pub(in crate::ast) fn bind_in(
}
}
}
Job::Enum(ranges) => {
Job::Enum(id, ranges) => {
let Some(mut ty) = values.pop() else {
return Err(unsupported("enum base type"));
};
let mut outer = ranges;
outer.extend(ty.packed_ranges);
ty.packed_ranges = outer;
ty.is_enum = true;
ty.enum_values = enum_values(id, native, tree, context, &ty);
values.push(ty);
}
Job::Aggregate {
Expand Down Expand Up @@ -282,3 +284,68 @@ pub(in crate::ast) fn expression_type(
let value = expression_binding::bind(root, tree, &query)?;
Ok(dimensions::bound_bits_type(&tree.state, &value, &query))
}

/// Domain metadata is best-effort during signature discovery. Only a caller
/// requesting randomization requires a resolved domain; unused types must not
/// start reporting new errors merely because this metadata is collected.
fn enum_values(
id: TypeId,
native: &celox_sv_syntax::Declarations,
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
ty: &Type,
) -> Option<Vec<i128>> {
let data = native.data_type(id);
if !data.packed_dimensions.is_empty() {
return None;
}
let DataTypeKind::Enum { items, .. } = &data.kind else {
return None;
};
let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?;
if shape.width > 64 {
return None;
}
let mut env = context.const_env.clone();
let mut next = 0i128;
let mut values = Vec::new();
for item in items {
if !item.dimensions.is_empty() {
return None;
}
let value = if let Some(id) = item.value {
let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases)
.ok()??;
// Unbased fills take the enum base's width and signedness, just
// as they do when resolving the declared enum constants (5.7.1).
let expr = match expr {
ConstExpr::Literal(literal) => ConstExpr::Literal(
resize_unbased_fill_literal_for_cast(&literal, shape.width, shape.signed)
.unwrap_or(literal),
),
expr => expr,
};
let value = eval_ast_const_expr(&tree.state, &expr, &env)?;
let value_type = infer_const_expr_type(&expr, &parameter_types_from_const_env(&env))?;
if !parameters::enum_initializer_fits_base_type(value, value_type, shape) {
return None;
}
value
} else {
if parameters::coerce_const_parameter_value(next, shape.width, shape.signed) != next {
return None;
}
next
};
let value = parameters::coerce_const_parameter_value(value, shape.width, shape.signed);
if values.contains(&value) {
return None;
}
values.push(value);
let name = normalize_identifier(&item.name.spelling);
env.insert(name.clone(), value);
dimensions::insert_parameter_type_markers(&mut env, &name, shape);
next = value.checked_add(1)?;
}
(!values.is_empty()).then_some(values)
}
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ pub(super) fn enclose_aliased_packed_type(
// array they form is unsigned, whatever its elements (IEEE 1800-2023
// 7.4.1); a type name takes no signing of its own.
if !direct_ranges.is_empty() {
r#type.enum_values = None;
r#type.signed_element_depth = if r#type.is_signed {
Some(direct_ranges.len())
} else {
Expand Down
22 changes: 21 additions & 1 deletion crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6610,7 +6610,11 @@ fn class_randomize_rejects_unsupported_semantics() {
"c.f()",
"object receiver",
),
("rand string x;", "c.randomize()", "integral non-enum"),
(
"rand string x;",
"c.randomize()",
"integral rand properties",
),
(
"rand int x;",
"c.randomize() with { x == 1; }",
Expand Down Expand Up @@ -6678,3 +6682,19 @@ fn randomization_signatures_do_not_force_unused_interface_class_layouts() {
analyze_source(&source, Path::new("unused_interface_class.sv")).unwrap();
}
}

#[test]
fn class_randomize_rejects_unresolved_enum_domains() {
for members in ["A=3, B", "A=0, B=0", "A=2'bx, B=1"] {
let source = format!(
"module Top;
class C; rand enum bit [1:0] {{{members}}} value; endclass
C c; initial begin c = new; void'(c.randomize()); end
endmodule"
);
assert!(
analyze_source(&source, Path::new("enum_domain.sv")).is_err(),
"{members}"
);
}
}
13 changes: 13 additions & 0 deletions crates/celox-test-suite/LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,19 @@ Verilator 5.052 has two narrower exclusions, recorded in the
0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control,
inline member selection and pre-hook control cases pass Verilator.

Enum class randomization (`sv_icarus_enum_randomization`) excludes the four
`class::randomization_enum_*` cases from Icarus 13.0 because it cannot elaborate
class randomization methods. [Original diagnostics](verification/repros/sv_enum_randomization_icarus.json)
retain the failures without changing the shared assertions.

Verilator 5.052 passes the direct enum and inherited enum cases, but treats a
typedef alias of an enum as the underlying integer during randomization
(`sv_verilator_enum_alias_randomization`). The generated randomizer assigns raw
8-bit random values rather than selecting declared enum values, contrary to
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.

## SystemVerilog packed unions

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