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
29 changes: 18 additions & 11 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ use std::path::Path;

use celox_design::{
BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType,
InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH,
PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind,
RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, WaitSite,
InitialStateData, InitialStateValue, ModuleId, NbaSite, PROCESS_DELAY_WIDTH,
PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo,
RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase,
WORKING_REGION, WaitSite,
};
use celox_frontend_core::process::PROCESS_RESUME_WIDTH;
use celox_frontend_core::symbolic::artifact::{
Expand Down Expand Up @@ -1984,7 +1985,7 @@ fn lower_module_with_overrides(
)
};
mark_ff_event_domains(&event_vars, &mut variables);
let (initial_values, processes, wait_sites) = lower_initial_processes(
let (initial_values, processes, wait_sites, nba_sites) = lower_initial_processes(
module,
&mut variables,
&mut name_to_id,
Expand Down Expand Up @@ -2093,7 +2094,7 @@ fn lower_module_with_overrides(
package_bindings: HashMap::default(),
counter_slots: Vec::new(),
wait_sites,
nba_sites: Vec::new(),
nba_sites,
},
variables,
port_order,
Expand Down Expand Up @@ -2755,11 +2756,12 @@ fn lower_initial_processes(
Vec<InitialStateValue<SourceVarId>>,
Vec<SymbolicProcess>,
Vec<WaitSite<SourceVarId>>,
Vec<NbaSite<SourceVarId>>,
),
sv::AnalyzerError,
> {
if module.initial_processes().is_empty() {
return Ok((Vec::new(), Vec::new(), Vec::new()));
return Ok((Vec::new(), Vec::new(), Vec::new(), Vec::new()));
}
let mut values = Vec::new();
let mut runtime = Vec::new();
Expand Down Expand Up @@ -2813,7 +2815,7 @@ fn lower_initial_processes(
}
}
if runtime.is_empty() {
return Ok((values, Vec::new(), Vec::new()));
return Ok((values, Vec::new(), Vec::new(), Vec::new()));
}

let mut next_id = SourceVarId(
Expand Down Expand Up @@ -2868,24 +2870,29 @@ fn lower_initial_processes(
pm.runtime_errors = std::mem::take(runtime_errors);
pm.extern_functions = std::mem::take(extern_functions);
let mut wait_sites = Vec::new();
let mut nba_sites = Vec::new();
let processes = runtime
.into_iter()
.zip(slots)
.enumerate()
.map(|(index, ((process, random_seed), slots))| {
let (kernel, sites) = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel(
let kernel = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel(
process.body(),
slots,
index,
)?;
wait_sites.extend(sites);
Ok(SymbolicProcess { kernel, slots })
wait_sites.extend(kernel.wait_sites);
nba_sites.extend(kernel.nba_sites);
Ok(SymbolicProcess {
kernel: kernel.unit,
slots,
})
})
.collect::<Result<Vec<_>, sv::AnalyzerError>>();
*runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites);
*runtime_errors = std::mem::take(&mut pm.runtime_errors);
*extern_functions = std::mem::take(&mut pm.extern_functions);
Ok((values, processes?, wait_sites))
Ok((values, processes?, wait_sites, nba_sites))
}

fn lower_comb_processes(
Expand Down
172 changes: 147 additions & 25 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

use super::procedural::*;
use super::*;
use celox_design::{CounterKind, WaitSite};
use celox_design::{CounterKind, NbaSite, WaitSite};
use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError};
use celox_sir::{RegisterId, RegisterType};
use celox_slt::SLTToSIRLowerer;
Expand Down Expand Up @@ -64,6 +64,8 @@ pub(super) struct Ff<'p, 'a> {
process: usize,
/// The wait sites of the process, by local index.
wait_sites: Vec<WaitSite<SourceVarId>>,
/// The nonblocking assignment sites of the process, by local index.
nba_sites: Vec<NbaSite<SourceVarId>>,
direct: bool,
}

Expand Down Expand Up @@ -111,6 +113,7 @@ impl<'p, 'a> Ff<'p, 'a> {
direct: false,
process: 0,
wait_sites: Vec::new(),
nba_sites: Vec::new(),
}
}

Expand Down Expand Up @@ -1815,6 +1818,22 @@ impl<'p, 'a> Ff<'p, 'a> {

fn exec(&mut self, stmt: &sv::ir::Stmt) -> Result<bool, sv::AnalyzerError> {
match stmt {
sv::ir::Stmt::Assign {
lhs,
rhs,
nonblocking: true,
} if self.kernel.is_some() => {
self.nonblocking(std::slice::from_ref(lhs), rhs)?;
Ok(true)
}
sv::ir::Stmt::AssignConcat {
parts,
rhs,
nonblocking: true,
} if self.kernel.is_some() => {
self.nonblocking(parts, rhs)?;
Ok(true)
}
sv::ir::Stmt::Assign { lhs, rhs, .. } => {
self.assign(lhs, rhs)?;
Ok(true)
Expand Down Expand Up @@ -3172,30 +3191,8 @@ impl Ff<'_, '_> {
body: &[sv::ir::Stmt],
slots: ProcessSlots<SourceVarId>,
process: usize,
) -> Result<(ExecutionUnit<Addr>, Vec<WaitSite<SourceVarId>>), sv::AnalyzerError> {
) -> Result<KernelUnit, sv::AnalyzerError> {
self.process = process;
// A nonblocking update would take effect in a later region of the
// time step, after the process has run on.
for stmt in body {
let mut nonblocking = false;
stmt.walk(&mut |stmt| {
nonblocking |= matches!(
stmt,
sv::ir::Stmt::Assign {
nonblocking: true,
..
} | sv::ir::Stmt::AssignConcat {
nonblocking: true,
..
}
);
});
if nonblocking {
return Err(unsupported(
"nonblocking assignment in an initial block that runs as a process",
));
}
}
let mut kernel = ProcessKernelBuilder::new(slots);
std::mem::swap(&mut self.b, kernel.builder());
self.kernel = Some(kernel);
Expand All @@ -3204,7 +3201,125 @@ impl Ff<'_, '_> {
std::mem::swap(&mut self.b, kernel.builder());
let mut unit = kernel.build();
prune_unreachable_blocks(&mut unit);
Ok((unit, self.wait_sites))
Ok(KernelUnit {
unit,
wait_sites: self.wait_sites,
nba_sites: self.nba_sites,
})
}

/// A nonblocking assignment in a process (IEEE 1800-2023 10.4.2): the
/// right-hand side is evaluated now, once, and each target part becomes
/// an update the runtime queues for the NBA region.
fn nonblocking(
&mut self,
parts: &[sv::ir::LValue],
rhs: &sv::ir::Expr,
) -> Result<(), sv::AnalyzerError> {
let mut targets = Vec::with_capacity(parts.len());
for part in parts {
targets.push(self.nba_target(part)?);
}
let total: usize = targets.iter().map(|(_, _, width)| width).sum();
let four_state = targets.iter().any(|(id, _, _)| self.m.var(*id).is_4state);
let (_, value_name) = self.m.temp("nba", total, false, four_state);
self.assign(&sv::ir::LValue::Ident(value_name.clone()), rhs)?;
// The parts, most significant first, take consecutive bits of the
// value.
let mut high = total;
for (id, lsb, width) in targets {
let low = high - width;
let (staged, staged_name) =
self.m
.temp("nba_part", width, false, self.m.var(id).is_4state);
self.assign(
&sv::ir::LValue::Ident(staged_name),
&sv::ir::Expr::Select {
expr: Box::new(sv::ir::Expr::Ident(value_name.clone())),
msb: sv::ir::ConstExpr::Literal((high - 1).to_string()),
lsb: sv::ir::ConstExpr::Literal(low.to_string()),
signed: false,
},
)?;
high = low;
let site = NbaSite {
process: self.process,
target: id,
lsb,
width,
value: staged,
offset: None,
pending: None,
};
let index = self.nba_sites.len() as u32;
let staged_four_state = self.m.var(staged).is_4state;
self.with_kernel(|kernel| {
kernel.nonblocking(index, &site, |builder| {
let value = if staged_four_state {
builder.alloc_logic(width)
} else {
builder.alloc_bit(width, false)
};
builder.emit(SIRInstruction::Load(
value,
stable(staged),
SIROffset::Static(0),
width,
));
Ok::<_, ProcessKernelError>((value, None))
})
})
.map_err(kernel_error)?;
self.nba_sites.push(site);
}
Ok(())
}

/// The variable and the constant bit range a nonblocking assignment in
/// a process writes.
fn nba_target(
&self,
lvalue: &sv::ir::LValue,
) -> Result<(SourceVarId, usize, usize), sv::AnalyzerError> {
let id = self
.m
.id(lvalue.name())
.ok_or_else(|| unsupported(format!("assignment target `{}`", lvalue.name())))?;
let variable = self.m.var(id);
if !variable.array_dims.is_empty() {
return Err(unsupported(
"nonblocking assignment to an unpacked array in a process",
));
}
match lvalue {
sv::ir::LValue::Ident(_) => Ok((id, 0, variable.width)),
sv::ir::LValue::Select { msb, lsb, .. } => {
let constant = |expr| {
sv::typecheck::eval_const_expr_with_types(
expr,
self.m.constants,
self.m.parameter_types,
)
};
let (Some(msb), Some(lsb)) = (constant(msb), constant(lsb)) else {
return Err(unsupported(
"nonblocking assignment with a run-time position in a process",
));
};
let (Some(msb), Some(lsb)) = (
packed_index_offset(variable, msb),
packed_index_offset(variable, lsb),
) else {
return Err(unsupported("nonblocking assignment outside its target"));
};
if msb < lsb {
return Err(unsupported(
"nonblocking assignment to a reversed part select in a process",
));
}
Ok((id, lsb, msb - lsb + 1))
}
}
}

/// `#amount` (IEEE 1800-2023 9.4.1). The amount is self-determined and
Expand Down Expand Up @@ -3401,6 +3516,13 @@ impl Ff<'_, '_> {
}
}

/// The kernel of a process and its wait and nonblocking assignment sites.
pub(super) struct KernelUnit {
pub unit: ExecutionUnit<Addr>,
pub wait_sites: Vec<WaitSite<SourceVarId>>,
pub nba_sites: Vec<NbaSite<SourceVarId>>,
}

/// Iterations, as a power of two, between the yields of a kernel loop that
/// may not suspend.
const LOOP_YIELD_BITS: usize = 16;
Expand Down
44 changes: 27 additions & 17 deletions crates/celox-frontend-veryl/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,30 +49,42 @@ pub fn external_signatures_named(
use veryl_analyzer::ir::Component;

// Veryl children link through the IR, but the SV modules beneath them
// still have to be prepared by the SV frontend.
fn sv_descendants(
module: &veryl_analyzer::ir::Module,
names: &mut Vec<String>,
seen: &mut crate::HashSet<StrId>,
) {
// still have to be prepared by the SV frontend. Instances of one analyzed
// body share it, so each body is visited once across all exported roots.
// Bodies are keyed by address: equal signatures can still differ in the
// aliases of their SV children.
type Memo = HashMap<*const veryl_analyzer::ir::Module, std::rc::Rc<Vec<StrId>>>;
fn sv_descendants(module: &veryl_analyzer::ir::Module, memo: &mut Memo) -> Vec<StrId> {
let mut names = Vec::new();
let mut seen = crate::HashSet::default();
for declaration in &module.declarations {
let veryl_analyzer::ir::Declaration::Inst(instance) = declaration else {
continue;
};
match instance.component.as_ref() {
Component::SystemVerilog(child) => {
if seen.insert(child.name) {
names.push(
veryl_parser::resource_table::get_str_value(child.name)
.unwrap_or_default(),
);
names.push(child.name);
}
}
Component::Module(child) => sv_descendants(child, names, seen),
Component::Module(child) => {
let key: *const _ = child;
let nested = match memo.get(&key) {
Some(nested) => nested.clone(),
None => {
let nested = std::rc::Rc::new(sv_descendants(child, memo));
memo.insert(key, nested.clone());
nested
}
};
names.extend(nested.iter().filter(|&&name| seen.insert(name)));
}
Component::Interface(_) => {}
}
}
names
}
let mut memo = Memo::default();

let mut external = ExternalHierarchy::default();
for component in &ir.components {
Expand Down Expand Up @@ -113,12 +125,10 @@ pub fn external_signatures_named(
let (mut sim_module, _) =
project_module_with_ids(&empty, module, config, ids, &HashMap::default())?;
sim_module.name = name(module);
let mut unresolved_instances = Vec::new();
sv_descendants(
module,
&mut unresolved_instances,
&mut crate::HashSet::default(),
);
let unresolved_instances = sv_descendants(module, &mut memo)
.into_iter()
.map(|name| veryl_parser::resource_table::get_str_value(name).unwrap_or_default())
.collect();
let id = celox_design::ModuleId(external.modules.len());
external.roots.insert(sim_module.name.clone(), id);
external.modules.insert(
Expand Down
Loading
Loading