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
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ GCC-style optimization level presets with per-pass overrides.
| `PartialForward` | Partial store-load forwarding in combinational blocks |
| `IdentityStoreBypass` | Detects identity copies and registers address aliases |
| `TailCallSplit` | Splits large functions into tail-call chains (enabled even at O0) |
| `DerivedEdgeUnits` | Runs edges of gated/divided clocks in generated units instead of the Rust plan walk (not a SIR transform; costs build time, `-sir:derived_edge_units` to opt out) |

### Cranelift Backend Optimization

Expand Down
17 changes: 17 additions & 0 deletions crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,22 @@ pub struct RuntimeSchema<A> {
/// scheduler itself once one is generated. Present when the design has
/// process kernels.
pub scheduler: Option<SchedulerSchema<A>>,
/// Generated units that run an edge of an event with every derived
/// clock domain it reaches, for the events that have them.
pub derived_edges: Vec<DerivedEdgeUnits<A>>,
}

/// The process units that run the edges of one event together with its
/// derived clock domains, the signal having already moved. Each reads
/// [`SchedulerSlots::dirty`] to know whether combinational logic must
/// settle before the domains evaluate.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DerivedEdgeUnits<A> {
/// The canonical event.
pub event: A,
/// Indices among the process units of the rising and the falling edge.
pub rising: usize,
pub falling: usize,
}

/// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`],
Expand Down Expand Up @@ -1084,6 +1100,7 @@ impl<A> Default for RuntimeSchema<A> {
active_commits: Vec::new(),
time_slots: Vec::new(),
scheduler: None,
derived_edges: Vec::new(),
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2201,6 +2201,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
active_commits,
time_slots,
scheduler,
derived_edges: Vec::new(),
},
};

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 @@ -151,6 +151,13 @@ pub trait SimBackend {
true
}

/// Whether the code now running has the generated derived-edge units
/// (`RuntimeSchema::derived_edges`); otherwise a host walks the
/// derived-tick plans.
fn runs_derived_edge_units(&self) -> bool {
true
}

// ── event enumeration ───────────────────────────────────────
fn id_to_addr_slice(&self) -> &[AbsoluteAddr];
fn id_to_event_slice(&self) -> &[Self::Event];
Expand Down
15 changes: 11 additions & 4 deletions crates/celox-sir-opt/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ define_sir_passes! {
/// Compatibility selector for Cranelift oversized-function planning.
/// This is not a SIR transform and is consumed at the backend boundary.
TailCallSplit => "tail_call_split",
/// Run the edges of events with derived clock domains (gated clocks,
/// dividers) in generated units instead of walking their plans in Rust.
/// Not a SIR transform: the builder consumes it. The units compile the
/// clock's domain once more, so disabling it trades tick speed for build
/// time.
DerivedEdgeUnits => "derived_edge_units",
}
/// Diagnostics and additional verification for the SIR optimizer.
///
Expand Down Expand Up @@ -278,11 +284,12 @@ impl OptimizeOptions {
self.opt_level.default_enabled(pass)
}

/// Returns true if any pass other than TailCallSplit is enabled.
/// Returns true if any SIR transform is enabled: any pass other than
/// the TailCallSplit and DerivedEdgeUnits selectors.
pub fn any_enabled(&self) -> bool {
SirPass::ALL
.iter()
.any(|&p| p != SirPass::TailCallSplit && self.is_enabled(p))
SirPass::ALL.iter().any(|&p| {
!matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p)
})
}

/// The base optimization level.
Expand Down
22 changes: 16 additions & 6 deletions crates/celox/src/backend/native/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ pub(crate) struct NativeRuntimeSchema {
pub(crate) active_commits: Vec<AbsoluteAddr>,
pub(crate) time_slots: Vec<AbsoluteAddr>,
pub(crate) scheduler: Option<celox_design::SchedulerSchema<AbsoluteAddr>>,
pub(crate) derived_edges: Vec<celox_design::DerivedEdgeUnits<AbsoluteAddr>>,
}

