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
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
48 changes: 46 additions & 2 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ pub(crate) struct LoweredSvPortConnection {
pub formal: String,
pub actual: String,
pub actual_expr: Option<sv::ir::Expr>,
pub bound_pattern: Option<sv::ast::BoundPattern>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -3180,6 +3181,7 @@ fn lower_module_with_overrides(
formal: connection.formal().to_string(),
actual: connection.actual().to_string(),
actual_expr: connection.actual_expr().cloned(),
bound_pattern: connection.bound_pattern().cloned(),
})
.collect(),
array_element,
Expand Down Expand Up @@ -3454,6 +3456,7 @@ fn array_element_connections(
return Ok(LoweredSvPortConnection {
formal: connection.formal.clone(),
actual: connection.actual.clone(),
bound_pattern: None,
actual_expr: Some(sv::ir::Expr::Select {
expr: Box::new(actual_expr.clone()),
msb: sv::ir::ConstExpr::Literal((lsb + port_width - 1).to_string()),
Expand Down Expand Up @@ -3489,11 +3492,50 @@ fn array_element_connections(
formal: connection.formal.clone(),
actual: connection.actual.clone(),
actual_expr: Some(slice),
bound_pattern: None,
})
})
.collect()
}

fn bind_port_patterns(
connections: &mut [LoweredSvPortConnection],
child: &LoweredSvModule,
) -> Result<(), ParserError> {
for connection in connections {
let Some(pattern) = connection.bound_pattern.take() else {
continue;
};
let port = child
.source
.ports()
.iter()
.find(|port| port.name() == connection.formal)
.ok_or_else(|| {
ParserError::illegal_context(
"systemverilog port assignment pattern",
format!("unknown port `{}`", connection.formal),
None,
)
})?;
if port.direction() != sv::ir::PortDirection::Input {
return Err(ParserError::illegal_context(
"systemverilog port assignment pattern",
"only input port assignment patterns are supported",
None,
));
}
connection.actual_expr = Some(port.bind_pattern(&pattern).map_err(|error| {
ParserError::illegal_context(
"systemverilog port assignment pattern",
error.to_string(),
None,
)
})?);
}
Ok(())
}

pub(crate) fn attach_instance_glue(
module: &mut SimModule,
lowered: &LoweredSvModule,
Expand Down Expand Up @@ -3525,6 +3567,8 @@ pub(crate) fn attach_instance_glue(
let Some(child) = lowered_modules.get(&child_id) else {
return Err(unsupported_sv_instance(instance.module_name.clone()));
};
let mut authored_connections = instance.port_connections.clone();
bind_port_patterns(&mut authored_connections, child)?;
let connections = match instance.array_element {
Some((position, count)) => {
module
Expand All @@ -3536,7 +3580,7 @@ pub(crate) fn attach_instance_glue(
.insert(instance.instance_name.clone(), instance.array_index_base);
}
array_element_connections(
&instance.port_connections,
&authored_connections,
child,
position,
count,
Expand All @@ -3546,7 +3590,7 @@ pub(crate) fn attach_instance_glue(
&lowered.parameter_types,
)?
}
None => instance.port_connections.clone(),
None => authored_connections,
};
ensure_parent_output_signals(
module,
Expand Down
7 changes: 7 additions & 0 deletions crates/celox-runtime/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,13 @@ pub trait SimBackend {
/// The heap, for changes made while no compiled code runs.
fn heap_mut(&mut self) -> &mut celox_heap::Heap;

/// Whether a compiled scheduler's unit runs time slots for less than
/// the runtime's loop does. An interpreter executes the unit slower
/// than the loop's native bookkeeping.
fn runs_compiled_scheduler(&self) -> bool {
true
}

// ── event enumeration ───────────────────────────────────────
fn id_to_addr_slice(&self) -> &[AbsoluteAddr];
fn id_to_event_slice(&self) -> &[Self::Event];
Expand Down
Loading
Loading