Skip to content
Closed
4 changes: 2 additions & 2 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1607,8 +1607,8 @@ chapter-9/9.4.1--delay_control-two-blocks-sim.sv 2state pass
chapter-9/9.4.1--delay_control-two-blocks-sim.sv 4state pass
chapter-9/9.4.1--delay_control.sv 2state pass
chapter-9/9.4.1--delay_control.sv 4state pass
chapter-9/9.4.2--event_control_edge.sv 2state fail
chapter-9/9.4.2--event_control_edge.sv 4state fail
chapter-9/9.4.2--event_control_edge.sv 2state pass
chapter-9/9.4.2--event_control_edge.sv 4state pass
chapter-9/9.4.2--event_control_negedge.sv 2state pass
chapter-9/9.4.2--event_control_negedge.sv 4state pass
chapter-9/9.4.2--event_control_posedge.sv 2state pass
Expand Down
136 changes: 136 additions & 0 deletions crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,141 @@ pub struct RuntimeSchema<A> {
/// most one per module instance. Before each round a timed scheduler
/// stores the current time into each, as [`TIME_SLOT_WIDTH`] bits.
pub time_slots: Vec<A>,
/// The state a compiled scheduler exchanges with the runtime, and the
/// scheduler itself once one is generated. Present when the design has
/// process kernels.
pub scheduler: Option<SchedulerSchema<A>>,
}

/// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`],
/// [`SchedulerSlots::exit_arg`], [`SchedulerSlots::count`],
/// [`SchedulerSlots::current`], [`SchedulerSlots::levels`] and every [`SchedulerSlots::wake`] object.
pub const SCHEDULER_TIME_WIDTH: usize = 64;
/// Width of [`SchedulerSlots::exit`], [`SchedulerSlots::finish`],
/// [`SchedulerSlots::cont`] and every [`SchedulerSlots::waiting`] object.
pub const SCHEDULER_FLAG_WIDTH: usize = 8;

/// Hidden state objects through which a compiled scheduler and the runtime
/// exchange a run of time slots. Between runs they hold no state: the
/// runtime's scheduling state is the source of truth, so state files leave
/// them out.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SchedulerSlots<A> {
/// The last time the run may reach.
pub limit: A,
/// The time of the last slot the run reached.
pub now: A,
/// Why the run returned, a [`SchedulerExit`] code.
pub exit: A,
/// The process an exit concerns.
pub exit_arg: A,
/// Set when a `$finish` record was emitted in the unit just run.
pub finish: A,
/// Where a shared combinational settle continues.
pub cont: A,
/// The number of time slots the run ran.
pub count: A,
/// The kernel running when the run returned, `u64::MAX` for none.
pub current: A,
/// The levels of the event signals at the start of the last slot, one
/// bit per event in event order.
pub levels: A,
/// The time each process kernel resumes at, in kernel order, valid
/// where [`Self::waiting`] is set.
pub wake: Vec<A>,
/// Whether each process kernel waits for its wake time.
pub waiting: Vec<A>,
}

impl<A> SchedulerSlots<A> {
pub fn map<B>(self, mut map: impl FnMut(A) -> B) -> SchedulerSlots<B> {
SchedulerSlots {
limit: map(self.limit),
now: map(self.now),
exit: map(self.exit),
exit_arg: map(self.exit_arg),
finish: map(self.finish),
cont: map(self.cont),
count: map(self.count),
current: map(self.current),
levels: map(self.levels),
wake: self.wake.into_iter().map(&mut map).collect(),
waiting: self.waiting.into_iter().map(map).collect(),
}
}

/// Every slot.
pub fn iter(&self) -> impl Iterator<Item = &A> {
[
&self.limit,
&self.now,
&self.exit,
&self.exit_arg,
&self.finish,
&self.cont,
&self.count,
&self.current,
&self.levels,
]
.into_iter()
.chain(&self.wake)
.chain(&self.waiting)
}
}

/// Why a run of the compiled scheduler returned.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[repr(u8)]
pub enum SchedulerExit {
/// The next time slot is after the limit.
Limit = 0,
/// A process or a `$finish` record finished the simulation.
Finish = 1,
/// The delay of process [`SchedulerSlots::exit_arg`] overflows the
/// simulation time.
DelayOverflow = 2,
/// A process suspended in a way the scheduler does not compile.
Internal = 3,
}

impl SchedulerExit {
pub const fn from_code(code: u8) -> Option<Self> {
match code {
0 => Some(Self::Limit),
1 => Some(Self::Finish),
2 => Some(Self::DelayOverflow),
3 => Some(Self::Internal),
_ => None,
}
}
}