/// Pointer-free native compiler artifact which can be attached to the
Expand Down Expand Up @@ -526,6 +527,7 @@ impl NativeProgramImage {
active_commits: self.runtime_schema.active_commits.clone(),
time_slots: self.runtime_schema.time_slots.clone(),
scheduler: self.runtime_schema.scheduler.clone(),
derived_edges: self.runtime_schema.derived_edges.clone(),
},
testbench: self.testbench.clone(),
}
Expand Down Expand Up @@ -621,12 +623,19 @@ impl NativeProgramImage {
usize::MAX
}
});
if self.process_offsets.len()
!= self
.runtime_schema
.processes
.len()
.saturating_add(scheduler_units)
// The derived-edge units follow the kernels and the scheduler.
let derived_units = 2 * self.runtime_schema.derived_edges.len();
let derived_in_range = self.runtime_schema.derived_edges.iter().all(|units| {
units.rising < self.process_offsets.len() && units.falling < self.process_offsets.len()
});
if !derived_in_range
|| self.process_offsets.len()
!= self
.runtime_schema
.processes
.len()
.saturating_add(scheduler_units)
.saturating_add(derived_units)
{
return Err("process kernels and their control slots disagree".into());
}
Expand Down Expand Up @@ -2443,6 +2452,7 @@ fn compile_program(
active_commits: sir.runtime().runtime_schema.active_commits.clone(),
time_slots: sir.runtime().runtime_schema.time_slots.clone(),
scheduler: sir.runtime().runtime_schema.scheduler.clone(),
derived_edges: sir.runtime().runtime_schema.derived_edges.clone(),
},
layout: layout.clone(),
native_memory_size,
Expand Down
2 changes: 1 addition & 1 deletion crates/celox/src/backend/native/image_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{fmt, path::Path};
use super::backend::NativeProgramImage;

const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI";
const CONTAINER_VERSION: u16 = 33;
const CONTAINER_VERSION: u16 = 34;
const TRAILER_SIZE: usize = 32;
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
Expand Down
21 changes: 16 additions & 5 deletions crates/celox/src/backend/tiered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,10 @@ pub struct TieredBackend {
/// first stage adopts a low-latency baseline image, this receiver yields
/// the optimizing image for an in-place shared-code replacement.
upgrade_receiver: Option<mpsc::Receiver<Result<CompiledCode, SimulatorError>>>,
/// The adopted code has the generated derived-edge units: a single-stage
/// image or the optimizing one. The baseline image leaves them out, so
/// their build cost lands in the optimizing tier.
derived_edges_live: bool,
/// Evaluate-only events whose apply phase has not run yet. Promotion is
/// deferred while this is non-zero so the compiled apply phase always
/// observes the interpreted evaluate-only results through an intact
Expand Down Expand Up @@ -799,6 +803,7 @@ impl TieredBackend {
cancel,
compiler_worker,
upgrade_receiver: None,
derived_edges_live: false,
pending_split_applies: 0,
promotion_threshold,
interpreted_steps: 0,
Expand Down Expand Up @@ -859,6 +864,8 @@ impl TieredBackend {
let (baseline_sender, baseline_receiver) = mpsc::channel();
let (upgrade_sender, upgrade_receiver) = mpsc::channel();
let background_laid_out = laid_out.clone();
// The baseline image runs derived edges by walking their plans.
let baseline_laid_out = crate::derived_edge::without_units(laid_out);
let worker_baseline_options = baseline_options.clone();
// A failed spawn keeps the interpreter as the permanent tier with the
// reason recorded, matching the single-stage background-failure policy.
Expand All @@ -868,11 +875,7 @@ impl TieredBackend {
let span = tracing::info_span!("celox.tiered.compile", target = "native");
span.in_scope(|| {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
compile(
&background_laid_out,
&worker_baseline_options,
&worker_cancel,
)
compile(&baseline_laid_out, &worker_baseline_options, &worker_cancel)
}))
.unwrap_or_else(|_| {
Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError))
Expand Down Expand Up @@ -929,6 +932,7 @@ impl TieredBackend {
cancel,
compiler_worker,
upgrade_receiver: Some(upgrade_receiver),
derived_edges_live: false,
pending_split_applies: 0,
promotion_threshold,
interpreted_steps: 0,
Expand Down Expand Up @@ -1141,6 +1145,8 @@ impl TieredBackend {
}
}
self.phase = Phase::Compiled(compiled);
// A second stage still to come means this is the baseline image.
self.derived_edges_live = self.upgrade_receiver.is_none();
self.promotion = Promotion::Promoted;
self.promoted_after_interpreted_steps = Some(self.interpreted_steps);
if let Some(timing) = &mut self.execution_timing
Expand Down Expand Up @@ -1205,6 +1211,7 @@ impl TieredBackend {
&& compiled.replace_native_code(code)
{
tracing::info!("tiered backend adopted optimizing native code");
self.derived_edges_live = true;
}
}
}
Expand All @@ -1225,6 +1232,10 @@ impl SimBackend for TieredBackend {
matches!(self.phase, Phase::Compiled(_))
}

fn runs_derived_edge_units(&self) -> bool {
matches!(self.phase, Phase::Compiled(_)) && self.derived_edges_live
}

type Event = TieredEventRef;

fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> {
Expand Down
Loading
Loading