Skip to main content

rlx_runtime/
kernel_trace.rs

1// RLX — versatile ML compiler + runtime.
2// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Compile-time gated kernel tracing (plan #7).
6//!
7//! Borrowed from MAX's `Trace, TraceLevel, trace_arg` pattern.
8//! Tracing calls are baked into hot paths but the *macro* expands to
9//! either a stamped `eprintln!` (when the `kernel-trace` feature is
10//! on) or to nothing (default). The compiler eliminates the
11//! disabled branch entirely — production builds pay zero overhead.
12//!
13//! Use it like:
14//! ```ignore
15//! rlx_runtime::ktrace!("matmul", "m={m} k={k} n={n}");
16//! ```
17//!
18//! The macro takes a `kind` (op/section name) and a format string
19//! plus args. Output is namespaced with `[ktrace:<kind>]` and
20//! includes a monotonic timestamp from `rlx_ir::Tick`.
21
22#[cfg(feature = "kernel-trace")]
23#[doc(hidden)]
24pub fn _emit(kind: &str, msg: std::fmt::Arguments<'_>) {
25    use std::sync::OnceLock;
26    static T0: OnceLock<rlx_ir::Tick> = OnceLock::new();
27    let start = *T0.get_or_init(rlx_ir::Tick::now);
28    let now = rlx_ir::Tick::now();
29    eprintln!("[ktrace:{kind}] +{:>10} ns  {msg}", now.elapsed_ns(start));
30}
31
32#[cfg(not(feature = "kernel-trace"))]
33#[doc(hidden)]
34pub fn _emit(_kind: &str, _msg: std::fmt::Arguments<'_>) {}
35
36/// Compile-time gated kernel trace. Expands to a no-op call without
37/// the `kernel-trace` feature; the optimizer removes it entirely.
38#[macro_export]
39macro_rules! ktrace {
40    ($kind:expr, $($arg:tt)+) => {{
41        $crate::kernel_trace::_emit($kind, format_args!($($arg)+));
42    }};
43}
44
45#[cfg(test)]
46mod tests {
47    #[test]
48    fn macro_compiles_and_runs() {
49        // The macro must compile and run regardless of feature state.
50        // With the feature off, this is a no-op call — verify it
51        // doesn't panic and doesn't write anything we can observe in
52        // a unit test.
53        crate::ktrace!("test", "x={} y={}", 1, 2);
54    }
55}