/// A design's compiled scheduler: the process unit that runs time slots of
/// the kernels it compiles, and its slots.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SchedulerSchema<A> {
pub slots: SchedulerSlots<A>,
/// The index of the scheduler unit among the process units, after the
/// kernels; `None` when no scheduler was generated.
pub unit: Option<usize>,
/// Per process kernel, why the scheduler does not run it, or `None` when
/// it does.
pub fallback: Vec<Option<String>>,
/// The event signals the scheduler's kernels write, in the order of
/// the bits of [`SchedulerSlots::levels`].
pub events: Vec<A>,
}

impl<A> SchedulerSchema<A> {
pub fn map<B>(self, map: impl FnMut(A) -> B) -> SchedulerSchema<B> {
let mut map = map;
SchedulerSchema {
slots: self.slots.map(&mut map),
unit: self.unit,
fallback: self.fallback,
events: self.events.into_iter().map(map).collect(),
}
}
}

/// Width of every [`RuntimeSchema::time_slots`] object.
Expand Down Expand Up @@ -869,6 +1004,7 @@ impl<A> Default for RuntimeSchema<A> {
host_request_sites: Vec::new(),
active_commits: Vec::new(),
time_slots: Vec::new(),
scheduler: None,
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-design/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub struct ScheduleModel<A> {
/// Objects the scheduler stores the current time into
/// ([`RuntimeSchema::time_slots`]).
pub time_slots: Vec<A>,
/// The compiled scheduler, if one was generated
/// ([`RuntimeSchema::scheduler`]).
pub scheduler: Option<crate::SchedulerSchema<A>>,
}

/// A counted signal and the canonical domains its counters trigger.
Expand Down Expand Up @@ -142,6 +145,7 @@ impl<A: Copy + Eq + std::hash::Hash> ScheduleModel<A> {
.any(|site| matches!(site.kind, RuntimeEventKind::Finish)),
active_commits: schema.active_commits.clone(),
time_slots: schema.time_slots.clone(),
scheduler: schema.scheduler.clone(),
}
}

Expand Down
78 changes: 77 additions & 1 deletion crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
.expect("source program identity exhausted").to_string())
.entered();
let SymbolicRtl {
modules,
mut modules,
module_names,
root_id,
packages,
Expand Down Expand Up @@ -645,6 +645,11 @@ pub fn schedule_symbolic_rtl_reporting_loops(

let (mut expanded, mut instance_modules, indexed_instances) =
timed_sub!("expand_hierarchy", expand_hierarchy(&root_id, &modules));
let process_count = instance_modules
.values()
.map(|module| modules[module].processes.len())
.sum();
let scheduler_slots = declare_scheduler_slots(&mut modules, root_id, process_count);
// Each package with variables is one instance outside the hierarchy,
// named by a path segment no instance name can take.
let mut package_instances = HashMap::default();
Expand Down Expand Up @@ -1971,6 +1976,18 @@ pub fn schedule_symbolic_rtl_reporting_loops(
.collect();
let active_commits: Vec<StateAddr> = active_commits.into_iter().map(project).collect();
let time_slots: Vec<StateAddr> = time_slots.into_iter().map(project).collect();
let root_instance = expanded[&InstancePath(Vec::new())];
let scheduler = scheduler_slots.map(|slots| celox_design::SchedulerSchema {
slots: slots.map(|var_id| {
project(AbsoluteAddr {
instance_id: root_instance,
var_id,
})
}),
unit: None,
fallback: Vec::new(),
events: Vec::new(),
});
// The runtime reads counters, the signals waits watch and staged
// nonblocking values directly; no unit loads a wait's signal.
let mut timing_read_roots: HashSet<StateAddr> = watches
Expand Down Expand Up @@ -2072,6 +2089,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
host_request_sites,
active_commits,
time_slots,
scheduler,
},
};

Expand All @@ -2089,6 +2107,64 @@ pub fn schedule_symbolic_rtl_reporting_loops(
})
}

