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
55 changes: 46 additions & 9 deletions crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,10 @@ impl PackageBindings {
}
}

/// Reject a package variable that two flip-flop processes write, that the
/// initial writes of two instances write, or that a continuous driver and
/// any other process write. Instances of one module are separate drivers.
/// Reject a package variable that two flip-flop processes write, that a
/// continuous driver and any other process write, or that an `always_ff`,
/// `always_comb` or `always_latch` run as a process and any other process
/// write. Instances of one module are separate drivers.
/// Overlapping continuous drivers are rejected by the scheduler.
fn check_package_variable_drivers(
bindings: &PackageBindings,
Expand Down Expand Up @@ -455,6 +456,9 @@ fn check_package_variable_drivers(
// values, and initial processes. The package's own declaration
// initializers are not drivers.
let mut initial_writes: Vec<((InstanceId, usize), AbsoluteAddr, BitAccess)> = Vec::new();
// The writes of processes that must be the only writers of what they
// write (IEEE 1800-2023 9.2.2.2 to 9.2.2.4).
let mut restricted_writes: Vec<((InstanceId, usize), AbsoluteAddr, BitAccess)> = Vec::new();
for (&instance, module_id) in instance_modules {
let module = &modules[module_id];
if package_instances.contains_key(module_id) {
Expand Down Expand Up @@ -485,17 +489,34 @@ fn check_package_variable_drivers(
}
}
for (index, process) in module.processes.iter().enumerate() {
let restricted = matches!(
process.origin.construct.as_str(),
"always_ff" | "always_comb" | "always_latch"
);
for block in process.kernel.blocks.values() {
for instruction in &block.instructions {
let (SIRInstruction::Store(address, ..)
| SIRInstruction::Commit(_, address, ..)) = instruction
let (SIRInstruction::Store(address, offset, bits, ..)
| SIRInstruction::Commit(_, address, offset, bits, _)) = instruction
else {
continue;
};
let address = bindings.locate(instance, address.var_id);
if packages.contains(&address) {
let access = BitAccess::new(0, width(&address).saturating_sub(1));
// The bits the store writes, as for flip-flop
// writes, so disjoint writers are not rejected.
let access = offset
.constant_bit_offset()
.zip(bits.checked_sub(1))
.and_then(|(lsb, tail)| {
Some(BitAccess::new(lsb, lsb.checked_add(tail)?))
})
.unwrap_or_else(|| {
BitAccess::new(0, width(&address).saturating_sub(1))
});
initial_writes.push(((instance, index), address, access));
if restricted {
restricted_writes.push(((instance, index), address, access));
Comment on lines +517 to +518

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve written bit ranges in restricted-process checks

When a restricted runtime process and another writer in the same instance update disjoint slices of a package variable, the new check incorrectly rejects the design. For example, with p::q declared as logic [1:0], always_ff @(posedge clk) begin p::q[0] = d; $display("host"); end and initial p::q[1] = 0; pass the frontend's range-aware validation, but assembly records the runtime process as writing the entire variable and reports an overlap. Previously the assembly check did not reject initial/process writes within one instance. Retain the actual written ranges when collecting restricted writes so this new comparison does not reject disjoint writers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1cc98fe: a restricted process's write now covers the bits its instruction's offset and width give, as ff_writes already does, so disjoint slices written by a restricted process and another writer of the same instance are no longer rejected. Covered by restricted_processes_may_share_disjoint_package_slices.

Comment on lines +517 to +518

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve slice ranges when collecting restricted process writes

When an always_ff runs as a process because it contains a host request, adding its writes to restricted_writes reuses the full-variable range constructed above, so the new check rejects writes to disjoint slices. For example, within one module, initial p::q[7:4] = 0; alongside always_ff @(posedge clk) begin p::q[3:0] = d; $display("host"); end passes the frontend's range-aware validation but now fails assembly with a multiple-driver error. Previously, the assembly check allowed these writes within one instance. Derive the process write's range from the instruction offset and width, as the ff_writes collection already does, rather than treating every restricted write as covering the whole variable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1cc98fe: a restricted process's write now covers the bits its instruction's offset and width give, as ff_writes already does, so disjoint slices written by a restricted process and another writer of the same instance are no longer rejected. Covered by restricted_processes_may_share_disjoint_package_slices.

}
}
}
}
Expand All @@ -518,12 +539,28 @@ fn check_package_variable_drivers(
.then_some(*address)
})
};
// Two flip-flop processes, or initial writes of two instances, race.
// Two flip-flop processes race. Initial writes and processes of several
// instances may write one package variable, as any processes may write
// a variable (IEEE 1800-2023 6.5).
if let Some(address) = conflict(&ff_writes, &|left, right| left != right) {
return Err(error(&address));
}
if let Some(address) = conflict(&initial_writes, &|left, right| left.0 != right.0) {
return Err(error(&address));
// A restricted process overlaps every write of another process.
for (writer, address, access) in &restricted_writes {
let overlaps = |(other, other_address, other_access): &(
(InstanceId, usize),
AbsoluteAddr,
BitAccess,
)| {
other_address == address && other_access.overlaps(access) && other != writer
};
if initial_writes.iter().any(overlaps)
|| ff_writes.iter().any(|(_, other_address, other_access)| {
other_address == address && other_access.overlaps(access)
})
{
return Err(error(address));
}
}
// A continuous driver overlaps every other write.
for path in comb_blocks {
Expand Down
119 changes: 107 additions & 12 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1043,11 +1043,25 @@ fn validate_package_variable_drivers<'a>(
for root in roots {
count(root, 1, module_ids, modules, &mut instances);
}
// A driver is one process or child output of one instance; a process may
// assign the variable several times.
type Driver = (ModuleId, usize, bool, usize);
let mut drivers: HashMap<(String, String), Vec<(Driver, Option<(i128, i128)>)>> =
HashMap::default();
// A driver is one process, child output or initial block of one
// instance; a process may assign the variable several times.
#[derive(Clone, Copy, PartialEq)]
enum Source {
Process,
Child,
Initial,
}
type Driver = (ModuleId, usize, Source, usize);
struct Writer {
driver: Driver,
range: Option<(i128, i128)>,
/// Treated as the only writer of what it writes.
exclusive: bool,
/// The only writer the standard allows, which an initial block
/// must not write either.
restricted: bool,
}
let mut drivers: HashMap<(String, String), Vec<Writer>> = HashMap::default();
for (&module_id, module) in modules {
let multiplicity = instances.get(&module_id).copied().unwrap_or(0);
if module.package_variables.is_empty() {
Expand All @@ -1060,24 +1074,62 @@ fn validate_package_variable_drivers<'a>(
let name = &module.variables[var_id].path[0];
let local = module_drivers.local(name);
let children = child_output_driver_ranges(module, &child_drivers, name);
// One-shot initial blocks; repeating ones are among `local`.
let initial = module_drivers
.initial(name)
.into_iter()
.filter(|(driver, _)| !module.source.initial_processes()[*driver].repeats())
.collect::<Vec<_>>();
let entry = drivers
.entry((package.clone(), variable.clone()))
.or_default();
for copy in 0..multiplicity {
for &(driver, range) in &local {
entry.push(((module_id, copy, false, driver), range));
entry.push(Writer {
driver: (module_id, copy, Source::Process, driver),
range,
exclusive: exclusive_driver(&module.source, driver),
restricted: restricted_driver(&module.source, driver),
});
}
for &(driver, range) in &children {
entry.push(((module_id, copy, true, driver), range));
entry.push(Writer {
driver: (module_id, copy, Source::Child, driver),
range,
exclusive: true,
restricted: true,
});
}
for &(driver, range) in &initial {
entry.push(Writer {
driver: (module_id, copy, Source::Initial, driver),
range,
exclusive: false,
restricted: false,
});
}
}
}
}
for ((package, variable), ranges) in drivers {
let overlap = ranges.iter().enumerate().any(|(index, (driver, range))| {
ranges[index + 1..].iter().any(|(other, other_range)| {
other != driver && net_driver_ranges_overlap(*range, *other_range)
})
// Processes of several instances may write a package variable, as any
// processes may write a variable, unless one of them must be its only
// writer (IEEE 1800-2023 6.5, 9.2.2); an initial block conflicts only
// with a writer the standard restricts.
for ((package, variable), writers) in drivers {
let conflict = |left: &Writer, right: &Writer| {
let initial = left.driver.2 == Source::Initial || right.driver.2 == Source::Initial;
left.driver != right.driver
&& if initial {
left.restricted || right.restricted
} else {
left.exclusive || right.exclusive
}
&& net_driver_ranges_overlap(left.range, right.range)
};
let overlap = writers.iter().enumerate().any(|(index, left)| {
writers[index + 1..]
.iter()
.any(|right| conflict(left, right))
});
if overlap {
return Err(sv::AnalyzerError::Unsupported(format!(
Expand Down Expand Up @@ -1803,6 +1855,49 @@ impl ModuleDrivers {
}
}

/// Whether process `driver` of [`ModuleDrivers::local`] must be the only writer of
/// the variables it writes: an `always_comb` or continuous assignment, an
/// edge procedure, or an `always_ff` run as a process, but not another
/// ordinary `always` process (IEEE 1800-2023 6.5, 9.2.2).
fn exclusive_driver(module: &sv::ir::Module, driver: usize) -> bool {
let edge = module.comb_processes().len() + module.ff_processes().len();
driver < edge || {
let process = module
.initial_processes()
.iter()
.filter(|process| process.repeats())
.nth(driver - edge);
process.is_some_and(|process| {
process.is_scheduled_edge()
|| process
.site()
.is_some_and(|site| site.construct == "always_ff")
})
}
}

/// Whether process `driver` of [`ModuleDrivers::local`] is one the standard lets
/// no other process write to the variables it writes: `always_comb`,
/// `always_latch`, `always_ff` or a continuous assignment (IEEE 1800-2023
/// 6.5, 9.2.2).
fn restricted_driver(module: &sv::ir::Module, driver: usize) -> bool {
let combinational = module.comb_processes().len();
let edge = combinational + module.ff_processes().len();
if let Some(process) = module.comb_processes().get(driver) {
return process.kind() != sv::ir::CombProcessKind::AlwaysStar;
}
if driver < edge {
return module.ff_processes()[driver - combinational].is_always_ff();
}
module
.initial_processes()
.iter()
.filter(|process| process.repeats())
.nth(driver - edge)
.and_then(|process| process.site())
.is_some_and(|site| matches!(site.construct, "always_ff" | "always_comb" | "always_latch"))
}

fn net_lvalue_range(
lvalue: &sv::ir::LValue,
constants: &HashMap<String, i128>,
Expand Down
60 changes: 35 additions & 25 deletions crates/celox/tests/frontends/systemverilog/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,31 +580,19 @@ fn classes_of_packages_in_other_sources_are_used_through_their_layouts() {
}

#[test]
fn misused_classes_of_other_scopes_are_rejected() {
for (source, want) in [
(
"package p; class Box #(int N = 2); endclass endpackage
module Top; import p::*; Box #(3) box; endmodule",
"specialization of parameterized class `p::Box` outside the scope that declares it",
),
// A package variable has one writing instance (#1146), static
// properties of package classes too.
(
"package p; class C; static int n; function new(); n++; endfunction endclass endpackage
module W; p::C c; initial c = new; endmodule
module Top; W a(); W b(); endmodule",
"multiple drivers of package",
),
] {
let Err(error) =
celox::Simulation::from_sv_sources(vec![(source, Path::new("class.sv"))], "Top")
.build()
else {
panic!("`{source}` is rejected");
};
let error = error.to_string();
assert!(error.contains(want), "{error}");
}
fn specializations_of_classes_of_other_scopes_are_rejected() {
let source = "package p; class Box #(int N = 2); endclass endpackage
module Top; import p::*; Box #(3) box; endmodule";
let Err(error) =
celox::Simulation::from_sv_sources(vec![(source, Path::new("class.sv"))], "Top").build()
else {
panic!("`{source}` is rejected");
};
let error = error.to_string();
assert!(
error.contains("outside the scope that declares it"),
"{error}"
);
}

#[test]
Expand All @@ -618,6 +606,28 @@ fn a_class_of_another_module_does_not_hide_a_package() {
assert_eq!(sim.get(sim.signal("bits")), 3u32.into());
}

#[test]
fn processes_of_several_instances_share_the_static_properties_of_a_package_class() {
let source = "`timescale 1ns/1ns
package p;
class C;
static int made;
function new(); made++; endfunction
endclass
endpackage
module W; p::C c; initial c = new; endmodule
module Top(output int made);
W first();
W second();
initial #1 made = p::C::made;
endmodule";
let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("class.sv"))], "Top")
.build()
.unwrap();
sim.run_until(1).unwrap();
assert_eq!(sim.get(sim.signal("made")), 2u32.into());
}

#[test]
fn type_arguments_keep_their_dimensions_scopes_and_class_scoped_types() {
let source = "module Top(output int defs, output int narrow, output int wide);
Expand Down
20 changes: 12 additions & 8 deletions crates/celox/tests/frontends/systemverilog/review_regressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8729,9 +8729,12 @@ fn timed_task_edge_drivers_are_checked_against_child_outputs() {
}

#[test]
fn timed_task_edge_drivers_of_package_variables_are_checked_across_instances() {
let error = cranelift_build_error(
r#"
fn timed_task_edge_processes_of_several_instances_may_write_a_package_variable() {
// `always` processes, unlike `always_ff`, may share their variables
// (IEEE 1800-2023 6.5, 9.2.2.4).
celox::Simulation::from_sv_sources(
vec![(
r#"
package p; bit q; endpackage
module Child(input bit clk);
task automatic pause; #1; endtask
Expand All @@ -8741,11 +8744,12 @@ fn timed_task_edge_drivers_of_package_variables_are_checked_across_instances() {
Child first(clk), second(clk);
endmodule
"#,
);
assert!(
error.contains("multiple drivers of package variable `p::q`"),
"{error}"
);
Path::new("timed_task_package_writers.sv"),
)],
"Top",
)
.build()
.unwrap_or_else(|error| panic!("{error}"));
}

mod aggregate_regressions {
Expand Down
Loading
Loading