Skip to main content

ruxla_codegen/
emit.rs

1//! Rust code from the IR: a function of fixed-size arrays and scalars.
2//!
3//! Values of one element are Rust scalars, other arrays are `[T; N]` in
4//! row-major order (inputs by reference, results by value). Elementwise
5//! operations call the scalar operations of `ruxla-kernels` (or the Rust
6//! operators with the same semantics), so the results are those of the
7//! interpreter. Data movement (broadcasts, slices, concatenation, gathers
8//! and scatters with constant or single start indices, ...) is compiled to
9//! copies: the positions are found by evaluating the operation on arrays
10//! of position codes ("probes") at generation time. Operations without a
11//! specialized emission call the interpreter on the equation.
12
13use std::collections::{BTreeMap, HashMap, HashSet};
14use std::fmt::Write;
15
16use ruxla_interp::Interp;
17use ruxla_ir::{
18    AVal, Atom, DType, DTypeKind, Eqn, Function, GatherScatterMode, HostArray, Params, Var,
19};
20use ruxla_kernels::{BinaryOp, CompareOp, UnaryOp};
21
22/// An error of code generation.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Error(pub String);
25
26impl std::fmt::Display for Error {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        f.write_str(&self.0)
29    }
30}
31
32impl std::error::Error for Error {}
33
34type Result<T> = std::result::Result<T, Error>;
35
36fn err<T>(m: impl Into<String>) -> Result<T> {
37    Err(Error(m.into()))
38}
39
40/// The largest array (in elements) that generated code keeps on the stack.
41const MAX_ARRAY: usize = 1 << 24;
42
43/// The size in bytes from which a local array is on the heap (`rt::Heap`)
44/// instead of the stack: the large intermediate arrays (Waymax's pairs of
45/// objects) would overflow a thread's stack.
46const HEAP_BYTES: usize = 256 * 1024;
47
48/// The largest convolution (the result's elements times the kernel's)
49/// compiled as a table of its products instead of a call of the kernel
50/// (Jumanji's Connector convolves its 10 x 10 grid with a 3 x 3 kernel for
51/// each agent at every reset, which the kernel's general loops and
52/// allocations made slow).
53const CONV_TABLE_TERMS: usize = 4096;
54
55/// The largest generated body (in bytes of source) marked `#[inline]`.
56const INLINE_BYTES: usize = 16 * 1024;
57
58/// The size (in bytes) from which a constant array is written to a binary
59/// file and read with `include_bytes!` instead of a list of literals, when
60/// the code is generated in a build script ([`blob_dir`]): rustc parses and
61/// checks a literal of every element, and Waymax's scenario (61 MB of
62/// literals) took 20 minutes to compile.
63const BLOB_BYTES: usize = 16 * 1024;
64
65/// The directory of the binary files of large constant arrays: a directory
66/// in the build script's `OUT_DIR` (the generated code is compiled in the
67/// same crate), or `None` outside a build script (the arrays are literals).
68fn blob_dir() -> Option<std::path::PathBuf> {
69    let dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR")?).join("ruxla-consts");
70    std::fs::create_dir_all(&dir).ok()?;
71    Some(dir)
72}
73
74/// How a variable is referred to in the generated code.
75#[derive(Clone, Debug)]
76struct Name {
77    expr: String,
78    /// A reference to an array (an input of the function).
79    is_ref: bool,
80}
81
82/// How a generated function takes an input.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum Input {
85    /// Scalars by value, arrays by reference (`&[T; N]`).
86    Default,
87    /// By mutable reference (`&mut T` or `&mut [T; N]`), so that an output
88    /// can be written back into it ([`Output::Into`]).
89    Mut,
90}
91
92/// How a generated function gives an output.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub enum Output {
95    /// In the returned tuple.
96    Return,
97    /// Written to an argument `&mut T` (after the inputs, in the order of
98    /// the outputs).
99    Write,
100    /// Written into the input of this index (which must be [`Input::Mut`]).
101    Into(usize),
102}
103
104/// The arguments and results of a generated function: by default, inputs
105/// by value or reference and outputs in the returned tuple.
106#[derive(Clone, Debug, Default, PartialEq, Eq)]
107pub struct Signature {
108    /// How each input is taken (missing ones: [`Input::Default`]).
109    pub inputs: Vec<Input>,
110    /// How each output is given (missing ones: [`Output::Return`]).
111    pub outputs: Vec<Output>,
112}
113
114/// Generates a Rust function `name` that computes `f`: arguments are the
115/// inputs of `f` (scalars by value, arrays as `&[T; N]`), and the result is
116/// the tuple of its outputs.
117///
118/// # Errors
119///
120/// Returns an error for element types or operations that cannot be
121/// generated (complex numbers, arrays of more than 2^20 elements).
122pub fn emit_function(name: &str, f: &Function) -> Result<String> {
123    emit_function_with(name, f, &Signature::default())
124}
125
126/// [`emit_function`] with the arguments and results of `sig`.
127///
128/// # Errors
129///
130/// As [`emit_function`], and for a signature that writes into an input
131/// that is not taken by mutable reference.
132pub fn emit_function_with(name: &str, f: &Function, sig: &Signature) -> Result<String> {
133    emit(name, f, sig, None)
134}
135
136/// The constant arrays of generated functions, shared by the functions of a
137/// module: each distinct array becomes one `static` (named by a hash of its
138/// type and elements), which [`ConstPool::code`] defines for the module
139/// instead of each function defining its own copies.
140#[derive(Clone, Debug, Default)]
141pub struct ConstPool {
142    defs: BTreeMap<String, String>,
143    /// The outlined functions of the module, by their code (with the name
144    /// left out): the same body in several functions (`step` and the step
145    /// with the final observation) is one function.
146    outlined: HashMap<String, String>,
147    /// The definitions of the outlined functions, in the order made.
148    outlined_code: Vec<String>,
149}
150
151impl ConstPool {
152    /// An empty pool.
153    pub fn new() -> Self {
154        Self::default()
155    }
156
157    /// The definitions of the arrays (`static` items, one per line), to put
158    /// in the module of the functions.
159    pub fn code(&self) -> String {
160        let mut s = String::new();
161        for d in self.defs.values() {
162            s.push_str(d);
163            s.push('\n');
164        }
165        // Each outlined function in a module of its own: rustc forms the
166        // codegen units of a crate by modules, so the large outlined bodies
167        // of one environment are optimized by LLVM in parallel instead of in
168        // one unit.
169        for f in &self.outlined_code {
170            let name = f
171                .split("pub fn ")
172                .nth(1)
173                .and_then(|r| r.split('(').next())
174                .unwrap_or_default();
175            if name.is_empty() {
176                s.push_str(f);
177                continue;
178            }
179            s.push_str(&format!(
180                "mod {name}_m {{\nuse super::*;\n{f}}}\nuse {name}_m::{name};\n"
181            ));
182        }
183        s
184    }
185
186    /// Whether the pool has no arrays.
187    pub fn is_empty(&self) -> bool {
188        self.defs.is_empty()
189    }
190}
191
192/// [`emit_function_with`] whose constant arrays go to `pool` (defined once
193/// by [`ConstPool::code`] for all the functions that share it).
194///
195/// # Errors
196///
197/// As [`emit_function_with`].
198pub fn emit_function_pooled(
199    name: &str,
200    f: &Function,
201    sig: &Signature,
202    pool: &mut ConstPool,
203) -> Result<String> {
204    emit(name, f, sig, Some(pool))
205}
206
207thread_local! {
208    /// The emitter's optimizations to skip (ablation; set by
209    /// [`crate::compile`] and its variants from [`crate::Options::skip`]).
210    static SKIP: std::cell::Cell<crate::Skip> = const { std::cell::Cell::new(crate::Skip {
211        select_branches: false,
212        masked_scatters: false,
213        scalarize: false,
214        passthrough: false,
215        fusion: false,
216        views: false,
217        in_place: false,
218    }) };
219}
220
221/// Runs `f` with the emitter's optimizations of `skip` skipped.
222pub(crate) fn with_skip<T>(skip: crate::Skip, f: impl FnOnce() -> T) -> T {
223    let old = SKIP.with(|s| s.replace(skip));
224    let r = f();
225    SKIP.with(|s| s.set(old));
226    r
227}
228
229fn skip() -> crate::Skip {
230    SKIP.with(std::cell::Cell::get)
231}
232
233fn emit(name: &str, f: &Function, sig: &Signature, pool: Option<&mut ConstPool>) -> Result<String> {
234    let split = split_straight_line(f);
235    let f = &split;
236    let mut e = Emitter {
237        pooled: pool.is_some(),
238        known_outlined: pool
239            .as_ref()
240            .map(|p| p.outlined.clone())
241            .unwrap_or_default(),
242        ..Emitter::default()
243    };
244    let mut args = Vec::new();
245    let input = |k: usize| sig.inputs.get(k).copied().unwrap_or(Input::Default);
246    let output = |k: usize| sig.outputs.get(k).copied().unwrap_or(Output::Return);
247    for (k, v) in f.invars.iter().enumerate() {
248        let ty = e.ty(v.aval())?;
249        let arg = format!("a{k}");
250        let (decl, is_ref) = match input(k) {
251            Input::Mut => (format!("{arg}: &mut {ty}"), true),
252            Input::Default if size(v.aval()) == 1 => (format!("{arg}: {ty}"), false),
253            Input::Default => (format!("{arg}: &{ty}"), true),
254        };
255        args.push(decl);
256        if input(k) == Input::Mut {
257            e.mut_inputs.insert(v.id());
258        }
259        e.names.insert(v.id(), Name { expr: arg, is_ref });
260    }
261    let mut returns = Vec::new();
262    for (k, a) in f.outvars.iter().enumerate() {
263        match output(k) {
264            Output::Return => returns.push(e.ty(&a.aval())?),
265            Output::Write => args.push(format!("o{k}: &mut {}", e.ty(&a.aval())?)),
266            Output::Into(j) if input(j) == Input::Mut => {}
267            Output::Into(j) => {
268                return err(format!("output {k} into input {j}, which is not mutable"));
269            }
270        }
271    }
272    // Outputs written to arguments and used for nothing else are computed
273    // directly into them.
274    let mut uses: HashMap<u64, usize> = HashMap::new();
275    for eq in &f.eqns {
276        for a in &eq.inputs {
277            if let Atom::Var(v) = a {
278                *uses.entry(v.id()).or_default() += 1;
279            }
280        }
281    }
282    for a in &f.outvars {
283        if let Atom::Var(v) = a {
284            *uses.entry(v.id()).or_default() += 1;
285        }
286    }
287    let defined: HashSet<u64> = f
288        .eqns
289        .iter()
290        .flat_map(|eq| eq.outputs.iter().map(Var::id))
291        .collect();
292    for (k, a) in f.outvars.iter().enumerate() {
293        if output(k) == Output::Write
294            && let Atom::Var(v) = a
295            && defined.contains(&v.id())
296            && uses.get(&v.id()) == Some(&1)
297        {
298            e.targets
299                .insert(reshape_source(f, v.id(), &uses), format!("o{k}"));
300        }
301    }
302    // An output written back into an input whose old value nothing reads
303    // after the output's equation: computed directly into the input.
304    let mut root: HashMap<u64, u64> = HashMap::new();
305    for eq in &f.eqns {
306        if eq.prim.name() == "reshape"
307            && let Atom::Var(v) = &eq.inputs[0]
308        {
309            let r = *root.get(&v.id()).unwrap_or(&v.id());
310            root.insert(eq.outputs[0].id(), r);
311        }
312    }
313    let mut last_read: HashMap<u64, usize> = HashMap::new();
314    let mut def_pos: HashMap<u64, usize> = HashMap::new();
315    for (p, eq) in f.eqns.iter().enumerate() {
316        for a in &eq.inputs {
317            if let Atom::Var(v) = a {
318                last_read.insert(*root.get(&v.id()).unwrap_or(&v.id()), p);
319            }
320        }
321        for o in &eq.outputs {
322            def_pos.insert(o.id(), p);
323        }
324    }
325    let output_ids: HashSet<u64> = f
326        .outvars
327        .iter()
328        .filter_map(|a| match a {
329            Atom::Var(v) => Some(*root.get(&v.id()).unwrap_or(&v.id())),
330            Atom::Lit(_) => None,
331        })
332        .collect();
333    for (k, a) in f.outvars.iter().enumerate() {
334        if let Output::Into(j) = output(k)
335            && let Atom::Var(v) = a
336            && uses.get(&v.id()) == Some(&1)
337            && let Some(&p) = def_pos.get(&v.id())
338        {
339            let iv = f.invars[j].id();
340            if !skip().in_place
341                && last_read.get(&iv).is_none_or(|&r| r <= p)
342                && !output_ids.contains(&iv)
343            {
344                e.targets.insert(v.id(), format!("a{j}"));
345                e.into_targets.insert(v.id());
346            }
347        }
348    }
349    e.indent = 1;
350    e.function_body(f)?;
351    // The outputs written into inputs that other outputs still read are
352    // copied first: the inputs themselves, and values that live in an
353    // input's storage (updated in place).
354    let written: HashMap<u64, usize> = (0..f.outvars.len())
355        .filter_map(|k| match output(k) {
356            Output::Into(j) => Some((f.invars[j].id(), k)),
357            _ => None,
358        })
359        .collect();
360    // An output whose storage is an input (an input updated in place, a
361    // scatter into it for example) is read through the input's name, so it
362    // is copied first too where another output overwrites that input.
363    let overwritten: HashMap<String, usize> = (0..f.outvars.len())
364        .filter_map(|k| match (output(k), &f.outvars[k]) {
365            (Output::Into(j), Atom::Var(var))
366                if var.id() == f.invars[j].id()
367                    || e.names
368                        .get(&var.id())
369                        .is_some_and(|n| n.expr == format!("a{j}")) =>
370            {
371                None
372            }
373            (Output::Into(j), _) => Some((format!("a{j}"), k)),
374            _ => None,
375        })
376        .collect();
377    let mut results = Vec::new();
378    let mut writes = Vec::new();
379    for (k, a) in f.outvars.iter().enumerate() {
380        let mut v = e.val(a)?;
381        if let Atom::Var(var) = a
382            && let Some(w) = written.get(&var.id()).copied().or_else(|| {
383                e.names
384                    .get(&var.id())
385                    .and_then(|n| overwritten.get(&n.expr).copied())
386            })
387            && w != k
388        {
389            let t = format!("t{k}");
390            e.line(format!("let {t} = {v};"));
391            v = t;
392        }
393        match output(k) {
394            Output::Return => results.push(v),
395            Output::Write => {
396                let done = matches!(a, Atom::Var(var)
397                    if e.names.get(&var.id()).is_some_and(|n| n.expr == format!("o{k}")));
398                if !done {
399                    writes.push(format!("*o{k} = {v};"));
400                }
401            }
402            Output::Into(j) => {
403                // Unchanged (or updated in place): nothing to write.
404                let same = matches!(a, Atom::Var(var)
405                    if var.id() == f.invars[j].id()
406                        || e.names.get(&var.id()).is_some_and(|n| n.expr == format!("a{j}")));
407                if !same {
408                    writes.push(format!("*a{j} = {v};"));
409                }
410            }
411        }
412    }
413    for w in writes {
414        e.line(w);
415    }
416    let mut s = String::new();
417    writeln!(
418        s,
419        "#[allow(unused, unused_comparisons, clippy::all, non_snake_case, unused_parens, unused_mut, unused_variables)]"
420    )
421    .ok();
422    // Small functions may be inlined into their callers in other crates (a
423    // call costs about as much as CartPole's step); large ones are compiled
424    // once, in their own crate, not again in every crate that calls them.
425    if e.out.len() <= INLINE_BYTES {
426        writeln!(s, "#[inline]").ok();
427    }
428    writeln!(
429        s,
430        "pub fn {name}({}) -> ({}) {{",
431        args.join(", "),
432        tuple_types(&returns)
433    )
434    .ok();
435    match pool {
436        Some(pool) => {
437            for (k, d) in std::mem::take(&mut e.pool) {
438                pool.defs.entry(k).or_insert(d);
439            }
440            pool.outlined.extend(std::mem::take(&mut e.known_outlined));
441            pool.outlined_code.extend(std::mem::take(&mut e.outlined));
442        }
443        None => {
444            // The function's own constant arrays, at the top of its body.
445            for d in e.pool.values() {
446                writeln!(s, "    {d}").ok();
447            }
448        }
449    }
450    s.push_str(&e.out);
451    writeln!(s, "    ({})", tuple_values(&results)).ok();
452    writeln!(s, "}}").ok();
453    for o in &e.outlined {
454        s.push_str(o);
455    }
456    Ok(s)
457}
458
459/// The size (in equations, with those of nested bodies) from which a loop
460/// body or a branch is a function of its own: rustc's time grows faster than
461/// the size of a function (Brax's Humanoid made one function of 33,000
462/// lines), and a call costs little next to such a body.
463pub(crate) const OUTLINE_EQNS: usize = 1500;
464
465/// The number of equations (not counting those of nested bodies) from which
466/// the equations of a function are split into pieces
467/// ([`split_straight_line`]): long straight code, not a few equations with
468/// large bodies (Craftax's step, whose arrays would be copied between
469/// pieces at every step).
470const SPLIT_EQNS: usize = 8000;
471
472/// The number of equations of each piece of a split function.
473const CHUNK_EQNS: usize = 4000;
474
475/// A large function (from [`SPLIT_EQNS`]) with its equations in pieces of
476/// about [`CHUNK_EQNS`], each the one branch of a conditional on the index 0
477/// (which [`Emitter::body_results`] makes a function of its own): Brax's and
478/// Playground's resets and physics steps are tens of thousands of equations
479/// without loops. A piece takes the variables it uses (its constants copied)
480/// and gives those that later equations use. The last piece stays in place.
481fn split_straight_line(f: &Function) -> Function {
482    if f.eqns.len() < SPLIT_EQNS {
483        return f.clone();
484    }
485    // The pieces: [start, end) of CHUNK_EQNS equations, the rest left in place.
486    let mut pieces = Vec::new();
487    let (mut start, mut acc) = (0, 0);
488    for i in 0..f.eqns.len() {
489        acc += 1;
490        if acc >= CHUNK_EQNS && i + 1 < f.eqns.len() {
491            pieces.push((start, i + 1));
492            start = i + 1;
493            acc = 0;
494        }
495    }
496    if pieces.is_empty() {
497        return f.clone();
498    }
499    // The last equation that uses each variable (outputs count as after all).
500    let n = f.eqns.len();
501    let mut last_use: HashMap<u64, usize> = HashMap::new();
502    for (i, e) in f.eqns.iter().enumerate() {
503        for a in &e.inputs {
504            if let Atom::Var(v) = a {
505                last_use.insert(v.id(), i);
506            }
507        }
508    }
509    for a in &f.outvars {
510        if let Atom::Var(v) = a {
511            last_use.insert(v.id(), n);
512        }
513    }
514    let consts: HashMap<u64, HostArray> = f
515        .constvars
516        .iter()
517        .map(|(v, x)| (v.id(), x.clone()))
518        .collect();
519    let mut subst: HashMap<u64, Atom> = HashMap::new();
520    let sub = |a: &Atom, subst: &HashMap<u64, Atom>| match a {
521        Atom::Var(v) => subst.get(&v.id()).cloned().unwrap_or_else(|| a.clone()),
522        Atom::Lit(_) => a.clone(),
523    };
524    let mut eqns = Vec::new();
525    let mut next = 0;
526    for &(a, b) in &pieces {
527        let piece = &f.eqns[a..b];
528        let defined: HashSet<u64> = piece
529            .iter()
530            .flat_map(|e| e.outputs.iter().map(Var::id))
531            .collect();
532        let mut inputs: Vec<Var> = Vec::new();
533        let mut piece_consts: Vec<(Var, HostArray)> = Vec::new();
534        let mut seen = HashSet::new();
535        for e in piece {
536            for x in &e.inputs {
537                if let Atom::Var(v) = x
538                    && !defined.contains(&v.id())
539                    && seen.insert(v.id())
540                {
541                    match consts.get(&v.id()) {
542                        Some(c) => piece_consts.push((v.clone(), c.clone())),
543                        None => inputs.push(v.clone()),
544                    }
545                }
546            }
547        }
548        let outputs: Vec<Var> = piece
549            .iter()
550            .flat_map(|e| e.outputs.iter())
551            .filter(|o| last_use.get(&o.id()).is_some_and(|&u| u >= b))
552            .cloned()
553            .collect();
554        let branch = Function {
555            constvars: piece_consts,
556            invars: inputs.clone(),
557            eqns: piece.to_vec(),
558            outvars: outputs.iter().cloned().map(Atom::from).collect(),
559        };
560        let fresh: Vec<Var> = outputs.iter().map(|o| Var::new(o.aval().clone())).collect();
561        let mut operands = vec![Atom::Lit(ruxla_ir::Literal::new(HostArray::scalar(0i32)))];
562        operands.extend(inputs.iter().map(|v| sub(&Atom::from(v.clone()), &subst)));
563        eqns.push(Eqn {
564            prim: ruxla_prims::COND,
565            inputs: operands,
566            params: Params::Cond {
567                branches: vec![std::sync::Arc::new(branch)],
568            },
569            outputs: fresh.clone(),
570            loc: None,
571        });
572        for (o, v) in outputs.iter().zip(fresh) {
573            subst.insert(o.id(), v.into());
574        }
575        next = b;
576    }
577    for e in &f.eqns[next..] {
578        let mut e = e.clone();
579        e.inputs = e.inputs.iter().map(|a| sub(a, &subst)).collect();
580        eqns.push(e);
581    }
582    Function {
583        constvars: f.constvars.clone(),
584        invars: f.invars.clone(),
585        eqns,
586        outvars: f.outvars.iter().map(|a| sub(a, &subst)).collect(),
587    }
588}
589
590/// The equations of `f` and of the bodies and branches it contains.
591fn count_eqns(f: &Function) -> usize {
592    f.eqns
593        .iter()
594        .map(|e| {
595            1 + match &e.params {
596                Params::Cond { branches } => branches.iter().map(|b| count_eqns(b)).sum(),
597                Params::While { cond, body, .. } => count_eqns(cond) + count_eqns(body),
598                Params::Scan { body, .. } => count_eqns(body),
599                _ => 0,
600            }
601        })
602        .sum()
603}
604
605/// `code` with its variables (`v` and the variable's number) renumbered in
606/// the order they appear, so that the same body optimized in two functions
607/// (with other variable numbers) gives the same code.
608fn canonical_vars(code: &str) -> String {
609    let b = code.as_bytes();
610    let ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
611    let mut map: HashMap<&str, usize> = HashMap::new();
612    let mut out = String::with_capacity(code.len());
613    let mut i = 0;
614    let mut last = 0;
615    while i < b.len() {
616        if b[i] == b'v'
617            && (i == 0 || !ident(b[i - 1]))
618            && i + 1 < b.len()
619            && b[i + 1].is_ascii_digit()
620        {
621            let mut j = i + 1;
622            while j < b.len() && b[j].is_ascii_digit() {
623                j += 1;
624            }
625            let n = map.len();
626            let k = *map.entry(&code[i + 1..j]).or_insert(n);
627            out.push_str(&code[last..i]);
628            write!(out, "v{k}").ok();
629            last = j;
630            i = j;
631        } else {
632            i += 1;
633        }
634    }
635    out.push_str(&code[last..]);
636    out
637}
638
639/// A unique name of an outlined function in the generated code.
640fn outlined_name() -> String {
641    static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
642    format!(
643        "outlined_{}",
644        NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
645    )
646}
647
648/// The variable whose elements `id` has through `reshape`s of variables
649/// that nothing else uses (`id` itself if none): a destination of `id` is
650/// also that variable's, since a `reshape` names the same storage.
651fn reshape_source(f: &Function, mut id: u64, uses: &HashMap<u64, usize>) -> u64 {
652    loop {
653        let source = f
654            .eqns
655            .iter()
656            .find_map(|e| match (&e.inputs[..], e.prim.name()) {
657                ([Atom::Var(u)], "reshape")
658                    if e.outputs[0].id() == id
659                        && uses.get(&u.id()) == Some(&1)
660                        && f.eqns
661                            .iter()
662                            .any(|d| d.outputs.iter().any(|o| o.id() == u.id())) =>
663                {
664                    Some(u.id())
665                }
666                _ => None,
667            });
668        match source {
669            Some(u) => id = u,
670            None => return id,
671        }
672    }
673}
674
675fn tuple_types(ts: &[String]) -> String {
676    if ts.is_empty() {
677        String::new()
678    } else if ts.len() == 1 {
679        format!("{},", ts[0])
680    } else {
681        ts.join(", ")
682    }
683}
684
685fn tuple_values(vs: &[String]) -> String {
686    tuple_types(vs)
687}
688
689fn size(aval: &AVal) -> usize {
690    aval.shape.size()
691}
692
693fn strides(dims: &[usize]) -> Vec<usize> {
694    let mut st = vec![1; dims.len()];
695    for d in (0..dims.len().saturating_sub(1)).rev() {
696        st[d] = st[d + 1] * dims[d + 1];
697    }
698    st
699}
700
701/// The Rust type of elements of `dtype`.
702pub fn elem_ty(dtype: DType) -> Result<&'static str> {
703    Ok(match dtype {
704        DType::Bool => "bool",
705        DType::I8 => "i8",
706        DType::I16 => "i16",
707        DType::I32 => "i32",
708        DType::I64 => "i64",
709        DType::U8 => "u8",
710        DType::U16 => "u16",
711        DType::U32 => "u32",
712        DType::U64 => "u64",
713        DType::F16 => "rt::f16",
714        DType::BF16 => "rt::bf16",
715        DType::F32 => "f32",
716        DType::F64 => "f64",
717        other => return err(format!("element type {other} is not supported")),
718    })
719}
720
721/// Whether the element type is a Rust primitive (with its operators).
722fn primitive(dtype: DType) -> bool {
723    !matches!(dtype, DType::F16 | DType::BF16) && !dtype.is_complex()
724}
725
726fn is_float(dtype: DType) -> bool {
727    dtype.kind() == DTypeKind::Float
728}
729
730fn is_int(dtype: DType) -> bool {
731    dtype.is_int()
732}
733
734/// A Rust expression of element `i` of `x`.
735/// Whether an expression is a literal of [`elem_lit`] (which may be
736/// repeated freely).
737fn is_literal(x: &str) -> bool {
738    let body = x.trim_start_matches(['(', '-']);
739    x == "true"
740        || x == "false"
741        || body.starts_with(|c: char| c.is_ascii_digit())
742        || ((x.starts_with("f32::from_bits(") || x.starts_with("f64::from_bits("))
743            && !x[15..].contains(['(', ' ']))
744}
745
746fn elem_lit(x: &HostArray, i: usize) -> Result<String> {
747    macro_rules! int {
748        ($t:ty, $s:literal) => {{
749            let v = x.as_slice::<$t>().map_err(|e| Error(e.to_string()))?[i];
750            // Unsigned types expand the macro too, where the test is always false.
751            #[allow(unused_comparisons)]
752            let neg = v < 0;
753            if neg {
754                format!(concat!("({}", $s, ")"), v)
755            } else {
756                format!(concat!("{}", $s), v)
757            }
758        }};
759    }
760    Ok(match x.dtype() {
761        DType::Bool => {
762            let v = x.as_slice::<bool>().map_err(|e| Error(e.to_string()))?[i];
763            v.to_string()
764        }
765        DType::I8 => int!(i8, "i8"),
766        DType::I16 => int!(i16, "i16"),
767        DType::I32 => int!(i32, "i32"),
768        DType::I64 => int!(i64, "i64"),
769        DType::U8 => int!(u8, "u8"),
770        DType::U16 => int!(u16, "u16"),
771        DType::U32 => int!(u32, "u32"),
772        DType::U64 => int!(u64, "u64"),
773        DType::F32 => {
774            let v = x.as_slice::<f32>().map_err(|e| Error(e.to_string()))?[i];
775            if v.is_finite() {
776                if v.is_sign_negative() {
777                    format!("({v:?}f32)")
778                } else {
779                    format!("{v:?}f32")
780                }
781            } else {
782                format!("f32::from_bits({:#x})", v.to_bits())
783            }
784        }
785        DType::F64 => {
786            let v = x.as_slice::<f64>().map_err(|e| Error(e.to_string()))?[i];
787            if v.is_finite() {
788                if v.is_sign_negative() {
789                    format!("({v:?}f64)")
790                } else {
791                    format!("{v:?}f64")
792                }
793            } else {
794                format!("f64::from_bits({:#x})", v.to_bits())
795            }
796        }
797        DType::F16 => {
798            let v = x
799                .as_slice::<ruxla_kernels::f16>()
800                .map_err(|e| Error(e.to_string()))?[i];
801            format!("rt::f16::from_bits({:#x})", v.to_bits())
802        }
803        DType::BF16 => {
804            let v = x
805                .as_slice::<ruxla_kernels::bf16>()
806                .map_err(|e| Error(e.to_string()))?[i];
807            format!("rt::bf16::from_bits({:#x})", v.to_bits())
808        }
809        other => return err(format!("element type {other} is not supported")),
810    })
811}
812
813/// A source of a copied element: an operand's element, the padding value,
814/// or zero.
815#[derive(Clone, Copy, PartialEq, Eq, Debug)]
816enum Src {
817    In(usize, i64),
818    Pad,
819    Zero,
820}
821
822/// The code of element `idx` of operand `k` in a probe.
823fn code(k: usize, idx: usize) -> i64 {
824    (((k + 1) as i64) << 32) | idx as i64
825}
826
827fn decode(m: i64) -> Src {
828    if m == 0 {
829        Src::Zero
830    } else if m < 0 {
831        Src::Pad
832    } else {
833        Src::In(((m >> 32) - 1) as usize, m & 0xffff_ffff)
834    }
835}
836
837/// An array of the codes of operand `k`'s elements, of shape `aval`.
838fn probe(k: usize, aval: &AVal) -> HostArray {
839    let n = size(aval);
840    HostArray::from_vec(
841        (0..n).map(|i| code(k, i)).collect::<Vec<i64>>(),
842        aval.shape.clone(),
843    )
844}
845
846/// A run of copies: `len` destinations from `out` (consecutive), from
847/// `src`'s elements `start + j * stride`.
848#[derive(Clone, Copy, Debug)]
849struct Run {
850    out: usize,
851    src: Src,
852    stride: i64,
853    len: usize,
854}
855
856/// A run repeated in nested loops: `levels` (innermost first) are
857/// `(reps, dout, dstart)`, each repetition `dout` destinations and `dstart`
858/// source elements after the previous.
859#[derive(Clone, Debug)]
860struct Pattern {
861    run: Run,
862    levels: Vec<(usize, usize, i64)>,
863}
864
865/// The largest number of nested loops of a pattern.
866const MAX_LEVELS: usize = 6;
867
868/// Compresses (destination, source) pairs (destinations increasing) into
869/// runs, and runs into patterns of nested loops.
870fn patterns(pairs: &[(usize, Src)]) -> Vec<Pattern> {
871    let mut runs: Vec<Run> = Vec::new();
872    for &(o, s) in pairs {
873        if let Some(r) = runs.last_mut()
874            && r.out + r.len == o
875        {
876            match (r.src, s) {
877                (Src::Pad, Src::Pad) | (Src::Zero, Src::Zero) => {
878                    r.len += 1;
879                    continue;
880                }
881                (Src::In(k0, s0), Src::In(k, s1)) if k0 == k => {
882                    if r.len == 1 {
883                        r.stride = s1 - s0;
884                        r.len = 2;
885                        continue;
886                    }
887                    if s1 == s0 + r.stride * r.len as i64 {
888                        r.len += 1;
889                        continue;
890                    }
891                }
892                _ => {}
893            }
894        }
895        runs.push(Run {
896            out: o,
897            src: s,
898            stride: 0,
899            len: 1,
900        });
901    }
902    let start = |r: &Run| match r.src {
903        Src::In(_, s) => s,
904        _ => 0,
905    };
906    let operand = |r: &Run| match r.src {
907        Src::In(k, _) => Some(k),
908        _ => None,
909    };
910    let mut pats: Vec<Pattern> = runs
911        .into_iter()
912        .map(|run| Pattern {
913            run,
914            levels: Vec::new(),
915        })
916        .collect();
917    // Groups of consecutive patterns of the same form, at constant distances,
918    // become one more level, until nothing merges.
919    for _ in 0..MAX_LEVELS {
920        let mut merged: Vec<Pattern> = Vec::new();
921        let mut k = 0;
922        while k < pats.len() {
923            let p = &pats[k];
924            let same = |q: &Pattern| {
925                operand(&q.run) == operand(&p.run)
926                    && std::mem::discriminant(&q.run.src) == std::mem::discriminant(&p.run.src)
927                    && q.run.stride == p.run.stride
928                    && q.run.len == p.run.len
929                    && q.levels == p.levels
930            };
931            let mut end = k + 1;
932            if end < pats.len() && same(&pats[end]) && pats[end].run.out > p.run.out {
933                let dout = pats[end].run.out - p.run.out;
934                let dstart = start(&pats[end].run) - start(&p.run);
935                while end < pats.len()
936                    && same(&pats[end])
937                    && pats[end].run.out == p.run.out + (end - k) * dout
938                    && start(&pats[end].run) == start(&p.run) + (end - k) as i64 * dstart
939                {
940                    end += 1;
941                }
942                if end - k > 1 {
943                    let mut levels = p.levels.clone();
944                    levels.push((end - k, dout, dstart));
945                    merged.push(Pattern { run: p.run, levels });
946                    k = end;
947                    continue;
948                }
949            }
950            merged.push(p.clone());
951            k += 1;
952        }
953        let done = merged.len() == pats.len();
954        pats = merged;
955        if done {
956            break;
957        }
958    }
959    pats
960}
961
962/// [`patterns`] of the copies of each source (operand, padding, or zero)
963/// separately, for destinations that are all different (so that the order
964/// of the copies does not matter); the patterns of every source, or all of
965/// [`patterns`] if some destination repeats.
966fn patterns_by_source(pairs: &[(usize, Src)]) -> Vec<Pattern> {
967    let mut seen = HashSet::new();
968    if !pairs.iter().all(|&(o, _)| seen.insert(o)) {
969        return patterns(pairs);
970    }
971    let key = |s: &Src| match *s {
972        Src::In(k, _) => k as i64,
973        Src::Pad => -1,
974        Src::Zero => -2,
975    };
976    let mut keys: Vec<i64> = pairs.iter().map(|(_, s)| key(s)).collect();
977    keys.sort_unstable();
978    keys.dedup();
979    keys.into_iter()
980        .flat_map(|k| {
981            let part: Vec<(usize, Src)> =
982                pairs.iter().copied().filter(|(_, s)| key(s) == k).collect();
983            patterns(&part)
984        })
985        .collect()
986}
987
988#[derive(Default)]
989struct Emitter {
990    out: String,
991    indent: usize,
992    names: HashMap<u64, Name>,
993    counter: usize,
994    /// The analyses of the functions being emitted (innermost last).
995    scopes: Vec<Scope>,
996    /// The expressions of fused arrays, with `@I@` for the element index.
997    fused: HashMap<u64, String>,
998    /// Inputs taken by mutable reference (updated in place where dead).
999    mut_inputs: HashSet<u64>,
1000    /// The parent's variables that the next branch's inputs stand for.
1001    pending_inherit: HashMap<u64, u64>,
1002    /// The inputs of the next loop body that are its carries: mutable
1003    /// locals of the loop, reassigned after each iteration, so the body may
1004    /// update them in place where it no longer uses them.
1005    pending_owned: HashSet<u64>,
1006    /// Outputs computed directly into the argument they are written to.
1007    targets: HashMap<u64, String>,
1008    /// The targets that are inputs (`Output::Into`), whose old value other
1009    /// code may still read.
1010    into_targets: HashSet<u64>,
1011    /// Constant arrays of one repeated value: the value.
1012    uniform_consts: HashMap<u64, String>,
1013    /// The arrays that are references into others (never updated in place).
1014    views: HashSet<u64>,
1015    /// The local arrays on the heap ([`HEAP_BYTES`]): written and read as
1016    /// references (`*v = ...`, `(*v)`).
1017    heap_names: HashSet<String>,
1018    /// Data movement results that are not built: their sources, and the
1019    /// source of each element.
1020    moves: HashMap<u64, (Vec<Atom>, Vec<Src>)>,
1021    /// The constant arrays (`static` items) by name.
1022    pool: BTreeMap<String, String>,
1023    /// Whether the constant arrays go to a pool of the module (else into the
1024    /// function's body, where other functions cannot see them).
1025    pooled: bool,
1026    /// The outlined functions of the module so far (see
1027    /// [`ConstPool::outlined`]).
1028    known_outlined: HashMap<String, String>,
1029    /// The functions of large loop bodies and branches (see
1030    /// [`OUTLINE_EQNS`]), defined after the function.
1031    outlined: Vec<String>,
1032}
1033
1034/// What the emission of a function knows about its variables.
1035#[derive(Default)]
1036struct Scope {
1037    /// Arrays computed as expressions inside their only (elementwise) use
1038    /// instead of variables.
1039    fused: HashSet<u64>,
1040    /// The position of the last use of each variable (by its root), where
1041    /// fused expressions count as used at their evaluation.
1042    last_use: HashMap<u64, usize>,
1043    /// The variable whose storage a variable shares (`reshape`).
1044    root: HashMap<u64, u64>,
1045    /// Arrays that are mutable locals of this function.
1046    owned: HashSet<u64>,
1047    /// Arrays that broadcast one value: the value.
1048    uniform: HashMap<u64, Atom>,
1049    /// The position of the equation being emitted.
1050    pos: usize,
1051    /// Data movement results used only by other data movement: not built,
1052    /// but followed to their sources by the copies that use them.
1053    virtual_moves: HashSet<u64>,
1054    /// For a branch of a conditional: the parent's variable that each input
1055    /// stands for (it may be updated in place where the parent no longer
1056    /// uses it, since only one branch runs).
1057    inherited: HashMap<u64, u64>,
1058    /// Scalar `sin` and `cos` of the same float: computed together
1059    /// (`sin_cos`), by output: the outputs `(sin, cos)`.
1060    sin_cos: HashMap<u64, (u64, u64)>,
1061    /// `dynamic_slice`s of contiguous windows of a built array: references
1062    /// into it (`Emitter::dynamic_slice`), which keep it alive (`root`).
1063    views: HashSet<u64>,
1064    /// For an array with references into it ([`Scope::views`]): the last
1065    /// equation that reads a reference (the array is not updated in place
1066    /// there, which would write what the equation reads).
1067    view_last: HashMap<u64, usize>,
1068}
1069
1070impl Scope {
1071    fn root(&self, id: u64) -> u64 {
1072        *self.root.get(&id).unwrap_or(&id)
1073    }
1074}
1075
1076/// Whether an equation is emitted as an elementwise loop (`rt::build`).
1077fn is_elementwise(e: &Eqn, uniform: &HashMap<u64, Atom>) -> bool {
1078    if e.outputs.len() != 1 || size(e.outputs[0].aval()) == 1 {
1079        return false;
1080    }
1081    let name = e.prim.name();
1082    if UnaryOp::ALL.iter().any(|o| o.name() == name) {
1083        return e.inputs.len() == 1
1084            && !e.inputs[0].aval().dtype.is_complex()
1085            && e.inputs[0].aval().dtype == e.outputs[0].aval().dtype;
1086    }
1087    if BinaryOp::ALL.iter().any(|o| o.name() == name) {
1088        return e.inputs.len() == 2;
1089    }
1090    if CompareOp::ALL.iter().any(|o| o.name() == name) {
1091        return true;
1092    }
1093    match name {
1094        "convert_element_type" | "clamp" | "integer_pow" | "round" | "is_finite" => true,
1095        "bitcast_convert_type" => {
1096            bitcast_expr(e.inputs[0].aval().dtype, e.outputs[0].aval().dtype, "x").is_some()
1097        }
1098        "select_n" => {
1099            !(e.inputs.len() == 3
1100                && (size(&e.inputs[0].aval()) == 1
1101                    || matches!(&e.inputs[0], Atom::Var(p) if uniform.contains_key(&p.id()))))
1102        }
1103        _ => false,
1104    }
1105}
1106
1107/// The size from which a reduction evaluates an elementwise operand (and
1108/// the data movement it reads) in its loops instead of reading it built:
1109/// smaller ones are faster built by one loop that vectorizes.
1110const FUSE_INTO_REDUCE: usize = 512;
1111
1112/// Whether an equation is a gather that [`Emitter::gather_groups`] emits:
1113/// several index vectors given at run time.
1114fn is_group_gather(e: &Eqn, constvars: &HashSet<u64>) -> bool {
1115    if e.prim.name() != "gather" || e.inputs.len() != 2 || e.outputs.len() != 1 {
1116        return false;
1117    }
1118    let (x, idx) = (&e.inputs[0], &e.inputs[1]);
1119    let ia = idx.aval();
1120    let q = ia.shape.rank();
1121    let groups: usize = ia.shape.dims()[..q.saturating_sub(1)].iter().product();
1122    matches!(idx, Atom::Var(v) if !constvars.contains(&v.id()))
1123        && size(&x.aval()) > 1
1124        && groups > 1
1125        && size(e.outputs[0].aval()) > 1
1126}
1127
1128/// Whether an equation is a reduction ([`Emitter::reduce`]), which reads
1129/// its operand element by element and may evaluate a fused one.
1130fn is_reduce(e: &Eqn) -> bool {
1131    matches!(
1132        e.prim.name(),
1133        "reduce_sum" | "reduce_max" | "reduce_min" | "reduce_and" | "reduce_or"
1134    ) && e.inputs.len() == 1
1135        && size(&e.inputs[0].aval()) > 1
1136}
1137
1138/// A reduction over trailing axes of at most 8 elements in all (as the sum
1139/// of the squares of the coordinates of points): the number of reduced
1140/// elements of each output element. Such a reduction can be an expression
1141/// of its output element (fused into its consumer, as elementwise
1142/// operations are).
1143fn small_reduce(e: &Eqn) -> Option<usize> {
1144    if !matches!(e.prim.name(), "reduce_sum" | "reduce_max" | "reduce_min")
1145        || e.inputs.len() != 1
1146        || size(e.outputs[0].aval()) <= 1
1147    {
1148        return None;
1149    }
1150    let Params::Reduce { axes } = &e.params else {
1151        return None;
1152    };
1153    let xa = e.inputs[0].aval();
1154    if xa.dtype.is_complex() || xa.dtype == DType::Bool {
1155        return None;
1156    }
1157    let dims = xa.shape.dims();
1158    let mut sorted = axes.clone();
1159    sorted.sort_unstable();
1160    let r = dims.len().checked_sub(sorted.len())?;
1161    if sorted != (r..dims.len()).collect::<Vec<_>>() {
1162        return None;
1163    }
1164    let m: usize = dims[r..].iter().product();
1165    (2..=8).contains(&m).then_some(m)
1166}
1167
1168/// `argmax` or `argmin` of an operand that its loops can evaluate
1169/// (fused elementwise operations, data movement read in place).
1170fn is_arg(e: &Eqn) -> bool {
1171    matches!(e.prim.name(), "argmax" | "argmin")
1172        && size(&e.inputs[0].aval()) > 1
1173        && !e.inputs[0].aval().dtype.is_complex()
1174        && e.inputs[0].aval().dtype != DType::Bool
1175}
1176
1177/// A template with its element index `@I@` replaced by `i`, and the tokens
1178/// `@D{s}:{n}@` (the index along a dimension of stride `s` and size `n` of
1179/// the element) by `i / s % n`. With `i` = `@I@`, the template itself.
1180fn subst_index(template: &str, i: &str) -> String {
1181    if i == "@I@" {
1182        return template.to_string();
1183    }
1184    // Templates use the index in arithmetic (`idx[@I@ * 2 + 1]`), so an
1185    // index that is an expression (`25 + i`, a loop over part of the
1186    // elements) is parenthesized.
1187    let simple = i.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
1188    let wrapped;
1189    let i = if simple {
1190        i
1191    } else {
1192        wrapped = format!("({i})");
1193        wrapped.as_str()
1194    };
1195    let mut out = String::with_capacity(template.len());
1196    let mut rest = template;
1197    // One pass: `i` may itself contain `@I@`.
1198    while let Some(p) = rest.find("@D") {
1199        out.push_str(&rest[..p].replace("@I@", i));
1200        let tail = &rest[p + 2..];
1201        let end = tail.find('@').expect("a closed token");
1202        let (s, n) = tail[..end].split_once(':').expect("a dimension token");
1203        if s == "1" {
1204            out.push_str(&format!("(({i}) % {n})"));
1205        } else {
1206            out.push_str(&format!("(({i}) / {s} % {n})"));
1207        }
1208        rest = &tail[end + 1..];
1209    }
1210    out.push_str(&rest.replace("@I@", i));
1211    out
1212}
1213
1214/// The index `base + sum(i{d} * strides[d])` over dimensions `dims` (the
1215/// loop variables `i{d}`; dimensions of one element are skipped).
1216fn affine_index(dims: &[usize], strides: &[i64], base: i64) -> String {
1217    let mut terms: Vec<String> = Vec::new();
1218    if base != 0 {
1219        terms.push(format!("{base}"));
1220    }
1221    for (d, &st) in strides.iter().enumerate() {
1222        if dims[d] <= 1 {
1223            continue;
1224        }
1225        match st {
1226            0 => {}
1227            1 => terms.push(format!("i{d}")),
1228            _ => terms.push(format!("i{d} * {st}")),
1229        }
1230    }
1231    if terms.is_empty() {
1232        "0".to_string()
1233    } else {
1234        terms.join(" + ")
1235    }
1236}
1237
1238/// The fusion and liveness analysis of a function.
1239fn analyze(f: &Function) -> Scope {
1240    let sk = skip();
1241    let mut scope = Scope::default();
1242    let constvars: HashSet<u64> = f.constvars.iter().map(|(v, _)| v.id()).collect();
1243    let n = f.eqns.len();
1244    for e in &f.eqns {
1245        if e.prim.name() == "broadcast_in_dim" && size(&e.inputs[0].aval()) == 1 {
1246            scope.uniform.insert(e.outputs[0].id(), e.inputs[0].clone());
1247        }
1248        if e.prim.name() == "reshape"
1249            && let Atom::Var(v) = &e.inputs[0]
1250        {
1251            let r = scope.root(v.id());
1252            scope.root.insert(e.outputs[0].id(), r);
1253        }
1254    }
1255    // Pairs of scalar `sin` and `cos` of the same argument.
1256    let mut trig: HashMap<String, (Option<u64>, Option<u64>)> = HashMap::new();
1257    for e in &f.eqns {
1258        let name = e.prim.name();
1259        if (name == "sin" || name == "cos")
1260            && e.inputs.len() == 1
1261            && size(e.outputs[0].aval()) == 1
1262            && matches!(e.outputs[0].aval().dtype, DType::F32 | DType::F64)
1263        {
1264            let key = format!("{:?}", e.inputs[0]);
1265            let entry = trig.entry(key).or_default();
1266            if name == "sin" {
1267                entry.0.get_or_insert(e.outputs[0].id());
1268            } else {
1269                entry.1.get_or_insert(e.outputs[0].id());
1270            }
1271        }
1272    }
1273    for (sv, cv) in trig.into_values() {
1274        if let (Some(sv), Some(cv)) = (sv, cv) {
1275            scope.sin_cos.insert(sv, (sv, cv));
1276            scope.sin_cos.insert(cv, (sv, cv));
1277        }
1278    }
1279    let ew: Vec<bool> = f
1280        .eqns
1281        .iter()
1282        .map(|e| is_elementwise(e, &scope.uniform) || small_reduce(e).is_some())
1283        .collect();
1284    let mut uses: HashMap<u64, Vec<usize>> = HashMap::new();
1285    for (i, e) in f.eqns.iter().enumerate() {
1286        for a in &e.inputs {
1287            if let Atom::Var(v) = a {
1288                uses.entry(v.id()).or_default().push(i);
1289            }
1290        }
1291    }
1292    for a in &f.outvars {
1293        if let Atom::Var(v) = a {
1294            uses.entry(v.id()).or_default().push(n);
1295        }
1296    }
1297    let mut consumer: HashMap<usize, usize> = HashMap::new();
1298    let movement = |name: &str| {
1299        matches!(
1300            name,
1301            "broadcast_in_dim"
1302                | "transpose"
1303                | "slice"
1304                | "concatenate"
1305                | "rev"
1306                | "squeeze"
1307                | "expand_dims"
1308                | "copy"
1309        )
1310    };
1311    for (i, e) in f.eqns.iter().enumerate() {
1312        if sk.views
1313            || !movement(e.prim.name())
1314            || e.outputs.len() != 1
1315            || size(e.outputs[0].aval()) == 1
1316        {
1317            continue;
1318        }
1319        let o = &e.outputs[0];
1320        if let Some(&[j]) = uses.get(&o.id()).map(Vec::as_slice)
1321            && j < n
1322        {
1323            let c = &f.eqns[j];
1324            let pos = c
1325                .inputs
1326                .iter()
1327                .position(|a| matches!(a, Atom::Var(v) if v.id() == o.id()));
1328            let ok = (movement(c.prim.name()) || c.prim.name() == "pad") && pos.is_some()
1329                || (c.prim.name() == "dynamic_update_slice"
1330                    && pos == Some(1)
1331                    && size(&c.inputs[0].aval()) > 1);
1332            if ok {
1333                scope.virtual_moves.insert(o.id());
1334                scope.fused.insert(o.id());
1335                consumer.insert(i, j);
1336            }
1337        }
1338    }
1339    // A pad used only as the operand of a dynamic_slice: not built, but read
1340    // through a table by the window (`Emitter::dynamic_slice_of_move`).
1341    for (i, e) in f.eqns.iter().enumerate() {
1342        if sk.views || e.prim.name() != "pad" || size(e.outputs[0].aval()) <= 1 {
1343            continue;
1344        }
1345        let o = &e.outputs[0];
1346        if let Some(&[j]) = uses.get(&o.id()).map(Vec::as_slice)
1347            && j < n
1348            && f.eqns[j].prim.name() == "dynamic_slice"
1349            && matches!(&f.eqns[j].inputs[0], Atom::Var(v) if v.id() == o.id())
1350            && size(f.eqns[j].outputs[0].aval()) > 1
1351        {
1352            scope.virtual_moves.insert(o.id());
1353            scope.fused.insert(o.id());
1354            consumer.insert(i, j);
1355        }
1356    }
1357    for (i, e) in f.eqns.iter().enumerate() {
1358        if sk.fusion || !ew[i] {
1359            continue;
1360        }
1361        let o = &e.outputs[0];
1362        let copies_from = |j: usize| {
1363            let c = &f.eqns[j];
1364            let pos = c
1365                .inputs
1366                .iter()
1367                .position(|a| matches!(a, Atom::Var(v) if v.id() == o.id()));
1368            // The indices of a gather with several index vectors, read once
1369            // per group (`group_bases`).
1370            if pos == Some(1) && is_group_gather(c, &constvars) {
1371                return true;
1372            }
1373            matches!(
1374                (c.prim.name(), pos),
1375                (
1376                    "scatter"
1377                        | "scatter-add"
1378                        | "scatter_add"
1379                        | "scatter-mul"
1380                        | "scatter_mul"
1381                        | "scatter-min"
1382                        | "scatter_min"
1383                        | "scatter-max"
1384                        | "scatter_max",
1385                    Some(2),
1386                ) | ("dynamic_update_slice", Some(1))
1387                    | (
1388                        "broadcast_in_dim"
1389                            | "transpose"
1390                            | "slice"
1391                            | "concatenate"
1392                            | "rev"
1393                            | "pad"
1394                            | "squeeze"
1395                            | "expand_dims"
1396                            | "copy",
1397                        Some(_),
1398                    )
1399            )
1400        };
1401        if let Some(&[j]) = uses.get(&o.id()).map(Vec::as_slice)
1402            && j < n
1403            && ((ew[j] && size(f.eqns[j].outputs[0].aval()) == size(o.aval()))
1404                || copies_from(j)
1405                || ((is_reduce(&f.eqns[j]) || is_arg(&f.eqns[j]))
1406                    && size(o.aval()) >= FUSE_INTO_REDUCE))
1407        {
1408            scope.fused.insert(o.id());
1409            consumer.insert(i, j);
1410        }
1411    }
1412    // Gathers with several index vectors used only by an elementwise
1413    // operation of their size or by a (large) reduction: expressions of the
1414    // element (their groups' starts and the offsets in the window), not
1415    // built (`Emitter::gather_groups`).
1416    for (i, e) in f.eqns.iter().enumerate() {
1417        if sk.fusion || !is_group_gather(e, &constvars) {
1418            continue;
1419        }
1420        let o = &e.outputs[0];
1421        if let Some(&[j]) = uses.get(&o.id()).map(Vec::as_slice)
1422            && j < n
1423            && ((ew[j] && size(f.eqns[j].outputs[0].aval()) == size(o.aval()))
1424                || (is_reduce(&f.eqns[j]) && size(o.aval()) >= FUSE_INTO_REDUCE))
1425        {
1426            scope.fused.insert(o.id());
1427            consumer.insert(i, j);
1428        }
1429    }
1430    // Data movement used only by an elementwise operation that is a loop of
1431    // its own (not fused further): not built, but read from its sources by
1432    // runs of that loop (`Emitter::elementwise_moved`).
1433    for (i, e) in f.eqns.iter().enumerate() {
1434        let name = e.prim.name();
1435        if sk.views
1436            || !movement(name)
1437            || e.outputs.len() != 1
1438            || size(e.outputs[0].aval()) == 1
1439            || scope.virtual_moves.contains(&e.outputs[0].id())
1440        {
1441            continue;
1442        }
1443        let o = &e.outputs[0];
1444        // The loop that evaluates the consumer: the consumer itself, or the
1445        // elementwise operation its fused expression ends in.
1446        let root_is_loop = |mut j: usize| loop {
1447            // A reduction (or an argmax) evaluates its (large) operand in
1448            // its own loops.
1449            if is_reduce(&f.eqns[j]) || is_arg(&f.eqns[j]) {
1450                return size(o.aval()) >= FUSE_INTO_REDUCE;
1451            }
1452            if !ew[j] || size(f.eqns[j].outputs[0].aval()) != size(o.aval()) {
1453                return false;
1454            }
1455            if !scope.fused.contains(&f.eqns[j].outputs[0].id()) {
1456                return true;
1457            }
1458            match consumer.get(&j) {
1459                Some(&k) => j = k,
1460                None => return false,
1461            }
1462        };
1463        if let Some(&[j]) = uses.get(&o.id()).map(Vec::as_slice)
1464            && j < n
1465            && root_is_loop(j)
1466        {
1467            scope.virtual_moves.insert(o.id());
1468            scope.fused.insert(o.id());
1469            consumer.insert(i, j);
1470        }
1471    }
1472    // A small reduction is computed again wherever its fused expression is
1473    // read: not fused when the expression reaches its loop through a
1474    // broadcast that repeats its elements (Pgx's Go counts the liberties
1475    // with an 81 x 81 comparison of a sum of 4 neighbors, which was summed
1476    // again for every pair).
1477    for (i, e) in f.eqns.iter().enumerate() {
1478        if small_reduce(e).is_none() || !scope.fused.contains(&e.outputs[0].id()) {
1479            continue;
1480        }
1481        let mut j = i;
1482        let mut repeated = false;
1483        while let Some(&k) = consumer.get(&j) {
1484            let c = &f.eqns[k];
1485            if c.prim.name() == "broadcast_in_dim"
1486                && size(c.outputs[0].aval()) > size(&c.inputs[0].aval())
1487            {
1488                repeated = true;
1489                break;
1490            }
1491            if !scope.fused.contains(&c.outputs[0].id()) {
1492                break;
1493            }
1494            j = k;
1495        }
1496        if repeated {
1497            scope.fused.remove(&e.outputs[0].id());
1498            consumer.remove(&i);
1499        }
1500    }
1501    // Contiguous windows of built arrays: references, not copies. The array
1502    // stays alive (and is not updated in place) while the reference is used.
1503    for e in &f.eqns {
1504        if sk.views || e.prim.name() != "dynamic_slice" || size(e.outputs[0].aval()) <= 1 {
1505            continue;
1506        }
1507        let Atom::Var(x) = &e.inputs[0] else {
1508            continue;
1509        };
1510        if size(x.aval()) <= 1 || scope.fused.contains(&x.id()) {
1511            continue;
1512        }
1513        let (dims, sizes) = (
1514            x.aval().shape.dims().to_vec(),
1515            e.outputs[0].aval().shape.dims().to_vec(),
1516        );
1517        let k = sizes.iter().position(|&s| s != 1).unwrap_or(sizes.len());
1518        if (k + 1..sizes.len()).all(|j| sizes[j] == dims[j]) {
1519            let o = e.outputs[0].id();
1520            scope.views.insert(o);
1521            let r = scope.root(x.id());
1522            scope.root.insert(o, r);
1523        }
1524    }
1525    // Empty arrays are never fused: they are bound as empty arrays.
1526    for (i, e) in f.eqns.iter().enumerate() {
1527        if e.outputs.iter().all(|o| size(o.aval()) == 0) {
1528            for o in &e.outputs {
1529                scope.fused.remove(&o.id());
1530                scope.virtual_moves.remove(&o.id());
1531            }
1532            consumer.remove(&i);
1533        }
1534    }
1535    // Where each equation's result is computed: fused ones at their use.
1536    let mut at = vec![0; n];
1537    for i in (0..n).rev() {
1538        at[i] = consumer.get(&i).map_or(i, |&j| at[j]);
1539    }
1540    for (id, us) in &uses {
1541        let last = us
1542            .iter()
1543            .map(|&u| if u == n { n } else { at[u] })
1544            .max()
1545            .unwrap_or(0);
1546        let r = scope.root(*id);
1547        let e = scope.last_use.entry(r).or_insert(0);
1548        *e = (*e).max(last);
1549        if scope.views.contains(id) {
1550            let v = scope.view_last.entry(r).or_insert(0);
1551            *v = (*v).max(last);
1552        }
1553    }
1554    scope
1555}
1556
1557impl Emitter {
1558    fn line(&mut self, s: impl AsRef<str>) {
1559        let s = self.heapify(s.as_ref());
1560        for _ in 0..self.indent {
1561            self.out.push_str("    ");
1562        }
1563        self.out.push_str(&s);
1564        self.out.push('\n');
1565    }
1566
1567    /// A declaration `let [mut] v: [T; N] = init;` of an array of more than
1568    /// [`HEAP_BYTES`], on the heap (`rt::Heap<T, N>`, recorded in `heap_names`);
1569    /// other lines unchanged.
1570    fn heapify(&mut self, s: &str) -> String {
1571        let Some(rest) = s.strip_prefix("let ") else {
1572            return s.to_string();
1573        };
1574        let rest = rest.strip_prefix("mut ").unwrap_or(rest);
1575        let Some((name, rest)) = rest.split_once(": [") else {
1576            return s.to_string();
1577        };
1578        if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1579            return s.to_string();
1580        }
1581        let Some((t, rest)) = rest.split_once("; ") else {
1582            return s.to_string();
1583        };
1584        let Some((n, rest)) = rest.split_once("] = ") else {
1585            return s.to_string();
1586        };
1587        let (Ok(n), Some(init)) = (n.parse::<usize>(), rest.strip_suffix(';')) else {
1588            return s.to_string();
1589        };
1590        let bytes = match t {
1591            "bool" | "u8" | "i8" => 1,
1592            "u16" | "i16" | "f16" | "bf16" => 2,
1593            "u32" | "i32" | "f32" => 4,
1594            "u64" | "i64" | "f64" | "usize" => 8,
1595            _ => return s.to_string(),
1596        };
1597        if n * bytes <= HEAP_BYTES {
1598            return s.to_string();
1599        }
1600        let fill_suffix = format!("; {n}]");
1601        let init = if let Some(x) = init
1602            .strip_prefix("rt::overwritten([")
1603            .and_then(|x| x.strip_suffix(&format!("{fill_suffix})")))
1604        {
1605            format!("rt::reused::<{t}, {n}>({x})")
1606        } else if let Some(f) = init.strip_prefix("rt::build(") {
1607            format!("rt::build_boxed::<{t}, {n}>({f}")
1608        } else if let Some(f) = init.strip_prefix(&format!("rt::build::<{t}, {n}>(")) {
1609            format!("rt::build_boxed::<{t}, {n}>({f}")
1610        } else if let Some(x) = init
1611            .strip_prefix('[')
1612            .and_then(|x| x.strip_suffix(fill_suffix.as_str()))
1613            .filter(|x| x.matches('[').count() == x.matches(']').count())
1614        {
1615            format!("rt::filled::<{t}, {n}>({x})")
1616        } else {
1617            format!("rt::boxed_copy::<{t}, {n}>(&{init})")
1618        };
1619        self.heap_names.insert(name.to_string());
1620        // Used through a reference taken once (a pointer the loops keep in a
1621        // register, not a `Deref` at every element).
1622        format!(
1623            "let mut {name}_h: rt::Heap<{t}, {n}> = {init}; let {name}: &mut [{t}; {n}] = &mut {name}_h;"
1624        )
1625    }
1626
1627    /// Whether a name is written and read as a reference.
1628    fn by_ref(&self, n: &Name) -> bool {
1629        n.is_ref || self.heap_names.contains(&n.expr)
1630    }
1631
1632    /// The name of a constant array of type `ty` with the elements `elems`
1633    /// (a comma-separated list): a `static` of the pool, shared by every use
1634    /// of the same array.
1635    fn static_array(&mut self, ty: &str, elems: &str) -> String {
1636        // Numbers without their type suffixes (and parentheses), which the
1637        // type of the array gives: large tables are half as long.
1638        let elem = ty.trim_start_matches('[').split(';').next().unwrap_or("");
1639        let numeric = [
1640            "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", "usize",
1641        ]
1642        .contains(&elem);
1643        let short: String;
1644        let elems = if numeric {
1645            short = elems
1646                .split(", ")
1647                .map(|e| {
1648                    let e = e
1649                        .strip_prefix('(')
1650                        .and_then(|e| e.strip_suffix(')'))
1651                        .unwrap_or(e);
1652                    if e.contains("::") {
1653                        e
1654                    } else {
1655                        e.strip_suffix(elem).unwrap_or(e)
1656                    }
1657                })
1658                .collect::<Vec<_>>()
1659                .join(",");
1660            short.as_str()
1661        } else {
1662            elems
1663        };
1664        let def = |name: &str| format!("static {name}: {ty} = [{elems}];");
1665        // FNV-1a of the type and the elements.
1666        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1667        for b in ty.bytes().chain([0]).chain(elems.bytes()) {
1668            h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
1669        }
1670        loop {
1671            let name = format!("K{h:016X}");
1672            match self.pool.get(&name) {
1673                None => {
1674                    self.pool.insert(name.clone(), def(&name));
1675                    return name;
1676                }
1677                Some(d) if *d == def(&name) => return name,
1678                // A collision: another name.
1679                Some(_) => h = h.wrapping_add(1),
1680            }
1681        }
1682    }
1683
1684    /// A large constant array (of a primitive element type, not all equal)
1685    /// as a `static` read from a binary file ([`BLOB_BYTES`], [`blob_dir`]),
1686    /// or `None` to write it as literals.
1687    fn blob_const(&mut self, x: &HostArray) -> Result<Option<String>> {
1688        let width = x.dtype().size_in_bytes();
1689        if !primitive(x.dtype()) || x.size() * width < BLOB_BYTES {
1690            return Ok(None);
1691        }
1692        let Some(dir) = blob_dir() else {
1693            return Ok(None);
1694        };
1695        let bytes = x.to_bytes();
1696        if bytes.chunks_exact(width).all(|c| c == &bytes[..width]) {
1697            // One repeated value: a fill (`[v; N]`), as for the literals.
1698            return Ok(None);
1699        }
1700        let ty = self.ty(&x.aval())?;
1701        self.blob_static(&ty, &bytes, &dir).map(Some)
1702    }
1703
1704    /// A table of pairs (`[[elem; 2]; N]`, `elem` is `usize` or `i64`): a
1705    /// `static` from a binary file if it is large ([`Self::blob_const`]),
1706    /// else of literals.
1707    fn pair_table(&mut self, elem: &str, rows: &[[i64; 2]]) -> Result<String> {
1708        let ty = format!("[[{elem}; 2]; {}]", rows.len());
1709        if rows.len() * 16 >= BLOB_BYTES
1710            && let Some(dir) = blob_dir()
1711        {
1712            let mut bytes = Vec::with_capacity(rows.len() * 16);
1713            for x in rows.iter().flatten() {
1714                if elem == "usize" {
1715                    let x = usize::try_from(*x)
1716                        .map_err(|_| Error(format!("a negative position {x}")))?;
1717                    bytes.extend_from_slice(&x.to_ne_bytes());
1718                } else {
1719                    bytes.extend_from_slice(&x.to_ne_bytes());
1720                }
1721            }
1722            return self.blob_static(&ty, &bytes, &dir);
1723        }
1724        let elems: Vec<String> = rows.iter().map(|[a, b]| format!("[{a}, {b}]")).collect();
1725        Ok(self.static_array(&ty, &elems.join(", ")))
1726    }
1727
1728    /// A table of rows of `width` positions (`[[usize; width]; N]`, `flat`
1729    /// row-major): a `static` from a binary file if it is large, else of
1730    /// literals.
1731    fn usize_table(&mut self, width: usize, flat: &[usize]) -> Result<String> {
1732        let rows = flat.len() / width;
1733        let ty = format!("[[usize; {width}]; {rows}]");
1734        if flat.len() * 8 >= BLOB_BYTES
1735            && let Some(dir) = blob_dir()
1736        {
1737            let bytes: Vec<u8> = flat.iter().flat_map(|x| x.to_ne_bytes()).collect();
1738            return self.blob_static(&ty, &bytes, &dir);
1739        }
1740        let elems: Vec<String> = flat
1741            .chunks(width)
1742            .map(|r| {
1743                let r: Vec<String> = r.iter().map(ToString::to_string).collect();
1744                format!("[{}]", r.join(", "))
1745            })
1746            .collect();
1747        Ok(self.static_array(&ty, &elems.join(", ")))
1748    }
1749
1750    /// A `static` of type `ty` read from a binary file of `bytes` in `dir`.
1751    fn blob_static(&mut self, ty: &str, bytes: &[u8], dir: &std::path::Path) -> Result<String> {
1752        // FNV-1a of the type and the bytes.
1753        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1754        for b in ty.bytes().chain([0]).chain(bytes.iter().copied()) {
1755            h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
1756        }
1757        loop {
1758            let name = format!("K{h:016X}");
1759            let path = dir.join(format!("{name}.bin"));
1760            // The bytes are native-endian (the build script runs on the
1761            // target's byte order) and of a primitive type, valid for every
1762            // bit pattern except `bool`, whose bytes come from `bool`s.
1763            let def = format!(
1764                "// SAFETY: the file holds the native-endian bytes of the elements.\nstatic {name}: {ty} = unsafe {{ ::core::mem::transmute::<[u8; {}], {ty}>(*include_bytes!({:?})) }};",
1765                bytes.len(),
1766                path.display().to_string()
1767            );
1768            match self.pool.get(&name) {
1769                None => {
1770                    let same = std::fs::read(&path).is_ok_and(|b| b == bytes);
1771                    if !same && path.exists() {
1772                        // A file of another array under this name.
1773                        h = h.wrapping_add(1);
1774                        continue;
1775                    }
1776                    if !same {
1777                        std::fs::write(&path, bytes)
1778                            .map_err(|e| Error(format!("{}: {e}", path.display())))?;
1779                    }
1780                    self.pool.insert(name.clone(), def);
1781                    return Ok(name);
1782                }
1783                Some(d) if *d == def => return Ok(name),
1784                Some(_) => h = h.wrapping_add(1),
1785            }
1786        }
1787    }
1788
1789    fn fresh(&mut self, prefix: &str) -> String {
1790        self.counter += 1;
1791        format!("{prefix}{}", self.counter)
1792    }
1793
1794    fn ty(&self, aval: &AVal) -> Result<String> {
1795        let t = elem_ty(aval.dtype)?;
1796        let n = size(aval);
1797        if n > MAX_ARRAY {
1798            return err(format!("an array of {n} elements is too large"));
1799        }
1800        Ok(if n == 1 {
1801            t.to_string()
1802        } else {
1803            format!("[{t}; {n}]")
1804        })
1805    }
1806
1807    fn name(&self, v: &Var) -> Result<&Name> {
1808        self.names
1809            .get(&v.id())
1810            .ok_or_else(|| Error(format!("undefined variable {v:?}")))
1811    }
1812
1813    /// The value of an atom (an owned array is copied).
1814    fn val(&self, a: &Atom) -> Result<String> {
1815        match a {
1816            Atom::Lit(l) => elem_lit(l.value(), 0),
1817            Atom::Var(v) if self.fused.contains_key(&v.id()) => {
1818                let t = elem_ty(v.aval().dtype)?;
1819                let x = subst_index(&self.fused[&v.id()], "i");
1820                Ok(format!("rt::build::<{t}, {}>(|i| {x})", size(v.aval())))
1821            }
1822            Atom::Var(v) => {
1823                let n = self.name(v)?;
1824                Ok(if self.by_ref(n) {
1825                    format!("(*{})", n.expr)
1826                } else {
1827                    n.expr.clone()
1828                })
1829            }
1830        }
1831    }
1832
1833    /// The expression of element `i` of an atom (the value itself for one
1834    /// element).
1835    fn at(&self, a: &Atom, i: &str) -> Result<String> {
1836        if size(&a.aval()) == 1 {
1837            return self.val(a);
1838        }
1839        let Atom::Var(v) = a else {
1840            return err("an array literal");
1841        };
1842        if let Some(x) = self.fused.get(&v.id()) {
1843            return Ok(format!("({})", subst_index(x, i)));
1844        }
1845        if self.moves.contains_key(&v.id()) {
1846            // Read from its sources by the loop that evaluates it
1847            // (`elementwise_moved`).
1848            return Ok(format!("@M{}@", v.id()));
1849        }
1850        if let Some(x) = self.uniform_consts.get(&v.id()) {
1851            return Ok(x.clone());
1852        }
1853        Ok(format!("{}[{i}]", self.name(v)?.expr))
1854    }
1855
1856    /// Whether an atom is a fused array (an expression, not a variable).
1857    fn is_fused(&self, a: &Atom) -> bool {
1858        matches!(a, Atom::Var(v) if self.fused.contains_key(&v.id()))
1859    }
1860
1861    /// The expression of the slice `lo..hi` of an array atom.
1862    fn slice(&self, a: &Atom, lo: &str, hi: &str) -> Result<String> {
1863        let Atom::Var(v) = a else {
1864            return err("an array literal");
1865        };
1866        if self.fused.contains_key(&v.id()) {
1867            return Ok(format!("{}[{lo}..{hi}]", self.val(a)?));
1868        }
1869        Ok(format!("{}[{lo}..{hi}]", self.name(v)?.expr))
1870    }
1871
1872    /// A slice (`&[T]`) of all the elements of an atom.
1873    fn slice_of(&self, a: &Atom) -> Result<String> {
1874        let v = self.val(a)?;
1875        Ok(if size(&a.aval()) == 1 {
1876            format!("&[{v}]")
1877        } else {
1878            format!("&{v}[..]")
1879        })
1880    }
1881
1882    fn bind(&mut self, v: &Var, expr: &str) -> Result<()> {
1883        let ty = self.ty(v.aval())?;
1884        let name = format!("v{}", v.id());
1885        if let Some(t) = self.targets.get(&v.id()).cloned() {
1886            self.line(format!("*{t} = {expr};"));
1887            self.names.insert(
1888                v.id(),
1889                Name {
1890                    expr: t,
1891                    is_ref: true,
1892                },
1893            );
1894            self.own(v);
1895            return Ok(());
1896        }
1897        if size(v.aval()) == 1 {
1898            self.line(format!("let {name}: {ty} = {expr};"));
1899        } else {
1900            self.line(format!("let mut {name}: {ty} = {expr};"));
1901            self.own(v);
1902        }
1903        self.names.insert(
1904            v.id(),
1905            Name {
1906                expr: name,
1907                is_ref: false,
1908            },
1909        );
1910        Ok(())
1911    }
1912
1913    /// Whether `v` is (a name of) an input that the function updates in
1914    /// place ([`Input::Mut`]).
1915    fn is_mut_input(&self, v: &Var) -> bool {
1916        let Some(name) = self.names.get(&v.id()) else {
1917            return false;
1918        };
1919        self.mut_inputs
1920            .iter()
1921            .any(|id| self.names.get(id).is_some_and(|n| n.expr == name.expr))
1922    }
1923
1924    fn alias(&mut self, v: &Var, name: Name) {
1925        self.names.insert(v.id(), name);
1926    }
1927
1928    fn scope(&self) -> &Scope {
1929        self.scopes.last().expect("a function is being emitted")
1930    }
1931
1932    /// Marks an array as a mutable local of the current function.
1933    fn own(&mut self, v: &Var) {
1934        if let Some(s) = self.scopes.last_mut() {
1935            s.owned.insert(v.id());
1936        }
1937    }
1938
1939    /// Whether the array `a` may be updated in place by the current
1940    /// equation: a mutable local of this function, not used afterwards.
1941    fn reusable(&self, a: &Atom) -> bool {
1942        let Atom::Var(v) = a else {
1943            return false;
1944        };
1945        !skip().in_place
1946            && size(v.aval()) > 1
1947            && !self.scope().fused.contains(&v.id())
1948            && !self.views.contains(&v.id())
1949            && self.reusable_at(self.scopes.len() - 1, v.id())
1950    }
1951
1952    /// Whether the variable `id` is not used after the current equation of
1953    /// scope `d`, and is a mutable local there (or a branch input that
1954    /// stands for such a variable of the parent).
1955    fn reusable_at(&self, d: usize, id: u64) -> bool {
1956        if self.views.contains(&id) {
1957            return false;
1958        }
1959        let s = &self.scopes[d];
1960        let r = s.root(id);
1961        if s.last_use.get(&r) != Some(&s.pos) || s.view_last.get(&r) == Some(&s.pos) {
1962            return false;
1963        }
1964        if s.owned.contains(&r) {
1965            return true;
1966        }
1967        match s.inherited.get(&r) {
1968            Some(&p) if d > 0 => self.reusable_at(d - 1, p),
1969            _ => false,
1970        }
1971    }
1972
1973    /// Emits the constants and equations of `f` (its inputs already named).
1974    fn function_body(&mut self, f: &Function) -> Result<()> {
1975        for (v, x) in &f.constvars {
1976            if size(v.aval()) == 1 {
1977                let lit = elem_lit(x, 0)?;
1978                self.bind(v, &lit)?;
1979            } else if let Some(name) = self.blob_const(x)? {
1980                self.names.insert(
1981                    v.id(),
1982                    Name {
1983                        expr: name,
1984                        is_ref: false,
1985                    },
1986                );
1987            } else {
1988                let elems: Vec<String> = (0..x.size())
1989                    .map(|i| elem_lit(x, i))
1990                    .collect::<Result<_>>()?;
1991                // An empty array is a static `[]`.
1992                if !elems.is_empty() && elems.iter().all(|e| *e == elems[0]) {
1993                    // `[v; N]` (a fill, which needs no static).
1994                    self.uniform_consts.insert(v.id(), elems[0].clone());
1995                    self.names.insert(
1996                        v.id(),
1997                        Name {
1998                            expr: format!("[{}; {}]", elems[0], elems.len()),
1999                            is_ref: false,
2000                        },
2001                    );
2002                    continue;
2003                }
2004                let ty = self.ty(v.aval())?;
2005                let name = self.static_array(&ty, &elems.join(", "));
2006                self.names.insert(
2007                    v.id(),
2008                    Name {
2009                        expr: name,
2010                        is_ref: false,
2011                    },
2012                );
2013            }
2014        }
2015        let consts: HashMap<u64, HostArray> = f
2016            .constvars
2017            .iter()
2018            .map(|(v, x)| (v.id(), x.clone()))
2019            .collect();
2020        let mut scope = analyze(f);
2021        if self.scopes.is_empty() && !skip().in_place {
2022            scope.owned.extend(self.mut_inputs.iter().copied());
2023        }
2024        scope.inherited = std::mem::take(&mut self.pending_inherit);
2025        scope.owned.extend(std::mem::take(&mut self.pending_owned));
2026        self.scopes.push(scope);
2027        let mut result = Ok(());
2028        for (i, e) in f.eqns.iter().enumerate() {
2029            self.scopes.last_mut().expect("pushed above").pos = i;
2030            result = self
2031                .eqn(e, &consts)
2032                .map_err(|m| Error(format!("{} ({}): {}", e.prim.name(), loc(e), m.0)));
2033            if result.is_err() {
2034                break;
2035            }
2036        }
2037        self.scopes.pop();
2038        result
2039    }
2040
2041    fn eqn(&mut self, e: &Eqn, consts: &HashMap<u64, HostArray>) -> Result<()> {
2042        let name = e.prim.name();
2043        // Operations whose results are all empty (as MJX's unused fields):
2044        // empty arrays, nothing to compute.
2045        if !e.outputs.is_empty() && e.outputs.iter().all(|o| size(o.aval()) == 0) {
2046            for o in &e.outputs {
2047                let name = match self.targets.get(&o.id()) {
2048                    Some(t) => t.clone(),
2049                    None => {
2050                        let ty = self.ty(o.aval())?;
2051                        self.line(format!("let v{}: {ty} = [];", o.id()));
2052                        format!("v{}", o.id())
2053                    }
2054                };
2055                let is_ref = self.targets.contains_key(&o.id());
2056                self.names.insert(o.id(), Name { expr: name, is_ref });
2057            }
2058            return Ok(());
2059        }
2060        if let Some(&(sv, cv)) = self.scope().sin_cos.get(&e.outputs[0].id()) {
2061            // The pair is computed at the first of the two.
2062            if !self.names.contains_key(&sv) {
2063                let x = self.val(&e.inputs[0])?;
2064                // Through the kernels, as every other `sin` and `cos`, so
2065                // that the results match the native backend and the
2066                // interpreter on every target (`rt::Ops` keeps Apple's
2067                // `sincos` out; elsewhere LLVM still merges the two calls).
2068                let ty = elem_ty(e.outputs[0].aval().dtype).unwrap_or("?");
2069                self.line(format!(
2070                    "let (v{sv}, v{cv}) = (<{ty} as rt::Ops>::unary(rt::UnaryOp::Sin, {x}), \
2071                     <{ty} as rt::Ops>::unary(rt::UnaryOp::Cos, {x}));"
2072                ));
2073                for id in [sv, cv] {
2074                    self.names.insert(
2075                        id,
2076                        Name {
2077                            expr: format!("v{id}"),
2078                            is_ref: false,
2079                        },
2080                    );
2081                }
2082            }
2083            return Ok(());
2084        }
2085        // `round` has a rounding method (handled below); the unary operation
2086        // of the same name rounds halfway cases away from zero only.
2087        if let Some(op) = UnaryOp::ALL.into_iter().find(|o| o.name() == name)
2088            && name != "round"
2089            && e.inputs.len() == 1
2090            && !e.inputs[0].aval().dtype.is_complex()
2091            && e.inputs[0].aval().dtype == e.outputs[0].aval().dtype
2092        {
2093            let t = e.outputs[0].aval().dtype;
2094            return self.elementwise(e, |a| unary_expr(op, t, &a[0]));
2095        }
2096        if let Some(op) = BinaryOp::ALL.into_iter().find(|o| o.name() == name)
2097            && e.inputs.len() == 2
2098        {
2099            let t = e.outputs[0].aval().dtype;
2100            return self.elementwise(e, |a| binary_expr(op, t, &a[0], &a[1]));
2101        }
2102        if let Some(op) = CompareOp::ALL.into_iter().find(|o| o.name() == name) {
2103            let t = e.inputs[0].aval().dtype;
2104            return self.elementwise(e, |a| compare_expr(op, t, &a[0], &a[1]));
2105        }
2106        match name {
2107            "convert_element_type" => {
2108                let (from, to) = (e.inputs[0].aval().dtype, e.outputs[0].aval().dtype);
2109                self.elementwise(e, |a| convert_expr(from, to, &a[0]))
2110            }
2111            "bitcast_convert_type" => {
2112                let (from, to) = (e.inputs[0].aval().dtype, e.outputs[0].aval().dtype);
2113                match bitcast_expr(from, to, "X") {
2114                    Some(_) => self
2115                        .elementwise(e, |a| bitcast_expr(from, to, &a[0]).expect("checked above")),
2116                    None => self.fallback(e),
2117                }
2118            }
2119            "select_n"
2120                if e.inputs.len() == 3
2121                    && size(e.outputs[0].aval()) > 1
2122                    && (size(&e.inputs[0].aval()) == 1
2123                        || matches!(&e.inputs[0], Atom::Var(p) if self.scope().uniform.contains_key(&p.id()))) =>
2124            {
2125                self.uniform_select(e)
2126            }
2127            "select_n" => {
2128                let pred_bool = e.inputs[0].aval().dtype == DType::Bool;
2129                self.elementwise(e, |a| {
2130                    if pred_bool {
2131                        format!("if {} {{ {} }} else {{ {} }}", a[0], a[2], a[1])
2132                    } else {
2133                        let mut arms: Vec<String> = a[1..a.len() - 1]
2134                            .iter()
2135                            .enumerate()
2136                            .map(|(k, c)| format!("{k} => {c}"))
2137                            .collect();
2138                        arms.push(format!("_ => {}", a[a.len() - 1]));
2139                        format!("match {} {{ {} }}", a[0], arms.join(", "))
2140                    }
2141                })
2142            }
2143            "clamp" => {
2144                let t = e.outputs[0].aval().dtype;
2145                self.elementwise(e, |a| {
2146                    let inner = binary_expr(BinaryOp::Max, t, &a[1], &a[0]);
2147                    binary_expr(BinaryOp::Min, t, &inner, &a[2])
2148                })
2149            }
2150            "integer_pow" => {
2151                let Params::IntegerPow { y } = e.params else {
2152                    return err("parameters");
2153                };
2154                let t = e.outputs[0].aval().dtype;
2155                if matches!(t, DType::F32 | DType::F64) && y != 0 && y.unsigned_abs() <= 16 {
2156                    return self
2157                        .elementwise(e, |a| float_pow_expr(&a[0], y, elem_ty(t).unwrap_or("?")));
2158                }
2159                self.elementwise(e, |a| format!("rt::integer_pow({}, {y})", a[0]))
2160            }
2161            "round" => {
2162                let op = match e.params {
2163                    Params::Round {
2164                        method: ruxla_ir::RoundingMethod::ToNearestEven,
2165                    } => UnaryOp::RoundEven,
2166                    _ => UnaryOp::Round,
2167                };
2168                let t = e.outputs[0].aval().dtype;
2169                self.elementwise(e, |a| unary_expr(op, t, &a[0]))
2170            }
2171            "is_finite" => {
2172                let t = elem_ty(e.inputs[0].aval().dtype)?;
2173                self.elementwise(e, |a| format!("<{t} as rt::Ops>::is_finite({})", a[0]))
2174            }
2175            "reshape" => {
2176                // The same elements in the same order.
2177                let a = &e.inputs[0];
2178                match a {
2179                    Atom::Var(v) => {
2180                        let n = self.name(v)?.clone();
2181                        self.alias(&e.outputs[0], n);
2182                        Ok(())
2183                    }
2184                    Atom::Lit(_) => {
2185                        let x = self.val(a)?;
2186                        self.bind(&e.outputs[0], &x)
2187                    }
2188                }
2189            }
2190            "broadcast_in_dim" | "transpose" | "slice" | "concatenate" | "rev" | "pad"
2191            | "squeeze" | "expand_dims" | "copy" => self.movement(e),
2192            "iota" => self.movement(e),
2193            "dynamic_slice" => self.dynamic_slice(e),
2194            "dynamic_update_slice" => self.dynamic_update_slice(e),
2195            "gather" => self.gather(e, consts),
2196            "scatter" | "scatter-add" | "scatter_add" | "scatter-mul" | "scatter_mul"
2197            | "scatter-min" | "scatter_min" | "scatter-max" | "scatter_max" => {
2198                self.scatter(e, consts)
2199            }
2200            "reduce_sum" | "reduce_max" | "reduce_min" | "reduce_and" | "reduce_or" => {
2201                self.reduce(e)
2202            }
2203            "threefry2x32" => self.threefry(e),
2204            "cumsum" | "cumprod" | "cummax" | "cummin" => self.cumulative(e),
2205            "argmax" | "argmin" => self.arg_min_max(e),
2206            "sort" => self.sort(e),
2207            "conv_general_dilated" => self.conv(e),
2208            "dot_general" => self.dot_general(e),
2209            "top_k" => self.top_k(e),
2210            "cholesky" => self.cholesky(e),
2211            "triangular_solve" => self.triangular_solve(e),
2212            "cond" => self.cond(e),
2213            "while" => self.while_loop(e),
2214            "scan" => self.scan(e),
2215            _ => self.fallback(e),
2216        }
2217    }
2218
2219    /// An elementwise operation: `expr` of the operands' elements.
2220    fn elementwise(&mut self, e: &Eqn, expr: impl Fn(&[String]) -> String) -> Result<()> {
2221        let out = &e.outputs[0];
2222        let n = size(out.aval());
2223        if n == 1 {
2224            let args: Vec<String> = e
2225                .inputs
2226                .iter()
2227                .map(|a| self.val(a))
2228                .collect::<Result<_>>()?;
2229            return self.bind(out, &expr(&args));
2230        }
2231        if self.scope().fused.contains(&out.id()) {
2232            let args: Vec<String> = e
2233                .inputs
2234                .iter()
2235                .map(|a| self.at(a, "@I@"))
2236                .collect::<Result<_>>()?;
2237            self.fused.insert(out.id(), expr(&args));
2238            return Ok(());
2239        }
2240        let probe_args: Vec<String> = e
2241            .inputs
2242            .iter()
2243            .map(|a| self.at(a, "i"))
2244            .collect::<Result<_>>()?;
2245        let moved_ids = moved_ids(&probe_args);
2246        if !moved_ids.is_empty() {
2247            return self.elementwise_moved(e, &expr, &moved_ids);
2248        }
2249        let args: Vec<String> = e
2250            .inputs
2251            .iter()
2252            .map(|a| self.at(a, "i"))
2253            .collect::<Result<_>>()?;
2254        // An operand of the same type that is no longer used: in place.
2255        let target = e.inputs.iter().find(|a| {
2256            a.aval().dtype == out.aval().dtype && size(&a.aval()) == n && self.reusable(a)
2257        });
2258        if let Some(Atom::Var(v)) = target {
2259            let name = self.name(v)?.clone();
2260            self.line(format!(
2261                "for i in 0..{n}usize {{ let t = {}; {}[i] = t; }}",
2262                expr(&args),
2263                name.expr
2264            ));
2265            self.names.insert(out.id(), name);
2266            self.own(out);
2267            return Ok(());
2268        }
2269        self.bind(out, &format!("rt::build(|i| {})", expr(&args)))
2270    }
2271
2272    /// An elementwise operation some of whose operands are data movement
2273    /// that was not built ([`Scope::virtual_moves`]): the loop is split into
2274    /// runs over which each such operand reads one source at a fixed stride,
2275    /// so the moved arrays are never built (a `roll`, a concatenation of two
2276    /// slices, makes two runs). With too many runs, the operands are built.
2277    fn elementwise_moved(
2278        &mut self,
2279        e: &Eqn,
2280        expr: &dyn Fn(&[String]) -> String,
2281        ids: &[u64],
2282    ) -> Result<()> {
2283        const MAX_RUNS: usize = 8;
2284        let out = &e.outputs[0];
2285        let n = size(out.aval());
2286        let moved: Vec<Option<(Vec<Atom>, Vec<Src>)>> =
2287            ids.iter().map(|id| self.moves.get(id).cloned()).collect();
2288        // Each run: its start, its length, and for each moved operand its
2289        // source, first index, and stride.
2290        let mut runs: Vec<(usize, usize, Vec<RunPart>)> = Vec::new();
2291        let mut ok = true;
2292        let mut o = 0;
2293        while o < n && ok {
2294            let mut parts: Vec<Option<(usize, i64, i64)>> = Vec::new();
2295            for m in &moved {
2296                parts.push(match m {
2297                    Some((_, map)) => match map[o] {
2298                        Src::In(k, i) => Some((k, i, 0)),
2299                        _ => {
2300                            ok = false;
2301                            None
2302                        }
2303                    },
2304                    None => None,
2305                });
2306            }
2307            let mut len = 1;
2308            'grow: while o + len < n {
2309                let mut next = parts.clone();
2310                for (p, m) in next.iter_mut().zip(&moved) {
2311                    let (Some((k, base, stride)), Some((_, map))) = (p.as_mut(), m) else {
2312                        continue;
2313                    };
2314                    let Src::In(k2, i2) = map[o + len] else {
2315                        break 'grow;
2316                    };
2317                    if k2 != *k {
2318                        break 'grow;
2319                    }
2320                    if len == 1 {
2321                        *stride = i2 - *base;
2322                    } else if i2 != *base + *stride * len as i64 {
2323                        break 'grow;
2324                    }
2325                }
2326                parts = next;
2327                len += 1;
2328            }
2329            runs.push((o, len, parts));
2330            o += len;
2331            if runs.len() > MAX_RUNS {
2332                ok = false;
2333            }
2334        }
2335        // Short runs of a small array make loops that vectorize worse than
2336        // a copy and one loop (a `roll` by one of 64 booleans makes runs of
2337        // 1 and 63): the operands are built then.
2338        const MIN_RUN: usize = 16;
2339        const LARGE: usize = 512;
2340        if ok && n < LARGE && runs.len() > 1 && runs.iter().any(|r| r.1 < MIN_RUN) {
2341            ok = false;
2342        }
2343        if !ok && n >= LARGE {
2344            // Moves of large arrays whose elements are an affine function of
2345            // the output's multi-index (broadcasts, transposes, slices, and
2346            // their compositions) are read through index arithmetic instead
2347            // (small ones are faster built by copies).
2348            let dims = out.aval().shape.dims().to_vec();
2349            let affine: Option<Vec<(usize, i64, Vec<i64>)>> = moved
2350                .iter()
2351                .map(|m| m.as_ref().and_then(|(_, map)| affine_offset(map, &dims)))
2352                .collect();
2353            if let Some(affine) = affine {
2354                return self.elementwise_affine(e, expr, ids, &moved, &affine);
2355            }
2356        }
2357        if !ok {
2358            for &id in ids {
2359                self.materialize_move(id)?;
2360            }
2361            return self.elementwise(e, expr);
2362        }
2363        // The source names of the moved operands (an in-place target must
2364        // not be one of them: the runs read them out of order).
2365        let mut sources: HashSet<String> = HashSet::new();
2366        // A fused source is an expression that may read any array.
2367        let mut fused_source = false;
2368        for (srcs, _) in moved.iter().flatten() {
2369            for a in srcs {
2370                if let Atom::Var(v) = a {
2371                    fused_source |= self.fused.contains_key(&v.id());
2372                    if let Some(nm) = self.names.get(&v.id()) {
2373                        sources.insert(nm.expr.clone());
2374                    }
2375                }
2376            }
2377        }
2378        let target = e.inputs.iter().find(|a| {
2379            !fused_source
2380                && a.aval().dtype == out.aval().dtype
2381                && size(&a.aval()) == n
2382                && self.reusable(a)
2383                && !matches!(a, Atom::Var(v) if self.names.get(&v.id()).is_some_and(|nm| sources.contains(&nm.expr)))
2384        });
2385        let (name, _) = match target {
2386            Some(Atom::Var(v)) => (self.name(v)?.clone(), false),
2387            _ => {
2388                let ty = self.ty(out.aval())?;
2389                let zero = format!("<{} as Default>::default()", elem_ty(out.aval().dtype)?);
2390                let name = format!("v{}", out.id());
2391                self.line(format!("let mut {name}: {ty} = [{zero}; {n}];"));
2392                (
2393                    Name {
2394                        expr: name,
2395                        is_ref: false,
2396                    },
2397                    true,
2398                )
2399            }
2400        };
2401        for (start, len, parts) in &runs {
2402            let i = if *start == 0 {
2403                "i".to_string()
2404            } else {
2405                format!("{start} + i")
2406            };
2407            let mut reads = Vec::new();
2408            for (k, &id) in ids.iter().enumerate() {
2409                let (Some((src, base, stride)), Some((srcs, _))) = (&parts[k], &moved[k]) else {
2410                    continue;
2411                };
2412                let idx = match (*base, *stride) {
2413                    (b, 0) => format!("{b}"),
2414                    (0, 1) => "i".to_string(),
2415                    (b, 1) => format!("{b} + i"),
2416                    // Negative strides (`rev`) go down from the base.
2417                    (b, st) if st < 0 => format!("{b} - {} * i", -st),
2418                    (b, st) => format!("{b} + {st} * i"),
2419                };
2420                reads.push((format!("@M{id}@"), self.at(&srcs[*src], &idx)?));
2421            }
2422            let mut args = Vec::new();
2423            for a in &e.inputs {
2424                let mut x = self.at(a, &i)?;
2425                for (p, r) in &reads {
2426                    x = x.replace(p, r);
2427                }
2428                args.push(x);
2429            }
2430            self.line(format!(
2431                "for i in 0..{len}usize {{ let t = {}; {}[{i}] = t; }}",
2432                expr(&args),
2433                name.expr
2434            ));
2435        }
2436        self.names.insert(out.id(), name);
2437        self.own(out);
2438        Ok(())
2439    }
2440
2441    /// [`Self::elementwise_moved`] when every moved operand reads one source
2442    /// at an affine offset of the output's multi-index (`affine`: the
2443    /// source, the base, and the stride of each dimension): nested loops
2444    /// over the output's dimensions (adjacent ones merged where every
2445    /// operand reads them contiguously) that read the sources directly.
2446    fn elementwise_affine(
2447        &mut self,
2448        e: &Eqn,
2449        expr: &dyn Fn(&[String]) -> String,
2450        ids: &[u64],
2451        moved: &[Option<(Vec<Atom>, Vec<Src>)>],
2452        affine: &[(usize, i64, Vec<i64>)],
2453    ) -> Result<()> {
2454        let out = &e.outputs[0];
2455        let n = size(out.aval());
2456        // The dimensions, with each operand's strides and the output's.
2457        let mut dims: Vec<usize> = out.aval().shape.dims().to_vec();
2458        let mut ostrides: Vec<i64> = strides(&dims).iter().map(|&x| x as i64).collect();
2459        let mut sstrides: Vec<Vec<i64>> = affine.iter().map(|a| a.2.clone()).collect();
2460        // Drop dimensions of size 1, then merge `d` into `d - 1` where every
2461        // stride of `d - 1` is that of `d` times its size.
2462        let keep: Vec<usize> = (0..dims.len()).filter(|&d| dims[d] > 1).collect();
2463        dims = keep.iter().map(|&d| dims[d]).collect();
2464        ostrides = keep.iter().map(|&d| ostrides[d]).collect();
2465        for st in &mut sstrides {
2466            *st = keep.iter().map(|&d| st[d]).collect();
2467        }
2468        let mut d = dims.len();
2469        while d > 1 {
2470            d -= 1;
2471            let size = dims[d] as i64;
2472            let mergeable = ostrides[d - 1] == ostrides[d] * size
2473                && sstrides.iter().all(|st| st[d - 1] == st[d] * size);
2474            if mergeable {
2475                dims[d - 1] *= dims[d];
2476                dims.remove(d);
2477                ostrides.remove(d - 1);
2478                for st in &mut sstrides {
2479                    st.remove(d - 1);
2480                }
2481            }
2482        }
2483        let rank = dims.len();
2484        let index = |strides: &[i64], base: i64| {
2485            let mut terms: Vec<String> = Vec::new();
2486            if base != 0 {
2487                terms.push(format!("{base}"));
2488            }
2489            for (d, &st) in strides.iter().enumerate() {
2490                match st {
2491                    0 => {}
2492                    1 => terms.push(format!("i{d}")),
2493                    _ => terms.push(format!("i{d} * {st}")),
2494                }
2495            }
2496            if terms.is_empty() {
2497                "0".to_string()
2498            } else {
2499                terms.join(" + ")
2500            }
2501        };
2502        let mut reads = Vec::new();
2503        for (k, ((&id, m), (src, base, _))) in ids.iter().zip(moved).zip(affine).enumerate() {
2504            let (srcs, _) = m.as_ref().expect("affine moves have sources");
2505            let at = index(&sstrides[k], *base);
2506            reads.push((format!("@M{id}@"), self.at(&srcs[*src], &at)?));
2507        }
2508        let mut args = Vec::new();
2509        for a in &e.inputs {
2510            let mut x = self.at(a, "i")?;
2511            for (p, r) in &reads {
2512                x = x.replace(p, r);
2513            }
2514            args.push(x);
2515        }
2516        let ty = self.ty(out.aval())?;
2517        let zero = format!("<{} as Default>::default()", elem_ty(out.aval().dtype)?);
2518        let name = format!("v{}", out.id());
2519        self.line(format!("let mut {name}: {ty} = [{zero}; {n}];"));
2520        for (d, &size) in dims.iter().enumerate() {
2521            self.line(format!("for i{d} in 0..{size}usize {{"));
2522            self.indent += 1;
2523        }
2524        self.line(format!("let i = {};", index(&ostrides, 0)));
2525        self.line(format!("let t = {}; {name}[i] = t;", expr(&args)));
2526        for _ in 0..rank {
2527            self.indent -= 1;
2528            self.line("}");
2529        }
2530        self.names.insert(
2531            out.id(),
2532            Name {
2533                expr: name,
2534                is_ref: false,
2535            },
2536        );
2537        self.own(out);
2538        Ok(())
2539    }
2540
2541    /// Builds a data movement result that was not built
2542    /// ([`Scope::virtual_moves`]).
2543    fn materialize_move(&mut self, id: u64) -> Result<()> {
2544        let Some((srcs, map)) = self.moves.remove(&id) else {
2545            return Ok(());
2546        };
2547        let n = map.len();
2548        let dtype = srcs
2549            .iter()
2550            .map(|a| a.aval().dtype)
2551            .next()
2552            .ok_or_else(|| Error("a data movement without sources".into()))?;
2553        let pairs: Vec<(usize, Src)> = map.into_iter().enumerate().collect();
2554        let t = elem_ty(dtype)?;
2555        let zero = format!("<{t} as Default>::default()");
2556        let name = format!("v{id}");
2557        self.line(format!("let mut {name}: [{t}; {n}] = [{zero}; {n}];"));
2558        self.copies(&name, false, &pairs, &srcs, None, &zero, "", "", None)?;
2559        self.names.insert(
2560            id,
2561            Name {
2562                expr: name.clone(),
2563                is_ref: false,
2564            },
2565        );
2566        // A mutable local: the operation that reads it may write in place.
2567        if let Some(s) = self.scopes.last_mut() {
2568            s.owned.insert(id);
2569            s.fused.remove(&id);
2570        }
2571        // Fused expressions that read it: from the array now.
2572        let p = format!("@M{id}@");
2573        for x in self.fused.values_mut() {
2574            if x.contains(&p) {
2575                *x = x.replace(&p, &format!("{name}[@I@]"));
2576            }
2577        }
2578        Ok(())
2579    }
2580
2581    /// A select whose predicate is one value broadcast: one branch for the
2582    /// whole array, writing into a case that is not used afterwards.
2583    fn uniform_select(&mut self, e: &Eqn) -> Result<()> {
2584        let p = match &e.inputs[0] {
2585            Atom::Var(pv) if size(pv.aval()) > 1 => self.scope().uniform[&pv.id()].clone(),
2586            a => a.clone(),
2587        };
2588        let p = self.val(&p)?;
2589        let p = if e.inputs[0].aval().dtype == DType::Bool {
2590            p
2591        } else {
2592            format!("({p} != 0)")
2593        };
2594        let (c0, c1) = (&e.inputs[1], &e.inputs[2]);
2595        let out = &e.outputs[0];
2596        for (keep, other, cond) in [(c0, c1, p.clone()), (c1, c0, format!("!{p}"))] {
2597            if self.reusable(keep)
2598                && let Atom::Var(v) = keep
2599            {
2600                let n = self.name(v)?.clone();
2601                let o = self.val(other)?;
2602                let target = if self.by_ref(&n) {
2603                    format!("*{}", n.expr)
2604                } else {
2605                    n.expr.clone()
2606                };
2607                self.line(format!("if {cond} {{ {target} = {o}; }}"));
2608                self.names.insert(out.id(), n);
2609                self.own(out);
2610                return Ok(());
2611            }
2612        }
2613        let (a, b) = (self.val(c1)?, self.val(c0)?);
2614        self.bind(out, &format!("if {p} {{ {a} }} else {{ {b} }}"))
2615    }
2616
2617    /// The expression of a copied element.
2618    fn src_expr(
2619        &self,
2620        srcs: &[Atom],
2621        s: Src,
2622        pad: Option<&str>,
2623        zero: &str,
2624        base: &str,
2625        idx: &str,
2626    ) -> Result<String> {
2627        Ok(match s {
2628            Src::In(k, _) => {
2629                let a = &srcs[k];
2630                if size(&a.aval()) == 1 {
2631                    self.val(a)?
2632                } else {
2633                    let i = if base.is_empty() {
2634                        idx.to_string()
2635                    } else {
2636                        format!("{base} + {idx}")
2637                    };
2638                    self.at(a, &i)?
2639                }
2640            }
2641            Src::Pad => pad
2642                .ok_or_else(|| Error("padding without a value".into()))?
2643                .to_string(),
2644            Src::Zero => zero.to_string(),
2645        })
2646    }
2647
2648    /// Writes into `dst` (a mutable array, or a scalar variable when the
2649    /// destination has one element) the copies of `pairs` (destination,
2650    /// source), destinations offset by `dst_base`, sources by `src_base`.
2651    /// The pairs with the elements of data movement results that were not
2652    /// built ([`Scope::virtual_moves`]) replaced by their sources.
2653    fn resolve(&self, srcs: &[Atom], pairs: &[(usize, Src)]) -> (Vec<Atom>, Vec<(usize, Src)>) {
2654        let mut out: Vec<Atom> = Vec::new();
2655        let mut add = |a: &Atom| match out.iter().position(|b| b == a) {
2656            Some(k) => k,
2657            None => {
2658                out.push(a.clone());
2659                out.len() - 1
2660            }
2661        };
2662        let resolved = pairs
2663            .iter()
2664            .map(|&(o, s)| {
2665                let s = match s {
2666                    Src::In(k, i) => match &srcs[k] {
2667                        Atom::Var(v) if self.moves.contains_key(&v.id()) => {
2668                            let (vs, map) = &self.moves[&v.id()];
2669                            match map[i as usize] {
2670                                Src::In(k2, i2) => Src::In(add(&vs[k2]), i2),
2671                                other => other,
2672                            }
2673                        }
2674                        a => Src::In(add(a), i),
2675                    },
2676                    other => other,
2677                };
2678                (o, s)
2679            })
2680            .collect();
2681        (out, resolved)
2682    }
2683
2684    /// [`Self::copies`] of `pairs` (grouped by source, without combining)
2685    /// as a table of positions for each source, so that each loop reads
2686    /// one source (a table with a `match` on the source per element makes
2687    /// an indirect jump per element).
2688    #[allow(clippy::too_many_arguments)]
2689    fn copies_by_source(
2690        &mut self,
2691        dst: &str,
2692        pairs: &[(usize, Src)],
2693        srcs: &[Atom],
2694        pad: Option<&str>,
2695        zero: &str,
2696        at: &dyn Fn(String) -> String,
2697        src_base: &str,
2698    ) -> Result<()> {
2699        let mut start = 0;
2700        while start < pairs.len() {
2701            let same = |s: Src| match (pairs[start].1, s) {
2702                (Src::In(a, _), Src::In(b, _)) => a == b,
2703                (a, b) => std::mem::discriminant(&a) == std::mem::discriminant(&b),
2704            };
2705            let end = start + pairs[start..].iter().take_while(|&&(_, s)| same(s)).count();
2706            let group = &pairs[start..end];
2707            let entries: Vec<[i64; 2]> = group
2708                .iter()
2709                .map(|&(o, s)| match s {
2710                    Src::In(_, i) => [o as i64, i],
2711                    _ => [o as i64, 0],
2712                })
2713                .collect();
2714            let table = self.pair_table("usize", &entries)?;
2715            let v = match group[0].1 {
2716                Src::In(k, _) => {
2717                    let a = &srcs[k];
2718                    if size(&a.aval()) == 1 {
2719                        self.val(a)?
2720                    } else if src_base.is_empty() {
2721                        self.at(a, "i")?
2722                    } else {
2723                        self.at(a, &format!("{src_base} + i"))?
2724                    }
2725                }
2726                Src::Pad => pad
2727                    .ok_or_else(|| Error("padding without a value".into()))?
2728                    .to_string(),
2729                Src::Zero => zero.to_string(),
2730            };
2731            self.line(format!("for &[o, i] in {table}.iter() {{"));
2732            self.indent += 1;
2733            self.line("let _ = i;");
2734            self.line(format!("{dst}[{}] = {v};", at("o".into())));
2735            self.indent -= 1;
2736            self.line("}");
2737            start = end;
2738        }
2739        Ok(())
2740    }
2741
2742    // The source and destination each need a buffer, an offset, and strides.
2743    #[allow(clippy::too_many_arguments)]
2744    fn copies(
2745        &mut self,
2746        dst: &str,
2747        dst_scalar: bool,
2748        pairs: &[(usize, Src)],
2749        srcs: &[Atom],
2750        pad: Option<&str>,
2751        zero: &str,
2752        dst_base: &str,
2753        src_base: &str,
2754        combine: Option<(BinaryOp, DType)>,
2755    ) -> Result<()> {
2756        let (srcs, pairs) = if src_base.is_empty() {
2757            self.resolve(srcs, pairs)
2758        } else {
2759            (srcs.to_vec(), pairs.to_vec())
2760        };
2761        let (srcs, pairs) = (&srcs[..], &pairs[..]);
2762        let at = |o: String| {
2763            if dst_base.is_empty() {
2764                o
2765            } else {
2766                format!("{dst_base} + {o}")
2767            }
2768        };
2769        let assign = |target: String, value: String| match combine {
2770            None => format!("{target} = {value};"),
2771            Some((op, t)) => format!("{target} = {};", binary_expr(op, t, &target, &value)),
2772        };
2773        if dst_scalar {
2774            for &(_, s) in pairs {
2775                let v = self.src_expr(
2776                    srcs,
2777                    s,
2778                    pad,
2779                    zero,
2780                    src_base,
2781                    &match s {
2782                        Src::In(_, i) => i.to_string(),
2783                        _ => "0".into(),
2784                    },
2785                )?;
2786                self.line(assign(dst.to_string(), v));
2787            }
2788            return Ok(());
2789        }
2790        let mut pats = patterns(pairs);
2791        if pats.len() > 8 {
2792            // Interleaved sources (a `stack` along the last axis, say) make
2793            // runs of one element; the copies of each source alone may
2794            // still form a few patterns.
2795            let by_source = patterns_by_source(pairs);
2796            if by_source.len() < pats.len() {
2797                pats = by_source;
2798            }
2799        }
2800        let grouped;
2801        let mut pairs = pairs;
2802        if pats.len() > 64 && combine.is_none() {
2803            // Elements of several sources interleaved (a concatenation then
2804            // a transpose, say): each element is written once, so the
2805            // copies can go source by source, which often makes a few
2806            // strided loops.
2807            let mut g = pairs.to_vec();
2808            g.sort_by_key(|&(o, s)| {
2809                let k = match s {
2810                    Src::Pad => 0,
2811                    Src::Zero => 1,
2812                    Src::In(k, _) => k + 2,
2813                };
2814                (k, o)
2815            });
2816            let gp = patterns(&g);
2817            if gp.len() <= 64 {
2818                grouped = g;
2819                pairs = &grouped;
2820                pats = gp;
2821            } else {
2822                return self.copies_by_source(dst, &g, srcs, pad, zero, &at, src_base);
2823            }
2824        }
2825        if pats.len() > 64 {
2826            // A table of sources.
2827            let codes: Vec<[i64; 2]> = pairs
2828                .iter()
2829                .map(|&(o, s)| {
2830                    let c = match s {
2831                        Src::In(k, i) => code(k, i as usize),
2832                        Src::Pad => -1,
2833                        Src::Zero => 0,
2834                    };
2835                    [o as i64, c]
2836                })
2837                .collect();
2838            let table = self.pair_table("i64", &codes)?;
2839            self.line(format!("for &[o, m] in {table}.iter() {{"));
2840            self.indent += 1;
2841            self.line("let o = o as usize;");
2842            let mut arms = Vec::new();
2843            for (k, a) in srcs.iter().enumerate() {
2844                let i = if src_base.is_empty() {
2845                    "(m & 0xffff_ffff) as usize".to_string()
2846                } else {
2847                    format!("{src_base} + (m & 0xffff_ffff) as usize")
2848                };
2849                let v = if size(&a.aval()) == 1 {
2850                    self.val(a)?
2851                } else {
2852                    self.at(a, &i)?
2853                };
2854                arms.push(format!("{} => {v}", k + 1));
2855            }
2856            arms.push(format!("0 => {zero}"));
2857            arms.push(format!("_ => {}", pad.unwrap_or(zero)));
2858            self.line(assign(
2859                format!("{dst}[{}]", at("o".into())),
2860                format!("match m >> 32 {{ {} }}", arms.join(", ")),
2861            ));
2862            self.indent -= 1;
2863            self.line("}");
2864            return Ok(());
2865        }
2866        for p in pats {
2867            let r = p.run;
2868            let start = match r.src {
2869                Src::In(_, s) => s,
2870                _ => 0,
2871            };
2872            // The loops, outermost first.
2873            let depth = p.levels.len();
2874            for (l, &(reps, _, _)) in p.levels.iter().enumerate().rev() {
2875                self.line(format!("for r{l} in 0..{reps}usize {{"));
2876                self.indent += 1;
2877            }
2878            let mut o0 = r.out.to_string();
2879            let mut s_terms: Vec<(String, i64)> = Vec::new();
2880            for (l, &(_, dout, dstart)) in p.levels.iter().enumerate() {
2881                o0 = format!("{o0} + r{l} * {dout}");
2882                if dstart != 0 {
2883                    s_terms.push((format!("r{l}"), dstart));
2884                }
2885            }
2886            let s0 = if s_terms.iter().any(|(_, d)| *d < 0) {
2887                let terms: Vec<String> = s_terms
2888                    .iter()
2889                    .map(|(v, d)| format!(" + ({v} as i64) * {d}"))
2890                    .collect();
2891                format!("(({start}i64){}) as usize", terms.concat())
2892            } else {
2893                let terms: Vec<String> = s_terms
2894                    .iter()
2895                    .map(|(v, d)| format!(" + {v} * {d}"))
2896                    .collect();
2897                format!("{start}{}", terms.concat())
2898            };
2899            let scalar_src = match r.src {
2900                Src::In(k, _) => size(&srcs[k].aval()) == 1,
2901                _ => true,
2902            };
2903            if r.len == 1 {
2904                let v = self.src_expr(srcs, r.src, pad, zero, src_base, &s0)?;
2905                self.line(assign(format!("{dst}[{}]", at(o0.clone())), v));
2906            } else if (scalar_src || r.stride == 0) && combine.is_none() {
2907                let v = self.src_expr(srcs, r.src, pad, zero, src_base, &s0)?;
2908                self.line(format!(
2909                    "{dst}[{}..{}].fill({v});",
2910                    at(o0.clone()),
2911                    at(format!("{o0} + {}", r.len))
2912                ));
2913            } else if r.stride == 1
2914                && combine.is_none()
2915                && !matches!(r.src, Src::In(k, _) if self.is_fused(&srcs[k]))
2916            {
2917                let Src::In(k, _) = r.src else { unreachable!() };
2918                let s_lo = if src_base.is_empty() {
2919                    s0.clone()
2920                } else {
2921                    format!("{src_base} + {s0}")
2922                };
2923                let src = self.slice(&srcs[k], &s_lo, &format!("{s_lo} + {}", r.len))?;
2924                self.line(format!(
2925                    "{dst}[{}..{}].copy_from_slice(&{src});",
2926                    at(o0.clone()),
2927                    at(format!("{o0} + {}", r.len))
2928                ));
2929            } else {
2930                self.line(format!("for j in 0..{}usize {{", r.len));
2931                self.indent += 1;
2932                let idx = if r.stride >= 0 {
2933                    format!("{s0} + j * {}", r.stride)
2934                } else {
2935                    format!("{s0} - j * {}", -r.stride)
2936                };
2937                let v = self.src_expr(srcs, r.src, pad, zero, src_base, &idx)?;
2938                self.line(assign(format!("{dst}[{}]", at(format!("{o0} + j"))), v));
2939                self.indent -= 1;
2940                self.line("}");
2941            }
2942            for _ in 0..depth {
2943                self.indent -= 1;
2944                self.line("}");
2945            }
2946        }
2947        Ok(())
2948    }
2949
2950    /// Binds `out` to an array built from copies (every element written).
2951    fn build_from(
2952        &mut self,
2953        out: &Var,
2954        pairs: &[(usize, Src)],
2955        srcs: &[Atom],
2956        pad: Option<&str>,
2957        src_base: &str,
2958    ) -> Result<()> {
2959        let (srcs, pairs) = if src_base.is_empty() {
2960            self.resolve(srcs, pairs)
2961        } else {
2962            (srcs.to_vec(), pairs.to_vec())
2963        };
2964        let (srcs, pairs) = (&srcs[..], &pairs[..]);
2965        // Used only by other data movement: not built.
2966        if self.scope().virtual_moves.contains(&out.id()) && pad.is_none() {
2967            let mut map = vec![Src::Zero; size(out.aval())];
2968            for &(o, s) in pairs {
2969                map[o] = s;
2970            }
2971            self.moves.insert(out.id(), (srcs.to_vec(), map));
2972            return Ok(());
2973        }
2974        let t = out.aval().dtype;
2975        let zero = format!("<{} as Default>::default()", elem_ty(t)?);
2976        if size(out.aval()) == 1 {
2977            let (_, s) = pairs[0];
2978            let idx = match s {
2979                Src::In(_, i) => i.to_string(),
2980                _ => "0".into(),
2981            };
2982            let v = self.src_expr(srcs, s, pad, &zero, src_base, &idx)?;
2983            return self.bind(out, &v);
2984        }
2985        let ty = self.ty(out.aval())?;
2986        let name = format!("v{}", out.id());
2987        // A broadcast of one value.
2988        let same = |s: Src| match s {
2989            Src::In(k, i) => {
2990                if size(&srcs[k].aval()) == 1 {
2991                    Src::In(k, 0)
2992                } else {
2993                    Src::In(k, i)
2994                }
2995            }
2996            s => s,
2997        };
2998        let first = same(pairs[0].1);
2999        if pairs.len() == size(out.aval()) && pairs.iter().all(|&(_, s)| same(s) == first) {
3000            let idx = match first {
3001                Src::In(_, i) => i.to_string(),
3002                _ => "0".into(),
3003            };
3004            let v = self.src_expr(srcs, first, pad, &zero, src_base, &idx)?;
3005            if self.targets.contains_key(&out.id()) {
3006                return self.bind(out, &format!("[{v}; {}]", size(out.aval())));
3007            }
3008            // Not built: a fill `[s; N]` where a whole array is needed, and
3009            // the value itself where an element is read (`at`). The value is
3010            // kept in a local of its own, which nothing updates.
3011            let s = if is_literal(&v) {
3012                v
3013            } else {
3014                let s = self.fresh("u");
3015                self.line(format!("let {s}: {} = {v};", elem_ty(t)?));
3016                s
3017            };
3018            self.uniform_consts.insert(out.id(), s.clone());
3019            self.names.insert(
3020                out.id(),
3021                Name {
3022                    expr: format!("[{s}; {}]", size(out.aval())),
3023                    is_ref: false,
3024                },
3025            );
3026            return Ok(());
3027        }
3028        let target = self.targets.get(&out.id()).cloned().filter(|t| {
3029            !self.into_targets.contains(&out.id())
3030                || !srcs
3031                    .iter()
3032                    .any(|a| matches!(a, Atom::Var(v) if self.names.get(&v.id()).is_some_and(|n| &n.expr == t)))
3033        });
3034        let (name, is_ref) = match target {
3035            Some(t) => {
3036                // The destination holds initialized elements: cleared only if
3037                // the copies leave some of them.
3038                let mut covered = vec![false; size(out.aval())];
3039                for &(o, _) in pairs {
3040                    covered[o] = true;
3041                }
3042                if !covered.iter().all(|&c| c) {
3043                    self.line(format!("*{t} = [{zero}; {}];", size(out.aval())));
3044                }
3045                (t, true)
3046            }
3047            None => {
3048                // Every element copied: no need to clear the array first.
3049                let mut covered = vec![false; size(out.aval())];
3050                for &(o, _) in pairs {
3051                    covered[o] = true;
3052                }
3053                let init = format!("[{zero}; {}]", size(out.aval()));
3054                let init = if covered.iter().all(|&c| c) {
3055                    format!("rt::overwritten({init})")
3056                } else {
3057                    init
3058                };
3059                self.line(format!("let mut {name}: {ty} = {init};"));
3060                (name, false)
3061            }
3062        };
3063        self.copies(&name, false, pairs, srcs, pad, &zero, "", src_base, None)?;
3064        self.names.insert(out.id(), Name { expr: name, is_ref });
3065        self.own(out);
3066        Ok(())
3067    }
3068
3069    /// Data movement with static positions, found with a probe.
3070    fn movement(&mut self, e: &Eqn) -> Result<()> {
3071        let out = &e.outputs[0];
3072        let data: Vec<usize> = match e.prim.name() {
3073            "pad" => vec![0],
3074            _ => (0..e.inputs.len()).collect(),
3075        };
3076        let probes: Vec<HostArray> = e
3077            .inputs
3078            .iter()
3079            .enumerate()
3080            .map(|(k, a)| {
3081                if data.contains(&k) {
3082                    probe(k, &a.aval())
3083                } else {
3084                    HostArray::from_vec(vec![-1i64], a.aval().shape.clone())
3085                }
3086            })
3087            .collect();
3088        let params = match &e.params {
3089            Params::Iota {
3090                shape, dimension, ..
3091            } => Params::Iota {
3092                dtype: DType::I64,
3093                shape: shape.clone(),
3094                dimension: *dimension,
3095            },
3096            p => p.clone(),
3097        };
3098        if e.prim.name() == "iota" {
3099            // Not folded (a large iota): computed directly.
3100            let r = e
3101                .prim
3102                .eval(&Interp, &[], &e.params)
3103                .map_err(|x| Error(x.to_string()))?;
3104            let elems: Vec<String> = (0..r[0].size())
3105                .map(|i| elem_lit(&r[0], i))
3106                .collect::<Result<_>>()?;
3107            let ty = self.ty(out.aval())?;
3108            let name = self.static_array(&ty, &elems.join(", "));
3109            self.names.insert(
3110                out.id(),
3111                Name {
3112                    expr: name,
3113                    is_ref: false,
3114                },
3115            );
3116            return Ok(());
3117        }
3118        let r = e
3119            .prim
3120            .eval(&Interp, &probes, &params)
3121            .map_err(|x| Error(format!("probe: {x}")))?;
3122        let map = r[0].to_vec::<i64>().map_err(|x| Error(x.to_string()))?;
3123        let pairs: Vec<(usize, Src)> = map
3124            .iter()
3125            .enumerate()
3126            .map(|(o, &m)| (o, decode(m)))
3127            .collect();
3128        if e.prim.name() == "pad" && self.scope().virtual_moves.contains(&out.id()) {
3129            // Not built: the padding is element 0 of the padding value (the
3130            // second source), which `resolve` keeps with the move.
3131            let pairs: Vec<(usize, Src)> = pairs
3132                .into_iter()
3133                .map(|(o, s)| (o, if s == Src::Pad { Src::In(1, 0) } else { s }))
3134                .collect();
3135            return self.build_from(out, &pairs, &e.inputs, None, "");
3136        }
3137        let pad = if e.prim.name() == "pad" {
3138            Some(self.val(&e.inputs[1])?)
3139        } else {
3140            None
3141        };
3142        self.build_from(out, &pairs, &e.inputs, pad.as_deref(), "")
3143    }
3144
3145    /// The flat offset of a window whose start indices are `starts` (scalar
3146    /// expressions), clamped so that a window of `sizes` fits in `dims` (or,
3147    /// with `check`, also an expression of whether they were in bounds).
3148    fn window_base(
3149        &mut self,
3150        dims: &[usize],
3151        sizes: &[usize],
3152        starts: &[(usize, String)],
3153        check: bool,
3154    ) -> (String, Option<String>) {
3155        let st = strides(dims);
3156        let base = self.fresh("b");
3157        let mut terms = Vec::new();
3158        let mut checks = Vec::new();
3159        for (d, s) in starts {
3160            let hi = (dims[*d] - sizes[*d]) as i64;
3161            let sv = format!("({s} as i64)");
3162            if check {
3163                checks.push(format!("(0..={hi}).contains(&{sv})"));
3164            }
3165            if hi == 0 {
3166                continue;
3167            }
3168            terms.push(format!("({sv}.clamp(0, {hi}) as usize) * {}", st[*d]));
3169        }
3170        let expr = if terms.is_empty() {
3171            "0usize".to_string()
3172        } else {
3173            terms.join(" + ")
3174        };
3175        self.line(format!("let {base}: usize = {expr};"));
3176        let ok = if check {
3177            let name = self.fresh("ok");
3178            let expr = if checks.is_empty() {
3179                "true".to_string()
3180            } else {
3181                checks.join(" && ")
3182            };
3183            self.line(format!("let {name}: bool = {expr};"));
3184            Some(name)
3185        } else {
3186            None
3187        };
3188        (base, ok)
3189    }
3190
3191    fn dynamic_slice(&mut self, e: &Eqn) -> Result<()> {
3192        let x = &e.inputs[0];
3193        let out = &e.outputs[0];
3194        let xa = x.aval();
3195        if size(&xa) == 1 {
3196            let v = self.val(x)?;
3197            return self.bind(out, &v);
3198        }
3199        let dims = xa.shape.dims().to_vec();
3200        let sizes = out.aval().shape.dims().to_vec();
3201        let starts: Vec<(usize, String)> = e.inputs[1..]
3202            .iter()
3203            .enumerate()
3204            .map(|(d, a)| Ok((d, self.val(a)?)))
3205            .collect::<Result<_>>()?;
3206        let (base, _) = self.window_base(&dims, &sizes, &starts, false);
3207        if self.scope().views.contains(&out.id())
3208            && !self.targets.contains_key(&out.id())
3209            && let Atom::Var(xv) = x
3210            && !self.moves.contains_key(&xv.id())
3211            && !self.uniform_consts.contains_key(&xv.id())
3212            && !self.name(xv)?.expr.starts_with('[')
3213            && !self.is_mut_input(xv)
3214        {
3215            // A reference to the window (contiguous in `x`; not of an input
3216            // updated in place, whose buffer an output may overwrite while
3217            // the reference is read).
3218            let n = size(out.aval());
3219            let src = self.val(x)?;
3220            let name = format!("v{}", out.id());
3221            self.line(format!(
3222                "let {name}: &[{}; {n}] = (&{src}[{base}..{base} + {n}]).try_into().expect(\"a window\");",
3223                elem_ty(xa.dtype)?
3224            ));
3225            self.views.insert(out.id());
3226            self.names.insert(
3227                out.id(),
3228                Name {
3229                    expr: name,
3230                    is_ref: true,
3231                },
3232            );
3233            return Ok(());
3234        }
3235        // The offsets relative to the window's start.
3236        let mut probes = vec![probe(0, &xa)];
3237        for a in &e.inputs[1..] {
3238            probes.push(HostArray::zeros(a.aval().shape.clone(), a.aval().dtype));
3239        }
3240        let r = e
3241            .prim
3242            .eval(&Interp, &probes, &e.params)
3243            .map_err(|x| Error(x.to_string()))?;
3244        let map = r[0].to_vec::<i64>().map_err(|x| Error(x.to_string()))?;
3245        let pairs: Vec<(usize, Src)> = map
3246            .iter()
3247            .enumerate()
3248            .map(|(o, &m)| (o, decode(m)))
3249            .collect();
3250        if let Atom::Var(xv) = x
3251            && let Some((vs, xmap)) = self.moves.get(&xv.id()).cloned()
3252        {
3253            return self.dynamic_slice_of_move(out, &pairs, &base, &vs, &xmap);
3254        }
3255        self.build_from(out, &pairs, std::slice::from_ref(x), None, &base)
3256    }
3257
3258    /// A window (at `base`, element `o` at the offset of `pairs[o]`) of an
3259    /// array that is not built (a move of the sources `vs` by `xmap`: one
3260    /// array and scalars), each element read through a table of the move's
3261    /// positions.
3262    fn dynamic_slice_of_move(
3263        &mut self,
3264        out: &Var,
3265        pairs: &[(usize, Src)],
3266        base: &str,
3267        vs: &[Atom],
3268        xmap: &[Src],
3269    ) -> Result<()> {
3270        let arrays: Vec<usize> = (0..vs.len()).filter(|&k| size(&vs[k].aval()) > 1).collect();
3271        if arrays.len() > 1 {
3272            return err("a window of a move of several arrays");
3273        }
3274        let kd = arrays.first().copied();
3275        // The table: the array's position, `-1 - k` for scalar source `k`,
3276        // or `i32::MIN` for zero.
3277        let table: Vec<String> = xmap
3278            .iter()
3279            .map(|s| match *s {
3280                Src::In(k, i) if Some(k) == kd => i.to_string(),
3281                Src::In(k, _) => (-1 - k as i64).to_string(),
3282                _ => i32::MIN.to_string(),
3283            })
3284            .collect();
3285        let tname = self.static_array(&format!("[i32; {}]", table.len()), &table.join(", "));
3286        let rel: Vec<String> = pairs
3287            .iter()
3288            .map(|&(_, s)| match s {
3289                Src::In(_, i) => i.to_string(),
3290                _ => "0".into(),
3291            })
3292            .collect();
3293        let rname = self.static_array(&format!("[usize; {}]", rel.len()), &rel.join(", "));
3294        let t = out.aval().dtype;
3295        let mut expr = format!("<{} as Default>::default()", elem_ty(t)?);
3296        for k in (0..vs.len()).rev() {
3297            if Some(k) == kd {
3298                continue;
3299            }
3300            let v = self.val(&vs[k])?;
3301            expr = format!("if t == {} {{ {v} }} else {{ {expr} }}", -1 - k as i64);
3302        }
3303        if let Some(kd) = kd {
3304            let a = self.at(&vs[kd], "t as usize")?;
3305            expr = format!("if t >= 0 {{ {a} }} else {{ {expr} }}");
3306        }
3307        let name = format!("v{}", out.id());
3308        let ty = self.ty(out.aval())?;
3309        self.line(format!(
3310            "let mut {name}: {ty} = rt::build(|o| {{ let t = {tname}[{base} + {rname}[o]]; {expr} }});"
3311        ));
3312        self.names.insert(
3313            out.id(),
3314            Name {
3315                expr: name,
3316                is_ref: false,
3317            },
3318        );
3319        self.own(out);
3320        Ok(())
3321    }
3322
3323    /// Copies `x` into a new mutable array (or scalar) for `out`, and
3324    /// returns its name.
3325    fn copy_for_update(&mut self, out: &Var, x: &Atom) -> Result<String> {
3326        if self.reusable(x)
3327            && let Atom::Var(v) = x
3328        {
3329            let n = self.name(v)?.clone();
3330            self.names.insert(out.id(), n.clone());
3331            self.own(out);
3332            return Ok(n.expr);
3333        }
3334        if let Some(t) = self.targets.get(&out.id()).cloned()
3335            && !self.into_targets.contains(&out.id())
3336        {
3337            let v = self.val(x)?;
3338            self.line(format!("*{t} = {v};"));
3339            self.names.insert(
3340                out.id(),
3341                Name {
3342                    expr: t.clone(),
3343                    is_ref: true,
3344                },
3345            );
3346            self.own(out);
3347            return Ok(t);
3348        }
3349        let ty = self.ty(out.aval())?;
3350        let name = format!("v{}", out.id());
3351        let v = self.val(x)?;
3352        self.line(format!("let mut {name}: {ty} = {v};"));
3353        if size(out.aval()) > 1 {
3354            self.own(out);
3355        }
3356        self.names.insert(
3357            out.id(),
3358            Name {
3359                expr: name.clone(),
3360                is_ref: false,
3361            },
3362        );
3363        Ok(name)
3364    }
3365
3366    fn dynamic_update_slice(&mut self, e: &Eqn) -> Result<()> {
3367        let (x, u) = (&e.inputs[0], &e.inputs[1]);
3368        let out = &e.outputs[0];
3369        let xa = x.aval();
3370        if size(&xa) == 1 {
3371            let v = self.val(u)?;
3372            return self.bind(out, &v);
3373        }
3374        let dims = xa.shape.dims().to_vec();
3375        let sizes = u.aval().shape.dims().to_vec();
3376        let starts: Vec<(usize, String)> = e.inputs[2..]
3377            .iter()
3378            .enumerate()
3379            .map(|(d, a)| Ok((d, self.val(a)?)))
3380            .collect::<Result<_>>()?;
3381        let name = self.copy_for_update(out, x)?;
3382        let (base, _) = self.window_base(&dims, &sizes, &starts, false);
3383        let mut probes = vec![
3384            HostArray::from_vec(vec![-1i64; size(&xa)], xa.shape.clone()),
3385            probe(0, &u.aval()),
3386        ];
3387        for a in &e.inputs[2..] {
3388            probes.push(HostArray::zeros(a.aval().shape.clone(), a.aval().dtype));
3389        }
3390        let r = e
3391            .prim
3392            .eval(&Interp, &probes, &e.params)
3393            .map_err(|x| Error(x.to_string()))?;
3394        let map = r[0].to_vec::<i64>().map_err(|x| Error(x.to_string()))?;
3395        let pairs: Vec<(usize, Src)> = map
3396            .iter()
3397            .enumerate()
3398            .filter(|(_, m)| **m > 0)
3399            .map(|(o, &m)| (o, decode(m)))
3400            .collect();
3401        let zero = "Default::default()".to_string();
3402        self.copies(
3403            &name,
3404            false,
3405            &pairs,
3406            std::slice::from_ref(u),
3407            None,
3408            &zero,
3409            &base,
3410            "",
3411            None,
3412        )
3413    }
3414
3415    fn gather(&mut self, e: &Eqn, consts: &HashMap<u64, HostArray>) -> Result<()> {
3416        let Params::Gather {
3417            dimension_numbers: d,
3418            slice_sizes,
3419            mode,
3420            ..
3421        } = &e.params
3422        else {
3423            return err("parameters");
3424        };
3425        let (x, idx) = (&e.inputs[0], &e.inputs[1]);
3426        let out = &e.outputs[0];
3427        let xa = x.aval();
3428        let ia = idx.aval();
3429        // From one element, every (clamped) slice is that element.
3430        if size(&xa) == 1 && *mode != GatherScatterMode::FillOrDrop {
3431            let v = self.val(x)?;
3432            let n = size(out.aval());
3433            return self.bind(out, &if n == 1 { v } else { format!("[{v}; {n}]") });
3434        }
3435        if let Some(indices) = constant(idx, consts) {
3436            let r = e
3437                .prim
3438                .eval(&Interp, &[probe(0, &xa), indices], &e.params)
3439                .map_err(|x| Error(x.to_string()))?;
3440            let map = r[0].to_vec::<i64>().map_err(|x| Error(x.to_string()))?;
3441            let pairs: Vec<(usize, Src)> = map
3442                .iter()
3443                .enumerate()
3444                .map(|(o, &m)| (o, decode(m)))
3445                .collect();
3446            return self.build_from(out, &pairs, std::slice::from_ref(x), None, "");
3447        }
3448        let q = ia.shape.rank();
3449        let groups: usize = ia.shape.dims()[..q.saturating_sub(1)].iter().product();
3450        // Batching dimensions (a `vmap` of a gather) need no index: the
3451        // group's position in them is part of the offsets that the gather
3452        // with all starts at zero gives (`gather_groups`).
3453        if size(&xa) == 1 || (!d.operand_batching_dims.is_empty() && groups == 1) {
3454            return self.fallback(e);
3455        }
3456        if groups != 1 {
3457            return self.gather_groups(e, slice_sizes);
3458        }
3459        let starts: Vec<(usize, String)> = d
3460            .start_index_map
3461            .iter()
3462            .enumerate()
3463            .map(|(k, &od)| Ok((od, self.at(idx, &k.to_string())?)))
3464            .collect::<Result<_>>()?;
3465        let (base, _) = self.window_base(xa.shape.dims(), slice_sizes, &starts, false);
3466        let zeros = HostArray::zeros(ia.shape.clone(), ia.dtype);
3467        let r = e
3468            .prim
3469            .eval(&Interp, &[probe(0, &xa), zeros], &e.params)
3470            .map_err(|x| Error(x.to_string()))?;
3471        let map = r[0].to_vec::<i64>().map_err(|x| Error(x.to_string()))?;
3472        let pairs: Vec<(usize, Src)> = map
3473            .iter()
3474            .enumerate()
3475            .map(|(o, &m)| (o, decode(m)))
3476            .collect();
3477        self.build_from(out, &pairs, std::slice::from_ref(x), None, &base)
3478    }
3479
3480    fn scatter(&mut self, e: &Eqn, consts: &HashMap<u64, HostArray>) -> Result<()> {
3481        let Params::Scatter {
3482            dimension_numbers: d,
3483            mode,
3484            ..
3485        } = &e.params
3486        else {
3487            return err("parameters");
3488        };
3489        let (x, idx, u) = (&e.inputs[0], &e.inputs[1], &e.inputs[2]);
3490        let out = &e.outputs[0];
3491        let t = out.aval().dtype;
3492        let combine = match e.prim.name() {
3493            "scatter" => None,
3494            "scatter-add" | "scatter_add" => Some((BinaryOp::Add, t)),
3495            "scatter-mul" | "scatter_mul" => Some((BinaryOp::Mul, t)),
3496            "scatter-min" | "scatter_min" => Some((BinaryOp::Min, t)),
3497            _ => Some((BinaryOp::Max, t)),
3498        };
3499        let xa = x.aval();
3500        let ua = u.aval();
3501        let ia = idx.aval();
3502        let replace = |indices: HostArray| -> Result<Vec<i64>> {
3503            let r = ruxla_prims::SCATTER
3504                .eval(
3505                    &Interp,
3506                    &[
3507                        HostArray::from_vec(vec![-1i64; size(&xa)], xa.shape.clone()),
3508                        indices,
3509                        probe(0, &ua),
3510                    ],
3511                    &e.params,
3512                )
3513                .map_err(|x| Error(x.to_string()))?;
3514            r[0].to_vec::<i64>().map_err(|x| Error(x.to_string()))
3515        };
3516        let counts = |indices: HostArray| -> Result<bool> {
3517            let r = ruxla_prims::SCATTER_ADD
3518                .eval(
3519                    &Interp,
3520                    &[
3521                        HostArray::zeros(xa.shape.clone(), DType::I64),
3522                        indices,
3523                        HostArray::from_vec(vec![1i64; size(&ua)], ua.shape.clone()),
3524                    ],
3525                    &e.params,
3526                )
3527                .map_err(|x| Error(x.to_string()))?;
3528            Ok(r[0]
3529                .to_vec::<i64>()
3530                .map_err(|x| Error(x.to_string()))?
3531                .iter()
3532                .all(|&c| c <= 1))
3533        };
3534        if let Some(indices) = constant(idx, consts) {
3535            if !counts(indices.clone())? {
3536                return self.fallback(e);
3537            }
3538            let map = replace(indices)?;
3539            let pairs: Vec<(usize, Src)> = map
3540                .iter()
3541                .enumerate()
3542                .filter(|(_, m)| **m > 0)
3543                .map(|(o, &m)| (o, decode(m)))
3544                .collect();
3545            let name = self.copy_for_update(out, x)?;
3546            let zero = "Default::default()".to_string();
3547            return self.copies(
3548                &name,
3549                size(&xa) == 1,
3550                &pairs,
3551                std::slice::from_ref(u),
3552                None,
3553                &zero,
3554                "",
3555                "",
3556                combine,
3557            );
3558        }
3559        let q = ia.shape.rank();
3560        let scatter_dims: Vec<usize> = (0..ua.shape.rank())
3561            .filter(|i| !d.update_window_dims.contains(i))
3562            .collect();
3563        let groups: usize = scatter_dims.iter().map(|&i| ua.shape.dims()[i]).product();
3564        let index_groups: usize = ia.shape.dims()[..q.saturating_sub(1)].iter().product();
3565        if groups == index_groups && groups > 1 && size(&xa) > 1 {
3566            return self.scatter_groups(e, combine);
3567        }
3568        if groups != 1 || index_groups != 1 || !d.operand_batching_dims.is_empty() || size(&xa) == 1
3569        {
3570            return self.fallback(e);
3571        }
3572        let window = ruxla_kernels::array::scatter_window(xa.shape.rank(), ua.shape.dims(), d);
3573        let starts: Vec<(usize, String)> = d
3574            .scatter_dims_to_operand_dims
3575            .iter()
3576            .enumerate()
3577            .map(|(k, &od)| Ok((od, self.at(idx, &k.to_string())?)))
3578            .collect::<Result<_>>()?;
3579        let name = self.copy_for_update(out, x)?;
3580        let check = *mode != GatherScatterMode::Clip;
3581        let (base, ok) = self.window_base(xa.shape.dims(), &window, &starts, check);
3582        let zeros = HostArray::zeros(ia.shape.clone(), ia.dtype);
3583        let map = replace(zeros)?;
3584        let pairs: Vec<(usize, Src)> = map
3585            .iter()
3586            .enumerate()
3587            .filter(|(_, m)| **m > 0)
3588            .map(|(o, &m)| (o, decode(m)))
3589            .collect();
3590        if let Some(ok) = &ok {
3591            self.line(format!("if {ok} {{"));
3592            self.indent += 1;
3593        }
3594        let zero = "Default::default()".to_string();
3595        self.copies(
3596            &name,
3597            false,
3598            &pairs,
3599            std::slice::from_ref(u),
3600            None,
3601            &zero,
3602            &base,
3603            "",
3604            combine,
3605        )?;
3606        if ok.is_some() {
3607            self.indent -= 1;
3608            self.line("}");
3609        }
3610        Ok(())
3611    }
3612
3613    /// The flat offsets of the windows of `groups` index vectors (the rows
3614    /// of `idx`, whose component `k` starts operand dimension `map[k]`),
3615    /// clamped so that a window of `sizes` fits, and with `check`, whether
3616    /// each was in bounds.
3617    fn group_bases(
3618        &mut self,
3619        idx: &Atom,
3620        groups: usize,
3621        map: &[usize],
3622        dims: &[usize],
3623        sizes: &[usize],
3624        check: bool,
3625    ) -> Result<(String, Option<String>)> {
3626        let st = strides(dims);
3627        let q = map.len();
3628        let mut terms = Vec::new();
3629        let mut checks = Vec::new();
3630        for (k, &od) in map.iter().enumerate() {
3631            let hi = (dims[od] - sizes[od]) as i64;
3632            let x = self.at(idx, &format!("g * {q} + {k}"))?;
3633            let sv = format!("({x} as i64)");
3634            checks.push(format!("(0..={hi}).contains(&{sv})"));
3635            if hi > 0 {
3636                terms.push(format!("({sv}.clamp(0, {hi}) as usize) * {}", st[od]));
3637            }
3638        }
3639        let bases = self.fresh("bases");
3640        let expr = if terms.is_empty() {
3641            "0usize".to_string()
3642        } else {
3643            terms.join(" + ")
3644        };
3645        self.line(format!(
3646            "let {bases}: [usize; {groups}] = rt::build(|g| {expr});"
3647        ));
3648        let oks = if check {
3649            let name = self.fresh("oks");
3650            let expr = if checks.is_empty() {
3651                "true".to_string()
3652            } else {
3653                checks.join(" && ")
3654            };
3655            self.line(format!(
3656                "let {name}: [bool; {groups}] = rt::build(|g| {expr});"
3657            ));
3658            Some(name)
3659        } else {
3660            None
3661        };
3662        Ok((bases, oks))
3663    }
3664
3665    /// The start of group `group` (an expression) of a gather in its
3666    /// operand: [`Self::group_bases`] as an expression.
3667    fn group_base_expr(
3668        &self,
3669        idx: &Atom,
3670        group: &str,
3671        map: &[usize],
3672        dims: &[usize],
3673        sizes: &[usize],
3674    ) -> Result<String> {
3675        let st = strides(dims);
3676        let q = map.len();
3677        let mut terms = Vec::new();
3678        for (k, &od) in map.iter().enumerate() {
3679            let hi = (dims[od] - sizes[od]) as i64;
3680            if hi > 0 {
3681                let x = self.at(idx, &format!("{group} * {q} + {k}"))?;
3682                terms.push(format!(
3683                    "((({x}) as i64).clamp(0, {hi}) as usize) * {}",
3684                    st[od]
3685                ));
3686            }
3687        }
3688        Ok(if terms.is_empty() {
3689            "0usize".to_string()
3690        } else {
3691            format!("({})", terms.join(" + "))
3692        })
3693    }
3694
3695    /// A static table of `usize`s.
3696    fn table(&mut self, values: &[usize]) -> String {
3697        let list: Vec<String> = values.iter().map(usize::to_string).collect();
3698        self.static_array(&format!("[usize; {}]", values.len()), &list.join(", "))
3699    }
3700
3701    /// A gather with several run-time index vectors: each element of the
3702    /// result reads its group's window at its offset.
3703    fn gather_groups(&mut self, e: &Eqn, slice_sizes: &[usize]) -> Result<()> {
3704        let Params::Gather {
3705            dimension_numbers: d,
3706            ..
3707        } = &e.params
3708        else {
3709            return err("parameters");
3710        };
3711        let (x, idx) = (&e.inputs[0], &e.inputs[1]);
3712        let out = &e.outputs[0];
3713        let xa = x.aval();
3714        let ia = idx.aval();
3715        let q = ia.shape.rank();
3716        let groups: usize = ia.shape.dims()[..q - 1].iter().product();
3717        let out_dims = out.aval().shape.dims().to_vec();
3718        let batch_dims: Vec<usize> = (0..out_dims.len())
3719            .filter(|i| !d.offset_dims.contains(i))
3720            .collect();
3721        let batch_shape = &ia.shape.dims()[..q - 1];
3722        let bst = strides(batch_shape);
3723        // The group of each element of the result.
3724        let ost = strides(&out_dims);
3725        let grp: Vec<usize> = (0..size(out.aval()))
3726            .map(|o| {
3727                batch_dims
3728                    .iter()
3729                    .zip(&bst)
3730                    .map(|(&bd, &s)| (o / ost[bd]) % out_dims[bd] * s)
3731                    .sum()
3732            })
3733            .collect();
3734        // The offsets in the window: the gather with all starts at zero.
3735        let zeros = HostArray::zeros(ia.shape.clone(), ia.dtype);
3736        let r = e
3737            .prim
3738            .eval(&Interp, &[probe(0, &xa), zeros], &e.params)
3739            .map_err(|x| Error(x.to_string()))?;
3740        let rel: Vec<usize> = r[0]
3741            .to_vec::<i64>()
3742            .map_err(|x| Error(x.to_string()))?
3743            .iter()
3744            .map(|&m| match decode(m) {
3745                Src::In(_, i) => i as usize,
3746                _ => 0,
3747            })
3748            .collect();
3749        let identity = grp.iter().enumerate().all(|(o, &g)| g == o) && rel.iter().all(|&r| r == 0);
3750        if self.scope().fused.contains(&out.id()) {
3751            // An expression of the element `@I@`: its group's start (from the
3752            // group's index vector) plus its offset in the window. Data
3753            // movement that was not built is built first, since the
3754            // expression reads it at computed positions.
3755            for a in [x, idx] {
3756                if let Atom::Var(v) = a
3757                    && self.moves.contains_key(&v.id())
3758                {
3759                    self.materialize_move(v.id())?;
3760                }
3761            }
3762            let (group, offset) = if identity {
3763                ("@I@".to_string(), String::new())
3764            } else {
3765                let (tg, tr) = (self.table(&grp), self.table(&rel));
3766                (format!("{tg}[@I@]"), format!(" + {tr}[@I@]"))
3767            };
3768            let base = self.group_base_expr(
3769                idx,
3770                &group,
3771                &d.start_index_map,
3772                xa.shape.dims(),
3773                slice_sizes,
3774            )?;
3775            let x0 = self.at(x, &format!("{base}{offset}"))?;
3776            self.fused.insert(out.id(), x0);
3777            return Ok(());
3778        }
3779        let (bases, _) = self.group_bases(
3780            idx,
3781            groups,
3782            &d.start_index_map,
3783            xa.shape.dims(),
3784            slice_sizes,
3785            false,
3786        )?;
3787        let x0 = if identity {
3788            self.at(x, &format!("{bases}[o]"))?
3789        } else {
3790            let (tg, tr) = (self.table(&grp), self.table(&rel));
3791            self.at(x, &format!("{bases}[{tg}[o]] + {tr}[o]"))?
3792        };
3793        self.bind(out, &format!("rt::build(|o| {x0})"))
3794    }
3795
3796    /// A scatter with several run-time index vectors: the updates in
3797    /// row-major order, each into its group's window (dropped where the
3798    /// window is out of bounds, except with `Clip`).
3799    fn scatter_groups(&mut self, e: &Eqn, combine: Option<(BinaryOp, DType)>) -> Result<()> {
3800        let Params::Scatter {
3801            dimension_numbers: d,
3802            mode,
3803            ..
3804        } = &e.params
3805        else {
3806            return err("parameters");
3807        };
3808        let (x, idx, u) = (&e.inputs[0], &e.inputs[1], &e.inputs[2]);
3809        let out = &e.outputs[0];
3810        let xa = x.aval();
3811        let ia = idx.aval();
3812        let ua = u.aval();
3813        let q = ia.shape.rank();
3814        let groups: usize = ia.shape.dims()[..q - 1].iter().product();
3815        let udims = ua.shape.dims().to_vec();
3816        let ust = strides(&udims);
3817        let scatter_dims: Vec<usize> = (0..udims.len())
3818            .filter(|i| !d.update_window_dims.contains(i))
3819            .collect();
3820        let bst = strides(&ia.shape.dims()[..q - 1]);
3821        let window = ruxla_kernels::array::scatter_window(xa.shape.rank(), &udims, d);
3822        let window_operand: Vec<usize> = (0..xa.shape.rank())
3823            .filter(|i| !d.inserted_window_dims.contains(i) && !d.operand_batching_dims.contains(i))
3824            .collect();
3825        let xst = strides(xa.shape.dims());
3826        let n = size(&ua);
3827        let mut grp = Vec::with_capacity(n);
3828        let mut rel = Vec::with_capacity(n);
3829        for up in 0..n {
3830            let coord = |dim: usize| (up / ust[dim]) % udims[dim];
3831            grp.push(
3832                scatter_dims
3833                    .iter()
3834                    .zip(&bst)
3835                    .map(|(&sd, &s)| coord(sd) * s)
3836                    .sum::<usize>(),
3837            );
3838            // Batching dimensions (a `vmap` of a scatter): the operand's
3839            // position is the update's in the paired dimension of the
3840            // indices (the scatter dimensions of the updates are those of
3841            // the indices, in order).
3842            let batch: usize = d
3843                .scatter_indices_batching_dims
3844                .iter()
3845                .zip(&d.operand_batching_dims)
3846                .map(|(&ib, &ob)| coord(scatter_dims[ib]) * xst[ob])
3847                .sum();
3848            rel.push(
3849                batch
3850                    + window_operand
3851                        .iter()
3852                        .zip(&d.update_window_dims)
3853                        .map(|(&od, &ud)| coord(ud) * xst[od])
3854                        .sum::<usize>(),
3855            );
3856        }
3857        let name = self.copy_for_update(out, x)?;
3858        let check = *mode != GatherScatterMode::Clip;
3859        let (bases, oks) = self.group_bases(
3860            idx,
3861            groups,
3862            &d.scatter_dims_to_operand_dims,
3863            xa.shape.dims(),
3864            &window,
3865            check,
3866        )?;
3867        let uv = self.at(u, "j")?;
3868        // Windows of `w` updates in order (the update `j` is element `j % w`
3869        // of the window of group `j / w`, at the same offset in every
3870        // window): loops over the groups and the window, without tables
3871        // (Gymnax's Seaquest compacts its buffers of 100 entities of 3 to 5
3872        // fields with such scatters a dozen times a step).
3873        let w = n / groups.max(1);
3874        if groups > 1 && w * groups == n && (0..n).all(|j| grp[j] == j / w && rel[j] == rel[j % w])
3875        {
3876            let offsets: Vec<usize> = rel[..w].to_vec();
3877            let contiguous = offsets
3878                .iter()
3879                .enumerate()
3880                .all(|(k, &r)| r == offsets[0] + k);
3881            self.line(format!("for g in 0..{groups}usize {{"));
3882            self.indent += 1;
3883            if let Some(oks) = &oks {
3884                self.line(format!("if !{oks}[g] {{ continue; }}"));
3885            }
3886            self.line(format!("let b = {bases}[g];"));
3887            let off = if contiguous {
3888                format!("b + {} + k", offsets[0])
3889            } else {
3890                let tr = self.table(&offsets);
3891                format!("b + {tr}[k]")
3892            };
3893            self.line(format!("for k in 0..{w}usize {{"));
3894            self.indent += 1;
3895            self.line(format!("let j = g * {w} + k;"));
3896            self.line(format!("let o = {off};"));
3897            let target = format!("{name}[o]");
3898            let value = match combine {
3899                None => uv,
3900                Some((op, t)) => binary_expr(op, t, &target, &uv),
3901            };
3902            self.line(format!("{target} = {value};"));
3903            self.indent -= 1;
3904            self.line("}");
3905            self.indent -= 1;
3906            self.line("}");
3907            return Ok(());
3908        }
3909        let (tg, tr) = (self.table(&grp), self.table(&rel));
3910        self.line(format!("for j in 0..{n}usize {{"));
3911        self.indent += 1;
3912        self.line(format!("let g = {tg}[j];"));
3913        if let Some(oks) = &oks {
3914            self.line(format!("if !{oks}[g] {{ continue; }}"));
3915        }
3916        self.line(format!("let o = {bases}[g] + {tr}[j];"));
3917        let target = format!("{name}[o]");
3918        let value = match combine {
3919            None => uv,
3920            Some((op, t)) => binary_expr(op, t, &target, &uv),
3921        };
3922        self.line(format!("{target} = {value};"));
3923        self.indent -= 1;
3924        self.line("}");
3925        Ok(())
3926    }
3927
3928    fn reduce(&mut self, e: &Eqn) -> Result<()> {
3929        let Params::Reduce { axes } = &e.params else {
3930            return err("parameters");
3931        };
3932        let x = &e.inputs[0];
3933        let out = &e.outputs[0];
3934        let xa = x.aval();
3935        let t = xa.dtype;
3936        let ty = elem_ty(t)?;
3937        let op = match e.prim.name() {
3938            "reduce_sum" => BinaryOp::Add,
3939            "reduce_max" | "reduce_or" => BinaryOp::Max,
3940            _ => BinaryOp::Min,
3941        };
3942        let identity = match op {
3943            BinaryOp::Add => format!("<{ty} as Default>::default()"),
3944            BinaryOp::Max => format!("<{ty} as rt::Ops>::lowest()"),
3945            _ => format!("<{ty} as rt::Ops>::highest()"),
3946        };
3947        if self.scope().fused.contains(&out.id())
3948            && let Some(m) = small_reduce(e)
3949        {
3950            return self.reduce_fused(e, op, &identity, m);
3951        }
3952        let mut sorted = axes.clone();
3953        sorted.sort_unstable();
3954        let dims = xa.shape.dims();
3955        // A fused operand that reads data movement that was not built: read
3956        // through affine offsets in loops over the operand's dimensions, or
3957        // with the movement built first.
3958        if size(&xa) > 1
3959            && (self.is_fused(x) || matches!(x, Atom::Var(v) if self.moves.contains_key(&v.id())))
3960        {
3961            let template = self.at(x, "@I@")?;
3962            let ids = moved_ids(std::slice::from_ref(&template));
3963            if !ids.is_empty() {
3964                let affine: Option<Vec<(usize, i64, Vec<i64>)>> = ids
3965                    .iter()
3966                    .map(|id| {
3967                        self.moves
3968                            .get(id)
3969                            .and_then(|(_, map)| affine_offset(map, dims))
3970                    })
3971                    .collect();
3972                match affine {
3973                    Some(affine) => {
3974                        return self.reduce_affine(e, op, &identity, &template, &ids, &affine);
3975                    }
3976                    None => {
3977                        for &id in &ids {
3978                            self.materialize_move(id)?;
3979                        }
3980                    }
3981                }
3982            }
3983        }
3984        if !sorted.windows(2).all(|w| w[1] == w[0] + 1) {
3985            // Axes that are not adjacent: each element of the operand, in
3986            // order, into its output element (through a table of the output
3987            // elements), which reduces each output element over its
3988            // elements in order.
3989            let mut targets = Vec::with_capacity(size(&xa));
3990            let mut index = vec![0usize; dims.len()];
3991            for _ in 0..size(&xa) {
3992                let mut o = 0;
3993                for (d, &i) in index.iter().enumerate() {
3994                    if !sorted.contains(&d) {
3995                        o = o * dims[d] + i;
3996                    }
3997                }
3998                targets.push(o);
3999                for d in (0..dims.len()).rev() {
4000                    index[d] += 1;
4001                    if index[d] < dims[d] {
4002                        break;
4003                    }
4004                    index[d] = 0;
4005                }
4006            }
4007            let table = self.table(&targets);
4008            let name = format!("v{}", out.id());
4009            let oty = self.ty(out.aval())?;
4010            let n_out = size(out.aval());
4011            if n_out == 1 {
4012                self.line(format!("let mut {name}: {oty} = {identity};"));
4013            } else {
4014                self.line(format!("let mut {name}: {oty} = [{identity}; {n_out}];"));
4015            }
4016            self.line(format!("for i in 0..{}usize {{", size(&xa)));
4017            let xi = self.at(x, "i")?;
4018            let o = if n_out == 1 {
4019                name.clone()
4020            } else {
4021                format!("{name}[{table}[i]]")
4022            };
4023            self.line(format!("    {o} = {};", binary_expr(op, t, &o, &xi)));
4024            self.line("}");
4025            self.names.insert(
4026                out.id(),
4027                Name {
4028                    expr: name,
4029                    is_ref: false,
4030                },
4031            );
4032            return Ok(());
4033        }
4034        if sorted.is_empty() {
4035            let v = self.val(x)?;
4036            return self.bind(out, &v);
4037        }
4038        let (a, b) = (sorted[0], sorted[sorted.len() - 1] + 1);
4039        let pre: usize = dims[..a].iter().product();
4040        let n: usize = dims[a..b].iter().product();
4041        let post: usize = dims[b..].iter().product();
4042        if size(&xa) == 1 {
4043            let v = self.val(x)?;
4044            let v = binary_expr(op, t, &identity, &v);
4045            return self.bind(out, &v);
4046        }
4047        let name = format!("v{}", out.id());
4048        if pre * post == 1 {
4049            self.line(format!("let mut {name}: {ty} = {identity};"));
4050            self.line(format!("for j in 0..{n}usize {{"));
4051            let xi = self.at(x, "j")?;
4052            self.line(format!("    {name} = {};", binary_expr(op, t, &name, &xi)));
4053            self.line("}");
4054        } else if n <= 16 || post == 1 {
4055            // Each output element reduced in a register over its elements in
4056            // order (the same order as the loops below).
4057            let xi = self.at(x, &format!("(p * {n} + k) * {post} + q"))?;
4058            let acc = binary_expr(op, t, "acc", &xi);
4059            self.line(format!(
4060                "let mut {name}: {} = rt::build(|o| {{ let (p, q) = (o / {post}, o % {post}); let mut acc = {identity}; for k in 0..{n}usize {{ acc = {acc}; }} acc }});",
4061                self.ty(out.aval())?
4062            ));
4063        } else {
4064            let oty = self.ty(out.aval())?;
4065            self.line(format!(
4066                "let mut {name}: {oty} = [{identity}; {}];",
4067                pre * post
4068            ));
4069            self.line(format!(
4070                "for p in 0..{pre}usize {{ for k in 0..{n}usize {{ for q in 0..{post}usize {{"
4071            ));
4072            let xi = self.at(x, &format!("(p * {n} + k) * {post} + q"))?;
4073            let o = format!("{name}[p * {post} + q]");
4074            self.line(format!("    {o} = {};", binary_expr(op, t, &o, &xi)));
4075            self.line("} } }");
4076        }
4077        self.names.insert(
4078            out.id(),
4079            Name {
4080                expr: name,
4081                is_ref: false,
4082            },
4083        );
4084        Ok(())
4085    }
4086
4087    /// A reduction over `m` trailing elements ([`small_reduce`]) fused into
4088    /// its consumer: the expression of output element `@I@`, its elements
4089    /// combined in order from the identity (as the loops of
4090    /// [`Self::reduce`]). Data movement that the operand reads in place is
4091    /// read at affine offsets of the output element's index and the reduced
4092    /// element (or built first).
4093    fn reduce_fused(&mut self, e: &Eqn, op: BinaryOp, identity: &str, m: usize) -> Result<()> {
4094        let (x, out) = (&e.inputs[0], &e.outputs[0]);
4095        let xa = x.aval();
4096        let t = xa.dtype;
4097        let dims = xa.shape.dims().to_vec();
4098        let Params::Reduce { axes } = &e.params else {
4099            return err("parameters");
4100        };
4101        // The reduced axes are the trailing ones.
4102        let r = dims.len() - axes.len();
4103        let odims = &dims[..r];
4104        let ostrides = strides(odims);
4105        let mut template = self.at(x, "@I@")?;
4106        let mut affine = Vec::new();
4107        for id in moved_ids(std::slice::from_ref(&template)) {
4108            match self
4109                .moves
4110                .get(&id)
4111                .and_then(|(_, map)| affine_offset(map, &dims))
4112            {
4113                Some(a) => affine.push((id, a)),
4114                None => self.materialize_move(id)?,
4115            }
4116        }
4117        if affine.len() != moved_ids(std::slice::from_ref(&template)).len() {
4118            template = self.at(x, "@I@")?;
4119        }
4120        // The index of output dimension d of element `@I@` (a token that
4121        // the loops of the consumer resolve, [`subst_index`]).
4122        let coord = |d: usize| format!("@D{}:{}@", ostrides[d], odims[d]);
4123        let rstrides = strides(&dims[r..]);
4124        let mut acc = identity.to_string();
4125        for k in 0..m {
4126            let mut body = subst_index(&template, &format!("((@I@) * {m} + {k})"));
4127            for (id, (src, base, st)) in &affine {
4128                let mut terms = vec![base.to_string()];
4129                for (d, &sd) in st.iter().enumerate() {
4130                    if sd == 0 || dims[d] <= 1 {
4131                        continue;
4132                    }
4133                    let i = if d < r {
4134                        coord(d)
4135                    } else {
4136                        ((k / rstrides[d - r]) % dims[d]).to_string()
4137                    };
4138                    terms.push(format!("{i} * {sd}"));
4139                }
4140                let (srcs, _) = self.moves.get(id).cloned().expect("moved");
4141                let read = self.at(&srcs[*src], &terms.join(" + "))?;
4142                body = body.replace(&format!("@M{id}@"), &read);
4143            }
4144            acc = binary_expr(op, t, &acc, &format!("({body})"));
4145        }
4146        self.fused.insert(out.id(), acc);
4147        Ok(())
4148    }
4149
4150    /// [`Self::reduce`] of an operand given by `template` (its element
4151    /// `@I@`) that reads the moved arrays `ids` at affine offsets
4152    /// (`affine`): loops over the operand's dimensions in order, each
4153    /// element combined into its output element, so that every output
4154    /// element is reduced over its elements in the same order as the plain
4155    /// loops.
4156    fn reduce_affine(
4157        &mut self,
4158        e: &Eqn,
4159        op: BinaryOp,
4160        identity: &str,
4161        template: &str,
4162        ids: &[u64],
4163        affine: &[(usize, i64, Vec<i64>)],
4164    ) -> Result<()> {
4165        let Params::Reduce { axes } = &e.params else {
4166            return err("parameters");
4167        };
4168        let x = &e.inputs[0];
4169        let out = &e.outputs[0];
4170        let xa = x.aval();
4171        let t = xa.dtype;
4172        let dims = xa.shape.dims().to_vec();
4173        let xstrides = strides(&dims);
4174        // The output's stride of each operand dimension (0 if reduced).
4175        let kept: Vec<usize> = (0..dims.len()).filter(|d| !axes.contains(d)).collect();
4176        let kept_dims: Vec<usize> = kept.iter().map(|&d| dims[d]).collect();
4177        let kept_strides = strides(&kept_dims);
4178        let mut ostrides = vec![0usize; dims.len()];
4179        for (k, &d) in kept.iter().enumerate() {
4180            ostrides[d] = kept_strides[k];
4181        }
4182        let index = |strides: &[i64], base: i64| {
4183            let mut terms: Vec<String> = Vec::new();
4184            if base != 0 {
4185                terms.push(format!("{base}"));
4186            }
4187            for (d, &st) in strides.iter().enumerate() {
4188                if dims[d] <= 1 {
4189                    continue;
4190                }
4191                match st {
4192                    0 => {}
4193                    1 => terms.push(format!("i{d}")),
4194                    _ => terms.push(format!("i{d} * {st}")),
4195                }
4196            }
4197            if terms.is_empty() {
4198                "0".to_string()
4199            } else {
4200                terms.join(" + ")
4201            }
4202        };
4203        let mut body = template.to_string();
4204        for (&id, (src, base, st)) in ids.iter().zip(affine) {
4205            let (srcs, _) = self.moves.get(&id).cloned().expect("moved");
4206            let read = self.at(&srcs[*src], &index(st, *base))?;
4207            body = body.replace(&format!("@M{id}@"), &read);
4208        }
4209        let name = format!("v{}", out.id());
4210        let oty = self.ty(out.aval())?;
4211        let n_out = size(out.aval());
4212        if n_out == 1 {
4213            self.line(format!("let mut {name}: {oty} = {identity};"));
4214        } else {
4215            self.line(format!("let mut {name}: {oty} = [{identity}; {n_out}];"));
4216        }
4217        let mut open = 0;
4218        for (d, &size) in dims.iter().enumerate() {
4219            if size > 1 {
4220                self.line(format!("for i{d} in 0..{size}usize {{"));
4221                self.indent += 1;
4222                open += 1;
4223            }
4224        }
4225        if body.contains("@I@") {
4226            let flat: Vec<i64> = xstrides.iter().map(|&x| x as i64).collect();
4227            self.line(format!("let i = {};", index(&flat, 0)));
4228            body = subst_index(&body, "i");
4229        }
4230        let o = if n_out == 1 {
4231            name.clone()
4232        } else {
4233            let os: Vec<i64> = ostrides.iter().map(|&x| x as i64).collect();
4234            format!("{name}[{}]", index(&os, 0))
4235        };
4236        self.line(format!("{o} = {};", binary_expr(op, t, &o, &body)));
4237        for _ in 0..open {
4238            self.indent -= 1;
4239            self.line("}");
4240        }
4241        self.names.insert(
4242            out.id(),
4243            Name {
4244                expr: name,
4245                is_ref: false,
4246            },
4247        );
4248        Ok(())
4249    }
4250
4251    /// `sort`: a stable sort of index lines by the keys, then the operands
4252    /// permuted.
4253    fn sort(&mut self, e: &Eqn) -> Result<()> {
4254        let Params::Sort {
4255            dimension,
4256            num_keys,
4257            ..
4258        } = e.params
4259        else {
4260            return err("parameters");
4261        };
4262        let aval = e.inputs[0].aval();
4263        let total = size(&aval);
4264        if total == 1 || e.inputs.iter().any(|a| matches!(a, Atom::Lit(_))) {
4265            for (o, a) in e.outputs.iter().zip(&e.inputs) {
4266                let v = self.val(a)?;
4267                self.bind(o, &v)?;
4268            }
4269            return Ok(());
4270        }
4271        let dims = aval.shape.dims();
4272        let n = dims[dimension];
4273        let inner: usize = dims[dimension + 1..].iter().product();
4274        let outer: usize = dims[..dimension].iter().product();
4275        let perm = self.fresh("perm");
4276        self.line(format!("let mut {perm}: [usize; {total}] = [0; {total}];"));
4277        self.line(format!(
4278            "for o in 0..{outer}usize {{ for i in 0..{inner}usize {{"
4279        ));
4280        self.indent += 1;
4281        self.line(format!("let base = o * {} + i;", n * inner));
4282        self.line(format!(
4283            "let mut line: [usize; {n}] = rt::build(|k| base + k * {inner});"
4284        ));
4285        let cmps: Vec<String> = e.inputs[..num_keys]
4286            .iter()
4287            .map(|a| {
4288                Ok(format!(
4289                    "rt::sort_order({}, {})",
4290                    self.at(a, "a")?,
4291                    self.at(a, "b")?
4292                ))
4293            })
4294            .collect::<Result<_>>()?;
4295        let cmp = cmps
4296            .iter()
4297            .skip(1)
4298            .fold(cmps[0].clone(), |acc, c| format!("{acc}.then_with(|| {c})"));
4299        self.line(format!("line.sort_by(|&a, &b| {cmp});"));
4300        self.line(format!(
4301            "for k in 0..{n}usize {{ {perm}[base + k * {inner}] = line[k]; }}"
4302        ));
4303        self.indent -= 1;
4304        self.line("} }");
4305        for (o, a) in e.outputs.iter().zip(&e.inputs) {
4306            let x = self.at(a, &format!("{perm}[i]"))?;
4307            self.bind(o, &format!("rt::build(|i| {x})"))?;
4308        }
4309        Ok(())
4310    }
4311
4312    /// A cumulative operation along an axis, in order (the kernel's order
4313    /// for integers and booleans, and for floats along at most 16 elements;
4314    /// longer float axes follow XLA's blocks and are evaluated by the
4315    /// interpreter).
4316    fn cumulative(&mut self, e: &Eqn) -> Result<()> {
4317        let Params::Cumulative { axis, reverse } = e.params else {
4318            return err("parameters");
4319        };
4320        let x = &e.inputs[0];
4321        let out = &e.outputs[0];
4322        let xa = x.aval();
4323        let t = xa.dtype;
4324        let dims = xa.shape.dims();
4325        let n = dims[axis];
4326        if t.is_complex() {
4327            return self.fallback(e);
4328        }
4329        if size(&xa) == 1 {
4330            let v = self.val(x)?;
4331            return self.bind(out, &v);
4332        }
4333        if is_float(t) && n > 16 {
4334            // Longer float lines combine their elements in XLA's order (blocks
4335            // of a scan): the kernel's.
4336            let kop = match e.prim.name() {
4337                "cumsum" => "Sum",
4338                "cumprod" => "Prod",
4339                "cummax" => "Max",
4340                _ => "Min",
4341            };
4342            let xs = self.slice_of(x)?;
4343            let expr = format!(
4344                "rt::cumulative::<{}, {}>({xs}, &{dims:?}, {axis}, {reverse}, rt::CumulativeOp::{kop})",
4345                elem_ty(t)?,
4346                size(out.aval())
4347            );
4348            return self.bind(out, &expr);
4349        }
4350        let op = match e.prim.name() {
4351            "cumsum" => BinaryOp::Add,
4352            "cumprod" => BinaryOp::Mul,
4353            "cummax" => BinaryOp::Max,
4354            _ => BinaryOp::Min,
4355        };
4356        let pre: usize = dims[..axis].iter().product();
4357        let post: usize = dims[axis + 1..].iter().product();
4358        let ty = self.ty(out.aval())?;
4359        let name = format!("v{}", out.id());
4360        let zero = format!("<{} as Default>::default()", elem_ty(t)?);
4361        self.line(format!(
4362            "let mut {name}: {ty} = [{zero}; {}];",
4363            size(out.aval())
4364        ));
4365        self.line(format!(
4366            "for p in 0..{pre}usize {{ for q in 0..{post}usize {{"
4367        ));
4368        self.indent += 1;
4369        let ks = if reverse {
4370            format!("(0..{n}usize).rev()")
4371        } else {
4372            format!("0..{n}usize")
4373        };
4374        self.line("let mut first = true;");
4375        self.line(format!("let mut acc = {zero};"));
4376        self.line(format!("for k in {ks} {{"));
4377        self.indent += 1;
4378        self.line(format!("let i = (p * {n} + k) * {post} + q;"));
4379        let xi = self.at(x, "i")?;
4380        let combined = binary_expr(op, t, "acc", "v");
4381        self.line(format!("let v = {xi};"));
4382        self.line(format!("acc = if first {{ v }} else {{ {combined} }};"));
4383        self.line("first = false;");
4384        self.line(format!("{name}[i] = acc;"));
4385        self.indent -= 1;
4386        self.line("}");
4387        self.indent -= 1;
4388        self.line("} }");
4389        self.names.insert(
4390            out.id(),
4391            Name {
4392                expr: name,
4393                is_ref: false,
4394            },
4395        );
4396        self.own(out);
4397        Ok(())
4398    }
4399
4400    /// `argmax` and `argmin` along an axis: NaN counts as the extreme, and
4401    /// ties take the first index (the kernel's rule).
4402    fn arg_min_max(&mut self, e: &Eqn) -> Result<()> {
4403        let Params::ArgMinMax { axis, .. } = e.params else {
4404            return err("parameters");
4405        };
4406        let x = &e.inputs[0];
4407        let out = &e.outputs[0];
4408        let xa = x.aval();
4409        if xa.dtype.is_complex() || xa.dtype == DType::Bool {
4410            return self.fallback(e);
4411        }
4412        let dims = xa.shape.dims();
4413        let n = dims[axis];
4414        let pre: usize = dims[..axis].iter().product();
4415        let post: usize = dims[axis + 1..].iter().product();
4416        let it = elem_ty(out.aval().dtype)?;
4417        let cmp = if e.prim.name() == "argmax" { ">" } else { "<" };
4418        // An operand that reads data movement in place: loops over its
4419        // dimensions that read the moved arrays at affine offsets (or the
4420        // movement built first).
4421        let template = self.at(x, "@I@")?;
4422        let ids = moved_ids(std::slice::from_ref(&template));
4423        if !ids.is_empty() {
4424            let affine: Option<Vec<(usize, i64, Vec<i64>)>> = ids
4425                .iter()
4426                .map(|id| {
4427                    self.moves
4428                        .get(id)
4429                        .and_then(|(_, map)| affine_offset(map, dims))
4430                })
4431                .collect();
4432            match affine {
4433                Some(affine) => {
4434                    return self.arg_affine(e, axis, cmp, &template, &ids, &affine);
4435                }
4436                None => {
4437                    for &id in &ids {
4438                        self.materialize_move(id)?;
4439                    }
4440                }
4441            }
4442        }
4443        let body = |me: &mut Self, target: &str| -> Result<()> {
4444            me.line("let mut bi = 0usize;");
4445            let x0 = me.at(x, &format!("p * {} + q", n * post))?;
4446            me.line(format!("let mut bv = {x0};"));
4447            me.line(format!("for k in 1..{n}usize {{"));
4448            me.indent += 1;
4449            let xk = me.at(x, &format!("(p * {n} + k) * {post} + q"))?;
4450            me.line(format!("let v = {xk};"));
4451            me.line(format!(
4452                "#[allow(clippy::eq_op)] let better = if bv != bv {{ false }} else if v != v {{ true }} else {{ v {cmp} bv }};"
4453            ));
4454            me.line("if better { bi = k; bv = v; }");
4455            me.indent -= 1;
4456            me.line("}");
4457            me.line(format!("{target} = bi as {it};"));
4458            Ok(())
4459        };
4460        let name = format!("v{}", out.id());
4461        if size(out.aval()) == 1 {
4462            self.line(format!("let mut {name}: {it} = 0 as {it};"));
4463            self.line("{ let (p, q) = (0usize, 0usize);");
4464            self.indent += 1;
4465            body(self, &name)?;
4466            self.indent -= 1;
4467            self.line("}");
4468            self.names.insert(
4469                out.id(),
4470                Name {
4471                    expr: name,
4472                    is_ref: false,
4473                },
4474            );
4475            return Ok(());
4476        }
4477        let ty = self.ty(out.aval())?;
4478        self.line(format!(
4479            "let mut {name}: {ty} = [0 as {it}; {}];",
4480            size(out.aval())
4481        ));
4482        self.line(format!(
4483            "for p in 0..{pre}usize {{ for q in 0..{post}usize {{"
4484        ));
4485        self.indent += 1;
4486        body(self, &format!("{name}[p * {post} + q]"))?;
4487        self.indent -= 1;
4488        self.line("} }");
4489        self.names.insert(
4490            out.id(),
4491            Name {
4492                expr: name,
4493                is_ref: false,
4494            },
4495        );
4496        self.own(out);
4497        Ok(())
4498    }
4499
4500    /// [`Self::arg_min_max`] of an operand given by `template` (its element
4501    /// `@I@`) that reads the moved arrays `ids` at affine offsets: loops
4502    /// over the other dimensions, each with the loop along `axis` inside
4503    /// (the same comparisons in the same order).
4504    fn arg_affine(
4505        &mut self,
4506        e: &Eqn,
4507        axis: usize,
4508        cmp: &str,
4509        template: &str,
4510        ids: &[u64],
4511        affine: &[(usize, i64, Vec<i64>)],
4512    ) -> Result<()> {
4513        let (x, out) = (&e.inputs[0], &e.outputs[0]);
4514        let dims = x.aval().shape.dims().to_vec();
4515        let n = dims[axis];
4516        let it = elem_ty(out.aval().dtype)?;
4517        let mut body = template.to_string();
4518        for (&id, (src, base, st)) in ids.iter().zip(affine) {
4519            let (srcs, _) = self.moves.get(&id).cloned().expect("moved");
4520            let read = self.at(&srcs[*src], &affine_index(&dims, st, *base))?;
4521            body = body.replace(&format!("@M{id}@"), &read);
4522        }
4523        let xstrides = strides(&dims);
4524        // Indices along the operand's dimensions: its loop variables.
4525        for (d, (&st, &size)) in xstrides.iter().zip(&dims).enumerate() {
4526            let var = if size <= 1 {
4527                "0".to_string()
4528            } else {
4529                format!("i{d}")
4530            };
4531            body = body.replace(&format!("@D{st}:{size}@"), &var);
4532        }
4533        let flat: Vec<i64> = xstrides.iter().map(|&s| s as i64).collect();
4534        let flat = affine_index(&dims, &flat, 0);
4535        let body = subst_index(&body, &format!("({flat})"));
4536        let xt = elem_ty(x.aval().dtype)?;
4537        // The output's stride of each operand dimension (0 along `axis`).
4538        let kept: Vec<usize> = (0..dims.len()).filter(|&d| d != axis).collect();
4539        let kept_dims: Vec<usize> = kept.iter().map(|&d| dims[d]).collect();
4540        let kept_strides = strides(&kept_dims);
4541        let mut ostrides = vec![0i64; dims.len()];
4542        for (k, &d) in kept.iter().enumerate() {
4543            ostrides[d] = kept_strides[k] as i64;
4544        }
4545        let name = format!("v{}", out.id());
4546        let n_out = size(out.aval());
4547        let target = if n_out == 1 {
4548            self.line(format!("let mut {name}: {it} = 0 as {it};"));
4549            name.clone()
4550        } else {
4551            let ty = self.ty(out.aval())?;
4552            self.line(format!("let mut {name}: {ty} = [0 as {it}; {n_out}];"));
4553            format!("{name}[{}]", affine_index(&dims, &ostrides, 0))
4554        };
4555        let mut open = 0;
4556        for (d, &size) in dims.iter().enumerate() {
4557            if d != axis && size > 1 {
4558                self.line(format!("for i{d} in 0..{size}usize {{"));
4559                self.indent += 1;
4560                open += 1;
4561            }
4562        }
4563        // The values in blocks (a loop the compiler can vectorize), each
4564        // block then compared in order.
4565        const BLOCK: usize = 64;
4566        self.line(format!(
4567            "let mut bv: {xt} = {{ let i{axis} = 0usize; {body} }};"
4568        ));
4569        self.line("let mut bi = 0usize;");
4570        self.line("let mut start = 1usize;");
4571        self.line(format!("while start < {n}usize {{"));
4572        self.indent += 1;
4573        self.line(format!("let len = ({n}usize - start).min({BLOCK});"));
4574        self.line(format!("let mut block = [bv; {BLOCK}];"));
4575        self.line(format!(
4576            "for (j, b) in block[..len].iter_mut().enumerate() {{ let i{axis} = start + j; *b = {body}; }}"
4577        ));
4578        // The block compared only if it may have a better element (a NaN, or
4579        // an element beyond `bv`).
4580        self.line("let (mut ext, mut nan) = (block[0], false);");
4581        self.line(format!(
4582            "#[allow(clippy::eq_op)] for &v in &block[..len] {{ nan |= v != v; ext = if v {cmp} ext {{ v }} else {{ ext }}; }}"
4583        ));
4584        self.line(format!(
4585            "#[allow(clippy::eq_op)] if bv == bv && (nan || ext {cmp} bv) {{"
4586        ));
4587        self.indent += 1;
4588        self.line("for (j, &v) in block[..len].iter().enumerate() {");
4589        self.indent += 1;
4590        self.line(format!(
4591            "#[allow(clippy::eq_op)] let better = if bv != bv {{ false }} else if v != v {{ true }} else {{ v {cmp} bv }};"
4592        ));
4593        self.line("if better { bi = start + j; bv = v; }");
4594        self.indent -= 1;
4595        self.line("}");
4596        self.indent -= 1;
4597        self.line("}");
4598        self.line("start += len;");
4599        self.indent -= 1;
4600        self.line("}");
4601        self.line(format!("{target} = bi as {it};"));
4602        for _ in 0..open {
4603            self.indent -= 1;
4604            self.line("}");
4605        }
4606        self.names.insert(
4607            out.id(),
4608            Name {
4609                expr: name,
4610                is_ref: false,
4611            },
4612        );
4613        if n_out > 1 {
4614            self.own(out);
4615        }
4616        Ok(())
4617    }
4618
4619    fn threefry(&mut self, e: &Eqn) -> Result<()> {
4620        let n = size(e.outputs[0].aval());
4621        let (a, b) = (
4622            format!("v{}", e.outputs[0].id()),
4623            format!("v{}", e.outputs[1].id()),
4624        );
4625        if n == 1 {
4626            let args: Vec<String> = e
4627                .inputs
4628                .iter()
4629                .map(|x| self.val(x))
4630                .collect::<Result<_>>()?;
4631            self.line(format!(
4632                "let ({a}, {b}): (u32, u32) = rt::threefry2x32({});",
4633                args.join(", ")
4634            ));
4635        } else {
4636            let args: Vec<String> = e
4637                .inputs
4638                .iter()
4639                .map(|x| self.at(x, "i"))
4640                .collect::<Result<_>>()?;
4641            self.line(format!("let mut {a}: [u32; {n}] = [0; {n}];"));
4642            self.line(format!("let mut {b}: [u32; {n}] = [0; {n}];"));
4643            self.line(format!("for i in 0..{n}usize {{"));
4644            self.line(format!(
4645                "    ({a}[i], {b}[i]) = rt::threefry2x32({});",
4646                args.join(", ")
4647            ));
4648            self.line("}");
4649        }
4650        for (o, name) in e.outputs.iter().zip([a, b]) {
4651            self.names.insert(
4652                o.id(),
4653                Name {
4654                    expr: name,
4655                    is_ref: false,
4656                },
4657            );
4658        }
4659        Ok(())
4660    }
4661
4662    /// Emits a block computing `f` from `inputs` and ending with the tuple
4663    /// of its outputs (without the closing brace's line terminator).
4664    fn block(&mut self, f: &Function, inputs: &[Name]) -> Result<String> {
4665        let results = self.block_results(f, inputs, &[])?;
4666        Ok(format!("({})", tuple_values(&results)))
4667    }
4668
4669    /// Emits the body of `f` on `inputs`, writes the outputs that have a
4670    /// destination in `writes` (`Some(target)`), and returns the
4671    /// expressions of the others.
4672    fn block_results(
4673        &mut self,
4674        f: &Function,
4675        inputs: &[Name],
4676        writes: &[Option<String>],
4677    ) -> Result<Vec<String>> {
4678        for (v, n) in f.invars.iter().zip(inputs) {
4679            self.alias(v, n.clone());
4680        }
4681        // An output written to a destination and computed in this block for
4682        // nothing else is computed directly into the destination.
4683        let mut uses: HashMap<u64, usize> = HashMap::new();
4684        for e in &f.eqns {
4685            for a in &e.inputs {
4686                if let Atom::Var(v) = a {
4687                    *uses.entry(v.id()).or_default() += 1;
4688                }
4689            }
4690        }
4691        for a in &f.outvars {
4692            if let Atom::Var(v) = a {
4693                *uses.entry(v.id()).or_default() += 1;
4694            }
4695        }
4696        let defined: HashSet<u64> = f
4697            .eqns
4698            .iter()
4699            .flat_map(|e| e.outputs.iter().map(Var::id))
4700            .collect();
4701        for (k, a) in f.outvars.iter().enumerate() {
4702            if let (Some(Some(t)), Atom::Var(v)) = (writes.get(k), a)
4703                && defined.contains(&v.id())
4704                && uses.get(&v.id()) == Some(&1)
4705                && !t.starts_with('a')
4706            {
4707                self.targets
4708                    .insert(reshape_source(f, v.id(), &uses), t.clone());
4709            }
4710        }
4711        self.indent += 1;
4712        self.function_body(f)?;
4713        // The values first (those that read an input written here are
4714        // copied before the writes), then the writes.
4715        let mut values: Vec<(Option<String>, String)> = Vec::new();
4716        for (k, a) in f.outvars.iter().enumerate() {
4717            let t = writes.get(k).cloned().flatten();
4718            let done = matches!((&t, a), (Some(t), Atom::Var(v))
4719                if self.names.get(&v.id()).is_some_and(|n| &n.expr == t));
4720            if done {
4721                continue;
4722            }
4723            values.push((t, self.val(a)?));
4724        }
4725        let written: Vec<String> = values
4726            .iter()
4727            .filter_map(|(t, _)| t.clone().filter(|t| t.starts_with('a')))
4728            .collect();
4729        let reads =
4730            |v: &str, t: &str| v.contains(&format!("(*{t})")) || v.contains(&format!("{t}["));
4731        let mut results = Vec::new();
4732        let mut pending = Vec::new();
4733        for (t, v) in values {
4734            let v = if written
4735                .iter()
4736                .any(|w| reads(&v, w) && t.as_deref() != Some(w.as_str()))
4737            {
4738                let name = self.fresh("r");
4739                self.line(format!("let {name} = {v};"));
4740                name
4741            } else {
4742                v
4743            };
4744            match t {
4745                Some(t) => pending.push(format!("*{t} = {v};")),
4746                None => results.push(v),
4747            }
4748        }
4749        for w in pending {
4750            self.line(w);
4751        }
4752        self.indent -= 1;
4753        Ok(results)
4754    }
4755
4756    /// [`Self::block_results`], or a call of a function of its own for a
4757    /// large body ([`OUTLINE_EQNS`]): the inputs passed by reference (one
4758    /// element by value), the outputs returned, those with a destination
4759    /// written to it through a mutable reference (not returned and copied:
4760    /// the arrays of Craftax's branches are hundreds of kilobytes).
4761    /// `into` gives, for each output `k`, the position of the input that it
4762    /// updates in place, if any (a loop body's carries, or a branch's
4763    /// operands that the parent no longer uses): that input is passed by
4764    /// mutable reference and the output is its storage.
4765    fn body_results(
4766        &mut self,
4767        f: &Function,
4768        inputs: &[Name],
4769        writes: &[Option<String>],
4770        into: &[Option<usize>],
4771    ) -> Result<Vec<String>> {
4772        if count_eqns(f) < OUTLINE_EQNS {
4773            return self.block_results(f, inputs, writes);
4774        }
4775        self.pending_inherit.clear();
4776        // An output whose destination is the storage of one of the inputs
4777        // (a state updated in place, read by the body) updates that input in
4778        // place, as a carry does.
4779        let mut into: Vec<Option<usize>> = (0..f.outvars.len())
4780            .map(|k| into.get(k).copied().flatten())
4781            .collect();
4782        for k in 0..f.outvars.len() {
4783            let Some(t) = writes.get(k).cloned().flatten() else {
4784                continue;
4785            };
4786            let same: Vec<usize> = (0..inputs.len()).filter(|&j| inputs[j].expr == t).collect();
4787            if into[k].is_none()
4788                && let [j] = same[..]
4789                && *f.invars[j].aval() == f.outvars[k].aval()
4790                && !into.contains(&Some(j))
4791            {
4792                into[k] = Some(j);
4793            }
4794        }
4795        let into_of = |k: usize| into[k];
4796        // A destination that is also another input is written after the
4797        // call (a mutable reference to it could not be passed with it).
4798        let write_of = |k: usize| {
4799            writes
4800                .get(k)
4801                .cloned()
4802                .flatten()
4803                .filter(|t| !inputs.iter().any(|n| &n.expr == t))
4804        };
4805        let sig = Signature {
4806            inputs: (0..f.invars.len())
4807                .map(|j| {
4808                    if (0..f.outvars.len()).any(|k| into_of(k) == Some(j)) {
4809                        Input::Mut
4810                    } else {
4811                        Input::Default
4812                    }
4813                })
4814                .collect(),
4815            outputs: (0..f.outvars.len())
4816                .map(|k| match (into_of(k), write_of(k)) {
4817                    (Some(j), _) => Output::Into(j),
4818                    (None, Some(_)) => Output::Write,
4819                    (None, None) => Output::Return,
4820                })
4821                .collect(),
4822        };
4823        let name = if self.pooled {
4824            // The module's function of the same code, or a new one.
4825            let mut pool = ConstPool {
4826                outlined: std::mem::take(&mut self.known_outlined),
4827                ..ConstPool::default()
4828            };
4829            let code = canonical_vars(&emit("@OUTLINED@", f, &sig, Some(&mut pool))?);
4830            for (k, d) in pool.defs {
4831                self.pool.entry(k).or_insert(d);
4832            }
4833            self.known_outlined = pool.outlined;
4834            self.outlined.extend(pool.outlined_code);
4835            match self.known_outlined.get(&code) {
4836                Some(name) => name.clone(),
4837                None => {
4838                    let name = outlined_name();
4839                    self.outlined.push(code.replacen("@OUTLINED@", &name, 1));
4840                    self.known_outlined.insert(code, name.clone());
4841                    name
4842                }
4843            }
4844        } else {
4845            let name = outlined_name();
4846            let code = emit(&name, f, &sig, None)?;
4847            self.outlined.push(code);
4848            name
4849        };
4850        let mut args = Vec::new();
4851        for (k, (v, n)) in f.invars.iter().zip(inputs).enumerate() {
4852            let by_ref = self.by_ref(n);
4853            if sig.inputs[k] == Input::Mut {
4854                args.push(if by_ref {
4855                    format!("&mut *{}", n.expr)
4856                } else {
4857                    format!("&mut {}", n.expr)
4858                });
4859                continue;
4860            }
4861            args.push(match (size(v.aval()) == 1, by_ref) {
4862                (true, true) => format!("*{}", n.expr),
4863                (true, false) => n.expr.clone(),
4864                (false, true) => format!("&*{}", n.expr),
4865                (false, false) => format!("&{}", n.expr),
4866            });
4867        }
4868        for (k, out) in sig.outputs.iter().enumerate() {
4869            if *out == Output::Write
4870                && let Some(t) = write_of(k)
4871            {
4872                args.push(format!("&mut *{t}"));
4873            }
4874        }
4875        let o = self.fresh("o");
4876        self.indent += 1;
4877        self.line(format!("let {o} = {name}({});", args.join(", ")));
4878        let mut results = Vec::new();
4879        // The position of the next output in the returned tuple (without the
4880        // outputs updated in place or written to their destinations).
4881        let mut r = 0;
4882        for (k, output) in sig.outputs.iter().enumerate().take(f.outvars.len()) {
4883            if *output == Output::Write {
4884                continue;
4885            }
4886            if let Some(j) = into_of(k) {
4887                // Written in place into its destination: no result.
4888                if writes.get(k).cloned().flatten().is_some() {
4889                    continue;
4890                }
4891                // Updated in place: the carry's storage.
4892                let n = &inputs[j];
4893                results.push(if self.by_ref(n) {
4894                    format!("(*{})", n.expr)
4895                } else {
4896                    n.expr.clone()
4897                });
4898                continue;
4899            }
4900            match writes.get(k).cloned().flatten() {
4901                Some(t) => self.line(format!("*{t} = {o}.{r};")),
4902                None => results.push(format!("{o}.{r}")),
4903            }
4904            r += 1;
4905        }
4906        self.indent -= 1;
4907        Ok(results)
4908    }
4909
4910    fn atom_name(&mut self, a: &Atom) -> Result<Name> {
4911        match a {
4912            Atom::Var(v) => Ok(self.name(v)?.clone()),
4913            Atom::Lit(_) => {
4914                let n = self.fresh("l");
4915                let v = self.val(a)?;
4916                self.line(format!("let {n} = {v};"));
4917                Ok(Name {
4918                    expr: n,
4919                    is_ref: false,
4920                })
4921            }
4922        }
4923    }
4924
4925    fn cond(&mut self, e: &Eqn) -> Result<()> {
4926        let Params::Cond { branches } = &e.params else {
4927            return err("parameters");
4928        };
4929        let index = self.val(&e.inputs[0])?;
4930        let inputs: Vec<Name> = e.inputs[1..]
4931            .iter()
4932            .map(|a| self.atom_name(a))
4933            .collect::<Result<_>>()?;
4934        // Outputs computed directly into their destinations.
4935        let writes: Vec<Option<String>> = e
4936            .outputs
4937            .iter()
4938            .map(|o| self.targets.get(&o.id()).cloned())
4939            .collect();
4940        // Operands passed once may be updated in place by the branches.
4941        let mut counts: HashMap<u64, usize> = HashMap::new();
4942        for a in &e.inputs[1..] {
4943            if let Atom::Var(v) = a {
4944                *counts.entry(v.id()).or_default() += 1;
4945            }
4946        }
4947        // For the arms that are functions of their own (large bodies), each
4948        // output without a destination updates in place an operand of its
4949        // type that the parent no longer uses, if there is one: the arm then
4950        // writes it in its storage instead of copying the operand in and the
4951        // result out (Craftax's step copied its maps several times).
4952        let outlined = branches.iter().any(|b| count_eqns(b) >= OUTLINE_EQNS);
4953        let mut into: Vec<Option<usize>> = vec![None; e.outputs.len()];
4954        if outlined {
4955            for (k, o) in e.outputs.iter().enumerate() {
4956                if writes[k].is_some() || size(o.aval()) == 1 {
4957                    continue;
4958                }
4959                into[k] = e.inputs[1..].iter().enumerate().position(|(j, a)| {
4960                    matches!(a, Atom::Var(v) if counts[&v.id()] == 1 && v.aval() == o.aval())
4961                        && !into.contains(&Some(j))
4962                        && self.reusable(a)
4963                });
4964            }
4965        }
4966        // The arms, emitted aside to choose the results afterwards.
4967        let saved = std::mem::take(&mut self.out);
4968        let mut arms: Vec<(String, Vec<String>)> = Vec::new();
4969        for b in branches.iter() {
4970            self.pending_inherit = b
4971                .invars
4972                .iter()
4973                .zip(&e.inputs[1..])
4974                .filter_map(|(iv, a)| match a {
4975                    Atom::Var(v) if counts[&v.id()] == 1 => Some((iv.id(), v.id())),
4976                    _ => None,
4977                })
4978                .collect();
4979            self.indent += 1;
4980            let r = self.body_results(b, &inputs, &writes, &into);
4981            self.indent -= 1;
4982            let code = std::mem::take(&mut self.out);
4983            arms.push((code, r?));
4984        }
4985        self.out = saved;
4986        // A result that some arm gives in the storage of an operand (updated
4987        // in place, or unchanged), which the parent no longer uses: the
4988        // output is that storage, and the other arms write their result to
4989        // it (one copy, in the arm that makes a new array, instead of
4990        // copying the operand in every arm).
4991        let kept_idx: Vec<usize> = (0..e.outputs.len())
4992            .filter(|&k| writes[k].is_none())
4993            .collect();
4994        let mut aliased: HashMap<usize, Name> = HashMap::new();
4995        // The value of each aliased storage (`(*a3)` for a reference).
4996        let mut alias_val: HashMap<usize, String> = HashMap::new();
4997        // The outputs that the outlined arms update in place are that storage
4998        // (no other output may take it).
4999        for (k, j) in into.iter().enumerate() {
5000            if let Some(j) = *j
5001                && let Atom::Var(v) = &e.inputs[1 + j]
5002            {
5003                aliased.insert(k, self.names[&v.id()].clone());
5004                alias_val.insert(k, self.val(&e.inputs[1 + j])?);
5005            }
5006        }
5007        for (r, &k) in kept_idx.iter().enumerate() {
5008            if aliased.contains_key(&k) {
5009                continue;
5010            }
5011            let out_aval = e.outputs[k].aval();
5012            let operand = e.inputs[1..].iter().find_map(|a| match a {
5013                Atom::Var(v)
5014                    if counts[&v.id()] == 1
5015                        && size(v.aval()) > 1
5016                        && v.aval() == out_aval
5017                        && !aliased.values().any(|n| n.expr == self.names[&v.id()].expr)
5018                        && self
5019                            .val(a)
5020                            .is_ok_and(|x| arms.iter().any(|(_, res)| res[r] == x))
5021                        && self.reusable(a) =>
5022                {
5023                    Some((self.names[&v.id()].clone(), self.val(a).ok()?))
5024                }
5025                _ => None,
5026            });
5027            if let Some((n, x)) = operand {
5028                aliased.insert(k, n);
5029                alias_val.insert(k, x);
5030            }
5031        }
5032        // In an arm that writes a result to the storage of an output, no
5033        // other result may read that storage, and the result may not read
5034        // the storage of another output (the writes are in sequence).
5035        let conflicts: Vec<usize> = kept_idx
5036            .iter()
5037            .enumerate()
5038            .filter(|&(r, k)| {
5039                aliased.get(k).is_some_and(|n| {
5040                    arms.iter().any(|(_, res)| {
5041                        res[r] != alias_val[k]
5042                            && (res
5043                                .iter()
5044                                .enumerate()
5045                                .any(|(r2, v)| r2 != r && v.contains(n.expr.as_str()))
5046                                || aliased
5047                                    .iter()
5048                                    .any(|(k2, n2)| k2 != k && res[r].contains(n2.expr.as_str())))
5049                    })
5050                })
5051            })
5052            .map(|(_, &k)| k)
5053            .collect();
5054        for k in conflicts {
5055            aliased.remove(&k);
5056        }
5057        let rest: Vec<usize> = kept_idx
5058            .iter()
5059            .copied()
5060            .filter(|k| !aliased.contains_key(k))
5061            .collect();
5062        let names: Vec<String> = rest
5063            .iter()
5064            .map(|&k| {
5065                let o = &e.outputs[k];
5066                if size(o.aval()) > 1 {
5067                    format!("mut v{}", o.id())
5068                } else {
5069                    format!("v{}", o.id())
5070                }
5071            })
5072            .collect();
5073        let tys: Vec<String> = rest
5074            .iter()
5075            .map(|&k| self.ty(e.outputs[k].aval()))
5076            .collect::<Result<_>>()?;
5077        let last = branches.len() - 1;
5078        self.line(format!(
5079            "let ({}): ({}) = match ({index} as i64).clamp(0, {last}) {{",
5080            tuple_values(&names),
5081            tuple_types(&tys)
5082        ));
5083        for (a, (code, results)) in arms.into_iter().enumerate() {
5084            let arm = if a == last {
5085                "_".to_string()
5086            } else {
5087                a.to_string()
5088            };
5089            self.line(format!("    {arm} => {{"));
5090            self.out.push_str(&code);
5091            for (k, v) in kept_idx.iter().zip(&results) {
5092                if let Some(x) = alias_val.get(k)
5093                    && aliased.contains_key(k)
5094                    && v != x
5095                {
5096                    self.line(format!("        {x} = {v};"));
5097                }
5098            }
5099            let vals: Vec<String> = kept_idx
5100                .iter()
5101                .zip(&results)
5102                .filter(|(k, _)| !aliased.contains_key(k))
5103                .map(|(_, v)| v.clone())
5104                .collect();
5105            self.line(format!("        ({})", tuple_values(&vals)));
5106            self.line("    }");
5107        }
5108        self.line("};");
5109        for (k, o) in e.outputs.iter().enumerate() {
5110            let name = if let Some(t) = &writes[k] {
5111                Name {
5112                    expr: t.clone(),
5113                    is_ref: true,
5114                }
5115            } else if let Some(n) = aliased.get(&k) {
5116                n.clone()
5117            } else {
5118                Name {
5119                    expr: format!("v{}", o.id()),
5120                    is_ref: false,
5121                }
5122            };
5123            self.names.insert(o.id(), name);
5124            if size(o.aval()) > 1 {
5125                self.own(o);
5126            }
5127        }
5128        Ok(())
5129    }
5130
5131    /// The storage of a loop's carries (`init`, among the loop's operands
5132    /// `operands`): the storage of an array that the parent no longer uses
5133    /// after the loop (the loop updates it in place), or a new mutable
5134    /// local `{prefix}{k}`.
5135    fn loop_carries(
5136        &mut self,
5137        prefix: &str,
5138        init: &[Atom],
5139        operands: &[Atom],
5140    ) -> Result<Vec<Name>> {
5141        let mut counts: HashMap<u64, usize> = HashMap::new();
5142        for a in operands {
5143            if let Atom::Var(v) = a {
5144                *counts.entry(v.id()).or_default() += 1;
5145            }
5146        }
5147        let mut carries = Vec::new();
5148        for (k, a) in init.iter().enumerate() {
5149            if let Atom::Var(v) = a
5150                && counts[&v.id()] == 1
5151                && self.reusable(a)
5152            {
5153                carries.push(self.name(v)?.clone());
5154                continue;
5155            }
5156            let name = format!("{prefix}{k}");
5157            let ty = self.ty(&a.aval())?;
5158            let v = self.val(a)?;
5159            self.line(format!("let mut {name}: {ty} = {v};"));
5160            carries.push(Name {
5161                expr: name,
5162                is_ref: false,
5163            });
5164        }
5165        Ok(carries)
5166    }
5167
5168    /// Emits a loop body `f` on `inputs`, whose inputs `carry_vars` stand
5169    /// for the storage `carries` (mutable, overwritten after each iteration,
5170    /// so the body may update them in place), as `let t = { ... };` followed
5171    /// by the assignments of the new carries. The other results (from
5172    /// `carries.len()` on) are `t.{k}` with `k` from the returned list
5173    /// (`None` for an output that is the carry's storage itself).
5174    fn loop_body(
5175        &mut self,
5176        f: &Function,
5177        inputs: &[Name],
5178        carry_vars: &[Var],
5179        carries: &[Name],
5180    ) -> Result<Vec<usize>> {
5181        self.pending_owned = carry_vars
5182            .iter()
5183            .filter(|v| size(v.aval()) > 1)
5184            .map(Var::id)
5185            .collect();
5186        self.line("let t = {");
5187        // The carries' positions among the body's inputs.
5188        let carry_pos: Vec<usize> = carry_vars
5189            .iter()
5190            .filter_map(|c| f.invars.iter().position(|v| v.id() == c.id()))
5191            .collect();
5192        let carry_pos = if carry_pos.len() == carries.len() {
5193            carry_pos
5194        } else {
5195            Vec::new()
5196        };
5197        let into: Vec<Option<usize>> = carry_pos.iter().map(|&j| Some(j)).collect();
5198        let results = self.body_results(f, inputs, &[], &into);
5199        self.pending_owned.clear();
5200        let results = results?;
5201        let heap = self.heap_names.clone();
5202        let by_ref = |c: &Name| c.is_ref || heap.contains(&c.expr);
5203        let storage = |c: &Name| {
5204            if by_ref(c) {
5205                format!("(*{})", c.expr)
5206            } else {
5207                c.expr.clone()
5208            }
5209        };
5210        // A carry that the body updated in place (or left unchanged) is not
5211        // copied out and back.
5212        let mut tuple = Vec::new();
5213        let mut assigns = Vec::new();
5214        for (k, c) in carries.iter().enumerate() {
5215            if results[k] != storage(c) {
5216                assigns.push(format!(
5217                    "{}{} = t.{};",
5218                    if by_ref(c) { "*" } else { "" },
5219                    c.expr,
5220                    tuple.len()
5221                ));
5222                tuple.push(results[k].clone());
5223            }
5224        }
5225        let mut others = Vec::new();
5226        for r in &results[carries.len()..] {
5227            others.push(tuple.len());
5228            tuple.push(r.clone());
5229        }
5230        self.line(format!("    ({})", tuple_values(&tuple)));
5231        self.line("};");
5232        for a in assigns {
5233            self.line(a);
5234        }
5235        Ok(others)
5236    }
5237
5238    fn while_loop(&mut self, e: &Eqn) -> Result<()> {
5239        let Params::While {
5240            cond,
5241            body,
5242            cond_nconsts,
5243            body_nconsts,
5244        } = &e.params
5245        else {
5246            return err("parameters");
5247        };
5248        let (cn, bn) = (*cond_nconsts, *body_nconsts);
5249        let consts_c: Vec<Name> = e.inputs[..cn]
5250            .iter()
5251            .map(|a| self.atom_name(a))
5252            .collect::<Result<_>>()?;
5253        let consts_b: Vec<Name> = e.inputs[cn..cn + bn]
5254            .iter()
5255            .map(|a| self.atom_name(a))
5256            .collect::<Result<_>>()?;
5257        let init = &e.inputs[cn + bn..];
5258        let w = self.fresh("w");
5259        let carries = self.loop_carries(&format!("{w}_"), init, &e.inputs)?;
5260        self.line("loop {");
5261        self.indent += 1;
5262        let mut cin = consts_c.clone();
5263        cin.extend(carries.iter().cloned());
5264        self.line("let p: (bool,) = {");
5265        let r = self.block(cond, &cin)?;
5266        self.line(format!("    {r}"));
5267        self.line("};");
5268        self.line("if !p.0 { break; }");
5269        let mut bin = consts_b.clone();
5270        bin.extend(carries.iter().cloned());
5271        self.loop_body(body, &bin, &body.invars[bn..], &carries)?;
5272        self.indent -= 1;
5273        self.line("}");
5274        for (o, c) in e.outputs.iter().zip(carries) {
5275            self.names.insert(o.id(), c);
5276            if size(o.aval()) > 1 {
5277                self.own(o);
5278            }
5279        }
5280        Ok(())
5281    }
5282
5283    fn scan(&mut self, e: &Eqn) -> Result<()> {
5284        let Params::Scan {
5285            body,
5286            length,
5287            reverse,
5288            num_consts,
5289            num_carry,
5290        } = &e.params
5291        else {
5292            return err("parameters");
5293        };
5294        let (nc, nk, len) = (*num_consts, *num_carry, *length);
5295        let consts: Vec<Name> = e.inputs[..nc]
5296            .iter()
5297            .map(|a| self.atom_name(a))
5298            .collect::<Result<_>>()?;
5299        let s = self.fresh("s");
5300        let carries = self.loop_carries(&format!("{s}_c"), &e.inputs[nc..nc + nk], &e.inputs)?;
5301        let ys_vars = &e.outputs[nk..];
5302        let mut ys = Vec::new();
5303        for (k, o) in ys_vars.iter().enumerate() {
5304            let name = format!("{s}_y{k}");
5305            let ty = self.ty(o.aval())?;
5306            let zero = format!("<{} as Default>::default()", elem_ty(o.aval().dtype)?);
5307            if size(o.aval()) == 1 {
5308                self.line(format!("let mut {name}: {ty} = {zero};"));
5309            } else {
5310                self.line(format!(
5311                    "let mut {name}: {ty} = [{zero}; {}];",
5312                    size(o.aval())
5313                ));
5314            }
5315            ys.push(name);
5316        }
5317        self.line(format!("for it in 0..{len}usize {{"));
5318        self.indent += 1;
5319        let j = if *reverse {
5320            format!("{} - it", len - 1)
5321        } else {
5322            "it".to_string()
5323        };
5324        self.line(format!("let j: usize = {j};"));
5325        let mut inputs = consts;
5326        inputs.extend(carries.iter().cloned());
5327        for (k, a) in e.inputs[nc + nk..].iter().enumerate() {
5328            let m = size(&a.aval()) / len.max(1);
5329            let name = format!("{s}_x{k}");
5330            let ty = self.ty(&AVal::new(
5331                a.aval().shape.dims()[1..].to_vec(),
5332                a.aval().dtype,
5333            ))?;
5334            let v = if size(&a.aval()) == 1 {
5335                self.val(a)?
5336            } else if m == 1 {
5337                self.at(a, "j")?
5338            } else {
5339                let sl = self.slice(a, &format!("j * {m}"), &format!("(j + 1) * {m}"))?;
5340                format!("<{ty}>::try_from(&{sl}).unwrap()")
5341            };
5342            self.line(format!("let {name}: {ty} = {v};"));
5343            inputs.push(Name {
5344                expr: name,
5345                is_ref: false,
5346            });
5347        }
5348        let others = self.loop_body(body, &inputs, &body.invars[nc..nc + nk], &carries)?;
5349        for ((y, o), t) in ys.iter().zip(ys_vars).zip(others) {
5350            let m = size(o.aval()) / len.max(1);
5351            if size(o.aval()) == 1 {
5352                self.line(format!("{y} = t.{t};"));
5353            } else if m == 1 {
5354                self.line(format!("{y}[j] = t.{t};"));
5355            } else {
5356                self.line(format!(
5357                    "{y}[j * {m}..(j + 1) * {m}].copy_from_slice(&t.{t});"
5358                ));
5359            }
5360        }
5361        self.indent -= 1;
5362        self.line("}");
5363        for (o, c) in e.outputs[..nk].iter().zip(carries) {
5364            self.names.insert(o.id(), c);
5365            if size(o.aval()) > 1 {
5366                self.own(o);
5367            }
5368        }
5369        for (o, y) in ys_vars.iter().zip(ys) {
5370            self.names.insert(
5371                o.id(),
5372                Name {
5373                    expr: y,
5374                    is_ref: false,
5375                },
5376            );
5377            if size(o.aval()) > 1 {
5378                self.own(o);
5379            }
5380        }
5381        Ok(())
5382    }
5383    /// `top_k` by the kernel (the same order of ties).
5384    fn top_k(&mut self, e: &Eqn) -> Result<()> {
5385        let Params::TopK { k, axis, .. } = e.params else {
5386            return err("parameters");
5387        };
5388        let x = &e.inputs[0];
5389        let (vo, io) = (&e.outputs[0], &e.outputs[1]);
5390        let t = x.aval().dtype;
5391        if t.is_complex() || size(&x.aval()) <= 1 {
5392            return self.fallback(e);
5393        }
5394        let n = size(vo.aval());
5395        let xs = self.slice_of(x)?;
5396        let tk = self.fresh("tk");
5397        self.line(format!(
5398            "let ({tk}_v, {tk}_i): ([{}; {n}], [i32; {n}]) = rt::top_k::<{}, {n}>({xs}, &{:?}, {k}, {axis});",
5399            elem_ty(t)?,
5400            elem_ty(t)?,
5401            x.aval().shape.dims()
5402        ));
5403        let at = |a: &str| {
5404            if n == 1 {
5405                format!("{a}[0]")
5406            } else {
5407                a.to_string()
5408            }
5409        };
5410        self.bind(vo, &at(&format!("{tk}_v")))?;
5411        self.bind(io, &at(&format!("{tk}_i")))
5412    }
5413
5414    /// `cholesky` of real matrices by the kernel.
5415    fn cholesky(&mut self, e: &Eqn) -> Result<()> {
5416        let (x, out) = (&e.inputs[0], &e.outputs[0]);
5417        let t = x.aval().dtype;
5418        let dims = x.aval().shape.dims().to_vec();
5419        if !matches!(t, DType::F32 | DType::F64) || dims.len() < 2 || size(&x.aval()) <= 1 {
5420            return self.fallback(e);
5421        }
5422        let n = dims[dims.len() - 1];
5423        let total = size(&x.aval());
5424        let xs = self.slice_of(x)?;
5425        let ty = elem_ty(t)?;
5426        self.bind(
5427            out,
5428            &format!(
5429                "rt::cholesky::<{ty}, {total}>({xs}, {}, {n})",
5430                total / (n * n)
5431            ),
5432        )
5433    }
5434
5435    /// `triangular_solve` of real matrices by the kernel.
5436    fn triangular_solve(&mut self, e: &Eqn) -> Result<()> {
5437        let Params::TriangularSolve {
5438            left_side,
5439            lower,
5440            transpose_a,
5441            conjugate_a,
5442            unit_diagonal,
5443        } = e.params
5444        else {
5445            return err("parameters");
5446        };
5447        let (a, b, out) = (&e.inputs[0], &e.inputs[1], &e.outputs[0]);
5448        let t = b.aval().dtype;
5449        let bd = b.aval().shape.dims().to_vec();
5450        if !matches!(t, DType::F32 | DType::F64)
5451            || a.aval().dtype != t
5452            || bd.len() < 2
5453            || size(&b.aval()) <= 1
5454            || size(&a.aval()) <= 1
5455        {
5456            return self.fallback(e);
5457        }
5458        let (m, n) = (bd[bd.len() - 2], bd[bd.len() - 1]);
5459        let total = size(&b.aval());
5460        let (asl, bsl) = (self.slice_of(a)?, self.slice_of(b)?);
5461        let ty = elem_ty(t)?;
5462        self.bind(
5463            out,
5464            &format!(
5465                "rt::triangular_solve::<{ty}, {total}>({asl}, {bsl}, ({}, {m}, {n}), [{left_side}, {lower}, {transpose_a}, {conjugate_a}, {unit_diagonal}])",
5466                total / (m * n)
5467            ),
5468        )
5469    }
5470
5471    /// `dot_general` as loops over the result (batch, then the free
5472    /// dimensions of `lhs` and of `rhs`), each element summed over the
5473    /// contracting dimensions in order from zero, as the kernel does (16-bit
5474    /// floats, which the kernel accumulates in `f32`, and complex numbers by
5475    /// the interpreter).
5476    fn dot_general(&mut self, e: &Eqn) -> Result<()> {
5477        let Params::DotGeneral {
5478            dimension_numbers: d,
5479            ..
5480        } = &e.params
5481        else {
5482            return err("parameters");
5483        };
5484        let (l, r, out) = (&e.inputs[0], &e.inputs[1], &e.outputs[0]);
5485        let t = out.aval().dtype;
5486        if l.aval().dtype != t
5487            || r.aval().dtype != t
5488            || t.is_complex()
5489            || matches!(t, DType::F16 | DType::BF16)
5490        {
5491            return self.fallback(e);
5492        }
5493        let (ls, rs) = (
5494            l.aval().shape.dims().to_vec(),
5495            r.aval().shape.dims().to_vec(),
5496        );
5497        let (lst, rst) = (strides(&ls), strides(&rs));
5498        let lfree = ruxla_kernels::array::free_dims(ls.len(), &d.lhs_contracting, &d.lhs_batch);
5499        let rfree = ruxla_kernels::array::free_dims(rs.len(), &d.rhs_contracting, &d.rhs_batch);
5500        // The result's dimensions with their strides in `lhs` and `rhs`.
5501        let mut outer: Vec<(usize, usize, usize)> = Vec::new();
5502        for (&a, &b) in d.lhs_batch.iter().zip(&d.rhs_batch) {
5503            outer.push((ls[a], lst[a], rst[b]));
5504        }
5505        outer.extend(lfree.iter().map(|&a| (ls[a], lst[a], 0)));
5506        outer.extend(rfree.iter().map(|&b| (rs[b], 0, rst[b])));
5507        let inner: Vec<(usize, usize, usize)> = d
5508            .lhs_contracting
5509            .iter()
5510            .zip(&d.rhs_contracting)
5511            .map(|(&a, &b)| (ls[a], lst[a], rst[b]))
5512            .collect();
5513        let n = size(out.aval());
5514        let zero = format!("<{} as Default>::default()", elem_ty(t)?);
5515        if n == 1 {
5516            // A scalar result: the sum alone.
5517            let mut li = Vec::new();
5518            let mut ri = Vec::new();
5519            let mut loops = String::new();
5520            let mut close = String::new();
5521            for (k, &(dim, sl, sr)) in inner.iter().enumerate() {
5522                loops.push_str(&format!("for c{k} in 0..{dim}usize {{ "));
5523                close.push_str(" }");
5524                li.push(format!("c{k} * {sl}"));
5525                ri.push(format!("c{k} * {sr}"));
5526            }
5527            let join = |v: &[String]| {
5528                if v.is_empty() {
5529                    "0".to_string()
5530                } else {
5531                    v.join(" + ")
5532                }
5533            };
5534            let a = self.at(l, &join(&li))?;
5535            let b = self.at(r, &join(&ri))?;
5536            let sum = binary_expr(
5537                BinaryOp::Add,
5538                t,
5539                "acc",
5540                &binary_expr(BinaryOp::Mul, t, &a, &b),
5541            );
5542            let expr = format!("{{ let mut acc = {zero}; {loops}acc = {sum};{close} acc }}");
5543            return self.bind(out, &expr);
5544        }
5545        let (name, dst) = match self.targets.get(&out.id()).cloned() {
5546            Some(tg) => (tg.clone(), tg),
5547            None => {
5548                let name = format!("v{}", out.id());
5549                let ty = self.ty(out.aval())?;
5550                // Every element written by the loops below.
5551                self.line(format!(
5552                    "let mut {name}: {ty} = rt::overwritten([{zero}; {n}]);"
5553                ));
5554                (name.clone(), name)
5555            }
5556        };
5557        let is_target = self.targets.contains_key(&out.id());
5558        // When the free dimensions of `rhs` are its last ones, a row of the
5559        // result is contiguous in `rhs` for each contracting index: the
5560        // loops are interchanged so that the innermost loop runs over that
5561        // row (vectorized), accumulating into a local row. Each element is
5562        // still summed over the contracting dimensions in order from zero,
5563        // so the result is bitwise the same.
5564        let q = rfree.len();
5565        let trailing = q > 0 && rfree.iter().copied().eq(rs.len() - q..rs.len());
5566        let nr: usize = rfree.iter().map(|&b| rs[b]).product();
5567        let plain_r = match r {
5568            Atom::Var(v) => {
5569                size(&r.aval()) > 1
5570                    && !self.fused.contains_key(&v.id())
5571                    && !self.moves.contains_key(&v.id())
5572                    && !self.uniform_consts.contains_key(&v.id())
5573            }
5574            Atom::Lit(_) => false,
5575        };
5576        if trailing && plain_r && (4..=1024).contains(&nr) {
5577            let rname = match r {
5578                Atom::Var(v) => self.name(v)?.expr.clone(),
5579                Atom::Lit(_) => unreachable!("checked above"),
5580            };
5581            self.line("{");
5582            self.indent += 1;
5583            self.line("let mut o = 0usize;");
5584            let rows = &outer[..outer.len() - q];
5585            let mut lterms = Vec::new();
5586            let mut rterms = Vec::new();
5587            for (k, &(dim, sl, sr)) in rows.iter().enumerate() {
5588                self.line(format!("for i{k} in 0..{dim}usize {{"));
5589                self.indent += 1;
5590                if sl > 0 {
5591                    lterms.push(format!("i{k} * {sl}"));
5592                }
5593                if sr > 0 {
5594                    rterms.push(format!("i{k} * {sr}"));
5595                }
5596            }
5597            let join = |v: &[String]| {
5598                if v.is_empty() {
5599                    "0".to_string()
5600                } else {
5601                    v.join(" + ")
5602                }
5603            };
5604            self.line(format!("let lb: usize = {};", join(&lterms)));
5605            self.line(format!("let rb: usize = {};", join(&rterms)));
5606            self.line(format!("let mut row = [{zero}; {nr}];"));
5607            let mut li = vec!["lb".to_string()];
5608            let mut ri = vec!["rb".to_string()];
5609            for (k, &(dim, sl, sr)) in inner.iter().enumerate() {
5610                self.line(format!("for c{k} in 0..{dim}usize {{"));
5611                self.indent += 1;
5612                li.push(format!("c{k} * {sl}"));
5613                ri.push(format!("c{k} * {sr}"));
5614            }
5615            let a = self.at(l, &li.join(" + "))?;
5616            self.line(format!("let a = {a};"));
5617            self.line(format!("let ro: usize = {};", ri.join(" + ")));
5618            self.line(format!(
5619                "for (x, &b) in row.iter_mut().zip({rname}[ro..ro + {nr}].iter()) {{"
5620            ));
5621            self.indent += 1;
5622            let prod = binary_expr(BinaryOp::Mul, t, "a", "b");
5623            let sum = binary_expr(BinaryOp::Add, t, "(*x)", &prod);
5624            self.line(format!("*x = {sum};"));
5625            self.indent -= 1;
5626            self.line("}");
5627            for _ in &inner {
5628                self.indent -= 1;
5629                self.line("}");
5630            }
5631            self.line(format!("{dst}[o..o + {nr}].copy_from_slice(&row);"));
5632            self.line(format!("o += {nr};"));
5633            for _ in rows {
5634                self.indent -= 1;
5635                self.line("}");
5636            }
5637            self.indent -= 1;
5638            self.line("}");
5639            self.names.insert(
5640                out.id(),
5641                Name {
5642                    expr: name,
5643                    is_ref: is_target,
5644                },
5645            );
5646            self.own(out);
5647            return Ok(());
5648        }
5649        self.line("{");
5650        self.indent += 1;
5651        self.line("let mut o = 0usize;");
5652        let mut lterms = Vec::new();
5653        let mut rterms = Vec::new();
5654        for (k, &(dim, sl, sr)) in outer.iter().enumerate() {
5655            self.line(format!("for i{k} in 0..{dim}usize {{"));
5656            self.indent += 1;
5657            if sl > 0 {
5658                lterms.push(format!("i{k} * {sl}"));
5659            }
5660            if sr > 0 {
5661                rterms.push(format!("i{k} * {sr}"));
5662            }
5663        }
5664        let join = |v: &[String]| {
5665            if v.is_empty() {
5666                "0".to_string()
5667            } else {
5668                v.join(" + ")
5669            }
5670        };
5671        self.line(format!("let lb: usize = {};", join(&lterms)));
5672        self.line(format!("let rb: usize = {};", join(&rterms)));
5673        self.line(format!("let mut acc = {zero};"));
5674        let mut li = vec!["lb".to_string()];
5675        let mut ri = vec!["rb".to_string()];
5676        for (k, &(dim, sl, sr)) in inner.iter().enumerate() {
5677            self.line(format!("for c{k} in 0..{dim}usize {{"));
5678            self.indent += 1;
5679            li.push(format!("c{k} * {sl}"));
5680            ri.push(format!("c{k} * {sr}"));
5681        }
5682        let a = self.at(l, &li.join(" + "))?;
5683        let b = self.at(r, &ri.join(" + "))?;
5684        let prod = binary_expr(BinaryOp::Mul, t, &a, &b);
5685        let sum = binary_expr(BinaryOp::Add, t, "acc", &prod);
5686        self.line(format!("acc = {sum};"));
5687        for _ in &inner {
5688            self.indent -= 1;
5689            self.line("}");
5690        }
5691        self.line(format!("{dst}[o] = acc;"));
5692        self.line("o += 1;");
5693        for _ in &outer {
5694            self.indent -= 1;
5695            self.line("}");
5696        }
5697        self.indent -= 1;
5698        self.line("}");
5699        self.names.insert(
5700            out.id(),
5701            Name {
5702                expr: name,
5703                is_ref: is_target,
5704            },
5705        );
5706        self.own(out);
5707        Ok(())
5708    }
5709
5710    /// `conv_general_dilated` by the kernel, when both operands have the
5711    /// result's type (otherwise the interpreter converts them).
5712    fn conv(&mut self, e: &Eqn) -> Result<()> {
5713        let Params::ConvGeneralDilated {
5714            window_strides,
5715            padding,
5716            lhs_dilation,
5717            rhs_dilation,
5718            dimension_numbers: d,
5719            feature_group_count,
5720            batch_group_count,
5721            ..
5722        } = &e.params
5723        else {
5724            return err("parameters");
5725        };
5726        let (l, r, out) = (&e.inputs[0], &e.inputs[1], &e.outputs[0]);
5727        let t = out.aval().dtype;
5728        if l.aval().dtype != t || r.aval().dtype != t || t.is_complex() {
5729            return self.fallback(e);
5730        }
5731        let window = ruxla_kernels::window::ConvWindow {
5732            strides: window_strides,
5733            padding,
5734            lhs_dilation,
5735            rhs_dilation,
5736        };
5737        // A small convolution: a table of the products that the kernel sums
5738        // (in its order, so the same sums), read by one loop.
5739        if !matches!(t, DType::F64 | DType::F16 | DType::BF16)
5740            && size(out.aval()) > 1
5741            && size(out.aval()) * size(&r.aval()) <= CONV_TABLE_TERMS
5742        {
5743            let terms = ruxla_kernels::window::conv_terms(
5744                l.aval().shape.dims(),
5745                r.aval().shape.dims(),
5746                &window,
5747                d,
5748                *feature_group_count,
5749                *batch_group_count,
5750            );
5751            let flat: Vec<usize> = terms.iter().flatten().copied().collect();
5752            let table = self.usize_table(3, &flat)?;
5753            let ty = elem_ty(t)?;
5754            let n = size(out.aval());
5755            let zero = format!("<{ty} as Default>::default()");
5756            let (name, dst) = match self.targets.get(&out.id()).cloned() {
5757                Some(tg) => {
5758                    self.line(format!("{tg}.fill({zero});"));
5759                    (tg.clone(), tg)
5760                }
5761                None => {
5762                    let name = format!("v{}", out.id());
5763                    self.line(format!("let mut {name}: [{ty}; {n}] = [{zero}; {n}];"));
5764                    (name.clone(), name)
5765                }
5766            };
5767            let a = self.at(l, "li")?;
5768            let b = self.at(r, "ri")?;
5769            let sum = binary_expr(
5770                BinaryOp::Add,
5771                t,
5772                &format!("{dst}[o]"),
5773                &binary_expr(BinaryOp::Mul, t, &a, &b),
5774            );
5775            self.line(format!(
5776                "for &[o, li, ri] in {table}.iter() {{ {dst}[o] = {sum}; }}"
5777            ));
5778            let is_target = self.targets.contains_key(&out.id());
5779            self.names.insert(
5780                out.id(),
5781                Name {
5782                    expr: name,
5783                    is_ref: is_target,
5784                },
5785            );
5786            self.own(out);
5787            return Ok(());
5788        }
5789        let (ls, rs) = (self.slice_of(l)?, self.slice_of(r)?);
5790        let expr = format!(
5791            "rt::conv::<{}, {}>({ls}, &{:?}, {rs}, &{:?}, &rt::ConvWindow {{ strides: &{window_strides:?}, padding: &{padding:?}, lhs_dilation: &{lhs_dilation:?}, rhs_dilation: &{rhs_dilation:?} }}, &rt::ConvDims {{ lhs_spec: vec!{:?}, rhs_spec: vec!{:?}, out_spec: vec!{:?} }}, {feature_group_count}, {batch_group_count})",
5792            elem_ty(t)?,
5793            size(out.aval()),
5794            l.aval().shape.dims(),
5795            r.aval().shape.dims(),
5796            d.lhs_spec,
5797            d.rhs_spec,
5798            d.out_spec,
5799        );
5800        if size(out.aval()) == 1 {
5801            return self.bind(out, &format!("{expr}[0]"));
5802        }
5803        self.bind(out, &expr)
5804    }
5805
5806    fn fallback(&mut self, e: &Eqn) -> Result<()> {
5807        // The primitive, for whoever reads the code (these calls are slow).
5808        self.line(format!("// The interpreter: `{}`.", e.prim.name()));
5809        let mut invars = Vec::new();
5810        let mut inputs = Vec::new();
5811        let mut host = Vec::new();
5812        for a in &e.inputs {
5813            match a {
5814                Atom::Lit(_) => inputs.push(a.clone()),
5815                Atom::Var(v) => {
5816                    let nv = Var::new(v.aval().clone());
5817                    invars.push(nv.clone());
5818                    inputs.push(nv.into());
5819                    let t = elem_ty(v.aval().dtype)?;
5820                    let dims = format!("{:?}", v.aval().shape.dims());
5821                    let data = if size(v.aval()) == 1 {
5822                        format!("&[{}]", self.val(a)?)
5823                    } else {
5824                        if self.is_fused(a) {
5825                            format!("&{}[..]", self.val(a)?)
5826                        } else {
5827                            format!("&{}[..]", self.name(v)?.expr)
5828                        }
5829                    };
5830                    host.push(format!("rt::host::<{t}>({data}, &{dims})"));
5831                }
5832            }
5833        }
5834        let outputs: Vec<Var> = e
5835            .outputs
5836            .iter()
5837            .map(|o| Var::new(o.aval().clone()))
5838            .collect();
5839        let f = Function {
5840            constvars: Vec::new(),
5841            invars,
5842            eqns: vec![Eqn {
5843                prim: e.prim,
5844                inputs,
5845                params: e.params.clone(),
5846                outputs: outputs.clone(),
5847                loc: None,
5848            }],
5849            outvars: outputs.into_iter().map(Atom::Var).collect(),
5850        };
5851        let bytes = ruxla_ir::serialize::to_bytes(&f);
5852        let r = self.fresh("f");
5853        self.line(format!("let {r} = {{"));
5854        self.line("    static F: std::sync::OnceLock<rt::Function> = std::sync::OnceLock::new();");
5855        self.line(format!(
5856            "    static B: [u8; {}] = {:?};",
5857            bytes.len(),
5858            bytes
5859        ));
5860        self.line(format!("    rt::eval(&F, &B, vec![{}])", host.join(", ")));
5861        self.line("};");
5862        for (k, o) in e.outputs.iter().enumerate() {
5863            let t = elem_ty(o.aval().dtype)?;
5864            if size(o.aval()) == 1 {
5865                self.bind(o, &format!("rt::from_host_scalar::<{t}>(&{r}[{k}])"))?;
5866            } else {
5867                self.bind(
5868                    o,
5869                    &format!("rt::from_host::<{t}, {}>(&{r}[{k}])", size(o.aval())),
5870                )?;
5871            }
5872        }
5873        Ok(())
5874    }
5875}
5876
5877/// A moved operand over a run of `elementwise_moved`: its source, first
5878/// index, and stride.
5879type RunPart = Option<(usize, i64, i64)>;
5880
5881/// If every element of a move (`map`, of an array of shape `dims`) comes
5882/// from one source at `base + sum_d idx_d * stride_d` (non-negative
5883/// strides), that source, the base, and the strides.
5884fn affine_offset(map: &[Src], dims: &[usize]) -> Option<(usize, i64, Vec<i64>)> {
5885    let n = map.len();
5886    if n == 0 || dims.iter().product::<usize>() != n {
5887        return None;
5888    }
5889    let Src::In(k, base) = map[0] else {
5890        return None;
5891    };
5892    let ostrides = strides(dims);
5893    let mut sstrides = Vec::with_capacity(dims.len());
5894    for (d, &size) in dims.iter().enumerate() {
5895        if size <= 1 {
5896            sstrides.push(0);
5897            continue;
5898        }
5899        let Src::In(k2, i) = map[ostrides[d]] else {
5900            return None;
5901        };
5902        if k2 != k || i < base {
5903            return None;
5904        }
5905        sstrides.push(i - base);
5906    }
5907    // Check every element.
5908    let mut idx = vec![0usize; dims.len()];
5909    for s in map {
5910        let expected = base
5911            + idx
5912                .iter()
5913                .zip(&sstrides)
5914                .map(|(&x, &st)| x as i64 * st)
5915                .sum::<i64>();
5916        if *s != Src::In(k, expected) {
5917            return None;
5918        }
5919        for d in (0..dims.len()).rev() {
5920            idx[d] += 1;
5921            if idx[d] < dims[d] {
5922                break;
5923            }
5924            idx[d] = 0;
5925        }
5926    }
5927    Some((k, base, sstrides))
5928}
5929
5930/// The data movement results that were not built
5931/// ([`Scope::virtual_moves`]) that expressions read (`@M<id>@`).
5932fn moved_ids(exprs: &[String]) -> Vec<u64> {
5933    let mut ids = Vec::new();
5934    for x in exprs {
5935        let mut rest = x.as_str();
5936        while let Some(p) = rest.find("@M") {
5937            rest = &rest[p + 2..];
5938            let end = rest.find('@').unwrap_or(rest.len());
5939            if let Ok(id) = rest[..end].parse::<u64>()
5940                && !ids.contains(&id)
5941            {
5942                ids.push(id);
5943            }
5944            rest = &rest[end.min(rest.len())..];
5945            rest = rest.strip_prefix('@').unwrap_or(rest);
5946        }
5947    }
5948    ids
5949}
5950
5951fn loc(e: &Eqn) -> String {
5952    e.loc
5953        .map(|l| l.to_string())
5954        .unwrap_or_else(|| "unknown location".into())
5955}
5956
5957/// The value of an atom known at generation time.
5958fn constant(a: &Atom, consts: &HashMap<u64, HostArray>) -> Option<HostArray> {
5959    match a {
5960        Atom::Lit(l) => Some(l.value().clone()),
5961        Atom::Var(v) => consts.get(&v.id()).cloned(),
5962    }
5963}
5964
5965fn unary_expr(op: UnaryOp, t: DType, a: &str) -> String {
5966    let ty = elem_ty(t).unwrap_or("?");
5967    match op {
5968        UnaryOp::Neg if primitive(t) && is_float(t) => format!("(-{a})"),
5969        UnaryOp::Neg if is_int(t) => format!("{a}.wrapping_neg()"),
5970        UnaryOp::Not if primitive(t) => format!("(!{a})"),
5971        _ => format!("<{ty} as rt::Ops>::unary(rt::UnaryOp::{op:?}, {a})"),
5972    }
5973}
5974
5975/// `integer_pow` of a float by multiplications in the kernel's order
5976/// (`ruxla_kernels::integer_pow`: squaring, the set bits of `y` from the
5977/// lowest, and the reciprocal for a negative `y`).
5978fn float_pow_expr(x: &str, y: i32, ty: &str) -> String {
5979    let mut lines = vec![format!("let b = {x};")];
5980    let mut n = y.unsigned_abs();
5981    let mut acc: Option<String> = None;
5982    let mut base = "b".to_string();
5983    let mut k = 0;
5984    while n > 0 {
5985        if n & 1 == 1 {
5986            acc = Some(match acc {
5987                None => base.clone(),
5988                Some(a) => format!("({a} * {base})"),
5989            });
5990        }
5991        n >>= 1;
5992        if n > 0 {
5993            k += 1;
5994            lines.push(format!("let b{k} = {base} * {base};"));
5995            base = format!("b{k}");
5996        }
5997    }
5998    let acc = acc.expect("a nonzero exponent");
5999    let acc = if y < 0 {
6000        format!("(1.0 as {ty}) / {acc}")
6001    } else {
6002        acc
6003    };
6004    format!("{{ {} {acc} }}", lines.join(" "))
6005}
6006
6007fn binary_expr(op: BinaryOp, t: DType, a: &str, b: &str) -> String {
6008    let ty = elem_ty(t).unwrap_or("?");
6009    let p = primitive(t);
6010    match op {
6011        BinaryOp::Add if p && is_float(t) => format!("({a} + {b})"),
6012        BinaryOp::Sub if p && is_float(t) => format!("({a} - {b})"),
6013        BinaryOp::Mul if p && is_float(t) => format!("({a} * {b})"),
6014        BinaryOp::Div if p && is_float(t) => format!("({a} / {b})"),
6015        BinaryOp::Add if is_int(t) => format!("{a}.wrapping_add({b})"),
6016        BinaryOp::Sub if is_int(t) => format!("{a}.wrapping_sub({b})"),
6017        BinaryOp::Mul if is_int(t) => format!("{a}.wrapping_mul({b})"),
6018        BinaryOp::And if p && !is_float(t) => format!("({a} & {b})"),
6019        BinaryOp::Or if p && !is_float(t) => format!("({a} | {b})"),
6020        BinaryOp::Xor if p && !is_float(t) => format!("({a} ^ {b})"),
6021        BinaryOp::Max | BinaryOp::Min if is_int(t) => {
6022            let m = if op == BinaryOp::Max { "max" } else { "min" };
6023            format!("{a}.{m}({b})")
6024        }
6025        _ => format!("<{ty} as rt::Ops>::binary(rt::BinaryOp::{op:?}, {a}, {b})"),
6026    }
6027}
6028
6029fn compare_expr(op: CompareOp, t: DType, a: &str, b: &str) -> String {
6030    if !primitive(t) {
6031        return format!("rt::compare(rt::CompareOp::{op:?}, {a}, {b})");
6032    }
6033    let o = match op {
6034        CompareOp::Eq => "==",
6035        CompareOp::Ne => "!=",
6036        CompareOp::Lt => "<",
6037        CompareOp::Le => "<=",
6038        CompareOp::Gt => ">",
6039        CompareOp::Ge => ">=",
6040    };
6041    format!("({a} {o} {b})")
6042}
6043
6044fn convert_expr(from: DType, to: DType, a: &str) -> String {
6045    if from == to {
6046        return a.to_string();
6047    }
6048    let (f, t) = (elem_ty(from).unwrap_or("?"), elem_ty(to).unwrap_or("?"));
6049    if !primitive(from) || !primitive(to) {
6050        return format!("rt::cast::<{f}, {t}>({a})");
6051    }
6052    match (from.kind(), to.kind()) {
6053        (DTypeKind::Bool, DTypeKind::Float) => format!("({a} as u8 as {t})"),
6054        (_, DTypeKind::Bool) if is_float(from) => format!("({a} != 0.0)"),
6055        (_, DTypeKind::Bool) => format!("({a} != 0)"),
6056        _ => format!("({a} as {t})"),
6057    }
6058}
6059
6060fn bitcast_expr(from: DType, to: DType, a: &str) -> Option<String> {
6061    if from == to {
6062        return Some(a.to_string());
6063    }
6064    if !primitive(from)
6065        || !primitive(to)
6066        || from.size_in_bytes() != to.size_in_bytes()
6067        || from == DType::Bool
6068        || to == DType::Bool
6069    {
6070        return None;
6071    }
6072    let t = elem_ty(to).ok()?;
6073    Some(match (is_float(from), is_float(to)) {
6074        (false, false) => format!("({a} as {t})"),
6075        (true, false) => format!("({a}.to_bits() as {t})"),
6076        (false, true) => {
6077            let u = if to == DType::F32 { "u32" } else { "u64" };
6078            format!("{t}::from_bits({a} as {u})")
6079        }
6080        (true, true) => return None,
6081    })
6082}
6083
6084#[cfg(test)]
6085mod tests {
6086    use super::subst_index;
6087
6088    /// An index that is an expression is parenthesized where a template uses
6089    /// it in arithmetic (a gather fused into an elementwise loop that is
6090    /// split into parts: JaxMARL's STORM with n players read the index
6091    /// vectors of the second part at `25 + i * 2`).
6092    #[test]
6093    fn subst_index_parenthesizes_expressions() {
6094        assert_eq!(subst_index("x[@I@ * 2 + 1]", "i"), "x[i * 2 + 1]");
6095        assert_eq!(
6096            subst_index("x[@I@ * 2 + 1]", "25 + i"),
6097            "x[(25 + i) * 2 + 1]"
6098        );
6099        assert_eq!(
6100            subst_index("x[@D5:2@]", "25 + i"),
6101            "x[(((25 + i)) / 5 % 2)]"
6102        );
6103    }
6104}