/// Declare the hidden objects a compiled scheduler exchanges with the
/// runtime (`RuntimeSchema::scheduler`) as variables of the top module,
/// when the design has `process_count` process kernels.
fn declare_scheduler_slots(
modules: &mut HashMap<ModuleId, SimModule>,
root: ModuleId,
process_count: usize,
) -> Option<celox_design::SchedulerSlots<SourceVarId>> {
if process_count == 0 {
return None;
}
let variables = &mut modules.get_mut(&root)?.variables;
let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0);
let mut declare = |name: String, width: usize| {
let id = SourceVarId(next);
next += 1;
variables.insert(
id,
crate::symbolic::artifact::SymbolicVariable {
path: vec!["$scheduler".to_string(), name],
kind: crate::VariableKind::Variable,
signed: false,
metadata: VariableMetadata {
width,
is_4state: false,
kind: DomainKind::Other,
type_kind: celox_design::PortTypeKind::Bit,
array_dims: Vec::new(),
value_kind: Default::default(),
},
packed_dims: vec![width],
unpacked_ranges: Vec::new(),
source: None,
module_affiliated: false,
},
);
id
};
use celox_design::{SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME};
Some(celox_design::SchedulerSlots {
limit: declare("limit".into(), TIME),
now: declare("now".into(), TIME),
exit: declare("exit".into(), FLAG),
exit_arg: declare("exit_arg".into(), TIME),
finish: declare("finish".into(), FLAG),
cont: declare("cont".into(), FLAG),
count: declare("count".into(), TIME),
current: declare("current".into(), TIME),
levels: declare("levels".into(), TIME),
wake: (0..process_count)
.map(|index| declare(format!("wake[{index}]"), TIME))
.collect(),
waiting: (0..process_count)
.map(|index| declare(format!("waiting[{index}]"), FLAG))
.collect(),
})
}

fn module_variables(
modules: &HashMap<ModuleId, SimModule>,
) -> (
Expand Down
74 changes: 59 additions & 15 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2712,6 +2712,31 @@ fn lower_module_with_overrides(
force_signals: &[String],
level_lists: LevelLists<'_>,
) -> Result<LoweredSvModule, sv::AnalyzerError> {
let parameter_types = module
.imported_parameters()
.iter()
.chain(module.parameters())
.filter_map(|parameter| {
Some((
parameter.name().to_string(),
(
parameter.resolved_width()?,
parameter.resolved_signed().unwrap_or(false),
),
))
})
.collect();
let constants = module_constants_with_overrides(module, parameter_overrides);
let fallbacks = module
.ff_processes()
.iter()
.any(|process| runs_as_process(module, process, &constants, &parameter_types))
.then(|| {
module.clone().run_edge_processes_as_processes(|process| {
runs_as_process(module, process, &constants, &parameter_types)
})
});
let module = fallbacks.as_ref().unwrap_or(module);
let mut ff_event_roles = Vec::new();
for process in module.ff_processes() {
let clock = clock_event_from_ff_process(process)
Expand All @@ -2734,21 +2759,6 @@ fn lower_module_with_overrides(
});
}
}
let parameter_types = module
.imported_parameters()
.iter()
.chain(module.parameters())
.filter_map(|parameter| {
Some((
parameter.name().to_string(),
(
parameter.resolved_width()?,
parameter.resolved_signed().unwrap_or(false),
),
))
})
.collect();
let constants = module_constants_with_overrides(module, parameter_overrides);
let shared_memories = shared_edge_memories(module, &constants, &parameter_types, warnings);
validate_variable_driver_ranges(module, &constants, &parameter_types, &shared_memories)?;
let scheduled = module
Expand Down Expand Up @@ -8482,6 +8492,40 @@ fn insert_or_merge_ff_unit(
}
}

/// A plain `always` sensitive to edges is a flip-flop only in the shape of
/// one: a clock and asynchronous resets, each a one-bit variable. Any other
/// edge-sensitive `always` runs as a process waiting on the same events.
fn runs_as_process(
module: &sv::ir::Module,
process: &sv::ir::FfProcess,
constants: &HashMap<String, i128>,
parameter_types: &HashMap<String, (usize, bool)>,
) -> bool {
let multi_bit = |name: &str| {
let r#type = module
.ports()
.iter()
.find(|port| port.name() == name)
.map(sv::ir::Port::r#type)
.or_else(|| {
module
.signals()
.iter()
.find(|signal| signal.name() == name)
.map(sv::ir::Signal::r#type)
});
r#type
.and_then(|r#type| signal_type_from_sv(r#type, constants, parameter_types).ok())
.is_some_and(|type_info| type_info.width != 1)
};
!process.is_always_ff()
&& (clock_event_from_ff_process(process).is_none()
|| process
.events()
.iter()
.any(|event| multi_bit(event.signal())))
}

fn clock_event_from_ff_process(process: &sv::ir::FfProcess) -> Option<&sv::ir::FfEvent> {
let clock = process.events().first()?;
if process.events().len() == 1 {
Expand Down
Loading
Loading